@juspay/neurolink 10.11.3 → 10.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,7 @@ import { buildStableClaudeCodeBillingHeader, CLAUDE_CLI_USER_AGENT, CLAUDE_CODE_
17
17
  import { clearAccountCooldown, loadAccountCooldowns, saveAccountCooldown, } from "../../proxy/accountCooldown.js";
18
18
  import { anthropicAccountKeysEqual, ENV_ANTHROPIC_ACCOUNT_KEY, isAccountAllowed, LEGACY_ANTHROPIC_ACCOUNT_KEY, shouldLoadFallbackCredential, } from "../../proxy/accountSelection.js";
19
19
  import { getUnifiedRateLimitStatus, isQuotaOverageAvailable, loadAccountQuotas, parseQuotaHeaders, saveAccountQuota, } from "../../proxy/accountQuota.js";
20
+ import { fetchAccountUsage, listAnthropicAccountsForUsage, usageToQuota, } from "../../proxy/accountUsage.js";
20
21
  import { buildProxyLimitHeaders, summarizePoolHeadroom, } from "../../proxy/quotaHeaders.js";
21
22
  import { buildClaudeError, ClaudeStreamSerializer, generateToolUseId, parseClaudeRequest, serializeClaudeResponse, } from "../../proxy/claudeFormat.js";
22
23
  import { buildAnthropicModelsListResponse, buildTranslationOptions, extractText, extractToolArgs, extractUsageFromStreamResult, handleTranslatedJsonRequest, handleTranslatedStreamRequest, hasTranslatedOutput, } from "../../proxy/proxyTranslationEngine.js";
@@ -639,6 +640,127 @@ async function seedRuntimeQuotasFromDisk(accounts) {
639
640
  // Non-fatal: seeding is best-effort; ordering falls back to probe-first.
640
641
  }
641
642
  }
