@juspay/neurolink 9.81.2 → 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.
Files changed (56) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +4 -0
  3. package/dist/browser/neurolink.min.js +355 -355
  4. package/dist/cli/commands/proxy.js +5 -0
  5. package/dist/cli/factories/commandFactory.d.ts +2 -1
  6. package/dist/cli/factories/commandFactory.js +36 -16
  7. package/dist/cli/utils/audioPlayer.d.ts +37 -0
  8. package/dist/cli/utils/audioPlayer.js +138 -0
  9. package/dist/constants/contextWindows.js +10 -0
  10. package/dist/core/constants.d.ts +16 -0
  11. package/dist/core/constants.js +16 -0
  12. package/dist/core/modules/GenerationHandler.js +7 -1
  13. package/dist/core/modules/ToolsManager.d.ts +5 -0
  14. package/dist/core/modules/ToolsManager.js +62 -6
  15. package/dist/index.d.ts +6 -1
  16. package/dist/index.js +14 -6
  17. package/dist/lib/constants/contextWindows.js +10 -0
  18. package/dist/lib/core/constants.d.ts +16 -0
  19. package/dist/lib/core/constants.js +16 -0
  20. package/dist/lib/core/modules/GenerationHandler.js +7 -1
  21. package/dist/lib/core/modules/ToolsManager.d.ts +5 -0
  22. package/dist/lib/core/modules/ToolsManager.js +62 -6
  23. package/dist/lib/index.d.ts +6 -1
  24. package/dist/lib/index.js +14 -6
  25. package/dist/lib/neurolink.js +21 -3
  26. package/dist/lib/providers/googleNativeGemini3.d.ts +43 -0
  27. package/dist/lib/providers/googleNativeGemini3.js +73 -1
  28. package/dist/lib/providers/googleVertex.js +495 -80
  29. package/dist/lib/proxy/proxyDispatcher.d.ts +5 -0
  30. package/dist/lib/proxy/proxyDispatcher.js +61 -0
  31. package/dist/lib/types/generate.d.ts +5 -1
  32. package/dist/lib/utils/async/index.d.ts +1 -1
  33. package/dist/lib/utils/async/index.js +1 -1
  34. package/dist/lib/utils/async/withTimeout.d.ts +12 -0
  35. package/dist/lib/utils/async/withTimeout.js +45 -0
  36. package/dist/lib/utils/mcpErrorText.d.ts +11 -0
  37. package/dist/lib/utils/mcpErrorText.js +23 -0
  38. package/dist/lib/utils/systemMessages.d.ts +29 -0
  39. package/dist/lib/utils/systemMessages.js +45 -0
  40. package/dist/neurolink.js +21 -3
  41. package/dist/providers/googleNativeGemini3.d.ts +43 -0
  42. package/dist/providers/googleNativeGemini3.js +73 -1
  43. package/dist/providers/googleVertex.js +495 -80
  44. package/dist/proxy/proxyDispatcher.d.ts +5 -0
  45. package/dist/proxy/proxyDispatcher.js +60 -0
  46. package/dist/types/generate.d.ts +5 -1
  47. package/dist/utils/async/index.d.ts +1 -1
  48. package/dist/utils/async/index.js +1 -1
  49. package/dist/utils/async/withTimeout.d.ts +12 -0
  50. package/dist/utils/async/withTimeout.js +45 -0
  51. package/dist/utils/mcpErrorText.d.ts +11 -0
  52. package/dist/utils/mcpErrorText.js +23 -0
  53. package/dist/utils/systemMessages.d.ts +29 -0
  54. package/dist/utils/systemMessages.js +44 -0
  55. package/docs/assets/dashboards/neurolink-proxy-observability-dashboard.json +1258 -0
  56. package/package.json +3 -2
@@ -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
@@ -154,6 +154,8 @@ export const MODEL_CONTEXT_WINDOWS = {
154
154
  },
