@juspay/neurolink 9.14.0 → 9.15.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +15 -15
  3. package/dist/auth/anthropicOAuth.d.ts +377 -0
  4. package/dist/auth/anthropicOAuth.js +914 -0
  5. package/dist/auth/index.d.ts +20 -0
  6. package/dist/auth/index.js +29 -0
  7. package/dist/auth/tokenStore.d.ts +225 -0
  8. package/dist/auth/tokenStore.js +521 -0
  9. package/dist/cli/commands/auth.d.ts +50 -0
  10. package/dist/cli/commands/auth.js +1115 -0
  11. package/dist/cli/factories/authCommandFactory.d.ts +52 -0
  12. package/dist/cli/factories/authCommandFactory.js +146 -0
  13. package/dist/cli/factories/commandFactory.d.ts +6 -0
  14. package/dist/cli/factories/commandFactory.js +92 -2
  15. package/dist/cli/parser.js +11 -2
  16. package/dist/constants/enums.d.ts +20 -0
  17. package/dist/constants/enums.js +30 -0
  18. package/dist/constants/index.d.ts +3 -1
  19. package/dist/constants/index.js +11 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/lib/auth/anthropicOAuth.d.ts +377 -0
  22. package/dist/lib/auth/anthropicOAuth.js +915 -0
  23. package/dist/lib/auth/index.d.ts +20 -0
  24. package/dist/lib/auth/index.js +30 -0
  25. package/dist/lib/auth/tokenStore.d.ts +225 -0
  26. package/dist/lib/auth/tokenStore.js +522 -0
  27. package/dist/lib/constants/enums.d.ts +20 -0
  28. package/dist/lib/constants/enums.js +30 -0
  29. package/dist/lib/constants/index.d.ts +3 -1
  30. package/dist/lib/constants/index.js +11 -1
  31. package/dist/lib/index.d.ts +1 -1
  32. package/dist/lib/models/anthropicModels.d.ts +267 -0
  33. package/dist/lib/models/anthropicModels.js +528 -0
  34. package/dist/lib/providers/anthropic.d.ts +123 -2
  35. package/dist/lib/providers/anthropic.js +800 -10
  36. package/dist/lib/types/errors.d.ts +62 -0
  37. package/dist/lib/types/errors.js +107 -0
  38. package/dist/lib/types/index.d.ts +2 -1
  39. package/dist/lib/types/index.js +2 -0
  40. package/dist/lib/types/providers.d.ts +107 -0
  41. package/dist/lib/types/providers.js +69 -0
  42. package/dist/lib/types/subscriptionTypes.d.ts +893 -0
  43. package/dist/lib/types/subscriptionTypes.js +8 -0
  44. package/dist/lib/utils/providerConfig.d.ts +167 -0
  45. package/dist/lib/utils/providerConfig.js +619 -9
  46. package/dist/models/anthropicModels.d.ts +267 -0
  47. package/dist/models/anthropicModels.js +527 -0
  48. package/dist/providers/anthropic.d.ts +123 -2
  49. package/dist/providers/anthropic.js +800 -10
  50. package/dist/types/errors.d.ts +62 -0
  51. package/dist/types/errors.js +107 -0
  52. package/dist/types/index.d.ts +2 -1
  53. package/dist/types/index.js +2 -0
  54. package/dist/types/providers.d.ts +107 -0
  55. package/dist/types/providers.js +69 -0
  56. package/dist/types/subscriptionTypes.d.ts +893 -0
  57. package/dist/types/subscriptionTypes.js +7 -0
  58. package/dist/utils/providerConfig.d.ts +167 -0
  59. package/dist/utils/providerConfig.js +619 -9
  60. package/package.json +2 -1
@@ -8,6 +8,204 @@ import { AuthenticationError, NetworkError, ProviderError, RateLimitError, } fro
8
8
  import { logger } from "../utils/logger.js";
9
9
  import { createAnthropicConfig, getProviderModel, validateApiKey, } from "../utils/providerConfig.js";
10
10
  import { composeAbortSignals, createTimeoutController, TimeoutError, } from "../utils/timeout.js";
