@juspay/neurolink 13.16.2 → 13.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -3
- package/dist/adapters/providerImageAdapter.js +29 -495
- package/dist/browser/neurolink.min.js +464 -470
- package/dist/constants/contextWindows.js +13 -328
- package/dist/constants/enums.d.ts +1 -0
- package/dist/constants/enums.js +2 -1
- package/dist/context/anthropicLoopGuard.d.ts +1 -1
- package/dist/context/anthropicLoopGuard.js +2 -1
- package/dist/core/constants.js +6 -53
- package/dist/core/geminiLoopAdapter.js +8 -6
- package/dist/core/modules/structuredOutputPolicy.d.ts +0 -21
- package/dist/core/modules/structuredOutputPolicy.js +4 -54
- package/dist/factories/providerDescriptors.js +3 -2
- package/dist/factories/providerRegistry.js +3 -2
- package/dist/models/manifests/anthropic.d.ts +1 -1
- package/dist/models/manifests/anthropic.js +1 -1
- package/dist/models/manifests/azure.js +9 -9
- package/dist/models/manifests/ollama.js +13 -0
- package/dist/models/manifests/openai.d.ts +1 -1
- package/dist/models/manifests/openai.js +1 -1
- package/dist/models/modelRegistry.js +17 -42
- package/dist/providers/amazonBedrock/client.js +9 -37
- package/dist/providers/amazonBedrock/loopAdapter.js +3 -11
- package/dist/providers/anthropic/client.js +42 -97
- package/dist/providers/anthropic/loopAdapter.js +24 -22
- package/dist/providers/anthropic/structuredOutput.d.ts +0 -2
- package/dist/providers/anthropic/structuredOutput.js +3 -5
- package/dist/providers/azureOpenai.js +4 -22
- package/dist/providers/catalog/loader.js +12 -25
- package/dist/providers/cohere.js +5 -30
- package/dist/providers/googleAiStudio/client.js +12 -61
- package/dist/providers/googleNativeGemini3/utils.js +43 -102
- package/dist/providers/googleVertex/client.js +123 -184
- package/dist/providers/litellm/client.js +10 -50
- package/dist/providers/llamaCpp.js +4 -15
- package/dist/providers/lmStudio.js +9 -14
- package/dist/providers/nvidiaNim/client.js +4 -62
- package/dist/providers/ollama/client.js +14 -54
- package/dist/providers/ollama/constants.d.ts +1 -3
- package/dist/providers/ollama/constants.js +2 -3
- package/dist/providers/openAI/client.js +5 -57
- package/dist/providers/openRouter/client.js +4 -65
- package/dist/providers/openaiChatCompletionsBase.js +34 -58
- package/dist/providers/openaiChatCompletionsClient.js +17 -57
- package/dist/providers/openaiCompatible/client.js +9 -36
- package/dist/providers/rules/README.md +100 -0
- package/dist/providers/rules/anthropic.json +104 -0
- package/dist/providers/rules/azure.json +13 -0
- package/dist/providers/rules/bedrock.json +48 -0
- package/dist/providers/rules/cohere.json +32 -0
- package/dist/providers/rules/credentials.json +34 -0
- package/dist/providers/rules/errorRules.d.ts +17 -0
- package/dist/providers/rules/errorRules.js +197 -0
- package/dist/providers/rules/errorSignals.d.ts +2 -0
- package/dist/providers/rules/errorSignals.js +28 -0
- package/dist/providers/rules/fallbackModel.d.ts +4 -0
- package/dist/providers/rules/fallbackModel.js +21 -0
- package/dist/providers/rules/finalResultTool.d.ts +11 -0
- package/dist/providers/rules/finalResultTool.js +17 -0
- package/dist/providers/rules/finishReasons.d.ts +10 -0
- package/dist/providers/rules/finishReasons.js +28 -0
- package/dist/providers/rules/gemini.json +92 -0
- package/dist/providers/rules/google-ai.json +55 -0
- package/dist/providers/rules/limits.json +338 -0
- package/dist/providers/rules/litellm.json +36 -0
- package/dist/providers/rules/llamacpp.json +23 -0
- package/dist/providers/rules/lm-studio.json +21 -0
- package/dist/providers/rules/model-families.json +109 -0
- package/dist/providers/rules/modelFamilies.d.ts +10 -0
- package/dist/providers/rules/modelFamilies.js +45 -0
- package/dist/providers/rules/nvidia-nim.json +43 -0
- package/dist/providers/rules/ollama.json +37 -0
- package/dist/providers/rules/openai-chat.json +66 -0
- package/dist/providers/rules/openai-compatible.json +31 -0
- package/dist/providers/rules/openai.json +38 -0
- package/dist/providers/rules/openrouter.json +57 -0
- package/dist/providers/rules/proxy.json +44 -0
- package/dist/providers/rules/registry.d.ts +7 -0
- package/dist/providers/rules/registry.js +76 -0
- package/dist/providers/rules/requestDefaults.d.ts +7 -0
- package/dist/providers/rules/requestDefaults.js +9 -0
- package/dist/providers/rules/requestFields.d.ts +18 -0
- package/dist/providers/rules/requestFields.js +38 -0
- package/dist/providers/rules/sagemaker.json +88 -0
- package/dist/providers/rules/schema.d.ts +234 -0
- package/dist/providers/rules/schema.js +352 -0
- package/dist/providers/rules/structured-output.json +36 -0
- package/dist/providers/rules/thinkingLimits.d.ts +7 -0
- package/dist/providers/rules/thinkingLimits.js +9 -0
- package/dist/providers/rules/toolRules.d.ts +16 -0
- package/dist/providers/rules/toolRules.js +95 -0
- package/dist/providers/rules/usage.json +51 -0
- package/dist/providers/rules/vertex.json +65 -0
- package/dist/providers/rules/vision.json +505 -0
- package/dist/providers/rules/wireUsage.d.ts +38 -0
- package/dist/providers/rules/wireUsage.js +82 -0
- package/dist/providers/sagemaker/language-model.js +6 -33
- package/dist/providers/sagemaker/parsers.js +13 -48
- package/dist/providers/sagemaker/streaming.js +9 -16
- package/dist/proxy/claudeFormat.js +3 -16
- package/dist/proxy/geminiFormat.js +3 -9
- package/dist/proxy/openaiFormat.js +3 -16
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +2 -0
- package/dist/types/providerRules.d.ts +407 -0
- package/dist/types/providerRules.js +10 -0
- package/dist/utils/errorClassifier.d.ts +2 -2
- package/dist/utils/errorClassifier.js +3 -2
- package/dist/utils/modelDetection.d.ts +1 -1
- package/dist/utils/modelDetection.js +30 -71
- package/dist/utils/providerConfig.d.ts +10 -9
- package/dist/utils/providerConfig.js +26 -25
- package/dist/utils/providerHealth.js +1 -0
- package/dist/utils/thinkingConfig.d.ts +1 -1
- package/dist/utils/thinkingConfig.js +8 -8
- package/dist/utils/tokenUtils.d.ts +12 -38
- package/dist/utils/tokenUtils.js +44 -127
- package/docs-site/static/search-index.json +5 -5
- package/package.json +2 -1
- package/dist/providers/localRuntimeOpenAICompat.d.ts +0 -16
- package/dist/providers/localRuntimeOpenAICompat.js +0 -26
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
48
|
-
|
|
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 (
|
|
57
|
-
return
|
|
44
|
+
if (!isValidModelName(modelName)) {
|
|
45
|
+
return budgets.default;
|
|
58
46
|
}
|
|
59
|
-
return
|
|
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
|
|
63
|
-
//
|
|
64
|
-
//
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
}
|
|
63
|
+
const ranges = GEMINI_REASONING?.budgetRanges;
|
|
64
|
+
if (!ranges) {
|
|
65
|
+
throw new Error("gemini.json has no reasoning.budgetRanges");
|
|
96
66
|
}
|
|
97
|
-
|
|
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 (!
|
|
101
|
-
|
|
71
|
+
if (!FAMILY_LABELS) {
|
|
72
|
+
throw new Error("model-families.json has no modelFamilyLabels");
|
|
102
73
|
}
|
|
103
|
-
if (
|
|
104
|
-
return
|
|
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
|
|
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
|
-
|
|
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
|
|
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:
|
|
24
|
-
readonly ANTHROPIC_MIN:
|
|
25
|
-
readonly HUGGINGFACE_EXACT:
|
|
26
|
-
readonly AZURE_MIN:
|
|
27
|
-
readonly MISTRAL_EXACT:
|
|
28
|
-
readonly AWS_ACCESS_KEY:
|
|
29
|
-
readonly GOOGLE_AI_EXACT:
|
|
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
|
50
|
+
* API key lengths quoted in configuration hints (credentials.json
|
|
51
|
+
* `apiKeyLengths`).
|
|
51
52
|
*/
|
|
52
53
|
export const API_KEY_LENGTHS = {
|
|
53
|
-
OPENAI_MIN:
|
|
54
|
-
ANTHROPIC_MIN:
|
|
55
|
-
HUGGINGFACE_EXACT:
|
|
56
|
-
AZURE_MIN:
|
|
57
|
-
MISTRAL_EXACT:
|
|
58
|
-
AWS_ACCESS_KEY:
|
|
59
|
-
GOOGLE_AI_EXACT:
|
|
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)
|
|
@@ -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
|
|
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 =
|
|
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 =
|
|
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
|
-
*
|
|
6
|
-
*
|
|
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
|
-
*
|
|
22
|
-
*
|
|
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
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* `
|
|
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
|
/**
|
package/dist/utils/tokenUtils.js
CHANGED
|
@@ -2,140 +2,63 @@
|
|
|
2
2
|
* Centralized token usage extraction utilities
|
|
3
3
|
* Handles multiple provider formats and optional fields
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
8
|
+
import { getProviderRules } from "../providers/rules/registry.js";
|
|
9
|
+
import { valueAtPath } from "../providers/rules/wireUsage.js";
|
|
10
|
+
function loadUsageRules() {
|
|
11
|
+
const { usageFields, usageRebase } = getProviderRules("usage");
|
|
12
|
+
if (!usageFields || !usageRebase) {
|
|
13
|
+
throw new Error('usage.json needs "usageFields" and "usageRebase"');
|
|
14
|
+
}
|
|
15
|
+
return { fields: usageFields, rebase: usageRebase };
|
|
16
|
+
}
|
|
17
|
+
const { fields: FIELDS, rebase: REBASE } = loadUsageRules();
|
|
18
|
+
/** The first path in the field's list that holds a usable number. */
|
|
19
|
+
function readUsageField(usage, field) {
|
|
20
|
+
for (const path of field.paths) {
|
|
21
|
+
const value = valueAtPath(usage, path);
|
|
22
|
+
if (typeof value === "number" && (!field.positiveOnly || value > 0)) {
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
22
25
|
}
|
|
23
|
-
return
|
|
26
|
+
return undefined;
|
|
24
27
|
}
|
|
25
|
-
/**
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
/** Input token count (usage.json `usageFields.input`), or 0. */
|
|
29
|
+
export function extractInputTokens(usage) {
|
|
30
|
+
return readUsageField(usage, FIELDS.input) ?? 0;
|
|
31
|
+
}
|
|
32
|
+
/** Output token count (usage.json `usageFields.output`), or 0. */
|
|
29
33
|
export function extractOutputTokens(usage) {
|
|
30
|
-
|
|
31
|
-
return usage.output;
|
|
32
|
-
}
|
|
33
|
-
if (typeof usage.outputTokens === "number") {
|
|
34
|
-
return usage.outputTokens;
|
|
35
|
-
}
|
|
36
|
-
if (typeof usage.completionTokens === "number") {
|
|
37
|
-
return usage.completionTokens;
|
|
38
|
-
}
|
|
39
|
-
return 0;
|
|
34
|
+
return readUsageField(usage, FIELDS.output) ?? 0;
|
|
40
35
|
}
|
|
41
36
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
37
|
+
* Total token count. A literal 0 next to non-zero components means the
|
|
38
|
+
* provider omitted the figure, so only a positive total wins over the sum.
|
|
44
39
|
*/
|
|
45
40
|
export function extractTotalTokens(usage, input, output) {
|
|
46
|
-
|
|
47
|
-
// figure (several gateways/parsers emit total: 0) — fall through to the
|
|
48
|
-
// computed sum instead of letting the zero win.
|
|
49
|
-
if (typeof usage.total === "number" && usage.total > 0) {
|
|
50
|
-
return usage.total;
|
|
51
|
-
}
|
|
52
|
-
if (typeof usage.totalTokens === "number" && usage.totalTokens > 0) {
|
|
53
|
-
return usage.totalTokens;
|
|
54
|
-
}
|
|
55
|
-
return input + output;
|
|
41
|
+
return readUsageField(usage, FIELDS.total) ?? input + output;
|
|
56
42
|
}
|
|
57
|
-
/**
|
|
58
|
-
* Extract reasoning/thinking token count from various provider formats
|
|
59
|
-
* Supports: reasoningTokens, thinkingTokens, reasoning_tokens, reasoning
|
|
60
|
-
*/
|
|
43
|
+
/** Reasoning/thinking token count, or undefined when absent or zero. */
|
|
61
44
|
export function extractReasoningTokens(usage) {
|
|
62
|
-
|
|
63
|
-
return usage.reasoningTokens;
|
|
64
|
-
}
|
|
65
|
-
if (typeof usage.thinkingTokens === "number" && usage.thinkingTokens > 0) {
|
|
66
|
-
return usage.thinkingTokens;
|
|
67
|
-
}
|
|
68
|
-
if (typeof usage.reasoning_tokens === "number" &&
|
|
69
|
-
usage.reasoning_tokens > 0) {
|
|
70
|
-
return usage.reasoning_tokens;
|
|
71
|
-
}
|
|
72
|
-
if (typeof usage.reasoning === "number" && usage.reasoning > 0) {
|
|
73
|
-
return usage.reasoning;
|
|
74
|
-
}
|
|
75
|
-
return undefined;
|
|
45
|
+
return readUsageField(usage, FIELDS.reasoning);
|
|
76
46
|
}
|
|
77
|
-
/**
|
|
78
|
-
* Extract cache creation token count from various provider formats
|
|
79
|
-
* Supports: cacheCreationInputTokens, cacheCreationTokens, and the ai@6
|
|
80
|
-
* normalized `inputTokenDetails.cacheWriteTokens` (the only shape the native
|
|
81
|
-
* direct-Anthropic path reports through generateText).
|
|
82
|
-
*/
|
|
47
|
+
/** Cache-write token count (non-overlapping convention), or undefined. */
|
|
83
48
|
export function extractCacheCreationTokens(usage) {
|
|
84
|
-
|
|
85
|
-
usage.cacheCreationInputTokens > 0) {
|
|
86
|
-
return usage.cacheCreationInputTokens;
|
|
87
|
-
}
|
|
88
|
-
if (typeof usage.cacheCreationTokens === "number" &&
|
|
89
|
-
usage.cacheCreationTokens > 0) {
|
|
90
|
-
return usage.cacheCreationTokens;
|
|
91
|
-
}
|
|
92
|
-
if (typeof usage.inputTokenDetails?.cacheWriteTokens === "number" &&
|
|
93
|
-
usage.inputTokenDetails.cacheWriteTokens > 0) {
|
|
94
|
-
return usage.inputTokenDetails.cacheWriteTokens;
|
|
95
|
-
}
|
|
96
|
-
return undefined;
|
|
49
|
+
return readUsageField(usage, FIELDS.cacheCreation);
|
|
97
50
|
}
|
|
98
|
-
/**
|
|
99
|
-
* Extract cache read token count from various provider formats
|
|
100
|
-
* Supports: cacheReadInputTokens, cacheReadTokens, and the ai@6 normalized
|
|
101
|
-
* shapes — flat `cachedInputTokens` and nested
|
|
102
|
-
* `inputTokenDetails.cacheReadTokens` (the only shapes the native
|
|
103
|
-
* direct-Anthropic path reports through generateText).
|
|
104
|
-
*/
|
|
51
|
+
/** Cache-read token count (non-overlapping convention), or undefined. */
|
|
105
52
|
export function extractCacheReadTokens(usage) {
|
|
106
|
-
|
|
107
|
-
usage.cacheReadInputTokens > 0) {
|
|
108
|
-
return usage.cacheReadInputTokens;
|
|
109
|
-
}
|
|
110
|
-
if (typeof usage.cacheReadTokens === "number" && usage.cacheReadTokens > 0) {
|
|
111
|
-
return usage.cacheReadTokens;
|
|
112
|
-
}
|
|
113
|
-
if (typeof usage.cachedInputTokens === "number" &&
|
|
114
|
-
usage.cachedInputTokens > 0) {
|
|
115
|
-
return usage.cachedInputTokens;
|
|
116
|
-
}
|
|
117
|
-
if (typeof usage.inputTokenDetails?.cacheReadTokens === "number" &&
|
|
118
|
-
usage.inputTokenDetails.cacheReadTokens > 0) {
|
|
119
|
-
return usage.inputTokenDetails.cacheReadTokens;
|
|
120
|
-
}
|
|
121
|
-
return undefined;
|
|
53
|
+
return readUsageField(usage, FIELDS.cacheRead);
|
|
122
54
|
}
|
|
123
55
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
* `
|
|
127
|
-
*
|
|
128
|
-
* Unlike {@link extractCacheReadTokens} (non-overlapping Anthropic/Vertex
|
|
129
|
-
* convention where cache tokens are reported SEPARATELY from input), the value
|
|
130
|
-
* returned here is a SUBSET already included in `prompt_tokens`. Callers that
|
|
131
|
-
* use this value MUST subtract it from `input` to avoid double-counting.
|
|
56
|
+
* Cache-read count in the OVERLAPPING convention (OpenAI / DeepSeek / NIM /
|
|
57
|
+
* OpenAI-compatible): a SUBSET already included in the prompt count, so a
|
|
58
|
+
* caller MUST subtract it from `input` to avoid double-counting.
|
|
132
59
|
*/
|
|
133
60
|
export function extractCachedInputTokensOverlapping(usage) {
|
|
134
|
-
|
|
135
|
-
if (typeof cached === "number" && cached > 0) {
|
|
136
|
-
return cached;
|
|
137
|
-
}
|
|
138
|
-
return undefined;
|
|
61
|
+
return readUsageField(usage, FIELDS.cacheReadIncludedInInput);
|
|
139
62
|
}
|
|
140
63
|
/**
|
|
141
64
|
* Calculate cache savings percentage
|
|
@@ -217,21 +140,15 @@ export function extractTokenUsage(result, options = {}) {
|
|
|
217
140
|
// remainder, and the overlapping snake_case shape was already rebased
|
|
218
141
|
// above — neither must be rebased again.
|
|
219
142
|
if ((cacheReadTokens !== undefined || cacheCreationTokens !== undefined) &&
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
usage.cacheCreationTokens === undefined &&
|
|
224
|
-
usage.prompt_tokens_details?.cached_tokens === undefined &&
|
|
225
|
-
(usage.cachedInputTokens !== undefined ||
|
|
226
|
-
usage.inputTokenDetails !== undefined)) {
|
|
227
|
-
const noCacheTokens = usage.inputTokenDetails?.noCacheTokens;
|
|
143
|
+
REBASE.unlessAnyPresent.every((path) => valueAtPath(usage, path) === undefined) &&
|
|
144
|
+
REBASE.whenAnyPresent.some((path) => valueAtPath(usage, path) !== undefined)) {
|
|
145
|
+
const noCacheTokens = valueAtPath(usage, REBASE.uncachedInput);
|
|
228
146
|
if (typeof noCacheTokens === "number") {
|
|
229
147
|
input = noCacheTokens;
|
|
230
148
|
}
|
|
231
149
|
else {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
(usage.inputTokenDetails?.cacheWriteTokens ?? 0));
|
|
150
|
+
const cacheWrite = valueAtPath(usage, REBASE.cacheWrite);
|
|
151
|
+
input = Math.max(0, input - (cacheReadTokens ?? 0) - (cacheWrite ?? 0));
|
|
235
152
|
}
|
|
236
153
|
}
|
|
237
154
|
// Total: prefer the provider-reported figure; the fallback conserves every
|