@juspay/neurolink 9.81.3 → 9.82.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.
@@ -17,6 +17,7 @@ import ora from "ora";
17
17
  import { buildProxyHealthResponse, createProxyReadinessState, markProxyReady, waitForProxyReadiness, } from "../../lib/proxy/proxyHealth.js";
18
18
  import { logger } from "../../lib/utils/logger.js";
19
19
  import { formatUptime, isProcessRunning, StateFileManager, } from "../utils/serverUtils.js";
20
+ import { configureProxyKeepAliveDispatcher } from "../../lib/proxy/proxyDispatcher.js";
20
21
  import { loadProxyEnvFile, resolveProxyEnvFile, } from "../../lib/proxy/proxyEnv.js";
21
22
  import { createRequire } from "node:module";
22
23
  import { fileURLToPath } from "node:url";
@@ -1285,6 +1286,10 @@ async function startProxyCommandHandler(argv) {
1285
1286
  await ensureProxyStartAllowed(spinner);
1286
1287
  }
1287
1288
  const loadedEnvFile = await loadProxyStartEnv(argv, spinner);
1289
+ // Reuse upstream TCP connections (longer keep-alive + bounded pool) instead
1290
+ // of opening a new flow per request — cuts outbound flow churn through host
1291
+ // content-filters. Runs once, after env load so it can be tuned via env.
1292
+ configureProxyKeepAliveDispatcher();
1288
1293
  const { neurolink, cleanupLogs } = await createProxyNeurolinkRuntime(devPaths?.logsDir);
1289
1294
  const { proxyConfig, strategy, modelRouter, passthrough, primaryAccountKey, } = await loadProxyStartConfiguration(argv, spinner);