11
+ import { isModelAvailableForTier, getRecommendedModelForTier, getModelCapabilities, } from "../models/anthropicModels.js";
12
+ import { CLAUDE_CLI_USER_AGENT, CLAUDE_CODE_CLIENT_ID, ANTHROPIC_TOKEN_URL, MCP_TOOL_PREFIX, } from "../auth/anthropicOAuth.js";
13
+ import { homedir } from "os";
14
+ import { readFileSync, existsSync, writeFileSync, mkdirSync, renameSync, } from "fs";
15
+ import { join } from "path";
16
+ import { TOKEN_EXPIRY_BUFFER_MS } from "../constants/enums.js";
17
+ /**
18
+ * Beta headers for Claude Code integration.
19
+ * These enable experimental features:
20
+ * - claude-code-20250219: Claude Code specific features
21
+ * - interleaved-thinking-2025-05-14: Interleaved thinking mode
22
+ * - fine-grained-tool-streaming-2025-05-14: Fine-grained tool streaming
23
+ */
24
+ const ANTHROPIC_BETA_HEADERS = {
25
+ "anthropic-beta": [
26
+ "claude-code-20250219",
27
+ "interleaved-thinking-2025-05-14",
28
+ "fine-grained-tool-streaming-2025-05-14",
29
+ ].join(","),
30
+ };
31
+ /**
32
+ * Creates a custom fetch function for OAuth-authenticated requests.
33
+ * This wrapper applies all required transformations for OAuth mode:
34
+ * - Uses Authorization: Bearer header (NOT x-api-key)
35
+ * - Adds OAuth-required beta headers (oauth-2025-04-20 is critical)
36
+ * - Sets User-Agent to Claude CLI
37
+ * - Adds ?beta=true query parameter to /v1/messages
38
+ * - Prefixes tool names with mcp_
39
+ * - Strips mcp_ prefix from tool names in responses
40
+ *
41
+ * Accepts a getter function instead of a static token so that refreshed
42
+ * tokens are picked up automatically on each request.
43
+ */
44
+ function createOAuthFetch(getToken, includeOptionalBetas = true) {
45
+ return async (input, init) => {
46
+ // Build the URL
47
+ let requestUrl = null;
48
+ try {
49
+ if (typeof input === "string" || input instanceof URL) {
50
+ requestUrl = new URL(input.toString());
51
+ }
52
+ else if (input instanceof Request) {
53
+ requestUrl = new URL(input.url);
54
+ }
55
+ }
56
+ catch {
57
+ requestUrl = null;
58
+ }
59
+ // Add ?beta=true to /v1/messages endpoint
60
+ if (requestUrl &&
61
+ requestUrl.pathname === "/v1/messages" &&
62
+ !requestUrl.searchParams.has("beta")) {
63
+ requestUrl.searchParams.set("beta", "true");
64
+ }
65
+ // Build new headers
66
+ const requestHeaders = new Headers();
67
+ // Copy headers from Request object if present
68
+ if (input instanceof Request) {
69
+ input.headers.forEach((value, key) => {
70
+ requestHeaders.set(key, value);
71
+ });
72
+ }
73
+ // Copy headers from init if present
74
+ if (init?.headers) {
75
+ if (init.headers instanceof Headers) {
76
+ init.headers.forEach((value, key) => {
77
+ requestHeaders.set(key, value);
78
+ });
79
+ }
80
+ else if (Array.isArray(init.headers)) {
81
+ for (const [key, value] of init.headers) {
82
+ if (typeof value !== "undefined") {
83
+ requestHeaders.set(key, String(value));
84
+ }
85
+ }
86
+ }
87
+ else {
88
+ for (const [key, value] of Object.entries(init.headers)) {
89
+ if (typeof value !== "undefined") {
90
+ requestHeaders.set(key, String(value));
91
+ }
92
+ }
93
+ }
94
+ }
95
+ // Check if claude-code beta was requested
96
+ const incomingBeta = requestHeaders.get("anthropic-beta") || "";
97
+ const incomingBetasList = incomingBeta
98
+ .split(",")
99
+ .map((b) => b.trim())
100
+ .filter(Boolean);
101
+ const includeClaudeCode = incomingBetasList.includes("claude-code-20250219");
102
+ // Merge beta headers — oauth-2025-04-20 is always required for OAuth;
103
+ // optional betas (interleaved-thinking) gated on includeOptionalBetas.
104
+ const mergedBetas = [
105
+ "oauth-2025-04-20",
106
+ ...(includeOptionalBetas ? ["interleaved-thinking-2025-05-14"] : []),
107
+ ...(includeClaudeCode ? ["claude-code-20250219"] : []),
108
+ ].join(",");
109
+ // Set OAuth authorization (Bearer token, NOT x-api-key)
110
+ // Call getToken() each time so refreshed tokens are used automatically.
111
+ requestHeaders.set("authorization", `Bearer ${getToken()}`);
112
+ requestHeaders.set("anthropic-beta", mergedBetas);
113
+ requestHeaders.set("user-agent", CLAUDE_CLI_USER_AGENT);
114
+ requestHeaders.delete("x-api-key");
115
+ logger.debug("[createOAuthFetch] Making OAuth request:", {
116
+ url: requestUrl?.toString() || input.toString(),
117
+ hasAuthorization: requestHeaders.has("authorization"),
118
+ authType: "Bearer",
119
+ anthropicBeta: requestHeaders.get("anthropic-beta"),
120
+ userAgent: requestHeaders.get("user-agent"),
121
+ });
122
+ // Add mcp_ prefix to tool names in request body
123
+ let body = init?.body;
124
+ if (body && typeof body === "string") {
125
+ try {
126
+ const parsed = JSON.parse(body);
127
+ // Add prefix to tools definitions
128
+ if (parsed.tools && Array.isArray(parsed.tools)) {
129
+ parsed.tools = parsed.tools.map((tool) => ({
130
+ ...tool,
131
+ name: tool.name ? `${MCP_TOOL_PREFIX}${tool.name}` : tool.name,
132
+ }));
133
+ }
134
+ // Add prefix to tool_use blocks in messages
135
+ if (parsed.messages && Array.isArray(parsed.messages)) {
136
+ parsed.messages = parsed.messages.map((msg) => {
137
+ if (msg.content && Array.isArray(msg.content)) {
138
+ msg.content = msg.content.map((block) => {
139
+ const b = block;
140
+ if (b.type === "tool_use" && b.name) {
141
+ return {
142
+ ...b,
143
+ name: `${MCP_TOOL_PREFIX}${b.name}`,
144
+ };
145
+ }
146
+ return block;
147
+ });
148
+ }
149
+ return msg;
150
+ });
151
+ }
152
+ body = JSON.stringify(parsed);
153
+ }
154
+ catch {
155
+ // Ignore JSON parse errors
156
+ }
157
+ }
158
+ // Make the request
159
+ const response = await fetch(requestUrl?.toString() ||
160
+ (input instanceof Request ? input.url : input.toString()), {
161
+ ...init,
162
+ body,
163
+ headers: requestHeaders,
164
+ });
165
+ // Transform streaming response to rename tools back (remove mcp_ prefix).
166
+ // Uses a small carry buffer to handle cross-chunk boundary splits of
167
+ // `"name": "mcp_..."` patterns.
168
+ if (response.body) {
169
+ const reader = response.body.getReader();
170
+ const decoder = new TextDecoder();
171
+ const encoder = new TextEncoder();
172
+ // Carry tail covers the longest possible partial match: `"name": "mcp_`
173
+ const CARRY_TAIL = 24;
174
+ let carry = "";
175
+ const stream = new ReadableStream({
176
+ async pull(controller) {
177
+ const { done, value } = await reader.read();
178
+ if (done) {
179
+ // Flush any remaining carry
180
+ if (carry) {
181
+ const flushed = carry.replace(/"name"\s*:\s*"mcp_([^"]+)"/g, '"name": "$1"');
182
+ controller.enqueue(encoder.encode(flushed));
183
+ carry = "";
184
+ }
185
+ controller.close();
186
+ return;
187
+ }
188
+ const chunkText = decoder.decode(value, { stream: true });
189
+ const combined = carry + chunkText;
190
+ const replaced = combined.replace(/"name"\s*:\s*"mcp_([^"]+)"/g, '"name": "$1"');
191
+ // Keep a small tail as carry to cover partial matches at chunk boundary
192
+ const safeLen = Math.max(0, replaced.length - CARRY_TAIL);
193
+ carry = replaced.slice(safeLen);
194
+ const toEmit = replaced.slice(0, safeLen);
195
+ if (toEmit) {
196
+ controller.enqueue(encoder.encode(toEmit));
197
+ }
198
+ },
199
+ });
200
+ return new Response(stream, {
201
+ status: response.status,
202
+ statusText: response.statusText,
203
+ headers: response.headers,
204
+ });
205
+ }
206
+ return response;
207
+ };
208
+ }
11
209
  // Configuration helpers - now using consolidated utility
