@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
@@ -15,8 +15,7 @@ import { ModelConfigurationManager } from "../../core/modelConfiguration.js";
15
15
  import { isSchemaComplexityError } from "../../core/modules/structuredOutputPolicy.js";
16
16
  import { redactUrlForError, stringifyContentSafe, } from "../../utils/logSanitize.js";
17
17
  import { googleSdkProxyHttpOptions } from "../../proxy/proxyFetch.js";
18
- import { AuthenticationError, InvalidModelError, NetworkError, ProviderError, RateLimitError, } from "../../types/index.js";
19
- import { classifyProviderError, messageNamesStatus, } from "../../utils/errorClassifier.js";
18
+ import { AuthenticationError, ProviderError } from "../../types/index.js";
20
19
  import { ERROR_CODES, NeuroLinkError } from "../../utils/errorHandling.js";
21
20
  import { applyVertexAnthropicCacheBreakpoints } from "../../utils/anthropicCacheBreakpoints.js";
22
21
  import { FileDetector } from "../../utils/fileDetector.js";
@@ -55,6 +54,20 @@ import { resolveToolExecutionRecords } from "../../core/toolExecutionRecorder.js
55
54
  import { modelSupportsForcedToolChoice, resolveSamplingParams, } from "../../models/modelRegistry.js";
56
55
  import { sanitizeAnthropicMessagesForTrace } from "../../utils/anthropicTraceSanitizer.js";
57
56
  import { extractToolFailureText } from "../../utils/mcpErrorText.js";
57
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
58
+ import { getProviderErrorRules } from "../rules/registry.js";
59
+ import { getThinkingLimits } from "../rules/thinkingLimits.js";
60
+ import { getRequestDefault } from "../rules/requestDefaults.js";
61
+ import { toWireParams } from "../rules/requestFields.js";
62
+ import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
63
+ import { FINAL_RESULT_TOOL_DESCRIPTION, FINAL_RESULT_TOOL_NAME, finalResultToolInstruction, } from "../rules/finalResultTool.js";
64
+ import { getWireUsage, outputWithReasoning, splitIncludedCount, } from "../rules/wireUsage.js";
65
+ const ANTHROPIC_MESSAGES_FINISH = getFinishReasonMap("anthropic", "messages");
66
+ // Sizing of the forced finalization call after a Claude-on-Vertex loop stops.
67
+ const FINALIZATION_MIN_TOKENS = getRequestDefault("vertex", "finalizationMinTokens");
68
+ const FINALIZATION_HEADROOM_TOKENS = getRequestDefault("vertex", "finalizationHeadroomTokens");
69
+ const GEMINI_USAGE = getWireUsage("gemini");
70
+ const VERTEX_ERROR_RULES = getProviderErrorRules("vertex");
58
71
  // Import proper types for multimodal message handling
59
72
  // Dynamic import helper for native Anthropic Vertex SDK
60
73
  let anthropicVertexModule = null;
@@ -1299,8 +1312,8 @@ export class GoogleVertexProvider extends BaseProvider {
1299
1312
  }
1300
1313
  const typedSchema = ensureNestedSchemaTypes(inlinedSchema);
