@juspay/neurolink 9.87.3 → 9.88.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 (47) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/browser/neurolink.min.js +381 -381
  3. package/dist/cli/commands/proxy.d.ts +16 -1
  4. package/dist/cli/commands/proxy.js +275 -238
  5. package/dist/cli/factories/commandFactory.d.ts +39 -0
  6. package/dist/cli/factories/commandFactory.js +484 -3
  7. package/dist/core/conversationMemoryManager.d.ts +11 -1
  8. package/dist/core/conversationMemoryManager.js +44 -0
  9. package/dist/core/redisConversationMemoryManager.d.ts +12 -1
  10. package/dist/core/redisConversationMemoryManager.js +80 -0
  11. package/dist/lib/core/conversationMemoryManager.d.ts +11 -1
  12. package/dist/lib/core/conversationMemoryManager.js +44 -0
  13. package/dist/lib/core/redisConversationMemoryManager.d.ts +12 -1
  14. package/dist/lib/core/redisConversationMemoryManager.js +80 -0
  15. package/dist/lib/neurolink.d.ts +27 -0
  16. package/dist/lib/neurolink.js +133 -0
  17. package/dist/lib/proxy/globalInstaller.d.ts +5 -0
  18. package/dist/lib/proxy/globalInstaller.js +156 -0
  19. package/dist/lib/proxy/openaiFormat.d.ts +3 -1
  20. package/dist/lib/proxy/openaiFormat.js +19 -4
  21. package/dist/lib/proxy/proxyActivity.d.ts +8 -0
  22. package/dist/lib/proxy/proxyActivity.js +77 -0
  23. package/dist/lib/server/routes/claudeProxyRoutes.d.ts +56 -6
  24. package/dist/lib/server/routes/claudeProxyRoutes.js +208 -50
  25. package/dist/lib/server/routes/openaiProxyRoutes.js +47 -6
  26. package/dist/lib/types/cli.d.ts +4 -0
  27. package/dist/lib/types/conversation.d.ts +36 -0
  28. package/dist/lib/types/conversationMemoryInterface.d.ts +5 -1
  29. package/dist/lib/types/proxy.d.ts +49 -0
  30. package/dist/lib/utils/fileDetector.js +34 -10
  31. package/dist/neurolink.d.ts +27 -0
  32. package/dist/neurolink.js +133 -0
  33. package/dist/proxy/globalInstaller.d.ts +5 -0
  34. package/dist/proxy/globalInstaller.js +155 -0
  35. package/dist/proxy/openaiFormat.d.ts +3 -1
  36. package/dist/proxy/openaiFormat.js +19 -4
  37. package/dist/proxy/proxyActivity.d.ts +8 -0
  38. package/dist/proxy/proxyActivity.js +76 -0
  39. package/dist/server/routes/claudeProxyRoutes.d.ts +56 -6
  40. package/dist/server/routes/claudeProxyRoutes.js +208 -50
  41. package/dist/server/routes/openaiProxyRoutes.js +47 -6
  42. package/dist/types/cli.d.ts +4 -0
  43. package/dist/types/conversation.d.ts +36 -0
  44. package/dist/types/conversationMemoryInterface.d.ts +5 -1
  45. package/dist/types/proxy.d.ts +49 -0
  46. package/dist/utils/fileDetector.js +34 -10
  47. package/package.json +3 -2
