@juspay/yama 1.1.1 → 1.3.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.
@@ -23,6 +23,10 @@ export declare class ConfigManager {
23
23
  * Load configuration from a specific file
24
24
  */
25
25
  private loadConfigFile;
26
+ /**
27
+ * Apply provider-aware token limits using shared utility
28
+ */
29
+ private applyProviderTokenLimits;
26
30
  /**
27
31
  * Apply environment variable overrides
28
32
  */
@@ -8,6 +8,7 @@ import yaml from "yaml";
8
8
  import { homedir } from "os";
9
9
  import { ConfigurationError } from "../types/index.js";
10
10
  import { logger } from "./Logger.js";
11
+ import { validateProviderTokenLimit } from "./ProviderLimits.js";
11
12
  export class ConfigManager {
12
13
  config = null;
13
14
  configPaths = [];
@@ -24,7 +25,7 @@ export class ConfigManager {
24
25
  timeout: "10m",
25
26
  retryAttempts: 3,
26
27
  temperature: 0.3,
27
- maxTokens: 1000000,
28
+ maxTokens: 65000,
28
29
  },
29
30
  git: {
30
31
  platform: "bitbucket",
@@ -143,6 +144,11 @@ export class ConfigManager {
143
144
  exportFormat: "json",
144
145
  interval: "5m",
145
146
  },
147
+ memoryBank: {
148
+ enabled: true,
149
+ path: "memory-bank",
150
+ fallbackPaths: ["docs/memory-bank", ".memory-bank"],
151
+ },
146
152
  };
147
153
  constructor() {
148
154
  this.setupConfigPaths();
@@ -205,6 +211,8 @@ export class ConfigManager {
205
211
  }
206
212
  // Override with environment variables
207
213
  config = this.applyEnvironmentOverrides(config);
214
+ // Apply provider-aware token limits
215
+ config = this.applyProviderTokenLimits(config);
208
216
  // Validate configuration
209
217
  this.validateConfig(config);
210
218
  this.config = config;
@@ -232,6 +240,18 @@ export class ConfigManager {
232
240
  throw new ConfigurationError(`Failed to parse config file ${filePath}: ${error.message}`);
233
241
  }
234
242
  }
243
+ /**
244
+ * Apply provider-aware token limits using shared utility
245
+ */
246
+ applyProviderTokenLimits(config) {
247
+ const provider = config.providers.ai.provider || 'auto';
248
+ const configuredTokens = config.providers.ai.maxTokens;
249
+ // Use the shared utility to validate and adjust token limits
250
+ const validatedTokens = validateProviderTokenLimit(provider, configuredTokens, false // Use standard limits for configuration
251
+ );
252
+ config.providers.ai.maxTokens = validatedTokens;
253
+ return config;
254
+ }
235
255
  /**
236
256
  * Apply environment variable overrides
237
257
  */
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Memory Bank Manager - Handles configurable memory bank operations
3
+ * Provides abstraction for memory bank file access with fallback support
4
+ */
5
+ import { MemoryBankConfig, PRIdentifier } from "../types/index.js";
6
+ import { BitbucketProvider } from "../core/providers/BitbucketProvider.js";
7
+ export interface MemoryBankFile {
8
+ name: string;
9
+ content: string;
10
+ path: string;
11
+ }
12
+ export interface MemoryBankResult {
13
+ files: MemoryBankFile[];
14
+ resolvedPath: string;
15
+ filesProcessed: number;
16
+ fallbackUsed: boolean;
17
+ }
18
+ export declare class MemoryBankManager {
19
+ private config;
20
+ private bitbucketProvider;
21
+ constructor(config: MemoryBankConfig, bitbucketProvider: BitbucketProvider);
22
+ /**
23
+ * Get memory bank files from the configured path with fallback support
24
+ */
25
+ getMemoryBankFiles(identifier: PRIdentifier, forceRefresh?: boolean): Promise<MemoryBankResult>;
26
+ /**
27
+ * Try to get files from a specific path
28
+ */
29
+ private tryGetFilesFromPath;
30
+ /**
31
+ * Get the effective memory bank path (resolved after fallback logic)
32
+ */
33
+ getEffectiveMemoryBankPath(identifier: PRIdentifier): Promise<string | null>;
34
+ /**
35
+ * Check if memory bank exists at any configured path
36
+ */
37
+ hasMemoryBank(identifier: PRIdentifier): Promise<boolean>;
38
+ /**
39
+ * Get memory bank configuration
40
+ */
41
+ getConfig(): MemoryBankConfig;
42
+ /**
43
+ * Update memory bank configuration
44
+ */
45
+ updateConfig(newConfig: Partial<MemoryBankConfig>): void;
46
+ /**
47
+ * Validates that a path is safe for use as a relative path
48
+ * Protects against path traversal attacks including encoded variants
49
+ */
50
+ private static isSafeRelativePath;
51
+ /**
52
+ * Validate memory bank configuration
53
+ */
54
+ private validateConfig;
55
+ /**
56
+ * Clear memory bank cache for a specific repository
57
+ */
58
+ clearCache(identifier: PRIdentifier): void;
59
+ /**
60
+ * Get memory bank statistics
61
+ */
62
+ getStats(identifier: PRIdentifier): Promise<{
63
+ enabled: boolean;
64
+ primaryPath: string;
65
+ fallbackPaths: string[];
66
+ hasMemoryBank: boolean;
67
+ resolvedPath: string | null;
68
+ fileCount: number;
69
+ cacheHits: number;
70
+ }>;
71
+ }
72
+ export declare function createMemoryBankManager(config: MemoryBankConfig, bitbucketProvider: BitbucketProvider): MemoryBankManager;
73
+ //# sourceMappingURL=MemoryBankManager.d.ts.map
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Memory Bank Manager - Handles configurable memory bank operations
3
+ * Provides abstraction for memory bank file access with fallback support
4
+ */
5
+ import { ConfigurationError } from "../types/index.js";
6
+ import { logger } from "./Logger.js";
7
+ import { cache, Cache } from "./Cache.js";
8
+ export class MemoryBankManager {
9
+ config;
10
+ bitbucketProvider;
11
+ constructor(config, bitbucketProvider) {
12
+ this.config = config;
13
+ this.bitbucketProvider = bitbucketProvider;
14
+ this.validateConfig();
15
+ }
16
+ /**
17
+ * Get memory bank files from the configured path with fallback support
18
+ */
19
+ async getMemoryBankFiles(identifier, forceRefresh = false) {
20
+ if (!this.config.enabled) {
21
+ logger.debug("Memory bank is disabled in configuration");
22
+ return {
23
+ files: [],
24
+ resolvedPath: "",
25
+ filesProcessed: 0,
26
+ fallbackUsed: false,
27
+ };
28
+ }
29
+ const cacheKey = Cache.keys.memoryBankFiles(identifier.workspace, identifier.repository, identifier.branch || "main", this.config.path);
30
+ if (!forceRefresh && cache.has(cacheKey)) {
31
+ logger.debug("Using cached memory bank files");
32
+ return cache.get(cacheKey);
33
+ }
34
+ logger.debug(`Gathering memory bank files from configured paths...`);
35
+ // Try primary path first
36
+ const primaryResult = await this.tryGetFilesFromPath(identifier, this.config.path);
37
+ if (primaryResult.files.length > 0) {
38
+ const result = {
39
+ ...primaryResult,
40
+ resolvedPath: this.config.path,
41
+ fallbackUsed: false,
42
+ };
43
+ // Cache the result
44
+ cache.set(cacheKey, result, 7200); // 2 hours
45
+ return result;
46
+ }
47
+ // Try fallback paths if primary path failed
48
+ if (this.config.fallbackPaths && this.config.fallbackPaths.length > 0) {
49
+ logger.debug(`Primary path '${this.config.path}' not found, trying fallback paths...`);
50
+ for (const fallbackPath of this.config.fallbackPaths) {
51
+ logger.debug(`Trying fallback path: ${fallbackPath}`);
52
+ const fallbackResult = await this.tryGetFilesFromPath(identifier, fallbackPath);
53
+ if (fallbackResult.files.length > 0) {
54
+ logger.info(`Memory bank found at fallback path: ${fallbackPath} (${fallbackResult.files.length} files)`);
55
+ const result = {
56
+ ...fallbackResult,
57
+ resolvedPath: fallbackPath,
58
+ fallbackUsed: true,
59
+ };
60
+ // Cache the result
61
+ cache.set(cacheKey, result, 7200); // 2 hours
62
+ return result;
63
+ }
64
+ }
65
+ }
66
+ // No memory bank found anywhere
67
+ logger.debug(`No memory bank found in primary path '${this.config.path}' or fallback paths`);
68
+ const emptyResult = {
69
+ files: [],
70
+ resolvedPath: "",
71
+ filesProcessed: 0,
72
+ fallbackUsed: false,
73
+ };
74
+ // Cache empty result for shorter time to allow for quick retry
75
+ cache.set(cacheKey, emptyResult, 1800); // 30 minutes
76
+ return emptyResult;
77
+ }
78
+ /**
79
+ * Try to get files from a specific path
80
+ */
81
+ async tryGetFilesFromPath(identifier, path) {
82
+ try {
83
+ // Get directory listing
84
+ const directoryFiles = await this.bitbucketProvider.listDirectoryContent(identifier.workspace, identifier.repository, path, identifier.branch || "main");
85
+ if (!directoryFiles.length) {
86
+ logger.debug(`No files found in directory: ${path}`);
87
+ return { files: [], filesProcessed: 0 };
88
+ }
89
+ // Filter to only files (not directories)
90
+ const files = directoryFiles.filter((f) => f.type === "file");
91
+ logger.debug(`Found ${files.length} files in ${path}`);
92
+ // Get content of each file
93
+ const memoryBankFiles = [];
94
+ for (const file of files) {
95
+ try {
96
+ const content = await this.bitbucketProvider.getFileContent(identifier.workspace, identifier.repository, `${path}/${file.name}`, identifier.branch || "main");
97
+ memoryBankFiles.push({
98
+ name: file.name,
99
+ content,
100
+ path: `${path}/${file.name}`,
101
+ });
102
+ logger.debug(`✓ Loaded content for: ${file.name}`);
103
+ }
104
+ catch (error) {
105
+ logger.debug(`Could not read file ${file.name}: ${error.message}`);
106
+ // Continue with other files even if one fails
107
+ }
108
+ }
109
+ return {
110
+ files: memoryBankFiles,
111
+ filesProcessed: memoryBankFiles.length,
112
+ };
113
+ }
114
+ catch (error) {
115
+ logger.debug(`Failed to access path '${path}': ${error.message}`);
116
+ return { files: [], filesProcessed: 0 };
117
+ }
118
+ }
119
+ /**
120
+ * Get the effective memory bank path (resolved after fallback logic)
121
+ */
122
+ async getEffectiveMemoryBankPath(identifier) {
123
+ const result = await this.getMemoryBankFiles(identifier);
124
+ return result.resolvedPath || null;
125
+ }
126
+ /**
127
+ * Check if memory bank exists at any configured path
128
+ */
129
+ async hasMemoryBank(identifier) {
130
+ const result = await this.getMemoryBankFiles(identifier);
131
+ return result.files.length > 0;
132
+ }
133
+ /**
134
+ * Get memory bank configuration
135
+ */
136
+ getConfig() {
137
+ return { ...this.config };
138
+ }
139
+ /**
140
+ * Update memory bank configuration
141
+ */
142
+ updateConfig(newConfig) {
143
+ this.config = { ...this.config, ...newConfig };
144
+ this.validateConfig();
145
+ logger.debug("Memory bank configuration updated");
146
+ }
147
+ /**
148
+ * Validates that a path is safe for use as a relative path
149
+ * Protects against path traversal attacks including encoded variants
150
+ */
151
+ static isSafeRelativePath(path) {
152
+ if (!path || typeof path !== "string") {
153
+ return false;
154
+ }
155
+ // Reject empty or whitespace-only paths
156
+ if (path.trim().length === 0) {
157
+ return false;
158
+ }
159
+ // Reject excessively long paths
160
+ if (path.length > 1000) {
161
+ return false;
162
+ }
163
+ // Reject absolute paths (Unix-style)
164
+ if (path.startsWith("/")) {
165
+ return false;
166
+ }
167
+ // Reject absolute paths (Windows-style)
168
+ if (/^[a-zA-Z]:/.test(path)) {
169
+ return false;
170
+ }
171
+ // Reject UNC paths (Windows network paths)
172
+ if (path.startsWith("\\\\") || path.startsWith("//")) {
173
+ return false;
174
+ }
175
+ // Decode URL-encoded characters to catch encoded traversal attempts
176
+ let decodedPath = path;
177
+ try {
178
+ // Multiple rounds of decoding to catch double-encoded attacks
179
+ for (let i = 0; i < 3; i++) {
180
+ const previousPath = decodedPath;
181
+ decodedPath = decodeURIComponent(decodedPath);
182
+ if (decodedPath === previousPath) {
183
+ break; // No more decoding needed
184
+ }
185
+ }
186
+ }
187
+ catch {
188
+ // If decoding fails, treat as suspicious
189
+ return false;
190
+ }
191
+ // Normalize Unicode characters
192
+ decodedPath = decodedPath.normalize("NFC");
193
+ // Check for null bytes (can be used to bypass filters)
194
+ if (decodedPath.includes("\0") || decodedPath.includes("%00")) {
195
+ return false;
196
+ }
197
+ // Normalize path separators to forward slashes
198
+ const normalizedPath = decodedPath.replace(/\\/g, "/");
199
+ // Check for path traversal sequences after normalization
200
+ if (normalizedPath.includes("../") || normalizedPath.includes("/..")) {
201
+ return false;
202
+ }
203
+ // Check for path traversal at the beginning or end
204
+ if (normalizedPath.startsWith("..") || normalizedPath.endsWith("..")) {
205
+ return false;
206
+ }
207
+ // Check for hidden traversal patterns
208
+ if (normalizedPath.includes("./..") || normalizedPath.includes("../.")) {
209
+ return false;
210
+ }
211
+ // Split path into segments and validate each
212
+ const segments = normalizedPath.split("/").filter(segment => segment.length > 0);
213
+ for (const segment of segments) {
214
+ // Reject any segment that is exactly ".."
215
+ if (segment === "..") {
216
+ return false;
217
+ }
218
+ // Reject segments that contain ".." anywhere
219
+ if (segment.includes("..")) {
220
+ return false;
221
+ }
222
+ // Allow segments that start with a single dot (like .memory-bank, .config)
223
+ // but reject multiple dots or suspicious patterns
224
+ if (segment.startsWith(".") && segment !== ".") {
225
+ // Allow single dot followed by alphanumeric/dash/underscore
226
+ if (!/^\.[\w-]+$/.test(segment)) {
227
+ return false;
228
+ }
229
+ }
230
+ // Reject segments with control characters
231
+ // Check for control characters (0x00-0x1F and 0x7F)
232
+ for (let i = 0; i < segment.length; i++) {
233
+ const charCode = segment.charCodeAt(i);
234
+ if ((charCode >= 0 && charCode <= 31) || charCode === 127) {
235
+ return false;
236
+ }
237
+ }
238
+ }
239
+ // Additional check: ensure the resolved path doesn't escape the base
240
+ // This is a final safety check using path resolution logic
241
+ const pathParts = segments.filter(part => part !== ".");
242
+ let depth = 0;
243
+ for (const part of pathParts) {
244
+ if (part === "..") {
245
+ depth--;
246
+ if (depth < 0) {
247
+ return false; // Would escape the base directory
248
+ }
249
+ }
250
+ else {
251
+ depth++;
252
+ }
253
+ }
254
+ return true;
255
+ }
256
+ /**
257
+ * Validate memory bank configuration
258
+ */
259
+ validateConfig() {
260
+ if (!this.config.path) {
261
+ throw new ConfigurationError("Memory bank path must be specified when memory bank is enabled");
262
+ }
263
+ if (!MemoryBankManager.isSafeRelativePath(this.config.path)) {
264
+ throw new ConfigurationError(`Memory bank path is unsafe or contains path traversal: ${this.config.path}`);
265
+ }
266
+ // Validate fallback paths
267
+ if (this.config.fallbackPaths) {
268
+ for (const fallbackPath of this.config.fallbackPaths) {
269
+ if (!MemoryBankManager.isSafeRelativePath(fallbackPath)) {
270
+ throw new ConfigurationError(`Memory bank fallback path is unsafe or contains path traversal: ${fallbackPath}`);
271
+ }
272
+ }
273
+ }
274
+ logger.debug("Memory bank configuration validated successfully");
275
+ }
276
+ /**
277
+ * Clear memory bank cache for a specific repository
278
+ */
279
+ clearCache(identifier) {
280
+ const patterns = [
281
+ `memory-bank:${identifier.workspace}:${identifier.repository}:*`,
282
+ `project-context:${identifier.workspace}:${identifier.repository}:*`,
283
+ ];
284
+ patterns.forEach((pattern) => {
285
+ cache.invalidatePattern(pattern);
286
+ });
287
+ logger.debug(`Memory bank cache cleared for ${identifier.workspace}/${identifier.repository}`);
288
+ }
289
+ /**
290
+ * Get memory bank statistics
291
+ */
292
+ async getStats(identifier) {
293
+ const result = await this.getMemoryBankFiles(identifier);
294
+ const cacheStats = cache.stats();
295
+ return {
296
+ enabled: this.config.enabled,
297
+ primaryPath: this.config.path,
298
+ fallbackPaths: this.config.fallbackPaths || [],
299
+ hasMemoryBank: result.files.length > 0,
300
+ resolvedPath: result.resolvedPath || null,
301
+ fileCount: result.files.length,
302
+ cacheHits: cacheStats.hits,
303
+ };
304
+ }
305
+ }
306
+ // Export factory function
307
+ export function createMemoryBankManager(config, bitbucketProvider) {
308
+ return new MemoryBankManager(config, bitbucketProvider);
309
+ }
310
+ //# sourceMappingURL=MemoryBankManager.js.map
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Provider Token Limits Utility
3
+ * Centralized management of AI provider token limits and validation
4
+ */
5
+ /**
6
+ * AI Provider types supported by the system
7
+ */
8
+ export type AIProvider = 'vertex' | 'google-ai' | 'gemini' | 'openai' | 'gpt-4' | 'anthropic' | 'claude' | 'azure' | 'bedrock' | 'auto';
9
+ /**
10
+ * Provider token limits configuration
11
+ * These limits are conservative values to avoid API errors
12
+ */
13
+ export declare const PROVIDER_TOKEN_LIMITS: Record<AIProvider, number>;
14
+ /**
15
+ * Conservative limits used by CodeReviewer for safety
16
+ * These are slightly lower than the actual limits to provide buffer
17
+ */
18
+ export declare const CONSERVATIVE_PROVIDER_LIMITS: Record<AIProvider, number>;
19
+ /**
20
+ * Get the token limit for a specific provider
21
+ * @param provider - The AI provider name
22
+ * @param conservative - Whether to use conservative limits (default: false)
23
+ * @returns The token limit for the provider
24
+ */
25
+ export declare function getProviderTokenLimit(provider: string, conservative?: boolean): number;
26
+ /**
27
+ * Validate and adjust token limit for a provider
28
+ * @param provider - The AI provider name
29
+ * @param configuredTokens - The configured token limit
30
+ * @param conservative - Whether to use conservative limits (default: false)
31
+ * @returns The validated and potentially adjusted token limit
32
+ */
33
+ export declare function validateProviderTokenLimit(provider: string, configuredTokens: number | undefined, conservative?: boolean): number;
34
+ /**
35
+ * Get all supported providers
36
+ * @returns Array of supported provider names
37
+ */
38
+ export declare function getSupportedProviders(): AIProvider[];
39
+ /**
40
+ * Check if a provider is supported
41
+ * @param provider - The provider name to check
42
+ * @returns True if the provider is supported
43
+ */
44
+ export declare function isProviderSupported(provider: string): boolean;
45
+ /**
46
+ * Get provider information including limits and support status
47
+ * @param provider - The provider name
48
+ * @param conservative - Whether to use conservative limits
49
+ * @returns Provider information object
50
+ */
51
+ export declare function getProviderInfo(provider: string, conservative?: boolean): {
52
+ provider: string;
53
+ isSupported: boolean;
54
+ tokenLimit: number;
55
+ conservativeLimit: number;
56
+ standardLimit: number;
57
+ };
58
+ //# sourceMappingURL=ProviderLimits.d.ts.map
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Provider Token Limits Utility
3
+ * Centralized management of AI provider token limits and validation
4
+ */
5
+ import { logger } from "./Logger.js";
6
+ /**
7
+ * Provider token limits configuration
8
+ * These limits are conservative values to avoid API errors
9
+ */
10
+ export const PROVIDER_TOKEN_LIMITS = {
11
+ // Google/Vertex AI providers
12
+ 'vertex': 65536, // Vertex AI limit is 65537 exclusive = 65536 max
13
+ 'google-ai': 65536, // Google AI Studio limit
14
+ 'gemini': 65536, // Gemini model limit
15
+ // OpenAI providers
16
+ 'openai': 128000, // OpenAI GPT-4 and newer models
17
+ 'gpt-4': 128000, // GPT-4 specific limit
18
+ // Anthropic providers
19
+ 'anthropic': 200000, // Claude models limit
20
+ 'claude': 200000, // Claude specific limit
21
+ // Microsoft Azure
22
+ 'azure': 128000, // Azure OpenAI limit
23
+ // AWS Bedrock
24
+ 'bedrock': 100000, // AWS Bedrock limit
25
+ // Auto-selection mode (conservative default)
26
+ 'auto': 60000, // Conservative default for auto-selection
27
+ };
28
+ /**
29
+ * Conservative limits used by CodeReviewer for safety
30
+ * These are slightly lower than the actual limits to provide buffer
31
+ */
32
+ export const CONSERVATIVE_PROVIDER_LIMITS = {
33
+ 'vertex': 65536,
34
+ 'google-ai': 65536,
35
+ 'gemini': 65536,
36
+ 'openai': 120000, // Slightly lower for safety
37
+ 'gpt-4': 120000,
38
+ 'anthropic': 190000, // Slightly lower for safety
39
+ 'claude': 190000,
40
+ 'azure': 120000,
41
+ 'bedrock': 95000, // Significantly lower for safety
42
+ 'auto': 60000,
43
+ };
44
+ /**
45
+ * Get the token limit for a specific provider
46
+ * @param provider - The AI provider name
47
+ * @param conservative - Whether to use conservative limits (default: false)
48
+ * @returns The token limit for the provider
49
+ */
50
+ export function getProviderTokenLimit(provider, conservative = false) {
51
+ // Handle null, undefined, or empty string
52
+ if (!provider || typeof provider !== 'string') {
53
+ return conservative ? CONSERVATIVE_PROVIDER_LIMITS.auto : PROVIDER_TOKEN_LIMITS.auto;
54
+ }
55
+ const normalizedProvider = provider.toLowerCase();
56
+ const limits = conservative ? CONSERVATIVE_PROVIDER_LIMITS : PROVIDER_TOKEN_LIMITS;
57
+ // Handle empty string after normalization
58
+ if (normalizedProvider === '') {
59
+ return conservative ? CONSERVATIVE_PROVIDER_LIMITS.auto : PROVIDER_TOKEN_LIMITS.auto;
60
+ }
61
+ // Direct match
62
+ if (normalizedProvider in limits) {
63
+ return limits[normalizedProvider];
64
+ }
65
+ // Partial match - check if provider contains any known provider name
66
+ for (const [key, limit] of Object.entries(limits)) {
67
+ if (normalizedProvider.includes(key) || key.includes(normalizedProvider)) {
68
+ return limit;
69
+ }
70
+ }
71
+ // Default fallback
72
+ return conservative ? CONSERVATIVE_PROVIDER_LIMITS.auto : PROVIDER_TOKEN_LIMITS.auto;
73
+ }
74
+ /**
75
+ * Validate and adjust token limit for a provider
76
+ * @param provider - The AI provider name
77
+ * @param configuredTokens - The configured token limit
78
+ * @param conservative - Whether to use conservative limits (default: false)
79
+ * @returns The validated and potentially adjusted token limit
80
+ */
81
+ export function validateProviderTokenLimit(provider, configuredTokens, conservative = false) {
82
+ const providerLimit = getProviderTokenLimit(provider, conservative);
83
+ if (!configuredTokens || configuredTokens <= 0) {
84
+ logger.debug(`No configured tokens for ${provider}, using provider default: ${providerLimit}`);
85
+ return providerLimit;
86
+ }
87
+ if (configuredTokens > providerLimit) {
88
+ logger.warn(`Configured maxTokens (${configuredTokens}) exceeds ${provider} limit (${providerLimit}). Adjusting to ${providerLimit}.`);
89
+ return providerLimit;
90
+ }
91
+ logger.debug(`Token limit validation passed: ${configuredTokens} <= ${providerLimit} for provider ${provider}`);
92
+ return configuredTokens;
93
+ }
94
+ /**
95
+ * Get all supported providers
96
+ * @returns Array of supported provider names
97
+ */
98
+ export function getSupportedProviders() {
99
+ return Object.keys(PROVIDER_TOKEN_LIMITS);
100
+ }
101
+ /**
102
+ * Check if a provider is supported
103
+ * @param provider - The provider name to check
104
+ * @returns True if the provider is supported
105
+ */
106
+ export function isProviderSupported(provider) {
107
+ // Handle null, undefined, or empty string
108
+ if (!provider || typeof provider !== 'string') {
109
+ return false;
110
+ }
111
+ const normalizedProvider = provider.toLowerCase();
112
+ // Handle empty string after normalization
113
+ if (normalizedProvider === '') {
114
+ return false;
115
+ }
116
+ // Check direct match
117
+ if (normalizedProvider in PROVIDER_TOKEN_LIMITS) {
118
+ return true;
119
+ }
120
+ // Check partial match
121
+ for (const key of Object.keys(PROVIDER_TOKEN_LIMITS)) {
122
+ if (normalizedProvider.includes(key) || key.includes(normalizedProvider)) {
123
+ return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+ /**
129
+ * Get provider information including limits and support status
130
+ * @param provider - The provider name
131
+ * @param conservative - Whether to use conservative limits
132
+ * @returns Provider information object
133
+ */
134
+ export function getProviderInfo(provider, conservative = false) {
135
+ return {
136
+ provider,
137
+ isSupported: isProviderSupported(provider),
138
+ tokenLimit: getProviderTokenLimit(provider, conservative),
139
+ conservativeLimit: getProviderTokenLimit(provider, true),
140
+ standardLimit: getProviderTokenLimit(provider, false),
141
+ };
142
+ }
143
+ //# sourceMappingURL=ProviderLimits.js.map