12
210
  const getAnthropicApiKey = () => {
13
211
  return validateApiKey(createAnthropicConfig());
@@ -15,28 +213,600 @@ const getAnthropicApiKey = () => {
15
213
  const getDefaultAnthropicModel = () => {
16
214
  return getProviderModel("ANTHROPIC_MODEL", AnthropicModels.CLAUDE_3_5_SONNET);
17
215
  };
216
+ /**
217
+ * Get OAuth token from stored credentials file or environment.
218
+ * Priority:
219
+ * 1. Stored credentials file (~/.neurolink/anthropic-credentials.json)
220
+ * 2. Environment variables (ANTHROPIC_OAUTH_TOKEN or CLAUDE_OAUTH_TOKEN)
221
+ */
222
+ const getOAuthToken = () => {
223
+ // First, check stored credentials file (highest priority)
224
+ try {
225
+ const credentialsPath = join(homedir(), ".neurolink", "anthropic-credentials.json");
226
+ if (existsSync(credentialsPath)) {
227
+ const credentialsContent = readFileSync(credentialsPath, "utf-8");
228
+ const credentials = JSON.parse(credentialsContent);
229
+ if (credentials.type === "oauth" && credentials.oauth?.accessToken) {
230
+ logger.debug("[AnthropicProvider] Using OAuth token from stored credentials file");
231
+ return credentials.oauth;
232
+ }
233
+ }
234
+ }
235
+ catch (error) {
236
+ logger.debug("[AnthropicProvider] Failed to read stored credentials:", error);
237
+ }
238
+ // Fallback to environment variables
239
+ const tokenString = process.env.ANTHROPIC_OAUTH_TOKEN || process.env.CLAUDE_OAUTH_TOKEN;
240
+ if (!tokenString) {
241
+ return null;
242
+ }
243
+ // Try to parse as JSON (for full token object with refresh token and expiry)
244
+ try {
245
+ const parsed = JSON.parse(tokenString);
246
+ if (typeof parsed === "object" && parsed.accessToken) {
247
+ return parsed;
248
+ }
249
+ // If it's a simple string in JSON, use it as access token
250
+ if (typeof parsed === "string") {
251
+ return { accessToken: parsed };
252
+ }
253
+ }
254
+ catch {
255
+ // Not JSON, treat as plain access token string
256
+ }
257
+ // Treat as plain access token string
258
+ return { accessToken: tokenString };
259
+ };
260
+ /**
261
+ * Detect subscription tier from environment or token.
262
+ * Environment variable ANTHROPIC_SUBSCRIPTION_TIER takes precedence.
263
+ */
264
+ const detectSubscriptionTier = (oauthToken) => {
265
+ // Check explicit environment variable first
266
+ const envTier = process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();
267
+ if (envTier) {
268
+ const validTiers = [
269
+ "free",
270
+ "pro",
271
+ "max",
272
+ "max_5",
273
+ "max_20",
274
+ "api",
275
+ ];
276
+ if (validTiers.includes(envTier)) {
277
+ logger.debug("[detectSubscriptionTier] Using environment override", {
278
+ tier: envTier,
279
+ });
280
+ return envTier;
281
+ }
282
+ logger.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER", {
283
+ value: envTier,
284
+ validTiers,
285
+ });
286
+ }
287
+ // If using OAuth, default to 'pro' (most common subscription tier)
288
+ if (oauthToken) {
289
+ // Check if token scopes indicate tier (future-proofing)
290
+ const scopes = oauthToken.scopes ?? [];
291
+ let detectedTier = "pro";
292
+ if (scopes.includes("max_20")) {
293
+ detectedTier = "max_20";
294
+ }
295
+ else if (scopes.includes("max_5")) {
296
+ detectedTier = "max_5";
297
+ }
298
+ else if (scopes.includes("max")) {
299
+ detectedTier = "max";
300
+ }
301
+ logger.debug("[detectSubscriptionTier] Detected from OAuth token", {
302
+ tier: detectedTier,
303
+ scopes,
304
+ });
305
+ return detectedTier;
306
+ }
307
+ // Default to 'api' for API key authentication
308
+ logger.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier");
309
+ return "api";
310
+ };
311
+ /**
312
+ * Determine authentication method based on available credentials.
313
+ * OAuth takes precedence over API key if both are available.
314
+ */
315
+ const detectAuthMethod = (oauthToken) => {
316
+ // OAuth takes precedence if available
317
+ const method = oauthToken ? "oauth" : "api_key";
318
+ logger.debug("[detectAuthMethod] Auth method resolved", {
319
+ method,
320
+ hasOAuthToken: !!oauthToken,
321
+ });
322
+ return method;
323
+ };
324
+ /**
325
+ * Parse rate limit information from Anthropic API response headers.
326
+ * @param headers - Response headers from Anthropic API
327
+ * @returns Parsed rate limit information
328
+ */
329
+ const parseRateLimitHeaders = (headers) => {
330
+ const getHeader = (name) => {
331
+ if (headers instanceof Headers) {
332
+ return headers.get(name);
333
+ }
334
+ return headers[name] || headers[name.toLowerCase()] || null;
335
+ };
336
+ const parseNumber = (value) => {
337
+ if (!value) {
338
+ return undefined;
339
+ }
340
+ const num = parseInt(value, 10);
341
+ return isNaN(num) ? undefined : num;
342
+ };
343
+ return {
344
+ requestsLimit: parseNumber(getHeader("anthropic-ratelimit-requests-limit")),
345
+ requestsRemaining: parseNumber(getHeader("anthropic-ratelimit-requests-remaining")),
346
+ requestsReset: getHeader("anthropic-ratelimit-requests-reset") || undefined,
347
+ tokensLimit: parseNumber(getHeader("anthropic-ratelimit-tokens-limit")),
348
+ tokensRemaining: parseNumber(getHeader("anthropic-ratelimit-tokens-remaining")),
349
+ tokensReset: getHeader("anthropic-ratelimit-tokens-reset") || undefined,
350
+ retryAfter: parseNumber(getHeader("retry-after")),
351
+ };
352
+ };
18
353
  /**
19
354
  * Anthropic Provider v2 - BaseProvider Implementation
20
- * Fixed syntax and enhanced with proper error handling
355
+ * Enhanced with OAuth support, subscription tiers, and beta headers for Claude Code integration.
21
356
  */