@@ -651,7 +651,7 @@ export function convertClaudeToOpenAIResponse(claude, requestModel) {
651
651
  * - message_delta -> captures stop_reason and output token usage
652
652
  * - message_stop -> emits the final `finish_reason` chunk + `[DONE]`
653
653
  */
654
- export function createClaudeToOpenAIStreamTransform(requestModel) {
654
+ export function createClaudeToOpenAIStreamTransform(requestModel, options = {}) {
655
655
  const serializer = new OpenAIStreamSerializer(requestModel);
656
656
  const encoder = new TextEncoder();
657
657
  const decoder = new TextDecoder();
@@ -677,6 +677,9 @@ export function createClaudeToOpenAIStreamTransform(requestModel) {
677
677
  catch {
678
678
  return;
679
679
  }
680
+ if (finished) {
681
+ return;
682
+ }
680
683
  switch (eventName) {
681
684
  case "message_start": {
682
685
  const message = (data.message ?? {});
@@ -749,8 +752,18 @@ export function createClaudeToOpenAIStreamTransform(requestModel) {
749
752
  }
750
753
  return;
751
754
  }
755
+ case "error": {
756
+ const error = (data.error ?? {});
757
+ const message = typeof error.message === "string"
758
+ ? error.message
759
+ : "Anthropic stream failed";
760
+ finished = true;
761
+ options.onError?.(message);
762
+ emit(controller, serializer.emitError(message));
763
+ return;
764
+ }
752
765
  default:
753
- // ping, error, and unknown events are ignored.
766
+ // ping and unknown events are ignored.
754
767
  return;
755
768
  }
756
769
  };
@@ -790,10 +803,12 @@ export function createClaudeToOpenAIStreamTransform(requestModel) {
790
803
  // closing `\n\n` is not silently lost.
791
804
  buffer += decoder.decode();
792
805
  drainBufferedEvents(controller);
793
- // If the upstream closed without a message_stop, still finalize.
806
+ // Closing without message_stop is an interrupted stream, not success.
794
807
  if (!finished) {
795
808
  finished = true;
796
- emit(controller, serializer.finish(stopReason, usage));
809
+ const message = "Anthropic stream ended before message_stop";
810
+ options.onError?.(message);
811
+ emit(controller, serializer.emitError(message));
797
812
  }
798
813
  },
799
814
  });
@@ -0,0 +1,8 @@
1
+ import type { ProxyActivitySnapshot } from "../types/index.js";
2
+ /** Track one client-facing proxy request until its response body settles. */
3
+ export declare function beginProxyRequest(): () => void;
4
+ export declare function getProxyActivitySnapshot(): ProxyActivitySnapshot;
5
+ export declare function isProxyActivityQuiet(snapshot: ProxyActivitySnapshot, quietThresholdMs: number, nowMs?: number): boolean;
6
+ /** Keep activity open until the response body completes, errors, or is cancelled. */
7
+ export declare function trackProxyResponse(response: Response, finishRequest: () => void): Response;
8
+ export declare function resetProxyActivityForTests(): void;
@@ -0,0 +1,77 @@
1
+ let activeRequests = 0;
2
+ let lastActivityAtMs = null;
3
+ function touchActivity() {
4
+ lastActivityAtMs = Date.now();
5
+ }
6
+ /** Track one client-facing proxy request until its response body settles. */
7
+ export function beginProxyRequest() {
8
+ activeRequests += 1;
9
+ touchActivity();
10
+ let finished = false;
11
+ return () => {
12
+ if (finished) {
13
+ return;
14
+ }
15
+ finished = true;
16
+ activeRequests = Math.max(0, activeRequests - 1);
17
+ touchActivity();
18
+ };
19
+ }
20
+ export function getProxyActivitySnapshot() {
21
+ return {
22
+ activeRequests,
23
+ lastActivityAt: lastActivityAtMs === null ? null : new Date(lastActivityAtMs),
24
+ };
25
+ }
26
+ export function isProxyActivityQuiet(snapshot, quietThresholdMs, nowMs = Date.now()) {
27
+ if (snapshot.activeRequests > 0) {
28
+ return false;
29
+ }
30
+ if (snapshot.lastActivityAt === null) {
31
+ return true;
32
+ }
33
+ return nowMs - snapshot.lastActivityAt.getTime() >= quietThresholdMs;
34
+ }
35
+ /** Keep activity open until the response body completes, errors, or is cancelled. */
36
+ export function trackProxyResponse(response, finishRequest) {
37
+ if (!response.body) {
38
+ finishRequest();
39
+ return response;
40
+ }
41
+ const reader = response.body.getReader();
42
+ const trackedBody = new ReadableStream({
43
+ async pull(controller) {
44
+ try {
45
+ const { value, done } = await reader.read();
46
+ if (done) {
47
+ finishRequest();
48
+ controller.close();
49
+ return;
50
+ }
51
+ controller.enqueue(value);
52
+ }
53
+ catch (error) {
54
+ finishRequest();
55
+ controller.error(error);
56
+ }
57
+ },
58
+ async cancel(reason) {
59
+ try {
60
+ await reader.cancel(reason);
61
+ }
62
+ finally {
63
+ finishRequest();
64
+ }
65
+ },
66
+ });
67
+ return new Response(trackedBody, {
68
+ status: response.status,
69
+ statusText: response.statusText,
70
+ headers: response.headers,
71
+ });
72
+ }
73
+ export function resetProxyActivityForTests() {
74
+ activeRequests = 0;
75
+ lastActivityAtMs = null;
76
+ }
77
+ //# sourceMappingURL=proxyActivity.js.map
@@ -13,7 +13,7 @@ import { buildTranslationOptions } from "../../proxy/proxyTranslationEngine.js";
13
13
  import type { ModelRouter } from "../../proxy/modelRouter.js";
14
14
  import { ProxyTracer } from "../../proxy/proxyTracer.js";
15
15
  import { isPermanentRefreshFailure } from "../../proxy/tokenRefresh.js";
16
- import type { AccountAllowlist, AccountCooldownPlan, AccountQuota, AnthropicAttemptLogger, AnthropicAuthRetryResult, AnthropicLoopState, AnthropicSuccessResult, AnthropicUpstreamFetchResult, ClaudeFinalRequestLogger, ClaudeRequest, ParsedClaudeError, ProxyBodyCaptureLogger, ProxyPassthroughAccount, RouteGroup, RuntimeAccountState, ServerContext, StreamTerminalOutcome } from "../../types/index.js";
16
+ import type { AccountAllowlist, AccountCooldownPlan, AccountQuota, AnthropicAttemptLogger, AnthropicAuthRetryResult, AnthropicLoopState, AnthropicSuccessResult, AnthropicUpstreamFetchResult, ClaudeFinalRequestLogger, ClaudeLoggedErrorBuilder, ClaudeRequest, ParsedClaudeError, ProxyBodyCaptureLogger, ProxyPassthroughAccount, RouteGroup, RuntimeAccountState, ServerContext, StreamTerminalOutcome } from "../../types/index.js";
17
17
  /** Resolve the configured primary's stable key to its current index in the
18
18
  * request's enabledAccounts list. Returns 0 (insertion-order fallback) when
19
19
  * no key is configured or the key cannot be matched (account disabled/
@@ -62,17 +62,24 @@ declare function planCooldownFor429(quota: AccountQuota | null, retryAfterMs: nu
62
62
  declare function seedRuntimeQuotasFromDisk(accounts: ProxyPassthroughAccount[]): Promise<void>;
63
63
  /**
64
64
  * Order accounts to MAXIMIZE quota utilization (fill-first, smart order):
65
- * spend the account whose window refreshes SOONEST first, so its about-to-reset
65
+ * spend the window that expires SOONEST first, so its about-to-reset
66
66
  * allowance isn't wasted, then move to accounts with longer-dated resets.
67
67
  *
68
68
  * Priority among usable accounts:
69
69
  * 1. no quota data yet — probe first: one request reveals its windows and
70
70
  * self-corrects the ordering. (Ranking unknowns last would starve them
71
71
  * forever: never picked → never observed → never comparable.)
72
- * 2. soonest WEEKLY (7d) reset — the scarce, use-it-or-lose-it ceiling
73
- * 3. soonest SESSION (5h) reset
74
- * 4. highest weekly utilization finish off the one closest to done
75
- * 5. configured primary account, then insertion order
72
+ * 2. session headroom before session-saturated (>= soft limit or
73
+ * "throttled") saturated accounts then follow the same bucketed
74
+ * session ordering below: soonest back in service first, weekly
75
+ * deciding same-bucket ties.
76
+ * 3. soonest SESSION (5h) reset — the capacity expiring soonest; compared
77
+ * in tolerance buckets so near-simultaneous resets count as equal.
78
+ * 4. soonest WEEKLY (7d) reset — decides between same-bucket sessions.
79
+ * 5. highest weekly utilization — finish off the one closest to done
80
+ * 6. configured primary account, then insertion order
81
+ * An account with NO ticking session window (fresh, not yet started) has
82
+ * nothing expiring and sorts after ticking windows in step 3.
76
83
  * Cooling/rejected accounts sort last, soonest-back-to-service first, as
77
84
  * last resort.
78
85
  */
@@ -81,6 +88,47 @@ declare function trackUpstreamReadableStream(source: ReadableStream<Uint8Array>)
81
88
  stream: ReadableStream<Uint8Array>;
82
89
  outcome: Promise<StreamTerminalOutcome>;
83
90
  };