1290
1295
  if (spinner) {
@@ -35,8 +35,9 @@ export declare class CLICommandFactory {
35
35
  private static validateAnthropicSubscriptionOptions;
36
36
  private static handleOutput;
37
37
  /**
38
- * Helper method to handle TTS audio file output
38
+ * Helper method to handle TTS audio file output and playback
39
39
  * Saves audio to file when --tts-output flag is provided
40
+ * Plays audio when --tts-play flag is provided
40
41
  */
41
42
  private static handleTTSOutput;
42
43
  /**
@@ -20,6 +20,7 @@ import { handleError } from "../errorHandler.js";
20
20
  import { LoopSession } from "../loop/session.js";
21
21
  import { initializeCliParser } from "../parser.js";
22
22
  import { formatFileSize, saveAudioToFile } from "../utils/audioFileUtils.js";
23
+ import { playAudio } from "../utils/audioPlayer.js";
23
24
  import { resolveFilePaths } from "../utils/pathResolver.js";
24
25
  import { animatedWrite } from "../utils/typewriter.js";
25
26
  import { createStreamAbortHandler } from "../utils/abortHandler.js";
@@ -1040,13 +1041,15 @@ export class CLICommandFactory {
1040
1041
  }
1041
1042
  }
1042
1043
  /**
1043
- * Helper method to handle TTS audio file output
1044
+ * Helper method to handle TTS audio file output and playback
1044
1045
  * Saves audio to file when --tts-output flag is provided
1046
+ * Plays audio when --tts-play flag is provided
1045
1047
  */
1046
1048
  static async handleTTSOutput(result, options) {
1047
- // Check if --tts-output flag is provided
1048
1049
  const ttsOutputPath = options.ttsOutput;
1049
- if (!ttsOutputPath) {
1050
+ const shouldPlay = options.ttsPlay;
1051
+ // Nothing to do if neither save nor play is requested
1052
+ if (!ttsOutputPath && !shouldPlay) {
1050
1053
  return;
1051
1054
  }
1052
1055
  // Extract audio from result with proper type checking
@@ -1061,20 +1064,36 @@ export class CLICommandFactory {
1061
1064
  }
1062
1065
  return;
1063
1066
  }
1064
- try {
1065
- // Save audio to file
1066
- const saveResult = await saveAudioToFile(audio, ttsOutputPath);
1067
- if (saveResult.success) {
1068
- if (!options.quiet) {
1069
- logger.always(chalk.green(`🔊 Audio saved to: ${saveResult.path} (${formatFileSize(saveResult.size)})`));
1067
+ // Save audio to file if --tts-output is provided
1068
+ if (ttsOutputPath) {
1069
+ try {
1070
+ const saveResult = await saveAudioToFile(audio, ttsOutputPath);
1071
+ if (saveResult.success) {
1072
+ if (!options.quiet) {
1073
+ logger.always(chalk.green(`🔊 Audio saved to: ${saveResult.path} (${formatFileSize(saveResult.size)})`));
1074
+ }
1075
+ }
1076
+ else {
1077
+ handleError(new Error(saveResult.error || "Failed to save audio file"), "TTS Output");
1070
1078
  }
1071
1079
  }
1072
- else {
1073
- handleError(new Error(saveResult.error || "Failed to save audio file"), "TTS Output");
1080
+ catch (error) {
1081
+ handleError(error, "TTS Output");
1074
1082
  }
1075
1083
  }
1076
- catch (error) {
1077
- handleError(error, "TTS Output");
1084
+ // Play audio if --tts-play is provided
1085
+ if (shouldPlay) {
1086
+ try {
1087
+ if (!options.quiet) {
1088
+ logger.always(chalk.blue("Playing audio..."));
1089
+ }
1090
+ await playAudio(audio.buffer, audio.format);
1091
+ }
1092
+ catch (err) {
1093
+ // Non-fatal: warn but don't crash
1094
+ logger.always(chalk.yellow(`Audio playback failed: ${err.message}`));
1095
+ logger.always(chalk.yellow(" Tip: Save the audio with --tts-output <file> and play manually."));
1096
+ }
1078
1097
  }
1079
1098
  }
1080
1099
  /**
@@ -2898,15 +2917,16 @@ export class CLICommandFactory {
2898
2917
  logger.always(`\nOutput saved to ${options.output}`);
2899
2918
  }
2900
2919
  }
2901
- // Handle TTS audio output if --tts-output is provided
2920
+ // Handle TTS audio output/playback if --tts-output or --tts-play is provided
2902
2921
  // Note: For streaming, TTS audio is collected during the stream
2903
2922
  // and saved at the end if available
2904
2923
  const ttsOutputPath = options.ttsOutput;
2905
- if (ttsOutputPath) {
2924
+ const shouldPlay = options.ttsPlay;
2925
+ if (ttsOutputPath || shouldPlay) {
2906
2926
  // For now, streaming TTS output is not yet available
2907
2927
  // This will be enabled when the TTS streaming infrastructure is complete
2908
2928
  if (!options.quiet) {
2909
- logger.always(chalk.yellow("⚠️ TTS audio output for streaming is not yet available. Use 'generate' command for TTS output."));
2929
+ logger.always(chalk.yellow("TTS audio for streaming is not yet available. Use 'generate' command for TTS output."));
2910
2930
  }
2911
2931
  }
2912
2932
  // Debug output for streaming
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Audio playback utilities for CLI
3
+ *
4
+ * Provides functionality for playing TTS audio using platform-specific
5
+ * CLI tools with proper cleanup and error handling.
6
+ *
7
+ * @module cli/utils/audioPlayer
8
+ */
9
+ import type { AudioFormat } from "../../lib/types/index.js";
10
+ /**
11
+ * Get the file extension for an audio format
12
+ *
13
+ * @param format - Audio format
14
+ * @returns File extension string (e.g., "mp3", "wav")
15
+ */
16
+ export declare function getAudioExtension(format: AudioFormat): string;
17
+ /**
18
+ * Play audio from a buffer using platform-specific CLI tools
19
+ *
20
+ * Writes the buffer to a temporary file, plays it using the appropriate
21
+ * system audio player, and cleans up the temp file afterward.
22
+ *
23
+ * Supported platforms:
24
+ * - macOS: uses `afplay` (built-in, supports mp3/wav/aac/flac)
25
+ * - Linux: uses `paplay` for non-wav, `aplay` for wav
26
+ * - Windows: uses PowerShell SoundPlayer (wav) or WMPlayer.OCX (mp3)
27
+ *
28
+ * @param buffer - Audio data buffer
29
+ * @param format - Audio format (mp3, wav, ogg, opus)
30
+ * @throws Error if playback fails or platform is unsupported
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * await playAudio(audioBuffer, "mp3");
35
+ * ```
36
+ */
37
+ export declare function playAudio(buffer: Buffer, format: AudioFormat): Promise<void>;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Audio playback utilities for CLI
3
+ *
4
+ * Provides functionality for playing TTS audio using platform-specific
5
+ * CLI tools with proper cleanup and error handling.
6
+ *
7
+ * @module cli/utils/audioPlayer
8
+ */
9
+ import { execFile } from "node:child_process";
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { promisify } from "node:util";
14
+ const execFileAsync = promisify(execFile);
15
+ /**
16
+ * Get the file extension for an audio format
17
+ *
18
+ * @param format - Audio format
19
+ * @returns File extension string (e.g., "mp3", "wav")
20
+ */
21
+ export function getAudioExtension(format) {
22
+ switch (format) {
23
+ case "mp3":
24
+ return "mp3";
25
+ case "wav":
26
+ return "wav";
27
+ case "ogg":
28
+ return "ogg";
29
+ case "opus":
30
+ return "opus";
31
+ default:
32
+ return "mp3";
33
+ }
34
+ }
35
+ /**
36
+ * Get the platform-specific audio player command and arguments
37
+ *
38
+ * @param filePath - Path to the audio file
39
+ * @param format - Audio format
40
+ * @returns Object with command and args for execFile
41
+ */
42
+ function getPlayerCommand(filePath, format) {
43
+ const platform = process.platform;
44
+ switch (platform) {
45
+ case "darwin":
46
+ return { command: "afplay", args: [filePath] };
47
+ case "linux":
48
+ if (format === "wav") {
49
+ return { command: "aplay", args: [filePath] };
50
+ }
51
+ return { command: "paplay", args: [filePath] };
52
+ case "win32":
53
+ if (format === "wav") {
54
+ return {
55
+ command: "powershell",
56
+ args: [
57
+ "-NoProfile",
58
+ "-Command",
59
+ `(New-Object System.Media.SoundPlayer '${filePath}').PlaySync()`,
60
+ ],
61
+ };
62
+ }
63
+ return {
64
+ command: "powershell",
65
+ args: [
66
+ "-NoProfile",
67
+ "-Command",
68
+ `$player = New-Object -ComObject WMPlayer.OCX; $player.URL = '${filePath}'; $player.controls.play(); Start-Sleep -Seconds 1; while ($player.playState -eq 3) { Start-Sleep -Milliseconds 100 }; $player.close()`,
69
+ ],
70
+ };
71
+ default:
72
+ throw new Error(`Unsupported platform: ${platform}. Audio playback is supported on macOS, Linux, and Windows.`);
73
+ }
74
+ }
75
+ /**
76
+ * Play audio from a buffer using platform-specific CLI tools
77
+ *
78
+ * Writes the buffer to a temporary file, plays it using the appropriate
79
+ * system audio player, and cleans up the temp file afterward.
80
+ *
81
+ * Supported platforms:
82
+ * - macOS: uses `afplay` (built-in, supports mp3/wav/aac/flac)
83
+ * - Linux: uses `paplay` for non-wav, `aplay` for wav
84
+ * - Windows: uses PowerShell SoundPlayer (wav) or WMPlayer.OCX (mp3)
85
+ *
86
+ * @param buffer - Audio data buffer
87
+ * @param format - Audio format (mp3, wav, ogg, opus)
88
+ * @throws Error if playback fails or platform is unsupported
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * await playAudio(audioBuffer, "mp3");
93
+ * ```
94
+ */
95
+ export async function playAudio(buffer, format) {
96
+ const ext = getAudioExtension(format);
97
+ const tempFile = path.join(os.tmpdir(), `nl-tts-${Date.now()}.${ext}`);
98
+ try {
99
+ // Write audio buffer to temp file
100
+ await fs.promises.writeFile(tempFile, buffer);
101
+ const { command, args } = getPlayerCommand(tempFile, format);
102
+ try {
103
+ await execFileAsync(command, args);
104
+ }
105
+ catch (execError) {
106
+ const err = execError;
107
+ // Handle binary not found
108
+ if (err.code === "ENOENT") {
109
+ if (process.platform === "linux" && command === "paplay") {
110
+ // Fallback to aplay on Linux
111
+ try {
112
+ await execFileAsync("aplay", [tempFile]);
113
+ return;
114
+ }
115
+ catch (fallbackError) {
116
+ const fbErr = fallbackError;
117
+ if (fbErr.code === "ENOENT") {
118
+ throw new Error("Neither paplay nor aplay found. Install PulseAudio (paplay) or ALSA (aplay) for audio playback.", { cause: fallbackError });
119
+ }
120
+ throw fallbackError;
121
+ }
122
+ }
123
+ throw new Error(`Audio player '${command}' not found. Ensure it is installed and available in PATH.`, { cause: execError });
124
+ }
125
+ throw execError;
126
+ }
127
+ }
128
+ finally {
129
+ // Always clean up temp file
130
+ try {
131
+ await fs.promises.unlink(tempFile);
132
+ }
133
+ catch {
134
+ // Ignore cleanup errors
135
+ }
136
+ }
137
+ }
138
+ //# sourceMappingURL=audioPlayer.js.map
@@ -26,6 +26,7 @@ import { coerceJsonToSchema } from "../../utils/json/coerce.js";
26
26
  import { NoObjectGeneratedError } from "../../utils/generationErrors.js";
27
27
  import { Output, stepCountIs } from "../../utils/tool.js";
28
28
  import { generateText } from "../../utils/generation.js";
29
+ import { extractSystemMessages } from "../../utils/systemMessages.js";
29
30
  const genTracer = tracers.generation;
30
31
  /**
31
32
  * Safely preview-serialize a value for debug logging.
@@ -105,9 +106,14 @@ export class GenerationHandler {
105
106
  }
106
107
  }
107
108
  const prepareStep = options.prepareStep;
109
+ // Hoist system-role messages into generateText's top-level `system` option
110
+ // rather than passing them inside `messages` (deprecated by the AI SDK,
111
+ // rejected in v7). See extractSystemMessages for the rationale. (#1024)
112
+ const { system, messages: nonSystemMessages } = extractSystemMessages(messages);
108
113
  return await generateText({
109
114
  model,
110
- messages,
115
+ ...(system && { system }),
116
+ messages: nonSystemMessages,
111
117
  ...(shouldUseTools &&
112
118
  Object.keys(toolsWithCache).length > 0 && { tools: toolsWithCache }),
113
119
  stopWhen: stepCountIs(options.maxSteps ?? DEFAULT_MAX_STEPS),
package/dist/index.d.ts CHANGED
@@ -35,7 +35,12 @@ import { AIProviderFactory } from "./core/factory.js";
35
35
  export { AIProviderFactory };
36
36
  export { NeuroLinkConfigManager as ConfigManager } from "./config/configManager.js";
37
37
  export { BaseFactory, BaseRegistry, NeuroLinkFeatureError, createErrorFactory, withRetry, TypedEventEmitter, } from "./core/infrastructure/index.js";
38
- export { NeuroLinkClient, createClient, NeuroLinkApiError, NeuroLinkLanguageModel, NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/index.js";
38
+ export { NeuroLinkClient, createClient, NeuroLinkApiError, } from "./client/httpClient.js";
39
+ export { NeuroLinkLanguageModel, NeuroLinkProvider as NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, } from "./client/aiSdkAdapter.js";
40
+ export { createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, } from "./client/interceptors.js";
41
+ export { SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, } from "./client/streamingClient.js";
42
+ export { OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthenticationError as OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, } from "./client/auth.js";
43
+ export { ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/errors.js";
39
44
  export { AIProviderName, BedrockModels, OpenAIModels, VertexModels, } from "./constants/enums.js";
40
45
  export { dynamicModelProvider } from "./core/dynamicModels.js";
41
46
  export { validateTool } from "./sdk/toolRegistration.js";
package/dist/index.js CHANGED
@@ -41,20 +41,28 @@ export { BaseFactory, BaseRegistry, NeuroLinkFeatureError, createErrorFactory, w
41
41
  // ============================================================================
42
42
  // CLIENT SDK EXPORTS - Type-safe API access for browser and Node.js
43
43
  // Note: React hooks are NOT re-exported here. Import from '@juspay/neurolink/client'.
44
+ // These re-exports intentionally bypass ./client/index.js: that barrel statically
45
+ // re-exports ./reactHooks.js, so routing through it makes the ROOT import require
46
+ // `react` (an optional peer dep) and crash react-less installs at import time.
44
47
  // ============================================================================
45
48
  export {
46
49
  // HTTP Client
47
- NeuroLinkClient, createClient, NeuroLinkApiError,
50
+ NeuroLinkClient, createClient, NeuroLinkApiError, } from "./client/httpClient.js";
51
+ export {
48
52
  // AI SDK Adapter
49
- NeuroLinkLanguageModel, NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance,
53
+ NeuroLinkLanguageModel, NeuroLinkProvider as NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, } from "./client/aiSdkAdapter.js";
54
+ export {
50
55
  // Interceptors
51
- createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware,
56
+ createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, } from "./client/interceptors.js";
57
+ export {
52
58
  // Streaming Client
53
- SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream,
59
+ SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, } from "./client/streamingClient.js";
60
+ export {
54
61
  // Authentication
55
- OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv,
62
+ OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthenticationError as OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, } from "./client/auth.js";
63
+ export {
56
64
  // Errors
57
- ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/index.js";
65
+ ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/errors.js";
58
66
  export { AIProviderName, BedrockModels, OpenAIModels, VertexModels, } from "./constants/enums.js";
59
67
  // Dynamic Models exports
60
68
  export { dynamicModelProvider } from "./core/dynamicModels.js";
@@ -26,6 +26,7 @@ import { coerceJsonToSchema } from "../../utils/json/coerce.js";
26
26
  import { NoObjectGeneratedError } from "../../utils/generationErrors.js";
27
27
  import { Output, stepCountIs } from "../../utils/tool.js";
28
28
  import { generateText } from "../../utils/generation.js";
29
+ import { extractSystemMessages } from "../../utils/systemMessages.js";
29
30
  const genTracer = tracers.generation;
30
31
  /**
31
32
  * Safely preview-serialize a value for debug logging.
@@ -105,9 +106,14 @@ export class GenerationHandler {
105
106
  }
106
107
  }
107
108
  const prepareStep = options.prepareStep;
109
+ // Hoist system-role messages into generateText's top-level `system` option
110
+ // rather than passing them inside `messages` (deprecated by the AI SDK,
111
+ // rejected in v7). See extractSystemMessages for the rationale. (#1024)
112
+ const { system, messages: nonSystemMessages } = extractSystemMessages(messages);
108
113
  return await generateText({
109
114
  model,
110
- messages,
115
+ ...(system && { system }),
116
+ messages: nonSystemMessages,
111
117
  ...(shouldUseTools &&
112
118
  Object.keys(toolsWithCache).length > 0 && { tools: toolsWithCache }),
113
119
  stopWhen: stepCountIs(options.maxSteps ?? DEFAULT_MAX_STEPS),
@@ -35,7 +35,12 @@ import { AIProviderFactory } from "./core/factory.js";
35
35
  export { AIProviderFactory };
36
36
  export { NeuroLinkConfigManager as ConfigManager } from "./config/configManager.js";
37
37
  export { BaseFactory, BaseRegistry, NeuroLinkFeatureError, createErrorFactory, withRetry, TypedEventEmitter, } from "./core/infrastructure/index.js";
38
- export { NeuroLinkClient, createClient, NeuroLinkApiError, NeuroLinkLanguageModel, NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/index.js";
38
+ export { NeuroLinkClient, createClient, NeuroLinkApiError, } from "./client/httpClient.js";
39
+ export { NeuroLinkLanguageModel, NeuroLinkProvider as NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, } from "./client/aiSdkAdapter.js";
40
+ export { createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, } from "./client/interceptors.js";
41
+ export { SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, } from "./client/streamingClient.js";
42
+ export { OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthenticationError as OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, } from "./client/auth.js";
43
+ export { ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/errors.js";
39
44
  export { AIProviderName, BedrockModels, OpenAIModels, VertexModels, } from "./constants/enums.js";
40
45
  export { dynamicModelProvider } from "./core/dynamicModels.js";
41
46
  export { validateTool } from "./sdk/toolRegistration.js";
package/dist/lib/index.js CHANGED
@@ -41,20 +41,28 @@ export { BaseFactory, BaseRegistry, NeuroLinkFeatureError, createErrorFactory, w
41
41
  // ============================================================================
42
42
  // CLIENT SDK EXPORTS - Type-safe API access for browser and Node.js
43
43
  // Note: React hooks are NOT re-exported here. Import from '@juspay/neurolink/client'.
44
+ // These re-exports intentionally bypass ./client/index.js: that barrel statically
45
+ // re-exports ./reactHooks.js, so routing through it makes the ROOT import require
46
+ // `react` (an optional peer dep) and crash react-less installs at import time.
44
47
  // ============================================================================
45
48
  export {
46
49
  // HTTP Client
47
- NeuroLinkClient, createClient, NeuroLinkApiError,
50
+ NeuroLinkClient, createClient, NeuroLinkApiError, } from "./client/httpClient.js";
51
+ export {
48
52
  // AI SDK Adapter
49
- NeuroLinkLanguageModel, NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance,
53
+ NeuroLinkLanguageModel, NeuroLinkProvider as NeuroLinkAIProvider, createNeuroLinkProvider, createNeuroLinkModel, createStreamingResponse, neurolink as neuroLinkAIInstance, } from "./client/aiSdkAdapter.js";
54
+ export {
50
55
  // Interceptors
51
- createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware,
56
+ createApiKeyAuthInterceptor, createBearerAuthInterceptor, createDynamicAuthInterceptor, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, createRequestTransformInterceptor, createResponseTransformInterceptor, createCacheInterceptor, createTimeoutInterceptor, createErrorHandlerInterceptor, composeMiddleware, conditionalMiddleware, } from "./client/interceptors.js";
57
+ export {
52
58
  // Streaming Client
53
- SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream,
59
+ SSEClient, WebSocketStreamingClient, createStreamingClient, createAsyncStream, collectStream, } from "./client/streamingClient.js";
60
+ export {
54
61
  // Authentication
55
- OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv,
62
+ OAuth2TokenManager, JWTTokenManager, createApiKeyMiddleware, createBearerTokenMiddleware, createTokenManagerMiddleware, createAuthWithRetryMiddleware, createMultiAuthMiddleware, OAuth2Error, OAuth2AuthenticationError as OAuth2AuthError, TokenRefreshError, decodeJWTPayload, isJWTExpired, getJWTExpiry, getApiKeyFromEnv, } from "./client/auth.js";
63
+ export {
56
64
  // Errors
57
- ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/index.js";
65
+ ErrorCode as ClientErrorCode, NeuroLinkError as ClientNeuroLinkError, HttpError, ClientRateLimitError, ClientValidationError, ClientAuthenticationError, ClientAuthorizationError, NotFoundError, ClientNetworkError, ClientTimeoutError, ClientConnectionError, AbortError, ClientConfigurationError, StreamError, ClientProviderError, ContextLengthError, ContentFilterError, createErrorFromResponse, createErrorFromNative, mapStatusToErrorCode, isRetryableStatus, isRetryableError, isNeuroLinkError, isApiError, } from "./client/errors.js";
58
66
  export { AIProviderName, BedrockModels, OpenAIModels, VertexModels, } from "./constants/enums.js";
59
67
  // Dynamic Models exports
60
68
  export { dynamicModelProvider } from "./core/dynamicModels.js";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Install the tuned global undici dispatcher. Idempotent — safe to call once at
3
+ * proxy startup. No-op when `NEUROLINK_PROXY_KEEPALIVE` is off/false/0.
4
+ */
5
+ export declare function configureProxyKeepAliveDispatcher(): void;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Tuned global undici dispatcher for the proxy's upstream forwards.
3
+ *
4
+ * The Claude passthrough (`claudeProxyRoutes.ts`) forwards every request to
5
+ * Anthropic via the global `fetch` → undici global dispatcher. undici keep-alives
6
+ * by default, but with a ~4s idle timeout: between Claude Code turns (the user
7
+ * reads output, a tool runs, the model thinks) the idle socket closes, so the
8
+ * next request opens a brand-new TCP connection. Under sustained use that is a
9
+ * high rate of short-lived outbound flows.
10
+ *
11
+ * On hosts running a socket content-filter (CFIL) — e.g. SentinelOne or
12
+ * GlobalProtect network extensions — every new flow allocates per-flow kernel
13
+ * state, so a high flow rate amplifies any leak in that path. Reusing connections
14
+ * cuts the flow rate sharply, so we install a dispatcher with a longer keep-alive
15
+ * and a bounded, reused connection pool.
16
+ *
17
+ * Everything is overridable via env so it can be tuned (or disabled) per host:
18
+ * NEUROLINK_PROXY_KEEPALIVE=off disable; keep undici defaults
19
+ * NEUROLINK_PROXY_KEEPALIVE_MS idle keep-alive timeout (default 30000)
20
+ * NEUROLINK_PROXY_KEEPALIVE_MAX_MS keep-alive upper bound (default 600000)
21
+ * NEUROLINK_PROXY_MAX_CONNECTIONS max pooled connections per origin (default 64)
22
+ */
23
+ import { Agent, setGlobalDispatcher } from "undici";
24
+ import { logger } from "../utils/logger.js";
25
+ function readPositiveInt(name, fallback) {
26
+ const raw = process.env[name];
27
+ if (!raw) {
28
+ return fallback;
29
+ }
30
+ const parsed = Number.parseInt(raw, 10);
31
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
32
+ }
33
+ let configured = false;
34
+ /**
35
+ * Install the tuned global undici dispatcher. Idempotent — safe to call once at
36
+ * proxy startup. No-op when `NEUROLINK_PROXY_KEEPALIVE` is off/false/0.
37
+ */
38
+ export function configureProxyKeepAliveDispatcher() {
39
+ if (configured) {
40
+ return;
41
+ }
42
+ configured = true;
43
+ const toggle = (process.env.NEUROLINK_PROXY_KEEPALIVE ?? "").toLowerCase();
44
+ if (toggle === "off" || toggle === "false" || toggle === "0") {
45
+ logger.debug("[proxy] keep-alive dispatcher disabled via env");
46
+ return;
47
+ }
48
+ const keepAliveTimeout = readPositiveInt("NEUROLINK_PROXY_KEEPALIVE_MS", 30_000);
49
+ const keepAliveMaxTimeout = readPositiveInt("NEUROLINK_PROXY_KEEPALIVE_MAX_MS", 600_000);
50
+ const connections = readPositiveInt("NEUROLINK_PROXY_MAX_CONNECTIONS", 64);
51
+ setGlobalDispatcher(new Agent({
52
+ keepAliveTimeout,
53
+ keepAliveMaxTimeout,
54
+ connections,
55
+ pipelining: 1,
56
+ }));
57
+ logger.debug(`[proxy] tuned undici dispatcher installed ` +
58
+ `(keepAliveTimeout=${keepAliveTimeout}ms, ` +
59
+ `keepAliveMaxTimeout=${keepAliveMaxTimeout}ms, connections=${connections})`);
60
+ }
61
+ //# sourceMappingURL=proxyDispatcher.js.map
@@ -0,0 +1,29 @@
1
+ import type { ModelMessage, SystemModelMessage } from "../types/index.js";
2
+ /**
3
+ * Partition a built message array into system messages and the rest, so the
4
+ * system prompt can ride `generateText`'s top-level `system` option instead of
5
+ * the `messages` array.
6
+ *
7
+ * The AI SDK deprecates system-role entries inside `messages` (warns by default
8
+ * from ai@6.0.170 via the `allowSystemInMessages` option, rejected by default
9
+ * in v7, flagged as a prompt-injection risk). The `system` option accepts full
10
+ * SystemModelMessage objects, so per-message providerOptions (e.g. the anthropic
11
+ * cacheControl breakpoint set by buildMessagesArray) survive the move. See
12
+ * issue #1024.
13
+ *
14
+ * Order is preserved within both partitions and the input is not mutated.
15
+ *
16
+ * Guard: the partition only runs when it leaves a non-empty `messages` array.
17
+ * If every message is a system message (a system-only priming call) — or there
18
+ * are no system messages at all — the original array is returned untouched with
19
+ * `system: undefined`. The AI SDK rejects an empty `messages` array, and a
20
+ * system-only call has no hoisted form (the SDK also requires a non-system
21
+ * message), so that degenerate case is deliberately left on the old
22
+ * system-in-`messages` path rather than made to throw — it keeps whatever
23
+ * behaviour it had before #1024. The normal system-plus-conversation path is
24
+ * always hoisted.
25
+ */
26
+ export declare function extractSystemMessages(messages: ModelMessage[]): {
27
+ system: SystemModelMessage[] | undefined;
28
+ messages: ModelMessage[];
29
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Partition a built message array into system messages and the rest, so the
3
+ * system prompt can ride `generateText`'s top-level `system` option instead of
4
+ * the `messages` array.
5
+ *
6
+ * The AI SDK deprecates system-role entries inside `messages` (warns by default
7
+ * from ai@6.0.170 via the `allowSystemInMessages` option, rejected by default
8
+ * in v7, flagged as a prompt-injection risk). The `system` option accepts full
9
+ * SystemModelMessage objects, so per-message providerOptions (e.g. the anthropic
10
+ * cacheControl breakpoint set by buildMessagesArray) survive the move. See
11
+ * issue #1024.
12
+ *
13
+ * Order is preserved within both partitions and the input is not mutated.
14
+ *
15
+ * Guard: the partition only runs when it leaves a non-empty `messages` array.
16
+ * If every message is a system message (a system-only priming call) — or there
17
+ * are no system messages at all — the original array is returned untouched with
18
+ * `system: undefined`. The AI SDK rejects an empty `messages` array, and a
19
+ * system-only call has no hoisted form (the SDK also requires a non-system
20
+ * message), so that degenerate case is deliberately left on the old
21
+ * system-in-`messages` path rather than made to throw — it keeps whatever
22
+ * behaviour it had before #1024. The normal system-plus-conversation path is
23
+ * always hoisted.
24
+ */
25
+ export function extractSystemMessages(messages) {
26
+ const system = [];
27
+ const rest = [];
28
+ for (const message of messages) {
29
+ if (message.role === "system") {
30
+ system.push(message);
31
+ }
32
+ else {
33
+ rest.push(message);
34
+ }
35
+ }
36
+ // Only hoist when a non-empty messages array remains. A system-only call (or
37
+ // a no-system array) passes through unchanged: hoisting would empty
38
+ // `messages`, which the SDK rejects, and a system-only call has no compliant
39
+ // hoisted form.
40
+ if (system.length === 0 || rest.length === 0) {
41
+ return { system: undefined, messages };
42
+ }
43
+ return { system, messages: rest };
44
+ }
45
+ //# sourceMappingURL=systemMessages.js.map
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Install the tuned global undici dispatcher. Idempotent — safe to call once at
3
+ * proxy startup. No-op when `NEUROLINK_PROXY_KEEPALIVE` is off/false/0.
4
+ */
5
+ export declare function configureProxyKeepAliveDispatcher(): void;