1301
1314
  return {
1302
- name: "final_result",
1303
- 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.",
1315
+ name: FINAL_RESULT_TOOL_NAME,
1316
+ description: FINAL_RESULT_TOOL_DESCRIPTION,
1304
1317
  input_schema: {
1305
1318
  type: "object",
1306
1319
  properties: typedSchema.properties || typedSchema,
@@ -1501,8 +1514,8 @@ export class GoogleVertexProvider extends BaseProvider {
1501
1514
  // Add final_result tool to the existing function declarations
1502
1515
  const existingDeclarations = tools[0]?.functionDeclarations || [];
1503
1516
  existingDeclarations.push({
1504
- name: "final_result",
1505
- 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.",
1517
+ name: FINAL_RESULT_TOOL_NAME,
1518
+ description: FINAL_RESULT_TOOL_DESCRIPTION,
1506
1519
  parametersJsonSchema: typedSchema,
1507
1520
  });
1508
1521
  tools = [{ functionDeclarations: existingDeclarations }];
@@ -1552,7 +1565,7 @@ export class GoogleVertexProvider extends BaseProvider {
1552
1565
  // Build system prompt, adding final_result instruction if needed
1553
1566
  let effectiveSystemPrompt = options.systemPrompt || "";
1554
1567
  if (useFinalResultTool) {
1555
- const finalResultInstruction = "\n\nIMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.";
1568
+ const finalResultInstruction = finalResultToolInstruction("callWhenReady");
1556
1569
  effectiveSystemPrompt = effectiveSystemPrompt + finalResultInstruction;
1557
1570
  }
1558
1571
  if (effectiveSystemPrompt) {
@@ -1722,7 +1735,7 @@ export class GoogleVertexProvider extends BaseProvider {
1722
1735
  ...(declarations ? { declarations } : {}),
1723
1736
  ...(useFinalResultTool
1724
1737
  ? {
1725
- finalResultToolName: "final_result",
1738
+ finalResultToolName: FINAL_RESULT_TOOL_NAME,
1726
1739
  onTerminalResult: (text) => {
1727
1740
  try {
1728
1741
  finalResultStructuredOutput = JSON.parse(text);
@@ -1955,7 +1968,7 @@ export class GoogleVertexProvider extends BaseProvider {
1955
1968
  if (!finalText &&
1956
1969
  (stepsTaken >= maxSteps || wasAborted || hitContextLimit)) {
1957
1970
  hitStepLimit = stepsTaken >= maxSteps && !wasAborted;
1958
- const toolCallCount = allToolCalls.filter((tc) => tc.toolName !== "final_result").length;
1971
+ const toolCallCount = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length;
1959
1972
  // The consumer receives text via `incrementalTextChunks`; any text the
1960
1973
  // model emitted across steps is already preserved there. Only produce a
1961
1974
  // terminal message when NOTHING was produced (the pure-functionCall /
@@ -2042,7 +2055,7 @@ export class GoogleVertexProvider extends BaseProvider {
2042
2055
  phase: stopReason,
2043
2056
  step: stepsTaken,
2044
2057
  maxSteps,
2045
- toolCallCount: allToolCalls.filter((tc) => tc.toolName !== "final_result").length,
2058
+ toolCallCount: allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length,
2046
2059
  elapsedMs: turnClock.elapsedMs(),
2047
2060
  });
2048
2061
  }
@@ -2066,12 +2079,12 @@ export class GoogleVertexProvider extends BaseProvider {
2066
2079
  }
2067
2080
  }
2068
2081
  // Filter out final_result from tool calls as it's an internal pattern
2069
- const externalToolCalls = allToolCalls.filter((tc) => tc.toolName !== "final_result");
2070
- const externalToolExecutions = toolExecutions.filter((te) => te.name !== "final_result");
2082
+ const externalToolCalls = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME);
2083
+ const externalToolExecutions = toolExecutions.filter((te) => te.name !== FINAL_RESULT_TOOL_NAME);
2071
2084
  // Gemini promptTokenCount is OVERLAPPING (already includes
2072
2085
  // cachedContentTokenCount). Subtract once so the cached portion is billed at
2073
2086
  // the cheaper cacheRead rate without double-counting; total is conserved.
2074
- const adjustedInputTokens = Math.max(0, totalInputTokens - totalCacheReadTokens);
2087
+ const adjustedInputTokens = splitIncludedCount(totalInputTokens, totalCacheReadTokens).rest;
2075
2088
  const result = {
2076
2089
  stream: createTextStream(),
2077
2090
  provider: this.providerName,
@@ -2086,7 +2099,7 @@ export class GoogleVertexProvider extends BaseProvider {
2086
2099
  // candidates + thoughts), so they are folded into `output` — that is
2087
2100
  // what calculateCost bills at the output rate — with `reasoning`
2088
2101
  // reporting the thinking subset.
2089
- output: totalOutputTokens + totalReasoningTokens,
2102
+ output: outputWithReasoning(GEMINI_USAGE, totalOutputTokens, totalReasoningTokens),
2090
2103
  total: adjustedInputTokens +
2091
2104
  totalCacheReadTokens +
2092
2105
  totalOutputTokens +
@@ -2358,8 +2371,8 @@ export class GoogleVertexProvider extends BaseProvider {
2358
2371
  // Add final_result tool to the existing function declarations
2359
2372
  const existingDeclarations = tools[0]?.functionDeclarations || [];
2360
2373
  existingDeclarations.push({
2361
- name: "final_result",
2362
- 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.",
2374
+ name: FINAL_RESULT_TOOL_NAME,
2375
+ description: FINAL_RESULT_TOOL_DESCRIPTION,
2363
2376
  parametersJsonSchema: typedSchema,
2364
2377
  });
2365
2378
  tools = [{ functionDeclarations: existingDeclarations }];
@@ -2409,7 +2422,7 @@ export class GoogleVertexProvider extends BaseProvider {
2409
2422
  // Build system prompt, adding final_result instruction if needed
2410
2423
  let effectiveSystemPrompt = options.systemPrompt || "";
2411
2424
  if (useFinalResultTool) {
2412
- const finalResultInstruction = "\n\nIMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.";
2425
+ const finalResultInstruction = finalResultToolInstruction("callWhenReady");
2413
2426
  effectiveSystemPrompt = effectiveSystemPrompt + finalResultInstruction;
2414
2427
  }
2415
2428
  if (effectiveSystemPrompt) {
@@ -2568,7 +2581,7 @@ export class GoogleVertexProvider extends BaseProvider {
2568
2581
  ...(declarations ? { declarations } : {}),
2569
2582
  ...(useFinalResultTool
2570
2583
  ? {
2571
- finalResultToolName: "final_result",
2584
+ finalResultToolName: FINAL_RESULT_TOOL_NAME,
2572
2585
  onTerminalResult: (text) => {
2573
2586
  try {
2574
2587
  finalResultStructuredOutput = JSON.parse(text);
@@ -2761,7 +2774,13 @@ export class GoogleVertexProvider extends BaseProvider {
2761
2774
  throw this.handleProviderError(error);
2762
2775
  }
2763
2776
  }
2764
- await pump;
2777
+ // On the abort path the catch above already drained the pump. Awaiting
2778
+ // it again would rethrow the AbortError that branch chose to absorb, so
2779
+ // a turn-time-limit exit reached the caller as a bare "This operation
2780
+ // was aborted" instead of the turn's terminal result.
2781
+ if (!wasAborted) {
2782
+ await pump;
2783
+ }
2765
2784
  if (engineResult) {
2766
2785
  finalText = engineResult.text;
2767
2786
  lastFinishReason = engineResult.rawStopReason ?? lastFinishReason;
@@ -2794,7 +2813,7 @@ export class GoogleVertexProvider extends BaseProvider {
2794
2813
  if (!finalText &&
2795
2814
  (stepsTaken >= maxSteps || wasAborted || hitContextLimit)) {
2796
2815
  hitStepLimit = stepsTaken >= maxSteps && !wasAborted;
2797
- const toolCallCount = allToolCalls.filter((tc) => tc.toolName !== "final_result").length;
2816
+ const toolCallCount = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length;
2798
2817
  if (accumulatedText) {
2799
2818
  // Prefer the prose the model already produced across steps.
2800
2819
  logger.warn(hitContextLimit
@@ -2878,19 +2897,19 @@ export class GoogleVertexProvider extends BaseProvider {
2878
2897
  phase: stopReason,
2879
2898
  step: stepsTaken,
2880
2899
  maxSteps,
2881
- toolCallCount: allToolCalls.filter((tc) => tc.toolName !== "final_result").length,
2900
+ toolCallCount: allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length,
2882
2901
  elapsedMs: turnClock.elapsedMs(),
2883
2902
  });
2884
2903
  }
2885
2904
  const responseTime = Date.now() - startTime;
2886
2905
  // Filter out final_result from tool calls and executions as it's an internal pattern
2887
- const externalToolCalls = allToolCalls.filter((tc) => tc.toolName !== "final_result");
2888
- const externalToolExecutions = toolExecutions.filter((te) => te.name !== "final_result");
2906
+ const externalToolCalls = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME);
2907
+ const externalToolExecutions = toolExecutions.filter((te) => te.name !== FINAL_RESULT_TOOL_NAME);
2889
2908
  // Build EnhancedGenerateResult
2890
2909
  // Gemini promptTokenCount is OVERLAPPING (already includes
2891
2910
  // cachedContentTokenCount). Subtract once so the cached portion is billed at
2892
2911
  // the cheaper cacheRead rate without double-counting; total is conserved.
2893
- const adjustedInputTokens = Math.max(0, totalInputTokens - totalCacheReadTokens);
2912
+ const adjustedInputTokens = splitIncludedCount(totalInputTokens, totalCacheReadTokens).rest;
2894
2913
  const result = {
2895
2914
  content: finalText,
2896
2915
  provider: this.providerName,
@@ -2906,7 +2925,7 @@ export class GoogleVertexProvider extends BaseProvider {
2906
2925
  // candidates + thoughts), so they are folded into `output` — that is
2907
2926
  // what calculateCost bills at the output rate — with `reasoning`
2908
2927
  // reporting the thinking subset.
2909
- output: totalOutputTokens + totalReasoningTokens,
2928
+ output: outputWithReasoning(GEMINI_USAGE, totalOutputTokens, totalReasoningTokens),
2910
2929
  total: adjustedInputTokens +
2911
2930
  totalCacheReadTokens +
2912
2931
  totalOutputTokens +
@@ -2986,9 +3005,7 @@ export class GoogleVertexProvider extends BaseProvider {
2986
3005
  : "";
2987
3006
  synthConfig.systemInstruction =
2988
3007
  baseSystemInstruction +
2989
- "\n\nThe final_result tool is no longer available. Provide your " +
2990
- "final answer directly as plain text now, using the information " +
2991
- "gathered so far.";
3008
+ finalResultToolInstruction("noLongerAvailable");
2992
3009
  }
2993
3010
  // Bound the whole connect + drain with a timeout. The surrounding
2994
3011
  // try/catch only catches throws, not hangs, so without this a stalled
@@ -3155,6 +3172,23 @@ export class GoogleVertexProvider extends BaseProvider {
3155
3172
  * tool use — it forces the opposite — so it is not gated here, consistent
3156
3173
  * with oauthFetch.ts leaving `"none"` alone too.
3157
3174
  */
3175
+ /**
3176
+ * max_tokens, sampling and thinking for a forced finalization call, sized to
3177
+ * its own token limit. Thinking is rebuilt for that limit, so the sampling
3178
+ * the first request left out while thinking was on is sent again when
3179
+ * thinking no longer fits.
3180
+ */
3181
+ buildClaudeFinalizationParams(options, maxTokens, forcesToolChoice, sampling) {
3182
+ const thinking = this.buildClaudeThinkingParam(options, maxTokens, forcesToolChoice);
3183
+ return {
3184
+ ...toWireParams("anthropic", {
3185
+ maxTokens,
3186
+ temperature: sampling.temperature,
3187
+ topP: sampling.topP,
3188
+ }, { thinkingOn: thinking?.type === "enabled" }),
3189
+ thinking,
3190
+ };
3191
+ }
3158
3192
  buildClaudeThinkingParam(
3159
3193
  // Structural, not TextGenerationOptions: the streaming caller passes
3160
3194
  // StreamOptions, and only these two fields are read.
@@ -3169,18 +3203,19 @@ export class GoogleVertexProvider extends BaseProvider {
3169
3203
  if (!options.thinkingConfig?.enabled || !budget) {
3170
3204
  return undefined;
3171
3205
  }
3172
- // Two independent floors, checked explicitly rather than folded into one
3173
- // Math.max/min expression: Anthropic's own 1024 minimum on budget_tokens,
3174
- // and this function's 1024-token reservation for the answer that follows
3175
- // thinking. When maxTokens leaves no room for both — 1025..2047 is the
3176
- // narrow band where that happens — there is no valid budget, so thinking
3177
- // is omitted rather than silently coerced to exactly 1024 regardless of
3206
+ // Two independent floors (anthropic.json `thinkingLimits`), checked
3207
+ // explicitly rather than folded into one Math.max/min expression:
3208
+ // Anthropic's own minimum on budget_tokens, and the reservation for the
3209
+ // answer that follows thinking. When maxTokens leaves no room for both
3210
+ // (1025..2047 with today's values) there is no valid budget, so thinking
3211
+ // is omitted rather than silently coerced to the minimum regardless of
3178
3212
  // what the caller asked for.
3179
- if (maxTokens <= 1024) {
3213
+ const { minBudgetTokens, answerReserveTokens } = getThinkingLimits("anthropic");
3214
+ if (maxTokens <= answerReserveTokens) {
3180
3215
  return undefined;
3181
3216
  }
3182
- const clamped = Math.min(budget, maxTokens - 1024);
3183
- if (clamped < 1024) {
3217
+ const clamped = Math.min(budget, maxTokens - answerReserveTokens);
3218
+ if (clamped < minBudgetTokens) {
3184
3219
  return undefined;
3185
3220
  }
3186
3221
  return { type: "enabled", budget_tokens: clamped };
@@ -3381,8 +3416,7 @@ export class GoogleVertexProvider extends BaseProvider {
3381
3416
  }
3382
3417
  tools.push(finalResultTool);
3383
3418
  // Add instruction to system prompt
3384
- schemaSystemPromptSuffix =
3385
- "\n\nIMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.";
3419
+ schemaSystemPromptSuffix = finalResultToolInstruction("mustCall");
3386
3420
  logger.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (stream)", {
3387
3421
  schemaKeys: Object.keys(finalResultTool.input_schema.properties ?? {}),
3388
3422
  totalTools: tools.length,
@@ -3411,26 +3445,21 @@ export class GoogleVertexProvider extends BaseProvider {
3411
3445
  const streamThinking = this.buildClaudeThinkingParam(options, streamMaxTokens, forceFinalResult);
3412
3446
  const requestParams = {
3413
3447
  model: modelName,
3414
- // Default to the model's real output ceiling (e.g. 64K for Sonnet 4.x)
3415
- // instead of the legacy 4096, which silently truncated large structured
3416
- // responses mid-JSON. resolveClaudeMaxTokens also clamps over-large
3417
- // caller values so the native Vertex path never 400s.
3418
- max_tokens: streamMaxTokens,
3419
3448
  ...(streamThinking && { thinking: streamThinking }),
3420
3449
  messages: messages,
3421
3450
  ...(tools && tools.length > 0 && { tools }),
3422
3451
  ...(forceFinalResult && { tool_choice: { type: "any" } }),
3423
3452
  ...(systemPromptWithSchema && { system: systemPromptWithSchema }),
3424
- ...(streamSampling.temperature !== undefined && {
3453
+ // max_tokens defaults to the model's real output ceiling (e.g. 64K for
3454
+ // Sonnet 4.x) instead of the legacy 4096, which silently truncated large
3455
+ // structured responses mid-JSON. resolveClaudeMaxTokens also clamps
3456
+ // over-large caller values so the native Vertex path never 400s.
3457
+ ...toWireParams("anthropic", {
3458
+ maxTokens: streamMaxTokens,
3425
3459
  temperature: streamSampling.temperature,
3426
- }),
3427
- ...(streamSampling.topP !== undefined && {
3428
- top_p: streamSampling.topP,
3429
- }),
3430
- ...(options.stopSequences &&
3431
- options.stopSequences.length > 0 && {
3432
- stop_sequences: options.stopSequences,
3433
- }),
3460
+ topP: streamSampling.topP,
3461
+ stopSequences: options.stopSequences,
3462
+ }, { thinkingOn: streamThinking?.type === "enabled" }),
3434
3463
  };
3435
3464
  // ── Real-time streaming via stream.on('text', ...) ────────────────────
3436
3465
  //
@@ -3676,7 +3705,7 @@ export class GoogleVertexProvider extends BaseProvider {
3676
3705
  },
3677
3706
  ...(useFinalResultTool
3678
3707
  ? {
3679
- finalResultToolName: "final_result",
3708
+ finalResultToolName: FINAL_RESULT_TOOL_NAME,
3680
3709
  onTerminalResult: (text) => {
3681
3710
  // The engine ends the turn on a terminal call and hands back
3682
3711
  // the payload as text; this loop also streams it, so the push
@@ -3878,16 +3907,16 @@ export class GoogleVertexProvider extends BaseProvider {
3878
3907
  if (internalAbort.signal.aborted) {
3879
3908
  wasAborted = true;
3880
3909
  }
3881
- const externalToolCallCount = allToolCalls.filter((tc) => tc.toolName !== "final_result").length;
3910
+ const externalToolCallCount = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length;
3882
3911
  // Clamp the terminal calls' max_tokens so prompt + output stays
3883
3912
  // inside the model window: pre-4.5 Claude models 400 on
3884
3913
  // input + max_tokens > window, which would defeat the very
3885
3914
  // synthesis these calls exist for on context-capped turns. Only
3886
3915
  // bites when the prompt is near the window (min() is a no-op on
3887
3916
  // ordinary step-cap turns).
3888
- const terminalMaxTokens = Math.max(1024, Math.min(requestParams.max_tokens, getContextWindowSize("vertex", modelName) -
3917
+ const terminalMaxTokens = Math.max(FINALIZATION_MIN_TOKENS, Math.min(streamMaxTokens, getContextWindowSize("vertex", modelName) -
3889
3918
  contextGuard.projectedNextPromptTokens -
3890
- 4_000));
3919
+ FINALIZATION_HEADROOM_TOKENS));
3891
3920
  if (wasAborted) {
3892
3921
  // Budget already blown — never issue another model call. Deliver
3893
3922
  // exactly one HONEST terminal chunk matching the actual exit
@@ -3933,21 +3962,22 @@ export class GoogleVertexProvider extends BaseProvider {
3933
3962
  stepNumber: maxSteps + 1,
3934
3963
  model: requestParams.model,
3935
3964
  maxTokens: terminalMaxTokens,
3936
- temperature: requestParams.temperature,
3937
- topP: requestParams.top_p,
3965
+ temperature: streamSampling.temperature,
3966
+ topP: streamSampling.topP,
3938
3967
  system: cachedFinal.system,
3939
3968
  messages: cachedFinal.messages,
3940
3969
  }, async () => {
3941
3970
  const finalizationStream = await client.messages.stream({
3942
3971
  ...requestParams,
3943
- max_tokens: terminalMaxTokens,
3944
- // Resized, not inherited: terminalMaxTokens can sit below the
3945
- // budget requestParams' thinking was sized for.
3946
- thinking: this.buildClaudeThinkingParam(options, terminalMaxTokens, forceFinalResult),
3972
+ // Resized, not inherited: terminalMaxTokens can sit below the budget
3973
+ // requestParams' thinking was sized for, and the sampling the first
3974
+ // request left out while thinking was on returns when thinking no
3975
+ // longer fits at this size.
3976
+ ...this.buildClaudeFinalizationParams(options, terminalMaxTokens, forceFinalResult, streamSampling),
3947
3977
  ...(forceFinalResult && {
3948
3978
  tool_choice: {
3949
3979
  type: "tool",
3950
- name: "final_result",
3980
+ name: FINAL_RESULT_TOOL_NAME,
3951
3981
  },
3952
3982
  }),
3953
3983
  ...(cachedFinal.system !== undefined && {
@@ -3985,7 +4015,8 @@ export class GoogleVertexProvider extends BaseProvider {
3985
4015
  turnCacheUsage.read +
3986
4016
  turnCacheUsage.creation;
3987
4017
  lastStopReason = response.stop_reason;
3988
- const forcedFinalResult = response.content.find((block) => block.type === "tool_use" && block.name === "final_result");
4018
+ const forcedFinalResult = response.content.find((block) => block.type === "tool_use" &&
4019
+ block.name === FINAL_RESULT_TOOL_NAME);
3989
4020
  if (forcedFinalResult) {
3990
4021
  structuredOutputRef.value = forcedFinalResult.input;
3991
4022
  channel.push({
@@ -4078,14 +4109,18 @@ export class GoogleVertexProvider extends BaseProvider {
4078
4109
  stepNumber: maxSteps + 1,
4079
4110
  model: requestParams.model,
4080
4111
  maxTokens: terminalMaxTokens,
4081
- temperature: requestParams.temperature,
4082
- topP: requestParams.top_p,
4112
+ temperature: streamSampling.temperature,
4113
+ topP: streamSampling.topP,
4083
4114
  system: cachedBackstop.system,
4084
4115
  messages: cachedBackstop.messages,
4085
4116
  }, async () => {
4086
4117
  const backstopStream = await client.messages.stream({
4087
4118
  ...requestParams,
4088
- max_tokens: terminalMaxTokens,
4119
+ ...toWireParams("anthropic", {
4120
+ maxTokens: terminalMaxTokens,
4121
+ temperature: streamSampling.temperature,
4122
+ topP: streamSampling.topP,
4123
+ }, { thinkingOn: backstopThinking?.type === "enabled" }),
4089
4124
  // Assigned outright, never a conditional spread: spreading
4090
4125
  // requestParams above may already carry a `thinking` sized
4091
4126
  // for the original max_tokens, and only adding a key when
@@ -4200,7 +4235,7 @@ export class GoogleVertexProvider extends BaseProvider {
4200
4235
  const deliveredNothing = aggregatedTurnText.length === 0 &&
4201
4236
  liveTextPushedLength === 0 &&
4202
4237
  !structuredOutputRef.value;
4203
- const externalToolCallTotal = allToolCalls.filter((tc) => tc.toolName !== "final_result").length;
4238
+ const externalToolCallTotal = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length;
4204
4239
  if (deliveredNothing && externalToolCallTotal > 0) {
4205
4240
  const exitMessage = hitContextLimit && !wasAborted
4206
4241
  ? buildContextCapMessage(externalToolCallTotal)
@@ -4220,14 +4255,15 @@ export class GoogleVertexProvider extends BaseProvider {
4220
4255
  // (a mutable reference) because wrapper spreads snapshot the
4221
4256
  // top-level getter before this line runs.
4222
4257
  finishReasonRef.value =
4223
- lastStopReason === "max_tokens"
4258
+ translateFinishReason(ANTHROPIC_MESSAGES_FINISH, lastStopReason) ===
4259
+ "length"
4224
4260
  ? "length"
4225
4261
  : hitStepLimit && !synthesizedFinalAnswer
4226
4262
  ? "tool-calls"
4227
4263
  : "stop";
4228
4264
  metadata.finishReason = finishReasonRef.value;
4229
4265
  metadata.responseTime = Date.now() - startTime;
4230
- metadata.totalToolExecutions = allToolCalls.filter((tc) => tc.toolName !== "final_result").length;
4266
+ metadata.totalToolExecutions = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length;
4231
4267
  // Turn-exit discriminator + raw provider stop reason + step count —
4232
4268
  // mirrored onto metadata (mutable reference) for wrapper spreads,
4233
4269
  // like finishReason above.
@@ -4279,7 +4315,7 @@ export class GoogleVertexProvider extends BaseProvider {
4279
4315
  maxSteps,
4280
4316
  steps: step,
4281
4317
  toolCallCount: metadata.totalToolExecutions,
4282
- toolsCalled: toolsUsedRef.filter((name) => name !== "final_result"),
4318
+ toolsCalled: toolsUsedRef.filter((name) => name !== FINAL_RESULT_TOOL_NAME),
4283
4319
  structuredOutput: useFinalResultTool,
4284
4320
  ...(stopReasonRef.value ? { stopReason: stopReasonRef.value } : {}),
4285
4321
  usage: {
@@ -4352,17 +4388,17 @@ export class GoogleVertexProvider extends BaseProvider {
4352
4388
  Object.defineProperty(result, "toolCalls", {
4353
4389
  enumerable: true,
4354
4390
  configurable: true,
4355
- get: () => allToolCalls.filter((tc) => tc.toolName !== "final_result"),
4391
+ get: () => allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME),
4356
4392
  });
4357
4393
  Object.defineProperty(result, "toolsUsed", {
4358
4394
  enumerable: true,
4359
4395
  configurable: true,
4360
- get: () => toolsUsedRef.filter((name) => name !== "final_result"),
4396
+ get: () => toolsUsedRef.filter((name) => name !== FINAL_RESULT_TOOL_NAME),
4361
4397
  });
4362
4398
  Object.defineProperty(result, "toolExecutions", {
4363
4399
  enumerable: true,
4364
4400
  configurable: true,
4365
- get: () => transformToolExecutions(toolExecutions.filter((te) => te.name !== "final_result")),
4401
+ get: () => transformToolExecutions(toolExecutions.filter((te) => te.name !== FINAL_RESULT_TOOL_NAME)),
4366
4402
  });
4367
4403
  Object.defineProperty(result, "structuredOutput", {
4368
4404
  enumerable: true,
@@ -4596,8 +4632,7 @@ export class GoogleVertexProvider extends BaseProvider {
4596
4632
  }
4597
4633
  tools.push(finalResultTool);
4598
4634
  // Add instruction to system prompt
4599
- schemaSystemPromptSuffix =
4600
- "\n\nIMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.";
4635
+ schemaSystemPromptSuffix = finalResultToolInstruction("mustCall");
4601
4636
  logger.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (generate)", {
4602
4637
  schemaKeys: Object.keys(finalResultTool.input_schema.properties ?? {}),
4603
4638
  totalTools: tools.length,
@@ -4626,23 +4661,19 @@ export class GoogleVertexProvider extends BaseProvider {
4626
4661
  const generateThinking = this.buildClaudeThinkingParam(options, generateMaxTokens, forceFinalResult);
4627
4662
  const requestParams = {
4628
4663
  model: modelName,
4629
- // Default to the model's real output ceiling (see stream path note).
4630
- max_tokens: generateMaxTokens,
4631
4664
  ...(generateThinking && { thinking: generateThinking }),
4632
4665
  messages,
4633
4666
  ...(tools && tools.length > 0 && { tools }),
4634
4667
  ...(forceFinalResult && { tool_choice: { type: "any" } }),
4635
4668
  ...(systemPromptWithSchema && { system: systemPromptWithSchema }),
4636
- ...(generateSampling.temperature !== undefined && {
4669
+ // max_tokens defaults to the model's real output ceiling (see the
4670
+ // stream path note).
4671
+ ...toWireParams("anthropic", {
4672
+ maxTokens: generateMaxTokens,
4637
4673
  temperature: generateSampling.temperature,
4638
- }),
4639
- ...(generateSampling.topP !== undefined && {
4640
- top_p: generateSampling.topP,
4641
- }),
4642
- ...(options.stopSequences &&
4643
- options.stopSequences.length > 0 && {
4644
- stop_sequences: options.stopSequences,
4645
- }),
4674
+ topP: generateSampling.topP,
4675
+ stopSequences: options.stopSequences,
4676
+ }, { thinkingOn: generateThinking?.type === "enabled" }),
4646
4677
  };
4647
4678
  // Handle tool calling loop with max steps
4648
4679
  const maxSteps = options.maxSteps || DEFAULT_MAX_STEPS;
@@ -4813,7 +4844,7 @@ export class GoogleVertexProvider extends BaseProvider {
4813
4844
  },
4814
4845
  ...(useFinalResultTool
4815
4846
  ? {
4816
- finalResultToolName: "final_result",
4847
+ finalResultToolName: FINAL_RESULT_TOOL_NAME,
4817
4848
  onTerminalResult: (text) => {
4818
4849
  try {
4819
4850
  structuredOutput = JSON.parse(text);
@@ -4991,15 +5022,15 @@ export class GoogleVertexProvider extends BaseProvider {
4991
5022
  if (internalAbort.signal.aborted) {
4992
5023
  wasAborted = true;
4993
5024
  }
4994
- const externalToolCallCount = allToolCalls.filter((tc) => tc.toolName !== "final_result").length;
5025
+ const externalToolCallCount = allToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME).length;
4995
5026
  // Clamp the terminal calls' max_tokens so prompt + output stays inside
4996
5027
  // the model window: pre-4.5 Claude models 400 on input + max_tokens >
4997
5028
  // window, which would defeat the very synthesis these calls exist for
4998
5029
  // on context-capped turns. Only bites when the prompt is near the
4999
5030
  // window (min() is a no-op on ordinary step-cap turns).
5000
- const terminalMaxTokens = Math.max(1024, Math.min(requestParams.max_tokens, getContextWindowSize("vertex", modelName) -
5031
+ const terminalMaxTokens = Math.max(FINALIZATION_MIN_TOKENS, Math.min(generateMaxTokens, getContextWindowSize("vertex", modelName) -
5001
5032
  contextGuard.projectedNextPromptTokens -
5002
- 4_000));
5033
+ FINALIZATION_HEADROOM_TOKENS));
5003
5034
  if (wasAborted) {
5004
5035
  // Budget already blown — never issue another model call; prefer the
5005
5036
  // prose the model already produced (mirrors the Gemini abort path),
@@ -5042,20 +5073,21 @@ export class GoogleVertexProvider extends BaseProvider {
5042
5073
  stepNumber: maxSteps + 1,
5043
5074
  model: requestParams.model,
5044
5075
  maxTokens: terminalMaxTokens,
5045
- temperature: requestParams.temperature,
5046
- topP: requestParams.top_p,
5076
+ temperature: generateSampling.temperature,
5077
+ topP: generateSampling.topP,
5047
5078
  system: cachedFinal.system,
5048
5079
  messages: cachedFinal.messages,
5049
5080
  }, () => withTimeout(client.messages.create({
5050
5081
  ...requestParams,
5051
- max_tokens: terminalMaxTokens,
5052
- // Resized, not inherited: terminalMaxTokens can sit below the
5053
- // budget requestParams' thinking was sized for.
5054
- thinking: this.buildClaudeThinkingParam(options, terminalMaxTokens, forceFinalResult),
5082
+ // Resized, not inherited: terminalMaxTokens can sit below the budget
5083
+ // requestParams' thinking was sized for, and the sampling the first
5084
+ // request left out while thinking was on returns when thinking no
5085
+ // longer fits at this size.
5086
+ ...this.buildClaudeFinalizationParams(options, terminalMaxTokens, forceFinalResult, generateSampling),
5055
5087
  ...(forceFinalResult && {
5056
5088
  tool_choice: {
5057
5089
  type: "tool",
5058
- name: "final_result",
5090
+ name: FINAL_RESULT_TOOL_NAME,
5059
5091
  },
5060
5092
  }),
5061
5093
  ...(cachedFinal.system !== undefined && {
@@ -5073,7 +5105,8 @@ export class GoogleVertexProvider extends BaseProvider {
5073
5105
  totalCacheCreationTokens +=
5074
5106
  response.usage?.cache_creation_input_tokens || 0;
5075
5107
  lastStopReason = response.stop_reason;
5076
- const forcedFinalResult = response.content.find((block) => block.type === "tool_use" && block.name === "final_result");
5108
+ const forcedFinalResult = response.content.find((block) => block.type === "tool_use" &&
5109
+ block.name === FINAL_RESULT_TOOL_NAME);
5077
5110
  if (forcedFinalResult) {
5078
5111
  structuredOutput = forcedFinalResult.input;
5079
5112
  finalText = JSON.stringify(structuredOutput);
@@ -5162,13 +5195,17 @@ export class GoogleVertexProvider extends BaseProvider {
5162
5195
  stepNumber: maxSteps + 1,
5163
5196
  model: requestParams.model,
5164
5197
  maxTokens: terminalMaxTokens,
5165
- temperature: requestParams.temperature,
5166
- topP: requestParams.top_p,
5198
+ temperature: generateSampling.temperature,
5199
+ topP: generateSampling.topP,
5167
5200
  system: cachedBackstop.system,
5168
5201
  messages: cachedBackstop.messages,
5169
5202
  }, () => withTimeout(client.messages.create({
5170
5203
  ...requestParams,
5171
- max_tokens: terminalMaxTokens,
5204
+ ...toWireParams("anthropic", {
5205
+ maxTokens: terminalMaxTokens,
5206
+ temperature: generateSampling.temperature,
5207
+ topP: generateSampling.topP,
5208
+ }, { thinkingOn: backstopThinking?.type === "enabled" }),
5172
5209
  // Assigned outright, never a conditional spread: spreading
5173
5210
  // requestParams above may already carry a `thinking` sized
5174
5211
  // for the original max_tokens, and only adding a key when
@@ -5266,8 +5303,8 @@ export class GoogleVertexProvider extends BaseProvider {
5266
5303
  args: call.args,
5267
5304
  }))
5268
5305
  : allToolCalls;
5269
- const externalToolCalls = engineToolCalls.filter((tc) => tc.toolName !== "final_result");
5270
- const externalToolExecutions = toolExecutions.filter((te) => te.name !== "final_result");
5306
+ const externalToolCalls = engineToolCalls.filter((tc) => tc.toolName !== FINAL_RESULT_TOOL_NAME);
5307
+ const externalToolExecutions = toolExecutions.filter((te) => te.name !== FINAL_RESULT_TOOL_NAME);
5271
5308
  // Absolute backstop — no code path may surface empty content on a turn
5272
5309
  // that ran tools (the consumer-facing "empty response" incident shape).
5273
5310
  // Cause-aware: an aborted/timed-out turn gets the honest exit message,
@@ -5289,7 +5326,8 @@ export class GoogleVertexProvider extends BaseProvider {
5289
5326
  // "tool-calls" (aligned with the Gemini paths, so consumers detect
5290
5327
  // capped turns uniformly); everything else — including a successful
5291
5328
  // forced finalization or backstop synthesis — is a normal "stop".
5292
- const resolvedFinishReason = lastStopReason === "max_tokens"
5329
+ const resolvedFinishReason = translateFinishReason(ANTHROPIC_MESSAGES_FINISH, lastStopReason) ===
5330
+ "length"
5293
5331
  ? "length"
5294
5332
  : hitStepLimit && !synthesizedFinalAnswer
5295
5333
  ? "tool-calls"
@@ -6446,42 +6484,9 @@ export class GoogleVertexProvider extends BaseProvider {
6446
6484
  });
6447
6485
  }
6448
6486
  formatProviderError(error) {
6449
- const errorRecord = error;
6450
- const statusCode = typeof errorRecord?.status === "number"
6451
- ? errorRecord.status
6452
- : typeof errorRecord?.statusCode === "number"
6453
- ? errorRecord.statusCode
6454
- : undefined;
6455
- const rules = [
6456
- {
6457
- // Duck-typed on .name rather than `instanceof TimeoutError` —
6458
- // Vertex's own `withTimeout` (../../utils/async/index.js) throws a
6459
- // TimeoutError class distinct from the one classifyProviderError's
6460
- // built-in fast path checks (../../utils/timeout.js), so that fast
6461
- // path never fires for a real Vertex timeout. This rule preserves
6462
- // the pre-migration duck-typed match (both classes set
6463
- // `.name = "TimeoutError"`) and the original Vertex-specific
6464
- // message — see task-4-report.md for the full writeup.
6465
- match: (ctx) => ctx.errorName === "TimeoutError",
6466
- errorClass: NetworkError,
6467
- message: "Google Vertex AI request timed out. Consider increasing timeout or using a lighter model.",
6468
- },
6469
- {
6470
- match: (ctx) => /PERMISSION_DENIED|UNAUTHENTICATED|Invalid API key/i.test(ctx.message) ||
6471
- statusCode === 401 ||
6472
- statusCode === 403,
6473
- errorClass: AuthenticationError,
6474
- message: () => `Google Vertex AI Permission Denied. Your Google Cloud credentials don't have permission to access Vertex AI. ` +
6475
- `Required Steps: 1. Ensure your service account has Vertex AI User role ` +
6476
- `2. Check if Vertex AI API is enabled in your project ` +
6477
- `3. Verify your project ID is correct ` +
6478
- `4. Confirm your location/region has Vertex AI available`,
6479
- },
6480
- {
6481
- match: (ctx) => /NOT_FOUND|model not found|Model not found/i.test(ctx.message) ||
6482
- statusCode === 404,
6483
- errorClass: InvalidModelError,
6484
- message: () => {
6487
+ return classifyWithProviderRules(error, VERTEX_ERROR_RULES, this.providerName, this.modelName, {
6488
+ hooks: {
6489
+ "vertex.modelUnavailable": () => {
6485
6490
  const modelSuggestions = this.getModelSuggestions(this.modelName);
6486
6491
  return (`Model '${this.modelName}' is not available in region ${this.location}. ` +
6487
6492
  `Suggested alternatives: ${modelSuggestions}. ` +
@@ -6490,31 +6495,11 @@ export class GoogleVertexProvider extends BaseProvider {
6490
6495
  `3. Ensure your project has access to the model ` +
6491
6496
  `4. For Claude models, enable Anthropic integration in Google Cloud Console`);
6492
6497
  },
6493
- },
6494
- {
6495
- // Rate limit / quota / capacity errors. Anthropic-on-Vertex capacity
6496
- // exhaustion surfaces as overloaded_error (HTTP 529) — same
6497
- // operational meaning as a 429, so classify it here instead of the
6498
- // generic 5xx branch below.
6499
- match: (ctx) => /QUOTA_EXCEEDED|RATE_LIMIT_EXCEEDED|rate limit/i.test(ctx.message) ||
6500
- messageNamesStatus(ctx.message, 429) ||
6501
- statusCode === 429 ||
6502
- statusCode === 529 ||
6503
- /overloaded/i.test(ctx.message),
6504
- errorClass: RateLimitError,
6505
- message: (ctx) => {
6506
- // Surface retry guidance when the SDK error carries it.
6507
- // @google/genai ApiError nests RetryInfo inside the JSON error
6508
- // body's details array, so fall back to scraping retryDelay out
6509
- // of the raw message.
6498
+ "vertex.rateLimit": (ctx) => {
6499
+ const errorRecord = ctx.error;
6510
6500
  const retryDelay = typeof errorRecord?.retryDelay === "string"
6511
6501
  ? errorRecord.retryDelay
6512
6502
  : (/["']?retryDelay["']?\s*[:=]\s*["']?(\d+(?:\.\d+)?s)/.exec(ctx.message)?.[1] ?? undefined);
6513
- // Prefer the per-request context the native catches attach to the
6514
- // error (this.modelName can be stale when options.model overrides
6515
- // the instance default). Gemini models are force-routed to the
6516
- // "global" endpoint regardless of configured location — report
6517
- // the region the request actually hit.
6518
6503
  const requestModel = typeof errorRecord?.requestModel === "string"
6519
6504
  ? errorRecord.requestModel
6520
6505
  : this.modelName;
@@ -6532,34 +6517,7 @@ export class GoogleVertexProvider extends BaseProvider {
6532
6517
  `4. Request provisioned throughput for sustained load`);
6533
6518
  },
6534
6519
  },
6535
- {
6536
- match: (ctx) => /ECONNRESET|ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|connection/i.test(ctx.message),
6537
- errorClass: NetworkError,
6538
- message: (ctx) => `Connection error: ${ctx.message}`,
6539
- },
6540
- {
6541
- match: (ctx) => /server error|Internal Server Error|INTERNAL|UNAVAILABLE/i.test(ctx.message) ||
6542
- [500, 502, 503, 504].some((code) => messageNamesStatus(ctx.message, code)) ||
6543
- (statusCode !== undefined && statusCode >= 500 && statusCode < 600),
6544
- errorClass: ProviderError,
6545
- message: (ctx) => `Google Vertex AI server error: ${ctx.message}. Please try again later.`,
6546
- },
6547
- {
6548
- match: (ctx) => /INVALID_ARGUMENT/i.test(ctx.message),
6549
- errorClass: ProviderError,
6550
- message: (ctx) => `Google Vertex AI Invalid Request: ${ctx.message}. ` +
6551
- `Check: 1. Request parameters are within model limits ` +
6552
- `2. Input text is properly formatted ` +
6553
- `3. Temperature and other settings are valid ` +
6554
- `4. Model supports your request type`,
6555
- },
6556
- {
6557
- match: () => true,
6558
- errorClass: ProviderError,
6559
- message: (ctx) => `Google Vertex AI error: ${ctx.message}`,
6560
- },
6561
- ];
6562
- return classifyProviderError(error, rules, this.providerName, this.modelName);
6520
+ });
6563
6521
  }
6564
6522
  /**
6565
6523
  * Memory-safe cache management for model configurations