643
+ // ---------------------------------------------------------------------------
644
+ // Manual limits refresh (GET /limits)
645
+ // ---------------------------------------------------------------------------
646
+ /** Minimum spacing between usage-endpoint fetches for one account. Bounds
647
+ * abuse of the ungated endpoint; inside the window the last reading is
648
+ * returned as "throttled" (still fresher than any passive snapshot). */
649
+ const MIN_USAGE_REFETCH_INTERVAL_MS = 15_000;
650
+ const lastUsageFetchAt = new Map();
651
+ let limitsRefreshInFlight = null;
652
+ const USAGE_REFRESH_CONCURRENCY = 4;
653
+ /**
654
+ * Fetch fresh limits from Anthropic's usage endpoint for every eligible OAuth
655
+ * account and write them through the exact same chain the passive header
656
+ * capture uses (runtime state → cooldown reconciliation → debounced disk
657
+ * snapshot), so routing and `auth list` see the refreshed windows and the
658
+ * automatic path keeps working unchanged on top of them.
659
+ */
660
+ async function refreshAccountLimits(options = {}) {
661
+ const fetchedAt = Date.now();
662
+ const allAccounts = await listAnthropicAccountsForUsage(options.accountAllowlist);
663
+ const accounts = options.accountFilter
664
+ ? allAccounts.filter((account) => account.label === options.accountFilter ||
665
+ account.key === options.accountFilter)
666
+ : allAccounts;
667
+ const persisted = await loadAccountQuotas().catch(() => ({}));
668
+ const buildResult = (account, status, quota, error) => {
669
+ const state = accountRuntimeState.get(account.key);
670
+ const result = {
671
+ account: account.label,
672
+ key: account.key,
673
+ type: account.type,
674
+ status,
675
+ quota: quota ?? state?.quota ?? persisted[account.label] ?? null,
676
+ };
677
+ if (error !== undefined) {
678
+ result.error = error;
679
+ }
680
+ if (state?.coolingUntil && state.coolingUntil > Date.now()) {
681
+ result.coolingUntil = state.coolingUntil;
682
+ if (state.coolingReason) {
683
+ result.coolingReason = state.coolingReason;
684
+ }
685
+ }
686
+ return result;
687
+ };
688
+ if (options.snapshotOnly) {
689
+ return {
690
+ fetchedAt,
691
+ snapshot: true,
692
+ results: accounts.map((account) => buildResult(account, "snapshot", null)),
693
+ };
694
+ }
695
+ const results = new Array(accounts.length);
696
+ let nextIndex = 0;
697
+ const worker = async () => {
698
+ for (;;) {
699
+ const index = nextIndex++;
700
+ if (index >= accounts.length) {
701
+ return;
702
+ }
703
+ const account = accounts[index];
704
+ if (account.type !== "oauth") {
705
+ results[index] = buildResult(account, "skipped_api_key", null);
706
+ continue;
707
+ }
708
+ const lastFetch = lastUsageFetchAt.get(account.key) ?? 0;
709
+ if (Date.now() - lastFetch < MIN_USAGE_REFETCH_INTERVAL_MS) {
710
+ results[index] = buildResult(account, "throttled", null);
711
+ continue;
712
+ }
713
+ lastUsageFetchAt.set(account.key, Date.now());
714
+ // Isolate failures per account: an unexpected rejection must not abort
715
+ // the Promise.all sweep and turn the whole /limits response into a 502.
716
+ try {
717
+ const fetchResult = await fetchAccountUsage(account);
718
+ // `=== false` (not `!ok`) — the react-hooks sub-build compiles this
719
+ // file without strictNullChecks, where negated boolean-discriminant
720
+ // narrowing does not apply.
721
+ if (fetchResult.ok === false) {
722
+ results[index] = buildResult(account, "error", null, fetchResult.error);
723
+ continue;
724
+ }
725
+ const state = getOrCreateRuntimeState(account.key);
726
+ const capturedAt = Date.now();
727
+ const quota = usageToQuota(fetchResult.usage, {
728
+ now: capturedAt,
729
+ prior: state.quota ?? persisted[account.label] ?? null,
730
+ });
731
+ if (!quota) {
732
+ results[index] = buildResult(account, "error", null, "usage payload had no recognizable limit windows");
733
+ continue;
734
+ }
735
+ // Guard against a passive header capture that landed mid-fetch: never
736
+ // replace a fresher runtime snapshot with an older reading.
737
+ if (quota.lastUpdated >= (state.quota?.lastUpdated ?? 0)) {
738
+ state.quota = quota;
739
+ }
740
+ const cooldownUpdate = reconcileCooldownFromQuota(state, quota, capturedAt);
741
+ if (cooldownUpdate?.kind === "cooled") {
742
+ await saveAccountCooldown(account.key, cooldownUpdate.coolingUntil, cooldownUpdate.coolingReason).catch(() => {
743
+ // Non-fatal: cooldown is already active in memory.
744
+ });
745
+ }
746
+ else if (cooldownUpdate?.kind === "cleared") {
747
+ await clearAccountCooldown(account.key, cooldownUpdate.coolingUntil).catch(() => {
748
+ // Non-fatal: the next successful response will reconcile again.
749
+ });
750
+ }
751
+ await saveAccountQuota(account.label, quota).catch(() => {
752
+ // Non-fatal: quota persistence is best-effort
753
+ });
754
+ results[index] = buildResult(account, "refreshed", quota);
755
+ }
756
+ catch (err) {
757
+ results[index] = buildResult(account, "error", null, err instanceof Error ? err.message : String(err));
758
+ }
759
+ }
760
+ };
761
+ await Promise.all(Array.from({ length: Math.min(USAGE_REFRESH_CONCURRENCY, accounts.length || 1) }, () => worker()));
762
+ return { fetchedAt, snapshot: false, results };
763
+ }
642
764
  /** Quota-aware selection is on by default; disable with
643
765
  * NEUROLINK_PROXY_QUOTA_ROUTING=off|false|0. Only affects the fill-first
644
766
  * strategy (round-robin keeps strict rotation). */
@@ -5037,6 +5159,45 @@ export function createClaudeProxyRoutes(modelRouter, basePath = "", accountStrat
5037
5159
  description: "Count tokens for a messages request",
5038
5160
  tags: ["claude-proxy", "tokens"],
5039
5161
  },
