@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
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The provider-rules JSON format: provider- and model-specific behaviour
3
+ * written as data in `src/lib/providers/rules/<id>.json`, read by the shared
4
+ * rule engines in `src/lib/providers/rules/`, instead of being hard-coded in
5
+ * each provider class.
6
+ *
7
+ * The error-rule shape is a superset of the catalog's `CatalogErrorRuleJson`,
8
+ * so catalog entries and rules files compile through the same engine.
9
+ */
10
+ export {};
@@ -13,14 +13,14 @@
13
13
  * every provider's returned error, migrated or not, so duplicating it here
14
14
  * would risk the two copies disagreeing.
15
15
  */
16
- import { type ProviderErrorRule } from "../types/index.js";
16
+ import { type ProviderErrorContext, type ProviderErrorRule } from "../types/index.js";
17
17
  /**
18
18
  * Classify a raw provider error into a NeuroLink `ProviderError` subclass.
19
19
  * `rules` are tried in order; the first match wins. `TimeoutError` is
20
20
  * always handled first, ahead of any rule table — every provider treated
21
21
  * it identically before this change, so it is not made overridable.
22
22
  */
23
- export declare function classifyProviderError(error: unknown, rules: ProviderErrorRule[], provider: string, modelName?: string): Error;
23
+ export declare function classifyProviderError(error: unknown, rules: ProviderErrorRule[], provider: string, modelName?: string, adjustContext?: (ctx: ProviderErrorContext) => ProviderErrorContext): Error;
24
24
  /**
25
25
  * True when `status` is written in `message` as an HTTP status, as opposed to
26
26
  * an unrelated number that happens to have the same digits ("max_tokens (429)
@@ -104,11 +104,12 @@ function buildErrorContext(error, provider, modelName) {
104
104
  * always handled first, ahead of any rule table — every provider treated
105
105
  * it identically before this change, so it is not made overridable.
106
106
  */