91
+ declare function executeClaudeFallbackTranslation(args: {
92
+ ctx: ServerContext;
93
+ body: ClaudeRequest;
94
+ tracer?: ProxyTracer;
95
+ requestStartTime: number;
96
+ logProxyBody: ProxyBodyCaptureLogger;
97
+ logFinalRequest: (status: number, accountLabel: string, accountType: string, errorType?: string, errorMessage?: string, extra?: {
98
+ inputTokens?: number;
99
+ outputTokens?: number;
100
+ cacheCreationTokens?: number;
101
+ cacheReadTokens?: number;
102
+ }) => void;
103
+ options: Parameters<ServerContext["neurolink"]["stream"]>[0];
104
+ providerLabel: string;
105
+ }): Promise<unknown>;
106
+ declare function executeClaudeFallbackWithRetry(args: Parameters<typeof executeClaudeFallbackTranslation>[0]): Promise<unknown>;
107
+ declare function buildClaudeAnthropicFailureResponse(args: {
108
+ tracer?: ProxyTracer;
109
+ requestStartTime: number;
110
+ authFailureMessage: string | null;
111
+ authCooldownMessage: string | null;
112
+ invalidRequestFailure: {
113
+ status: number;
114
+ body: string;
115
+ contentType?: string;
116
+ } | null;
117
+ sawNetworkError: boolean;
118
+ sawTransientFailure: boolean;
119
+ sawRateLimit: boolean;
120
+ lastError: unknown;
121
+ fallbackFailureMessage?: string;
122
+ orderedAccounts: ProxyPassthroughAccount[];
123
+ buildLoggedClaudeError: ClaudeLoggedErrorBuilder;
124
+ logProxyBody: ProxyBodyCaptureLogger;
125
+ logFinalRequest: (status: number, accountLabel: string, accountType: string, errorType?: string, errorMessage?: string, extra?: {
126
+ inputTokens?: number;
127
+ outputTokens?: number;
128
+ cacheCreationTokens?: number;
129
+ cacheReadTokens?: number;
130
+ }) => void;
131
+ }): unknown;
84
132
  declare function handleAnthropicStreamingSuccessResponse(args: {
85
133
  ctx: ServerContext;
86
134
  body: ClaudeRequest;
@@ -249,5 +297,7 @@ export declare const __testHooks: {
249
297
  waitForTransientAccountAvailability: typeof waitForTransientAccountAvailability;
250
298
  describeTransportError: typeof describeTransportError;
251
299
  shouldAttemptClaudeFallback: typeof shouldAttemptClaudeFallback;
300
+ executeClaudeFallbackWithRetry: typeof executeClaudeFallbackWithRetry;
301
+ buildClaudeAnthropicFailureResponse: typeof buildClaudeAnthropicFailureResponse;
252
302
  };
253
303
  export {};