5162
+ // =====================================================================
5163
+ // GET /limits -- Fresh account limits from Anthropic's usage endpoint
5164
+ // =====================================================================
5165
+ {
5166
+ method: "GET",
5167
+ path: `${basePath}/limits`,
5168
+ handler: async (ctx) => {
5169
+ const effectiveAllowlist = runtimeConfigProvider
5170
+ ? runtimeConfigProvider().accountAllowlist
5171
+ : accountAllowlist;
5172
+ const snapshotOnly = ctx.query?.snapshot === "true" || ctx.query?.snapshot === "1";
5173
+ const accountFilter = ctx.query?.account;
5174
+ return withSpan({
5175
+ name: "neurolink.http.claudeProxy.limits",
5176
+ tracer: tracers.http,
5177
+ attributes: { "http.route": `${basePath}/limits` },
5178
+ }, async () => {
5179
+ // Single-flight: concurrent full refreshes share one sweep.
5180
+ if (!snapshotOnly && !accountFilter) {
5181
+ if (!limitsRefreshInFlight) {
5182
+ limitsRefreshInFlight = refreshAccountLimits({
5183
+ accountAllowlist: effectiveAllowlist,
5184
+ }).finally(() => {
5185
+ limitsRefreshInFlight = null;
5186
+ });
5187
+ }
5188
+ return limitsRefreshInFlight;
5189
+ }
5190
+ return refreshAccountLimits({
5191
+ accountAllowlist: effectiveAllowlist,
5192
+ accountFilter,
5193
+ snapshotOnly,
5194
+ });
5195
+ });
5196
+ },
5197
+ description: "Fetch fresh per-account limits from Anthropic (usage API). " +
5198
+ "?account=<label> for one account, ?snapshot=true for stored state",
5199
+ tags: ["claude-proxy", "limits"],
5200
+ },
5040
5201
  ],
5041
5202
  };
5042
5203
  }