22
357
  export class AnthropicProvider extends BaseProvider {
23
358
  model;
24
- constructor(modelName, sdk) {
25
- super(modelName, "anthropic", sdk);
26
- // Initialize Anthropic model with API key validation and proxy support
27
- const apiKey = getAnthropicApiKey();
28
- // Create Anthropic instance with proxy fetch
29
- const anthropic = createAnthropic({
30
- apiKey: apiKey,
31
- fetch: createProxyFetch(),
359
+ authMethod;
360
+ subscriptionTier;
361
+ enableBetaFeatures;
362
+ oauthToken;
363
+ lastResponseMetadata = null;
364
+ usageInfo = null;
365
+ refreshPromise;
366
+ /**
367
+ * Create a new Anthropic provider instance.
368
+ *
369
+ * @param modelName - Optional model name to use (defaults to CLAUDE_3_5_SONNET)
370
+ * @param sdk - Optional NeuroLink SDK instance
371
+ * @param config - Optional configuration options for auth, subscription tier, and beta features
372
+ */
373
+ constructor(modelName, sdk, config) {
374
+ // Pre-compute effective model with tier validation before calling super
375
+ const oauthToken = config?.oauthToken ?? getOAuthToken();
376
+ const subscriptionTier = config?.subscriptionTier ?? detectSubscriptionTier(oauthToken);
377
+ const targetModel = modelName || getDefaultAnthropicModel();
378
+ // Determine effective model based on tier access
379
+ let effectiveModel = targetModel;
380
+ if (subscriptionTier !== "api" &&
381
+ !isModelAvailableForTier(targetModel, subscriptionTier)) {
382
+ effectiveModel = getRecommendedModelForTier(subscriptionTier);
383
+ logger.warn("Model not available for subscription tier, using recommended model", {
384
+ requestedModel: targetModel,
385
+ subscriptionTier,
386
+ recommendedModel: effectiveModel,
387
+ });
388
+ }
389
+ super(effectiveModel, "anthropic", sdk);
390
+ // Apply configuration with defaults
391
+ this.enableBetaFeatures = config?.enableBetaFeatures ?? true;
392
+ // Store computed values
393
+ this.oauthToken = oauthToken;
394
+ this.subscriptionTier = subscriptionTier;
395
+ // Determine auth method - config takes precedence, then auto-detect
396
+ this.authMethod = config?.authMethod ?? detectAuthMethod(this.oauthToken);
397
+ // Build headers based on auth method and subscription tier
398
+ const headers = this.getAuthHeaders();
399
+ // Create Anthropic instance based on auth method
400
+ let anthropic;
401
+ logger.debug("[AnthropicProvider] Constructor - checking OAuth:", {
402
+ authMethod: this.authMethod,
403
+ hasOAuthToken: !!this.oauthToken,
404
+ hasAccessToken: !!this.oauthToken?.accessToken,
32
405
  });
33
- // Initialize Anthropic model with proxy-aware instance
406
+ if (this.authMethod === "oauth" && this.oauthToken) {
407
+ // OAuth authentication - use custom fetch wrapper that handles:
408
+ // - Bearer token authorization
409
+ // - OAuth beta headers (oauth-2025-04-20, NOT claude-code-20250219)
410
+ // - User-Agent spoofing
411
+ // - ?beta=true query param
412
+ // - Tool name prefixing/stripping
413
+ logger.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");
414
+ // Pass a getter so the fetch wrapper always uses the current token,
415
+ // even after an automatic token refresh.
416
+ // oauthToken is guaranteed non-null here (checked by the enclosing if-guard).
417
+ const tokenRef = this.oauthToken;
418
+ const oauthFetch = createOAuthFetch(() => tokenRef.accessToken, this.enableBetaFeatures);
419
+ // For OAuth, we use a dummy API key since our fetch wrapper handles auth
420
+ // IMPORTANT: Do NOT pass beta headers here - our fetch wrapper handles them
421
+ // The claude-code-20250219 beta header triggers "credential only for Claude Code" error
422
+ anthropic = createAnthropic({
423
+ apiKey: "oauth-authenticated", // Placeholder, actual auth is in fetch wrapper
424
+ // Note: No headers passed - fetch wrapper sets oauth-2025-04-20 beta header
425
+ fetch: oauthFetch,
426
+ });
427
+ logger.debug("[AnthropicProvider] Anthropic SDK created with OAuth fetch wrapper");
428
+ logger.debug("Anthropic Provider initialized with OAuth", {
429
+ modelName: this.modelName,
430
+ provider: this.providerName,
431
+ authMethod: this.authMethod,
432
+ subscriptionTier: this.subscriptionTier,
433
+ enableBetaFeatures: this.enableBetaFeatures,
434
+ hasRefreshToken: !!this.oauthToken.refreshToken,
435
+ tokenExpiry: this.oauthToken.expiresAt
436
+ ? new Date(this.oauthToken.expiresAt).toISOString()
437
+ : "none",
438
+ });
439
+ }
440
+ else {
441
+ // Traditional API key authentication
442
+ const apiKeyToUse = config?.apiKey ?? getAnthropicApiKey();
443
+ anthropic = createAnthropic({
444
+ apiKey: apiKeyToUse,
445
+ headers,
446
+ fetch: createProxyFetch(),
447
+ });
448
+ logger.debug("Anthropic Provider initialized with API key", {
449
+ modelName: this.modelName,
450
+ provider: this.providerName,
451
+ authMethod: this.authMethod,
452
+ subscriptionTier: this.subscriptionTier,
453
+ enableBetaFeatures: this.enableBetaFeatures,
454
+ });
455
+ }
456
+ // Initialize Anthropic model with configured instance
34
457
  this.model = anthropic(this.modelName || getDefaultAnthropicModel());
458
+ // Initialize usage tracking
459
+ this.usageInfo = {
460
+ messagesUsed: 0,
461
+ messagesRemaining: -1, // Unknown until we get rate limit headers
462
+ tokensUsed: 0,
463
+ tokensRemaining: -1,
464
+ inputTokensUsed: 0,
465
+ outputTokensUsed: 0,
466
+ lastRequestTimestamp: 0,
467
+ isRateLimited: false,
468
+ requestCount: 0,
469
+ messageQuotaPercent: 0,
470
+ tokenQuotaPercent: 0,
471
+ };
35
472
  logger.debug("Anthropic Provider v2 initialized", {
36
473
  modelName: this.modelName,
37
474
  provider: this.providerName,
475
+ authMethod: this.authMethod,
476
+ subscriptionTier: this.subscriptionTier,
477
+ enableBetaFeatures: this.enableBetaFeatures,
478
+ betaFeatures: this.enableBetaFeatures
479
+ ? ANTHROPIC_BETA_HEADERS["anthropic-beta"]
480
+ : "disabled",
38
481
  });
39
482
  }
483
+ /**
484
+ * Get authentication headers based on current auth method and configuration.
485
+ *
486
+ * @returns Headers object containing auth and beta feature headers
487
+ */
488
+ getAuthHeaders() {
489
+ const headers = {};
490
+ // Add beta headers if enabled
491
+ if (this.enableBetaFeatures) {
492
+ headers["anthropic-beta"] = ANTHROPIC_BETA_HEADERS["anthropic-beta"];
493
+ }
494
+ // Add subscription-specific headers if applicable
495
+ if (this.subscriptionTier !== "api") {
496
+ headers["x-subscription-tier"] = this.subscriptionTier;
497
+ }
498
+ return headers;
499
+ }
500
+ /**
501
+ * Validate if a model is accessible with the current subscription tier.
502
+ *
503
+ * @param model - The model ID to validate
504
+ * @returns true if the model is accessible, false otherwise
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * const provider = new AnthropicProvider();
509
+ * if (provider.validateModelAccess("claude-opus-4-5-20251101")) {
510
+ * // Use the model
511
+ * } else {
512
+ * // Fall back to a different model or show upgrade prompt
513
+ * }
514
+ * ```
515
+ */
516
+ validateModelAccess(model) {
517
+ // API tier has access to all models
518
+ if (this.subscriptionTier === "api") {
519
+ return true;
520
+ }
521
+ const hasAccess = isModelAvailableForTier(model, this.subscriptionTier);
522
+ if (!hasAccess) {
523
+ logger.debug("[validateModelAccess] Model not available for tier", {
524
+ model,
525
+ tier: this.subscriptionTier,
526
+ });
527
+ }
528
+ return hasAccess;
529
+ }
530
+ /**
531
+ * Get current usage information.
532
+ *
533
+ * Returns usage tracking data including messages sent, tokens consumed,
534
+ * and remaining quotas. This information is updated after each API request.
535
+ *
536
+ * @returns Current usage info or null if no requests have been made
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * const usage = provider.getUsageInfo();
541
+ * if (usage && usage.tokenQuotaPercent > 80) {
542
+ * console.warn("Approaching token quota limit");
543
+ * }
544
+ * ```
545
+ */
546
+ getUsageInfo() {
547
+ return this.usageInfo;
548
+ }
549
+ /**
550
+ * Check if beta features are enabled for this provider instance.
551
+ *
552
+ * @returns true if beta features are enabled
553
+ */
554
+ areBetaFeaturesEnabled() {
555
+ return this.enableBetaFeatures;
556
+ }
557
+ /**
558
+ * Get model capabilities for the current model.
559
+ *
560
+ * @returns The model capabilities or undefined if not found
561
+ */
562
+ getModelCapabilities() {
563
+ return getModelCapabilities(this.modelName || this.getDefaultModel());
564
+ }
565
+ /**
566
+ * Get the current subscription tier.
567
+ * @returns The detected or configured subscription tier
568
+ */
569
+ getSubscriptionTier() {
570
+ return this.subscriptionTier;
571
+ }
572
+ /**
573
+ * Get the authentication method being used.
574
+ * @returns The current authentication method
575
+ */
576
+ getAuthMethod() {
577
+ return this.authMethod;
578
+ }
579
+ /**
580
+ * Refresh OAuth token if needed and possible.
581
+ * This method checks if the token is expired or about to expire,
582
+ * and attempts to refresh it using the refresh token if available.
583
+ *
584
+ * @returns Promise that resolves when refresh is complete (or not needed)
585
+ * @throws Error if refresh is needed but fails
586
+ */
587
+ async refreshAuthIfNeeded() {
588
+ // Only applicable for OAuth authentication
589
+ if (this.authMethod !== "oauth" || !this.oauthToken) {
590
+ logger.debug("Token refresh not applicable for API key authentication");
591
+ return;
592
+ }
593
+ // Check if token has expiry information
594
+ if (!this.oauthToken.expiresAt) {
595
+ logger.debug("Token has no expiry information, assuming valid");
596
+ return;
597
+ }
598
+ // expiresAt is stored as Unix milliseconds (matching how auth status/refresh stores it).
599
+ // Compare against Date.now() so both sides are in milliseconds.
600
+ const now = Date.now();
601
+ const isExpired = this.oauthToken.expiresAt <= now;
602
+ const isExpiringSoon = this.oauthToken.expiresAt <= now + TOKEN_EXPIRY_BUFFER_MS;
603
+ if (!isExpired && !isExpiringSoon) {
604
+ logger.debug("OAuth token is still valid", {
605
+ expiresInMs: this.oauthToken.expiresAt - now,
606
+ });
607
+ return;
608
+ }
609
+ // Check if we have a refresh token
610
+ if (!this.oauthToken.refreshToken) {
611
+ if (isExpired) {
612
+ throw new AuthenticationError("OAuth token expired and no refresh token available. Please re-authenticate.", this.providerName);
613
+ }
614
+ logger.warn("OAuth token expiring soon but no refresh token available", {
615
+ expiresInMs: this.oauthToken.expiresAt - now,
616
+ });
617
+ return;
618
+ }
619
+ // Serialize concurrent refresh attempts — if a refresh is already in flight,
620
+ // wait for it rather than issuing a duplicate request.
621
+ if (this.refreshPromise) {
622
+ await this.refreshPromise;
623
+ return;
624
+ }
625
+ // Attempt to refresh the token using the correct Anthropic token endpoint.
626
+ logger.info("Refreshing OAuth token", {
627
+ isExpired,
628
+ expiresInMs: this.oauthToken.expiresAt - now,
629
+ });
630
+ // Capture the token reference before entering the async IIFE;
631
+ // the enclosing guards already verified both fields are non-null.
632
+ const tokenRef = this.oauthToken;
633
+ const refreshToken = tokenRef.refreshToken;
634
+ this.refreshPromise = (async () => {
635
+ const REFRESH_TIMEOUT_MS = 30_000;
636
+ const controller = new AbortController();
637
+ const timeoutId = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);
638
+ const response = await fetch(ANTHROPIC_TOKEN_URL, {
639
+ method: "POST",
640
+ headers: {
641
+ "Content-Type": "application/x-www-form-urlencoded",
642
+ "User-Agent": CLAUDE_CLI_USER_AGENT,
643
+ },
644
+ body: new URLSearchParams({
645
+ grant_type: "refresh_token",
646
+ refresh_token: refreshToken,
647
+ client_id: CLAUDE_CODE_CLIENT_ID,
648
+ }),
649
+ signal: controller.signal,
650
+ });
651
+ clearTimeout(timeoutId);
652
+ if (!response.ok) {
653
+ const errorText = await response.text();
654
+ throw new AuthenticationError(`Failed to refresh OAuth token: ${response.status} ${errorText}`, this.providerName);
655
+ }
656
+ const newToken = (await response.json());
657
+ // Mutate the existing oauthToken object in-place so that the fetch wrapper
658
+ // closure (which captured the object reference, not a copy) picks up the
659
+ // new accessToken automatically on the next request.
660
+ // Store expiresAt as milliseconds to match the format used by auth status/refresh.
661
+ tokenRef.accessToken = newToken.access_token;
662
+ tokenRef.refreshToken = newToken.refresh_token || tokenRef.refreshToken;
663
+ tokenRef.expiresAt = newToken.expires_in
664
+ ? Date.now() + newToken.expires_in * 1000
665
+ : undefined;
666
+ tokenRef.tokenType = newToken.token_type || "Bearer";
667
+ const updatedToken = tokenRef;
668
+ // Persist the refreshed token to disk atomically (tmp + rename) so
669
+ // subsequent provider instances and the CLI pick up the new credentials.
670
+ try {
671
+ const credentialsDir = join(homedir(), ".neurolink");
672
+ if (!existsSync(credentialsDir)) {
673
+ mkdirSync(credentialsDir, { recursive: true });
674
+ }
675
+ const credentialsPath = join(credentialsDir, "anthropic-credentials.json");
676
+ const tmpPath = `${credentialsPath}.tmp`;
677
+ const existingRaw = existsSync(credentialsPath)
678
+ ? JSON.parse(readFileSync(credentialsPath, "utf-8"))
679
+ : {};
680
+ const updated = {
681
+ ...existingRaw,
682
+ type: "oauth",
683
+ oauth: updatedToken,
684
+ updatedAt: Date.now(),
685
+ };
686
+ writeFileSync(tmpPath, JSON.stringify(updated, null, 2), {
687
+ mode: 0o600,
688
+ });
689
+ renameSync(tmpPath, credentialsPath);
690
+ logger.debug("Refreshed OAuth credentials persisted to disk");
691
+ }
692
+ catch (persistError) {
693
+ // Non-fatal: in-memory token is already updated; next CLI start will
694
+ // need a manual refresh but the current session will work.
695
+ logger.warn("Failed to persist refreshed OAuth token to disk", {
696
+ error: persistError instanceof Error
697
+ ? persistError.message
698
+ : String(persistError),
699
+ });
700
+ }
701
+ logger.info("OAuth token refreshed successfully", {
702
+ hasNewRefreshToken: !!newToken.refresh_token,
703
+ expiresIn: newToken.expires_in,
704
+ });
705
+ })();
706
+ try {
707
+ await this.refreshPromise;
708
+ }
709
+ catch (error) {
710
+ if (error instanceof AuthenticationError) {
711
+ throw error;
712
+ }
713
+ throw new AuthenticationError(`Failed to refresh OAuth token: ${error instanceof Error ? error.message : String(error)}`, this.providerName);
714
+ }
715
+ finally {
716
+ this.refreshPromise = undefined;
717
+ }
718
+ }
719
+ /**
720
+ * Get the last response metadata including rate limit information.
721
+ * @returns The last response metadata or null if no request has been made
722
+ */
723
+ getLastResponseMetadata() {
724
+ return this.lastResponseMetadata;
725
+ }
726
+ /**
727
+ * Update response metadata from API response headers.
728
+ * This should be called after each API request to track rate limits.
729
+ * @param headers - Response headers from the API
730
+ * @param requestId - Optional request ID
731
+ */
732
+ updateResponseMetadata(headers, requestId, usageUpdate) {
733
+ this.lastResponseMetadata = {
734
+ rateLimit: parseRateLimitHeaders(headers),
735
+ requestId: requestId ||
736
+ (headers instanceof Headers
737
+ ? headers.get("x-request-id") || undefined
738
+ : headers["x-request-id"]),
739
+ serverTiming: headers instanceof Headers
740
+ ? headers.get("server-timing") || undefined
741
+ : headers["server-timing"],
742
+ };
743
+ // Update usage tracking
744
+ const rateLimit = this.lastResponseMetadata.rateLimit;
745
+ if (this.usageInfo) {
746
+ this.usageInfo.requestCount++;
747
+ this.usageInfo.messagesUsed++;
748
+ this.usageInfo.lastRequestTimestamp = Date.now();
749
+ // Update token usage if provided
750
+ if (usageUpdate) {
751
+ if (usageUpdate.inputTokens !== undefined) {
752
+ this.usageInfo.inputTokensUsed += usageUpdate.inputTokens;
753
+ this.usageInfo.tokensUsed += usageUpdate.inputTokens;
754
+ }
755
+ if (usageUpdate.outputTokens !== undefined) {
756
+ this.usageInfo.outputTokensUsed += usageUpdate.outputTokens;
757
+ this.usageInfo.tokensUsed += usageUpdate.outputTokens;
758
+ }
759
+ }
760
+ // Update remaining quotas from rate limit headers
761
+ if (rateLimit?.requestsRemaining !== undefined) {
762
+ this.usageInfo.messagesRemaining = rateLimit.requestsRemaining;
763
+ }
764
+ if (rateLimit?.tokensRemaining !== undefined) {
765
+ this.usageInfo.tokensRemaining = rateLimit.tokensRemaining;
766
+ }
767
+ // Calculate quota percentages
768
+ if (rateLimit?.requestsLimit && rateLimit.requestsLimit > 0) {
769
+ this.usageInfo.messageQuotaPercent = Math.round(((rateLimit.requestsLimit - (rateLimit.requestsRemaining ?? 0)) /
770
+ rateLimit.requestsLimit) *
771
+ 100);
772
+ }
773
+ if (rateLimit?.tokensLimit && rateLimit.tokensLimit > 0) {
774
+ this.usageInfo.tokenQuotaPercent = Math.round(((rateLimit.tokensLimit - (rateLimit.tokensRemaining ?? 0)) /
775
+ rateLimit.tokensLimit) *
776
+ 100);
777
+ }
778
+ // Check for rate limiting
779
+ if (rateLimit?.retryAfter !== undefined) {
780
+ this.usageInfo.isRateLimited = true;
781
+ this.usageInfo.rateLimitExpiresAt =
782
+ Date.now() + rateLimit.retryAfter * 1000;
783
+ }
784
+ else {
785
+ this.usageInfo.isRateLimited = false;
786
+ this.usageInfo.rateLimitExpiresAt = undefined;
787
+ }
788
+ }
789
+ // Log rate limit warnings if approaching limits
790
+ if (rateLimit?.requestsRemaining !== undefined) {
791
+ if (rateLimit.requestsRemaining <= 5) {
792
+ logger.warn("Approaching Anthropic request rate limit", {
793
+ remaining: rateLimit.requestsRemaining,
794
+ limit: rateLimit.requestsLimit,
795
+ reset: rateLimit.requestsReset,
796
+ });
797
+ }
798
+ }
799
+ if (rateLimit?.tokensRemaining !== undefined) {
800
+ if (rateLimit.tokensLimit &&
801
+ rateLimit.tokensRemaining < rateLimit.tokensLimit * 0.1) {
802
+ logger.warn("Approaching Anthropic token rate limit", {
803
+ remaining: rateLimit.tokensRemaining,
804
+ limit: rateLimit.tokensLimit,
805
+ reset: rateLimit.tokensReset,
806
+ });
807
+ }
808
+ }
809
+ }
40
810
  getProviderName() {
41
811
  return "anthropic";
42
812
  }
@@ -83,7 +853,17 @@ export class AnthropicProvider extends BaseProvider {
83
853
  return new ProviderError(`Anthropic error: ${message}`, this.providerName);
84
854
  }
85
855
  // executeGenerate removed - BaseProvider handles all generation with tools
856
+ /**
857
+ * Override generate to refresh the OAuth token before delegating to
858
+ * BaseProvider so that expired tokens are renewed automatically.
859
+ */
860
+ async generate(optionsOrPrompt, analysisSchema) {
861
+ await this.refreshAuthIfNeeded();
862
+ return super.generate(optionsOrPrompt, analysisSchema);
863
+ }
86
864
  async executeStream(options, _analysisSchema) {
865
+ // Refresh OAuth token if needed before making any API request.
866
+ await this.refreshAuthIfNeeded();
87
867
  this.validateStreamOptions(options);
88
868
  const timeout = this.getTimeout(options);
89
869
  const timeoutController = createTimeoutController(timeout, this.providerName, "stream");
@@ -140,6 +920,12 @@ export class AnthropicProvider extends BaseProvider {
140
920
  }
141
921
  async isAvailable() {
142
922
  try {
923
+ // Check OAuth token first
924
+ const oauthToken = getOAuthToken();
925
+ if (oauthToken) {
926
+ return true;
927
+ }
928
+ // Fall back to API key check
143
929
  getAnthropicApiKey();
144
930
  return true;
145
931
  }
@@ -151,4 +937,8 @@ export class AnthropicProvider extends BaseProvider {
151
937
  return this.model;
152
938
  }
153
939
  }
940
+ // Re-export types and utilities for convenience
941
+ export { ModelAccessError, isModelAvailableForTier, getRecommendedModelForTier, getModelCapabilities, } from "../models/anthropicModels.js";
942
+ // Export beta headers constant for external use
943
+ export { ANTHROPIC_BETA_HEADERS };
154
944
  export default AnthropicProvider;