107
- export function classifyProviderError(error, rules, provider, modelName) {
107
+ export function classifyProviderError(error, rules, provider, modelName, adjustContext) {
108
108
  if (error instanceof TimeoutError) {
109
109
  return new NetworkError(`Request timed out: ${error.message}`, provider);
110
110
  }
111
- const ctx = buildErrorContext(error, provider, modelName);
111
+ const built = buildErrorContext(error, provider, modelName);
112
+ const ctx = adjustContext ? adjustContext(built) : built;
112
113
  const rule = rules.find((r) => r.match(ctx));
113
114
  if (!rule) {
114
115
  return new ProviderError(`${provider} error: ${ctx.message}`, provider);
@@ -27,7 +27,7 @@ export declare function hasRestrictedOutputLimit(modelName: string): boolean;
27
27
  /**
28
28
  * Get the max output tokens for a model (32768 for restricted models)
29
29
  */
30
- export declare const RESTRICTED_OUTPUT_TOKEN_LIMIT = 32768;
30
+ export declare const RESTRICTED_OUTPUT_TOKEN_LIMIT: number;
31
31
  /**
32
32
  * Normalize an Anthropic-API-style Claude model ID to the Vertex publisher
33
33
  * format.
@@ -2,6 +2,10 @@
2
2
  * Model detection utilities for capability checking
3
3
  */
4
4
  import { IMAGE_GENERATION_MODELS } from "../core/constants.js";
5
+ import { firstModelRule, inModelFamily, } from "../providers/rules/modelFamilies.js";
6
+ import { getProviderRules } from "../providers/rules/registry.js";
7
+ const GEMINI_REASONING = getProviderRules("gemini").reasoning;
8
+ const FAMILY_LABELS = getProviderRules("model-families").modelFamilyLabels;
5
9
  /**
6
10
  * Check if model name is valid for detection functions
7
11
  */
@@ -12,73 +16,40 @@ export function isGemini3Model(modelName) {
12
16
  if (!isValidModelName(modelName)) {
13
17
  return false;
14
18
  }
15
- return /^gemini-3(\.\d+)?(-.*)?$/i.test(modelName);
19
+ return inModelFamily("gemini3", modelName);
16
20
  }
17
21
  export function isGemini25Model(modelName) {
18
22
  if (!isValidModelName(modelName)) {
19
23
  return false;
20
24
  }
21
- return /^gemini-2\.5(-.*)?$/i.test(modelName);
25
+ return inModelFamily("gemini25", modelName);
22
26
  }
23
27
  export function supportsThinkingConfig(modelName) {
24
28
  if (!isValidModelName(modelName)) {
25
29
  return false;
26
30
  }
27
- const thinkingModels = [
28
- /^gemini-3/i,
29
- /^gemini-2\.5-pro/i,
30
- /^gemini-2\.5-flash/i,
31
- ];
32
- return thinkingModels.some((pattern) => pattern.test(modelName));
31
+ return inModelFamily("thinkingConfig", modelName);
33
32
  }
34
33
  export function supportsPromptCaching(modelName) {
35
34
  if (!isValidModelName(modelName)) {
36
35
  return false;
37
36
  }
38
- const cachingModels = [
39
- /^gemini-3/i,
40
- /^gemini-2\.5/i,
41
- /^gpt-4/i,
42
- /^claude-3/i,
43
- ];
44
- return cachingModels.some((pattern) => pattern.test(modelName));
37
+ return inModelFamily("promptCaching", modelName);
45
38
  }
46
39
  export function getMaxThinkingBudgetTokens(modelName) {
47
- if (!isValidModelName(modelName)) {
48
- return 10000;
49
- }
50
- if (/^gemini-3(\.\d+)?-pro/i.test(modelName)) {
51
- return 100000;
52
- }
53
- if (/^gemini-3(\.\d+)?-flash/i.test(modelName)) {
54
- return 50000;
40
+ const budgets = GEMINI_REASONING?.maxBudgetTokens;
41
+ if (!budgets) {
42
+ throw new Error("gemini.json has no reasoning.maxBudgetTokens");
55
43
  }
56
- if (/^gemini-2\.5/i.test(modelName)) {
57
- return 32000;
44
+ if (!isValidModelName(modelName)) {
45
+ return budgets.default;
58
46
  }
59
- return 10000;
47
+ return firstModelRule(budgets.rules, modelName)?.value ?? budgets.default;
60
48
  }
61
49
  // Per-model `thinkingBudget` bounds for the Gemini 2.5 family, confirmed
62
- // against live Vertex generateContent responses (not just vendor docs, which
63
- // have been observed to drift from runtime behavior — see the "known gotcha"
64
- // on Gemini 2.5 Pro's range in public bug reports). Vertex rejects a budget
65
- // outside these bounds with INVALID_ARGUMENT "thinking_budget is out of
66
- // range; supported values are integers from <min> to <max>".
67
- //
68
- // Flash's true floor is 1, but budget:1 measured 0 thoughtsTokenCount — i.e.
69
- // technically accepted but indistinguishable from thinking being off. The
70
- // floor is bumped to 128 (Pro's real floor) here so a "minimal" mapping
71
- // still produces observable thinking. Must precede the plain "flash" pattern
72
- // below — "gemini-2.5-flash-lite" also matches a bare `/^gemini-2\.5-flash/`.
73
- const GEMINI_25_THINKING_BUDGET_RANGES = [
74
- { pattern: /^gemini-2\.5-flash-lite/i, min: 512, max: 24576 },
75
- { pattern: /^gemini-2\.5-flash/i, min: 128, max: 24576 },
76
- { pattern: /^gemini-2\.5-pro/i, min: 128, max: 32768 },
77
- ];
78
- // Bounds safe for any Gemini 2.5 variant not explicitly listed above — the
79
- // intersection of all three known models' verified ranges, so a model we
80
- // haven't named still gets a budget every family member accepts.
81
- const GEMINI_25_FALLBACK_BUDGET_RANGE = { min: 512, max: 24576 };
50
+ // against live Vertex responses (gemini.json `reasoning.budgetRanges`; the
51
+ // reasons are in `reasoningNotes`). Vertex rejects a budget outside them with
52
+ // INVALID_ARGUMENT "thinking_budget is out of range".
82
53
  /**
83
54
  * Resolves the Vertex-accepted `thinkingBudget` bounds for a Gemini 2.5
84
55
  * model. Returns undefined for anything that isn't a Gemini 2.5 model —
@@ -89,33 +60,22 @@ export function getGemini25ThinkingBudgetRange(modelName) {
89
60
  if (!isValidModelName(modelName) || !isGemini25Model(modelName)) {
90
61
  return undefined;
91
62
  }
92
- for (const { pattern, min, max } of GEMINI_25_THINKING_BUDGET_RANGES) {
93
- if (pattern.test(modelName)) {
94
- return { min, max };
95
- }
63
+ const ranges = GEMINI_REASONING?.budgetRanges;
64
+ if (!ranges) {
65
+ throw new Error("gemini.json has no reasoning.budgetRanges");
96
66
  }
97
- return GEMINI_25_FALLBACK_BUDGET_RANGE;
67
+ const rule = firstModelRule(ranges.rules, modelName);
68
+ return rule ? { min: rule.min, max: rule.max } : ranges.fallback;
98
69
  }
99
70
  export function getModelFamily(modelName) {
100
- if (!isValidModelName(modelName)) {
101
- return "unknown";
71
+ if (!FAMILY_LABELS) {
72
+ throw new Error("model-families.json has no modelFamilyLabels");
102
73
  }
103
- if (/^gemini-3/i.test(modelName)) {
104
- return "gemini-3";
105
- }
106
- if (/^gemini-2\.5/i.test(modelName)) {
107
- return "gemini-2.5";
108
- }
109
- if (/^gemini-2/i.test(modelName)) {
110
- return "gemini-2";
111
- }
112
- if (/^gpt-4/i.test(modelName)) {
113
- return "gpt-4";
114
- }
115
- if (/^claude-3/i.test(modelName)) {
116
- return "claude-3";
74
+ if (!isValidModelName(modelName)) {
75
+ return FAMILY_LABELS.default;
117
76
  }
118
- return "unknown";
77
+ return (firstModelRule(FAMILY_LABELS.rules, modelName)?.label ??
78
+ FAMILY_LABELS.default);
119
79
  }
120
80
  // Compiled once at module load — hasRestrictedOutputLimit() is called per
121
81
  // request and previously rebuilt this array on every call.
@@ -130,8 +90,7 @@ export function hasRestrictedOutputLimit(modelName) {
130
90
  if (!isValidModelName(modelName)) {
131
91
  return false;
132
92
  }
133
- // Check for Gemini 3 models (anchored regex for consistency)
134
- if (/^gemini-3/i.test(modelName)) {
93
+ if (inModelFamily("restrictedOutput", modelName)) {
135
94
  return true;
136
95
  }
137
96
  if (IMAGE_MODEL_PATTERNS.some((pattern) => pattern.test(modelName))) {
@@ -142,7 +101,7 @@ export function hasRestrictedOutputLimit(modelName) {
142
101
  /**
143
102
  * Get the max output tokens for a model (32768 for restricted models)
144
103
  */
145
- export const RESTRICTED_OUTPUT_TOKEN_LIMIT = 32768;
104
+ export const RESTRICTED_OUTPUT_TOKEN_LIMIT = GEMINI_REASONING?.restrictedOutputTokenLimit ?? 32768;
146
105
  /**
147
106
  * Normalize an Anthropic-API-style Claude model ID to the Vertex publisher
148
107
  * format.
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import type { APIValidationResult, ProviderConfigOptions, AnthropicAuthMethod, ClaudeSubscriptionTier, AnthropicAuthConfig, AnthropicAuthConfigResult, OpenAICompatConfigInput, OpenAICompatCredentials } from "../types/index.js";
9
9
  /**
10
- * API key format validation patterns (extracted from advanced validation system)
10
+ * API key format validation patterns (credentials.json) (extracted from advanced validation system)
11
11
  * Exported for use across the codebase to replace scattered regex patterns
12
12
  */
13
13
  export declare const API_KEY_FORMATS: Record<string, RegExp>;
@@ -17,16 +17,17 @@ export declare const API_KEY_FORMATS: Record<string, RegExp>;
17
17
  */
18
18
  export declare const OAUTH_TOKEN_FORMATS: Record<string, RegExp>;
19
19
  /**
20
- * API key length constants to replace scattered magic numbers
20
+ * API key lengths quoted in configuration hints (credentials.json
21
+ * `apiKeyLengths`).
21
22
  */
22
23
  export declare const API_KEY_LENGTHS: {
23
- readonly OPENAI_MIN: 48;
24
- readonly ANTHROPIC_MIN: 95;
25
- readonly HUGGINGFACE_EXACT: 37;
26
- readonly AZURE_MIN: 32;
27
- readonly MISTRAL_EXACT: 32;
28
- readonly AWS_ACCESS_KEY: 20;
29
- readonly GOOGLE_AI_EXACT: 39;
24
+ readonly OPENAI_MIN: number;
25
+ readonly ANTHROPIC_MIN: number;
26
+ readonly HUGGINGFACE_EXACT: number;
27
+ readonly AZURE_MIN: number;
28
+ readonly MISTRAL_EXACT: number;
29
+ readonly AWS_ACCESS_KEY: number;
30
+ readonly GOOGLE_AI_EXACT: number;
30
31
  };
31
32
  /**
32
33
  * Project ID format validation (for Google Cloud)
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { logger } from "./logger.js";
9
9
  import { getCatalogJsonEntries, buildCatalogConfigOptions, } from "../providers/catalog/loader.js";
10
+ import { getProviderRules } from "../providers/rules/registry.js";
10
11
  // Re-export subscription types for convenience
11
12
  /**
12
13
  * Looks up a JSON catalog entry by id and derives its ProviderConfigOptions.
@@ -21,42 +22,42 @@ function catalogConfigOptions(id) {
21
22
  }
22
23
  return buildCatalogConfigOptions(entry);
23
24
  }
25
+ const CREDENTIAL_RULES = getProviderRules("credentials");
26
+ function compileFormats(sources) {
27
+ return Object.fromEntries(Object.entries(sources ?? {}).map(([key, source]) => [
28
+ key,
29
+ new RegExp(source),
30
+ ]));
31
+ }
24
32
  /**
25
- * API key format validation patterns (extracted from advanced validation system)
33
+ * API key format validation patterns (credentials.json) (extracted from advanced validation system)
26
34
  * Exported for use across the codebase to replace scattered regex patterns
27
35
  */
28
- export const API_KEY_FORMATS = {
29
- openai: /^sk-[A-Za-z0-9]{48,}$/,
30
- anthropic: /^sk-ant-[A-Za-z0-9\-_]{95,}$/,
31
- "google-ai": /^AIza[A-Za-z0-9\-_]{35}$/,
32
- huggingface: /^hf_[A-Za-z0-9]{37}$/,
33
- mistral: /^[A-Za-z0-9]{32}$/,
34
- azure: /^[A-Za-z0-9]{32}$/,
35
- aws: /^[A-Z0-9]{20}$/, // Access Key ID format
36
- bedrock: /^[A-Z0-9]{20}$/, // AWS access key ID: 20 uppercase alphanumerics
37
- };
36
+ export const API_KEY_FORMATS = compileFormats(CREDENTIAL_RULES.apiKeyFormats);
38
37
  /**
39
38
  * OAuth token format validation patterns
40
39
  * These patterns are more flexible as OAuth tokens can vary by provider
41
40
  */
42
- export const OAUTH_TOKEN_FORMATS = {
43
- // OAuth access tokens are typically JWT or opaque tokens
44
- // Claude OAuth access tokens: Bearer tokens with typical JWT structure or opaque format
45
- "anthropic-access": /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$|^[A-Za-z0-9\-_]{32,}$/,
46
- // Refresh tokens are typically longer opaque strings
47
- "anthropic-refresh": /^[A-Za-z0-9\-_]{32,}$/,
41
+ export const OAUTH_TOKEN_FORMATS = compileFormats(CREDENTIAL_RULES.oauthTokenFormats);
42
+ const keyLength = (name) => {
43
+ const length = CREDENTIAL_RULES.apiKeyLengths?.[name];
44
+ if (length === undefined) {
45
+ throw new Error(`credentials.json has no apiKeyLengths.${name}`);
46
+ }
47
+ return length;
48
48
  };
49
49
  /**
50
- * API key length constants to replace scattered magic numbers
50
+ * API key lengths quoted in configuration hints (credentials.json
51
+ * `apiKeyLengths`).
51
52
  */
52
53
  export const API_KEY_LENGTHS = {
53
- OPENAI_MIN: 48, // OpenAI API keys minimum length
54
- ANTHROPIC_MIN: 95, // Anthropic API keys minimum length
55
- HUGGINGFACE_EXACT: 37, // HuggingFace tokens exact length
56
- AZURE_MIN: 32, // Azure OpenAI API keys minimum length
57
- MISTRAL_EXACT: 32, // Mistral API keys exact length
58
- AWS_ACCESS_KEY: 20, // AWS access key ID exact length
59
- GOOGLE_AI_EXACT: 39, // Google AI Studio keys exact length (with AIza prefix)
54
+ OPENAI_MIN: keyLength("OPENAI_MIN"),
55
+ ANTHROPIC_MIN: keyLength("ANTHROPIC_MIN"),
56
+ HUGGINGFACE_EXACT: keyLength("HUGGINGFACE_EXACT"),
57
+ AZURE_MIN: keyLength("AZURE_MIN"),
58
+ MISTRAL_EXACT: keyLength("MISTRAL_EXACT"),
59
+ AWS_ACCESS_KEY: keyLength("AWS_ACCESS_KEY"),
60
+ GOOGLE_AI_EXACT: keyLength("GOOGLE_AI_EXACT"),
60
61
  };
61
62
  /**
62
63
  * Project ID format validation (for Google Cloud)
@@ -1157,6 +1157,7 @@ export class ProviderHealthChecker {
1157
1157
  case AIProviderName.OLLAMA: {
1158
1158
  const envModel = process.env.OLLAMA_MODEL;
1159
1159
  const defaults = [
1160
+ "gemma4:e2b",
1160
1161
  "llama3.2:latest",
1161
1162
  "llama3.1:latest",
1162
1163
  "mistral:latest",
@@ -8,7 +8,7 @@ import type { ThinkingLevel, ThinkingConfig, CreateThinkingConfigOptions, Native
8
8
  /**
9
9
  * Default token budget for thinking operations
10
10
  */
11
- export declare const DEFAULT_THINKING_BUDGET_TOKENS = 10000;
11
+ export declare const DEFAULT_THINKING_BUDGET_TOKENS: number;
12
12
  /**
13
13
  * Default thinking level for Gemini 3 models
14
14
  */
@@ -6,14 +6,19 @@
6
6
  */
7
7
  import { getGemini25ThinkingBudgetRange, isGemini3Model, } from "./modelDetection.js";
8
8
  import { logger } from "./logger.js";
9
+ import { getProviderRules } from "../providers/rules/registry.js";
10
+ const GEMINI_REASONING = getProviderRules("gemini").reasoning;
11
+ if (!GEMINI_REASONING) {
12
+ throw new Error("gemini.json has no reasoning block");
13
+ }
9
14
  /**
10
15
  * Default token budget for thinking operations
11
16
  */
12
- export const DEFAULT_THINKING_BUDGET_TOKENS = 10000;
17
+ export const DEFAULT_THINKING_BUDGET_TOKENS = GEMINI_REASONING.defaultBudgetTokens;
13
18
  /**
14
19
  * Default thinking level for Gemini 3 models
15
20
  */
16
- export const DEFAULT_THINKING_LEVEL = "high";
21
+ export const DEFAULT_THINKING_LEVEL = GEMINI_REASONING.defaultLevel;
17
22
  /**
18
23
  * Creates a thinkingConfig object from CLI-style options.
19
24
  *
@@ -74,12 +79,7 @@ export function createThinkingConfigFromRecord(options) {
74
79
  // Gemini 2.5 — only a numeric budget), not a vendor-specified mapping:
75
80
  // "minimal"/"high" pin the floor/ceiling of the model's own verified range,
76
81
  // "low"/"medium" split the middle so all four levels stay distinguishable.
77
- const THINKING_LEVEL_FRACTIONS = {
78
- minimal: 0,
79
- low: 0.25,
80
- medium: 0.55,
81
- high: 1,
82
- };
82
+ const THINKING_LEVEL_FRACTIONS = GEMINI_REASONING.levelFractions;
83
83
  /**
84
84
  * Maps a qualitative ThinkingLevel onto a numeric thinkingBudget within a
85
85
  * model's verified [min, max] range (see `getGemini25ThinkingBudgetRange`).
@@ -2,55 +2,29 @@
2
2
  * Centralized token usage extraction utilities
3
3
  * Handles multiple provider formats and optional fields
4
4
  *
5
- * Consolidates token extraction logic from:
6
- * - analytics.ts
7
- * - streamAnalytics.ts
5
+ * Which field holds which count, in priority order, is data:
6
+ * `usageFields` and `usageRebase` in src/lib/providers/rules/usage.json.
8
7
  */
9
8
  import type { TokenUsage, RawUsageObject, TokenExtractionOptions } from "../types/index.js";
10
- /**
11
- * Extract input token count from various provider formats
12
- * Priority: input > inputTokens > promptTokens
13
- */
9
+ /** Input token count (usage.json `usageFields.input`), or 0. */
14
10
  export declare function extractInputTokens(usage: RawUsageObject): number;
15
- /**
16
- * Extract output token count from various provider formats
17
- * Priority: output > outputTokens > completionTokens
18
- */
11
+ /** Output token count (usage.json `usageFields.output`), or 0. */
19
12
  export declare function extractOutputTokens(usage: RawUsageObject): number;
20
13
  /**
21
- * Extract total token count from various provider formats
22
- * Falls back to input + output if total is not provided
14
+ * Total token count. A literal 0 next to non-zero components means the
15
+ * provider omitted the figure, so only a positive total wins over the sum.
23
16
  */
24
17
  export declare function extractTotalTokens(usage: RawUsageObject, input: number, output: number): number;
25
- /**
26
- * Extract reasoning/thinking token count from various provider formats
27
- * Supports: reasoningTokens, thinkingTokens, reasoning_tokens, reasoning
28
- */
18
+ /** Reasoning/thinking token count, or undefined when absent or zero. */
29
19
  export declare function extractReasoningTokens(usage: RawUsageObject): number | undefined;
30
- /**
31
- * Extract cache creation token count from various provider formats
32
- * Supports: cacheCreationInputTokens, cacheCreationTokens, and the ai@6
33
- * normalized `inputTokenDetails.cacheWriteTokens` (the only shape the native
34
- * direct-Anthropic path reports through generateText).
35
- */
20
+ /** Cache-write token count (non-overlapping convention), or undefined. */
36
21
  export declare function extractCacheCreationTokens(usage: RawUsageObject): number | undefined;
37
- /**
38
- * Extract cache read token count from various provider formats
39
- * Supports: cacheReadInputTokens, cacheReadTokens, and the ai@6 normalized
40
- * shapes — flat `cachedInputTokens` and nested
41
- * `inputTokenDetails.cacheReadTokens` (the only shapes the native
42
- * direct-Anthropic path reports through generateText).
43
- */
22
+ /** Cache-read token count (non-overlapping convention), or undefined. */
44
23
  export declare function extractCacheReadTokens(usage: RawUsageObject): number | undefined;
45
24
  /**
46
- * Extract cache read token count from the OVERLAPPING-convention nested path
47
- * used by OpenAI / DeepSeek / NIM / OpenAI-compatible providers:
48
- * `usage.prompt_tokens_details.cached_tokens`.
49
- *
50
- * Unlike {@link extractCacheReadTokens} (non-overlapping Anthropic/Vertex
51
- * convention where cache tokens are reported SEPARATELY from input), the value
52
- * returned here is a SUBSET already included in `prompt_tokens`. Callers that
53
- * use this value MUST subtract it from `input` to avoid double-counting.
25
+ * Cache-read count in the OVERLAPPING convention (OpenAI / DeepSeek / NIM /
26
+ * OpenAI-compatible): a SUBSET already included in the prompt count, so a
27
+ * caller MUST subtract it from `input` to avoid double-counting.
54
28
  */
55
29
  export declare function extractCachedInputTokensOverlapping(usage: RawUsageObject): number | undefined;
56
30
  /**