155
155
  anthropic: {
156
156
  _default: 200_000,
157
+ // Claude 5 (mid 2026) — 1M context window
158
+ "claude-sonnet-5": 1_000_000,
157
159
  // Claude 4.6 (Feb 2026) — 1M context window
158
160
  "claude-opus-4-6": 1_000_000,
159
161
  "claude-sonnet-4-6": 1_000_000,
@@ -243,6 +245,7 @@ export const MODEL_CONTEXT_WINDOWS = {
243
245
  vertex: {
244
246
  _default: 1_048_576,
245
247
  // Claude on Vertex
248
+ "claude-sonnet-5": 1_000_000,
246
249
  "claude-opus-4-6": 1_000_000,
247
250
  "claude-sonnet-4-6": 1_000_000,
248
251
  "claude-sonnet-4-5": 200_000,
@@ -252,6 +255,13 @@ export const MODEL_CONTEXT_WINDOWS = {
252
255
  "claude-sonnet-4-20250514": 200_000,
253
256
  "claude-opus-4-20250514": 200_000,
254
257
  "claude-opus-4": 200_000,
258
+ // Catch-all for UNKNOWN Claude models on Vertex (prefix match runs after
259
+ // the specific keys above). Without this, an unlisted Claude model falls
260
+ // to the Gemini-shaped _default (1,048,576) — ABOVE Anthropic's real 1M
261
+ // API cap — so the pre-dispatch budget check and the in-loop context
262
+ // guard both under-guard it (the claude-sonnet-5 1,005,647-token 400s).
263
+ // 200K is the conservative Anthropic floor; list real models explicitly.
264
+ "claude-": 200_000,
255
265
  // Gemini 3.1 on Vertex (all require -preview suffix)
256
266
  "gemini-3.1-pro-preview": 1_048_576,
257
267
  "gemini-3.1-flash-lite-preview": 1_048_576,
@@ -36,6 +36,22 @@ export declare const DEFAULT_TOOL_EXECUTION_TIMEOUT_MS = 300000;
36
36
  * a wrap-up nudge rides the next tool-result turn.
37
37
  */
38
38
  export declare const DEFAULT_WRAPUP_TIME_LEAD_MS = 120000;
39
+ /**
40
+ * In-loop context guard threshold for native agentic loops: when the last
41
+ * model call's actual prompt size (provider-reported usage) plus the
42
+ * estimated growth from this step's tool results crosses this fraction of
43
+ * the model's context window, the loop stops calling tools and synthesizes a
44
+ * final answer instead of stepping into a provider 400 ("prompt is too
45
+ * long") that would destroy the whole turn's work.
46
+ */
47
+ export declare const DEFAULT_CONTEXT_GUARD_RATIO = 0.85;
48
+ /**
49
+ * Floor for the turn budget handed to the post-overflow recovery retry.
50
+ * The retry inherits the REMAINING `turnTimeoutMs` (whole-turn semantics —
51
+ * one generate() must not stack two full budgets), but never less than this,
52
+ * so a compacted retry still gets a workable window.
53
+ */
54
+ export declare const MIN_RECOVERY_TURN_BUDGET_MS = 30000;
39
55
  export declare const TOOL_STORAGE_TIMEOUT_MS = 5000;
40
56
  export declare const STEP_LIMITS: {
41
57
  min: number;
@@ -122,6 +122,22 @@ export const DEFAULT_TOOL_EXECUTION_TIMEOUT_MS = 300_000;
122
122
  * a wrap-up nudge rides the next tool-result turn.
123
123
  */
124
124
  export const DEFAULT_WRAPUP_TIME_LEAD_MS = 120_000;
125
+ /**
126
+ * In-loop context guard threshold for native agentic loops: when the last
127
+ * model call's actual prompt size (provider-reported usage) plus the
128
+ * estimated growth from this step's tool results crosses this fraction of
129
+ * the model's context window, the loop stops calling tools and synthesizes a
130
+ * final answer instead of stepping into a provider 400 ("prompt is too
131
+ * long") that would destroy the whole turn's work.
132
+ */
133
+ export const DEFAULT_CONTEXT_GUARD_RATIO = 0.85;
134
+ /**
135
+ * Floor for the turn budget handed to the post-overflow recovery retry.
136
+ * The retry inherits the REMAINING `turnTimeoutMs` (whole-turn semantics —
137
+ * one generate() must not stack two full budgets), but never less than this,
138
+ * so a compacted retry still gets a workable window.
139
+ */
140
+ export const MIN_RECOVERY_TURN_BUDGET_MS = 30_000;
125
141
  // Fire-and-forget tool storage writes (Redis). 5s is generous for a single
126
142
  // Redis write; if breached, the .catch logs a warning.
127
143
  export const TOOL_STORAGE_TIMEOUT_MS = 5000;
@@ -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),
@@ -18,6 +18,11 @@ export declare class ToolsManager {
18
18
  /**
19
19
  * BZ-666: Wrap tool execute with output truncation to prevent
20
20
  * context overflow when large results flow into the AI SDK accumulator.
21
+ *
22
+ * Passes the AI-SDK second argument (execution options: abortSignal,
23
+ * toolCallId, messages) through to the inner execute — the native loops
24
+ * provide an abortSignal there, and dropping it at this wrapper made
25
+ * every tool uncancellable (deadline overshoot / ghost executions).
21
26
  */
22
27
  private wrapExecuteWithTruncation;
23
28
  /**
@@ -7,6 +7,48 @@ import { getKeyCount } from "../../utils/transformationUtils.js";
7
7
  import { convertJsonSchemaToZod } from "../../utils/schemaConversion.js";
8
8
  import { generateToolOutputPreview } from "../../context/toolOutputLimits.js";
9
9
  import { tool as createAISDKTool, jsonSchema } from "../../utils/tool.js";
10
+ /** Abort-shaped error so provider loops route it to their cancellation path. */
11
+ function makeToolAbortError() {
12
+ const e = new Error("Tool execution aborted");
13
+ e.name = "AbortError";
14
+ return e;
15
+ }
16
+ /**
17
+ * Race a tool-execution promise against an AbortSignal so the calling loop
18
+ * observes a deadline/caller abort IMMEDIATELY instead of waiting for the
19
+ * tool to finish or its execution timeout to expire. The underlying call is
20
+ * not cancelled (bounded ghost execution — the same tradeoff as the tool
21
+ * timeout); real transport-level cancellation (executeExternalMCPTool → MCP
22
+ * client RequestOptions.signal) is tracked as a follow-up.
23
+ */
24
+ function raceWithAbortSignal(promise, signal) {
25
+ if (signal.aborted) {
26
+ // Swallow the abandoned settlement so it can't become an unhandled
27
+ // rejection later.
28
+ promise.catch(() => {
29
+ // Swallow the abandoned settlement — it must never surface as an
30
+ // unhandled rejection after the race has already been decided.
31
+ });
32
+ return Promise.reject(makeToolAbortError());
33
+ }
34
+ return new Promise((resolve, reject) => {
35
+ const onAbort = () => {
36
+ promise.catch(() => {
37
+ // Swallow the abandoned settlement — it must never surface as an
38
+ // unhandled rejection after the race has already been decided.
39
+ });
40
+ reject(makeToolAbortError());
41
+ };
42
+ signal.addEventListener("abort", onAbort, { once: true });
43
+ promise.then((value) => {
44
+ signal.removeEventListener("abort", onAbort);
45
+ resolve(value);
46
+ }, (error) => {
47
+ signal.removeEventListener("abort", onAbort);
48
+ reject(error);
49
+ });
50
+ });
51
+ }
10
52
  /**
11
53
  * ToolsManager class - Handles all tool management operations
12
54
  */
@@ -32,10 +74,24 @@ export class ToolsManager {
32
74
  /**
33
75
  * BZ-666: Wrap tool execute with output truncation to prevent
34
76
  * context overflow when large results flow into the AI SDK accumulator.
77
+ *
78
+ * Passes the AI-SDK second argument (execution options: abortSignal,
79
+ * toolCallId, messages) through to the inner execute — the native loops
80
+ * provide an abortSignal there, and dropping it at this wrapper made
81
+ * every tool uncancellable (deadline overshoot / ghost executions).
35
82
  */
36
83
  wrapExecuteWithTruncation(toolName, originalExecute) {
37
- return async (params) => {
38
- const result = await originalExecute(params);
84
+ return async (params, execOptions) => {
85
+ const signal = execOptions
86
+ ?.abortSignal;
87
+ const inner = originalExecute(params, execOptions);
88
+ // Inner executes that ignore the signal (external MCP / custom tools —
89
+ // the signal isn't plumbed to their transports yet) still return
90
+ // promptly on abort via the race; the loop's isAbortError handling
91
+ // treats the rejection as a cancellation, not a tool failure.
92
+ const result = signal && typeof signal.addEventListener === "function"
93
+ ? await raceWithAbortSignal(inner, signal)
94
+ : await inner;
39
95
  return this.truncateToolResult(toolName, result);
40
96
  };
41
97
  }
@@ -241,11 +297,11 @@ export class ToolsManager {
241
297
  const guardedExecute = this.wrapExecuteWithTruncation(toolName, originalExecute);
242
298
  tools[toolName] = {
243
299
  ...directTool,
244
- execute: async (params) => {
300
+ execute: async (params, execOptions) => {
245
301
  const startTime = Date.now();
246
302
  this.emitToolEvent("tool:start", toolName, { input: params });
247
303
  try {
248
- const result = await guardedExecute(params);
304
+ const result = await guardedExecute(params, execOptions);
249
305
  this.emitToolEvent("tool:end", toolName, {
250
306
  result,
251
307
  success: true,
@@ -541,11 +597,11 @@ export class ToolsManager {
541
597
  return createAISDKTool({
542
598
  description: tool.description || `External MCP tool ${tool.name}`,
543
599
  inputSchema: finalSchema, // AI SDK v6 uses inputSchema (not parameters)
544
- execute: async (params) => {
600
+ execute: async (params, execOptions) => {
545
601
  const startTime = Date.now();
546
602
  this.emitToolEvent("tool:start", tool.name, { input: params });
547
603
  try {
548
- const result = await guardedExecute(params);
604
+ const result = await guardedExecute(params, execOptions);
549
605
  this.emitToolEvent("tool:end", tool.name, {
550
606
  result,
551
607
  success: true,
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";
@@ -154,6 +154,8 @@ export const MODEL_CONTEXT_WINDOWS = {
154
154
  },
155
155
  anthropic: {
156
156
  _default: 200_000,
157
+ // Claude 5 (mid 2026) — 1M context window
158
+ "claude-sonnet-5": 1_000_000,
157
159
  // Claude 4.6 (Feb 2026) — 1M context window
158
160
  "claude-opus-4-6": 1_000_000,
159
161
  "claude-sonnet-4-6": 1_000_000,
@@ -243,6 +245,7 @@ export const MODEL_CONTEXT_WINDOWS = {
243
245
  vertex: {
244
246
  _default: 1_048_576,
245
247
  // Claude on Vertex
248
+ "claude-sonnet-5": 1_000_000,
246
249
  "claude-opus-4-6": 1_000_000,
247
250
  "claude-sonnet-4-6": 1_000_000,
248
251
  "claude-sonnet-4-5": 200_000,
@@ -252,6 +255,13 @@ export const MODEL_CONTEXT_WINDOWS = {
252
255
  "claude-sonnet-4-20250514": 200_000,
253
256
  "claude-opus-4-20250514": 200_000,
254
257
  "claude-opus-4": 200_000,
258
+ // Catch-all for UNKNOWN Claude models on Vertex (prefix match runs after
259
+ // the specific keys above). Without this, an unlisted Claude model falls
260
+ // to the Gemini-shaped _default (1,048,576) — ABOVE Anthropic's real 1M
261
+ // API cap — so the pre-dispatch budget check and the in-loop context
262
+ // guard both under-guard it (the claude-sonnet-5 1,005,647-token 400s).
263
+ // 200K is the conservative Anthropic floor; list real models explicitly.
264
+ "claude-": 200_000,
255
265
  // Gemini 3.1 on Vertex (all require -preview suffix)
256
266
  "gemini-3.1-pro-preview": 1_048_576,
257
267
  "gemini-3.1-flash-lite-preview": 1_048_576,
@@ -36,6 +36,22 @@ export declare const DEFAULT_TOOL_EXECUTION_TIMEOUT_MS = 300000;
36
36
  * a wrap-up nudge rides the next tool-result turn.
37
37
  */
38
38
  export declare const DEFAULT_WRAPUP_TIME_LEAD_MS = 120000;
39
+ /**
40
+ * In-loop context guard threshold for native agentic loops: when the last
41
+ * model call's actual prompt size (provider-reported usage) plus the
42
+ * estimated growth from this step's tool results crosses this fraction of
43
+ * the model's context window, the loop stops calling tools and synthesizes a
44
+ * final answer instead of stepping into a provider 400 ("prompt is too
45
+ * long") that would destroy the whole turn's work.
46
+ */
47
+ export declare const DEFAULT_CONTEXT_GUARD_RATIO = 0.85;
48
+ /**
49
+ * Floor for the turn budget handed to the post-overflow recovery retry.
50
+ * The retry inherits the REMAINING `turnTimeoutMs` (whole-turn semantics —
51
+ * one generate() must not stack two full budgets), but never less than this,
52
+ * so a compacted retry still gets a workable window.
53
+ */
54
+ export declare const MIN_RECOVERY_TURN_BUDGET_MS = 30000;
39
55
  export declare const TOOL_STORAGE_TIMEOUT_MS = 5000;
40
56
  export declare const STEP_LIMITS: {
41
57
  min: number;