@@ -5340,6 +5501,11 @@ export const __testHooks = {
5340
5501
  maybeResetPrimaryToHome,
5341
5502
  planCooldownFor429,
5342
5503
  reconcileCooldownFromQuota,
5504
+ refreshAccountLimits,
5505
+ clearLimitsRefreshStateForTests: () => {
5506
+ lastUsageFetchAt.clear();
5507
+ limitsRefreshInFlight = null;
5508
+ },
5343
5509
  isRetryableNetworkError,
5344
5510
  isPermanentRefreshFailure,
5345
5511
  getStreamFailureDetails,
@@ -11,6 +11,7 @@ import type { PPTGenerationResult } from "./ppt.js";
11
11
  import type { AvatarResult } from "./avatar.js";
12
12
  import type { MusicResult } from "./music.js";
13
13
  import type { OAuthTokens } from "./auth.js";
14
+ import type { AccountQuota } from "./proxy.js";
14
15
  import type { ClaudeSubscriptionTier } from "./subscription.js";
15
16
  import type { ServerFramework } from "./server.js";
16
17
  import type { AuthProviderType } from "./auth.js";
@@ -947,6 +948,8 @@ export type AuthCommandArgs = BaseCommandArgs & {
947
948
  label?: string;
948
949
  account?: string;
949
950
  force?: boolean;
951
+ /** `auth list --refresh`: fetch fresh limits from Anthropic before listing */
952
+ refresh?: boolean;
950
953
  /** Path to the proxy config YAML, used by set-/get-/clear-primary */
951
954
  config?: string;
952
955
  /** Email passed to `auth set-primary <email>` */
@@ -954,6 +957,15 @@ export type AuthCommandArgs = BaseCommandArgs & {
954
957
  /** Yargs positional arguments */
955
958
  _?: (string | number)[];
956
959
  };
960
+ /** Outcome of the `auth list --refresh` fresh-limit fetch. */
961
+ export type AuthListRefreshOutcome = {
962
+ /** How the fresh limits were obtained ("none" when every path failed). */
963
+ via: "proxy" | "direct" | "none";
964
+ /** Freshly fetched quotas keyed by account label; null when none fetched. */
965
+ quotas: Record<string, AccountQuota> | null;
966
+ /** Per-account and transport errors, already formatted for display. */
967
+ errors: string[];
968
+ };
957
969
  /** Telemetry command arguments */
958
970
  export type TelemetryCommandArgs = {
959
971
  format?: "text" | "json" | "table";
@@ -943,6 +943,107 @@ export type AccountQuota = {
943
943
  overageStatus: string;
944
944
  /** Epoch ms when we last captured this data */
945
945
  lastUpdated: number;
946
+ /** Dynamic per-plan limit buckets from the usage API `limits[]` array
947
+ * (session / weekly_all / model-scoped weeklies such as Fable / future
948
+ * kinds). Absent on purely header-sourced snapshots. */
949
+ windows?: AccountQuotaWindow[];
950
+ /** Epoch ms when `windows` was last refreshed from the usage API. */
951
+ windowsUpdatedAt?: number;
952
+ /** Provenance of this snapshot's numbers. */
953
+ source?: AccountQuotaSource;
954
+ };
955
+ /** Where an AccountQuota snapshot came from.
956
+ * - "headers" : passive capture of anthropic-ratelimit-unified-* response
957
+ * headers on a routed request (the automatic path).
958
+ * - "usage-api" : an explicit refresh against Anthropic's OAuth usage
959
+ * endpoint (manual refetch path). */
960
+ export type AccountQuotaSource = "headers" | "usage-api";
961
+ /** One dynamic limit bucket from the usage API. Provider vocabulary (`kind`,
962
+ * `group`, `severity`) is preserved verbatim so buckets Anthropic adds later
963
+ * survive storage and display without a code change. */
964
+ export type AccountQuotaWindow = {
965
+ /** Provider kind, verbatim ("session", "weekly_all", "weekly_scoped", ...). */
966
+ kind: string;
967
+ /** Provider group, verbatim ("session" | "weekly" | future values). */
968
+ group?: string;
969
+ /** 0.0-1.0 utilization (provider percent / 100). */
970
+ used: number;
971
+ /** Provider severity, verbatim ("normal", ...). */
972
+ severity?: string;
973
+ /** Derived "allowed" | "rejected" (see usageToQuota status mapping). */
974
+ status: string;
975
+ /** Unix timestamp (seconds) when this window resets; 0 when unparseable. */
976
+ resetsAt: number;
977
+ isActive?: boolean;
978
+ /** Model display name for model-scoped windows (e.g. "Fable"). */
979
+ scopeModel?: string;
980
+ /** Surface scope when the provider reports one. */
981
+ scopeSurface?: string;
982
+ };
983
+ /** One utilization window from the OAuth usage endpoint (wire shape, loose). */
984
+ export type AnthropicUsageWindow = {
985
+ /** 0-100 percent (note: NOT the 0-1 fraction used by headers). */
986
+ utilization?: number | null;
987
+ /** ISO-8601 timestamp. */
988
+ resets_at?: string | null;
989
+ };
990
+ /** One entry of the usage endpoint's generic `limits[]` array (wire shape). */
991
+ export type AnthropicUsageLimit = {
992
+ kind?: string;
993
+ group?: string;
994
+ /** 0-100 percent. */
995
+ percent?: number | null;
996
+ severity?: string | null;
997
+ resets_at?: string | null;
998
+ scope?: {
999
+ model?: {
1000
+ id?: string | null;
1001
+ display_name?: string | null;
1002
+ } | null;
1003
+ surface?: string | null;
1004
+ } | null;
1005
+ is_active?: boolean | null;
1006
+ };
1007
+ /** Response body of GET https://api.anthropic.com/api/oauth/usage (loose —
1008
+ * unknown keys are ignored, known keys may be absent or null). */
1009
+ export type AnthropicUsageResponse = {
1010
+ five_hour?: AnthropicUsageWindow | null;
1011
+ seven_day?: AnthropicUsageWindow | null;
1012
+ limits?: AnthropicUsageLimit[] | null;
1013
+ extra_usage?: {
1014
+ is_enabled?: boolean | null;
1015
+ } | null;
1016
+ };
1017
+ /** Outcome of one account's usage-endpoint fetch. Return-not-throw. */
1018
+ export type AccountUsageFetchResult = {
1019
+ ok: true;
1020
+ usage: AnthropicUsageResponse;
1021
+ } | {
1022
+ ok: false;
1023
+ reason: "not_oauth" | "auth" | "http" | "network" | "parse";
1024
+ error: string;
1025
+ status?: number;
1026
+ };
1027
+ /** Per-account result inside a GET /limits response. */
1028
+ export type ProxyLimitsAccountResult = {
1029
+ /** Account label (quota-store key). */
1030
+ account: string;
1031
+ /** Token-store key ("anthropic:<label>"). */
1032
+ key: string;
1033
+ type: ProxyAccountType;
1034
+ status: "refreshed" | "throttled" | "skipped_api_key" | "snapshot" | "error";
1035
+ /** Fresh quota on "refreshed"; last known snapshot otherwise (may be null). */
1036
+ quota: AccountQuota | null;
1037
+ error?: string;
1038
+ coolingUntil?: number;
1039
+ coolingReason?: AccountCoolingReason;
1040
+ };
1041
+ /** Response body of the proxy's GET /limits endpoint. */
1042
+ export type ProxyLimitsRefreshResponse = {
1043
+ fetchedAt: number;
1044
+ /** True when served from stored state without contacting Anthropic. */
1045
+ snapshot: boolean;
1046
+ results: ProxyLimitsAccountResult[];
946
1047
  };
947
1048
  /**
948
1049
  * Provenance of the quota numbers attached to a single proxy response.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "10.11.3",
3
+ "version": "10.12.1",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {
@@ -163,7 +163,7 @@
163
163
  "test:system-messages": "npx tsx test/continuous-test-suite-system-messages.ts",
164
164
  "test:test-stubs": "npx tsx test/continuous-test-suite-test-stubs.ts",
165
165
  "test:tool-routing-semantic": "npx tsx test/continuous-test-suite-tool-routing-semantic.ts",
166
- "test:unit": "pnpm run test:envguard && pnpm run test:bugfixes && pnpm run test:file-detector-extension && pnpm run test:file-detector-magic-bytes && pnpm run test:mcp:infra && pnpm run test:mcp:bash && pnpm run test:mcp:limits && pnpm run test:mcp:spans && pnpm run test:autoresearch:redis && pnpm run test:tool-routing && pnpm run test:tool-routing-cli && pnpm run test:tool-dedup && pnpm run test:model-pool && pnpm run test:litellm-context && pnpm run test:dedup-execute-map && pnpm run test:step-budget-guard && pnpm run test:agent-plumbing && pnpm run test:tool-execution-recorder && pnpm run test:proxy-terminal-errors && pnpm run test:system-messages && pnpm run test:tool-routing-semantic && pnpm run test:anthropic-tools-policy && pnpm run test:anthropic-structured && pnpm run test:sagemaker-tools && pnpm run test:anthropic-multimodal && pnpm run test:excel-interop && pnpm run test:model-capabilities && pnpm run test:agent-runtime:vitest && pnpm run test:agent-delegation && pnpm run test:retry-after:vitest && pnpm run test:sampling-params && pnpm run test:structured-recovery && pnpm run test:prompt-redaction && pnpm run test:mcp-result-cache && pnpm run test:test-stubs && pnpm run test:model-not-found-retryable && pnpm run test:websearch-grounding",
166
+ "test:unit": "pnpm run test:envguard && pnpm run test:bugfixes && pnpm run test:file-detector-extension && pnpm run test:file-detector-magic-bytes && pnpm run test:mcp:infra && pnpm run test:mcp:bash && pnpm run test:mcp:limits && pnpm run test:mcp:spans && pnpm run test:autoresearch:redis && pnpm run test:tool-routing && pnpm run test:tool-routing-cli && pnpm run test:tool-dedup && pnpm run test:model-pool && pnpm run test:litellm-context && pnpm run test:dedup-execute-map && pnpm run test:step-budget-guard && pnpm run test:agent-plumbing && pnpm run test:tool-execution-recorder && pnpm run test:proxy-terminal-errors && pnpm run test:proxy-usage-refresh && pnpm run test:system-messages && pnpm run test:tool-routing-semantic && pnpm run test:anthropic-tools-policy && pnpm run test:anthropic-structured && pnpm run test:sagemaker-tools && pnpm run test:anthropic-multimodal && pnpm run test:excel-interop && pnpm run test:model-capabilities && pnpm run test:agent-runtime:vitest && pnpm run test:agent-delegation && pnpm run test:retry-after:vitest && pnpm run test:sampling-params && pnpm run test:structured-recovery && pnpm run test:prompt-redaction && pnpm run test:mcp-result-cache && pnpm run test:test-stubs && pnpm run test:model-not-found-retryable && pnpm run test:websearch-grounding",
167
167
  "// CI tier — live providers, runs only when API keys are present (test:credentials and test:dynamic make real provider calls when keys are set, so they live here, not in test:unit)": "",
168
168
  "test:live": "pnpm run test:providers && pnpm run test:mcp:http && pnpm run test:mcp:sdk && pnpm run test:mcp:cli && pnpm run test:observability && pnpm run test:context && pnpm run test:memory && pnpm run test:tool-reliability && pnpm run test:evaluation && pnpm run test:autoresearch && pnpm run test:credentials && pnpm run test:dynamic",
169
169
  "// CI tier — product output (image/video/TTS/PPT) — costs $$ per run": "",
@@ -233,6 +233,7 @@
233
233
  "test:tool-execution-recorder": "npx tsx test/continuous-test-suite-tool-execution-recorder.ts",
234
234
  "test:proxy-terminal-errors": "npx tsx test/continuous-test-suite-proxy-terminal-errors.ts",
235
235
  "test:proxy-limit-headers": "npx tsx test/continuous-test-suite-proxy-limit-headers.ts",
236
+ "test:proxy-usage-refresh": "npx tsx test/continuous-test-suite-proxy-usage-refresh.ts",
236
237
  "test:anthropic-limit-capture": "npx tsx test/continuous-test-suite-anthropic-limit-capture.ts",
237
238
  "test:audio": "npx tsx test/continuous-test-suite-audio.ts",
238
239
  "test:file-formats": "npx tsx test/continuous-test-suite-file-formats.ts",