@juspay/neurolink 13.12.5 → 13.13.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.
@@ -153,6 +153,17 @@ export declare const SYSTEM_LIMITS: {
153
153
  DEFAULT_BACKOFF_MULTIPLIER: number;
154
154
  };
155
155
  export declare const DEFAULT_TOOL_ROUTING_TIMEOUT_MS = 15000;
156
+ export declare const JEV_ROUTING_AUDIT_LIMITS: {
157
+ readonly queryCharacters: 6000;
158
+ readonly candidateServers: 64;
159
+ readonly serverIdCharacters: 256;
160
+ readonly capabilityCharacters: 1000;
161
+ readonly serializedInputCharacters: 24000;
162
+ };
163
+ export declare const JEV_ROUTING_AUDIT_OBSERVATION_NAME = "jev-routing-audit";
164
+ export declare const JEV_ROUTING_AUDIT_PROVIDER = "typesafe";
165
+ export declare const JEV_ROUTING_AUDIT_SCHEMA_VERSION = "1";
166
+ export declare const JEV_ROUTING_AUDIT_COMPONENT = "[JevRoutingAudit]";
156
167
  export declare const ENV_DEFAULTS: {
157
168
  maxTokens: number | undefined;
158
169
  temperature: number;
@@ -334,6 +334,17 @@ export const SYSTEM_LIMITS = {
334
334
  };
335
335
  // Pre-call tool routing: hard ceiling for the router LLM call before failing open
336
336
  export const DEFAULT_TOOL_ROUTING_TIMEOUT_MS = 15000;
337
+ export const JEV_ROUTING_AUDIT_LIMITS = {
338
+ queryCharacters: 6000,
339
+ candidateServers: 64,
340
+ serverIdCharacters: 256,
341
+ capabilityCharacters: 1000,
342
+ serializedInputCharacters: 24000,
343
+ };
344
+ export const JEV_ROUTING_AUDIT_OBSERVATION_NAME = "jev-routing-audit";
345
+ export const JEV_ROUTING_AUDIT_PROVIDER = "typesafe";
346
+ export const JEV_ROUTING_AUDIT_SCHEMA_VERSION = "1";
347
+ export const JEV_ROUTING_AUDIT_COMPONENT = "[JevRoutingAudit]";
337
348
  // Environment Variable Support (for future use)
338
349
  export const ENV_DEFAULTS = {
339
350
  maxTokens: (() => {
@@ -1304,6 +1304,9 @@ export declare class NeuroLink {
1304
1304
  * resolver fails open to an empty exclusion list). Accepts both StreamOptions
1305
1305
  * and GenerateOptions since both share the required fields.
1306
1306
  */
1307
+ /** Excluded tools including those a non-empty `toolFilter` leaves out. */
1308
+ private effectiveExcludedTools;
1309
+ private flushJevRoutingAudit;
1307
1310
  private applyToolRoutingExclusions;
1308
1311
  /**
1309
1312
  * Record a tool routing decision on the active span. Telemetry only.
package/dist/neurolink.js CHANGED
@@ -33,7 +33,7 @@ import { emergencyContentTruncation } from "./context/emergencyTruncation.js";
33
33
  import { getContextOverflowProvider, isContextOverflowError, parseProviderOverflowDetails, } from "./context/errorDetection.js";
34
34
  import { ContextBudgetExceededError } from "./context/errors.js";
35
35
  import { repairToolPairs } from "./context/toolPairRepair.js";
36
- import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, MIN_RECOVERY_TURN_BUDGET_MS, } from "./core/constants.js";
36
+ import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, JEV_ROUTING_AUDIT_PROVIDER, MIN_RECOVERY_TURN_BUDGET_MS, } from "./core/constants.js";
37
37
  import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
38
38
  import { buildToolRoutingCatalog, buildRoutingQueryFromHistory, resolveToolRoutingExclusions, } from "./core/toolRouting.js";
39
39
  import { ToolRoutingCache } from "./core/toolRoutingCache.js";
@@ -102,6 +102,9 @@ import { assistantMessages } from "./telemetry/chatMessages.js";
102
102
  import { observationLevel, observe, observeTrace, usageDetails, } from "./telemetry/observation.js";
103
103
  import { toolSpanName } from "./telemetry/observationNames.js";
104
104
  import { isNestedOperation, tracers } from "./telemetry/tracers.js";
105
+ import { buildJevRoutingAuditInput, logJevRoutingAuditFailure, } from "./utils/jevRoutingAudit.js";
106
+ import { recordJevRoutingAudit } from "./telemetry/jevRoutingAudit.js";
107
+ const pendingJevRoutingAudits = new WeakMap();
105
108
  import { getConversationMessages, storeConversationTurn, } from "./utils/conversationMemory.js";
106
109
  // Enhanced error handling imports
107
110
  import { CircuitBreaker, ERROR_CODES, ErrorFactory, isAbortError, isCancelledByCaller, isRetriableError, logStructuredError, NeuroLinkError, throwIfSignalAborted, withRetry, withTimeout, } from "./utils/errorHandling.js";
@@ -4386,6 +4389,7 @@ Current user's request: ${currentInput}`;
4386
4389
  await this.applyClassifierRouting(options, options.input?.text ?? originalPrompt ?? "", !options.disableTools &&
4387
4390
  (!!(options.tools && Object.keys(options.tools).length > 0) ||
4388
4391
  this.getCustomTools().size > 0), !!(options.input?.images && options.input.images.length > 0), options.thinkingConfig?.thinkingLevel);
4392
+ this.flushJevRoutingAudit(options);
4389
4393
  await this.maybeApplyGenerateOrchestration(options);
4390
4394
  // Pre-call request router: opt-in, only when the caller did not set both
4391
4395
  // provider+model. Fails open (any router error leaves options unchanged).
@@ -7881,6 +7885,7 @@ Current user's request: ${currentInput}`;
7881
7885
  (!!(options.tools && Object.keys(options.tools).length > 0) ||
7882
7886
  this.getCustomTools().size > 0), !!(options.input?.images && options.input.images.length > 0), options
7883
7887
  .thinking?.thinkingLevel);
7888
+ this.flushJevRoutingAudit(options);
7884
7889
  // Pre-call request router for stream: opt-in, fails open.
7885
7890
  await this.applyRequestRouter(options, originalPrompt, !options.disableTools &&
7886
7891
  (!!(options.tools && Object.keys(options.tools).length > 0) ||
@@ -7974,6 +7979,29 @@ Current user's request: ${currentInput}`;
7974
7979
  * resolver fails open to an empty exclusion list). Accepts both StreamOptions
7975
7980
  * and GenerateOptions since both share the required fields.
7976
7981
  */
7982
+ /** Excluded tools including those a non-empty `toolFilter` leaves out. */
7983
+ effectiveExcludedTools(options, catalog) {
7984
+ const excluded = new Set(options.excludeTools ?? []);
7985
+ const allow = options.toolFilter;
7986
+ if (allow && allow.length > 0) {
7987
+ const allowed = new Set(allow);
7988
+ for (const server of catalog) {
7989
+ for (const name of server.toolNames) {
7990
+ if (!allowed.has(name)) {
7991
+ excluded.add(name);
7992
+ }
7993
+ }
7994
+ }
7995
+ }
7996
+ return [...excluded];
7997
+ }
7998
+ flushJevRoutingAudit(options) {
7999
+ const pending = pendingJevRoutingAudits.get(options);
8000
+ if (pending) {
8001
+ pendingJevRoutingAudits.delete(options);
8002
+ pending();
8003
+ }
8004
+ }
7977
8005
  async applyToolRoutingExclusions(options, userQuery) {
7978
8006
  const routingConfig = this.toolRoutingConfig;
7979
8007
  if (!routingConfig?.enabled || options.disableTools) {
@@ -8086,6 +8114,12 @@ Current user's request: ${currentInput}`;
8086
8114
  }
8087
8115
  let routedExcludeTools;
8088
8116
  let resolvedDecision;
8117
+ let auditEvidence = null;
8118
+ const auditEnabled = routingConfig.audit?.enabled === true;
8119
+ let auditPolicyExclusions = [];
8120
+ if (auditEnabled) {
8121
+ auditPolicyExclusions = this.effectiveExcludedTools(options, catalog);
8122
+ }
8089
8123
  // Intercept the decision so we can store it in the cache.
8090
8124
  const captureDecision = (decision) => {
8091
8125
  resolvedDecision = decision;
@@ -8129,7 +8163,28 @@ Current user's request: ${currentInput}`;
8129
8163
  // Bypass the instance's decision fast-path in that explicit mode.
8130
8164
  decideFn: routingConfig.generateFn
8131
8165
  ? undefined
8132
- : (decisionOptions) => this.siteDecide(decisionOptions, this.decisionSiteContext(options, sessionId || undefined)),
8166
+ : async (decisionOptions) => {
8167
+ let auditInput = null;
8168
+ if (auditEnabled) {
8169
+ auditInput = buildJevRoutingAuditInput(decisionOptions.state);
8170
+ }
8171
+ const result = await this.siteDecide(decisionOptions, this.decisionSiteContext(options, sessionId || undefined));
8172
+ if (auditInput !== null && result !== null) {
8173
+ try {
8174
+ if (result.provider === JEV_ROUTING_AUDIT_PROVIDER) {
8175
+ auditEvidence = {
8176
+ input: auditInput,
8177
+ provider: result.provider,
8178
+ model: result.model,
8179
+ };
8180
+ }
8181
+ }
8182
+ catch (error) {
8183
+ logJevRoutingAuditFailure(error);
8184
+ }
8185
+ }
8186
+ return result;
8187
+ },
8133
8188
  decisionMinDropConfidence: routingConfig.minDropConfidence,
8134
8189
  emitDecision: captureDecision,
8135
8190
  // L2 / ITEM D — only populated when embedding is configured.
@@ -8180,6 +8235,27 @@ Current user's request: ${currentInput}`;
8180
8235
  ...routedExcludeTools,
8181
8236
  ];
8182
8237
  }
8238
+ if (auditEnabled) {
8239
+ // Deferred until the classifier router has narrowed the tools, so the
8240
+ // audit reports the exclusions the request actually runs with.
8241
+ const auditContext = context.active();
8242
+ const evidence = auditEvidence;
8243
+ const decision = resolvedDecision;
8244
+ const policyExclusions = auditPolicyExclusions;
8245
+ pendingJevRoutingAudits.set(options, () => {
8246
+ context.with(auditContext, () => {
8247
+ const finalExcluded = this.effectiveExcludedTools(options, catalog);
8248
+ const policy = new Set(policyExclusions);
8249
+ const routed = new Set(routedExcludeTools);
8250
+ // Exclusions added after JEV ran (classifier) are not JEV's call.
8251
+ const lateExclusions = finalExcluded.filter((name) => !policy.has(name) && !routed.has(name));
8252
+ recordJevRoutingAudit(evidence, decision, catalog, finalExcluded, [
8253
+ ...policyExclusions,
8254
+ ...lateExclusions,
8255
+ ]);
8256
+ });
8257
+ });
8258
+ }
8183
8259
  }
8184
8260
  catch (error) {
8185
8261
  if (isAbortError(error)) {
@@ -104,8 +104,9 @@ const resolveAgainstSchema = (text, schema) => {
104
104
  * The one place a finish reason becomes the unified spelling. Accepts the wire's
105
105
  * `finish_reason` (`tool_calls`, `content_filter`) and the unified spelling a
106
106
  * middleware's own finish part already carries (`tool-calls`, `content-filter`),
107
- * since both reach the stream path. Anything else, including `stop`, `error` and
108
- * an absent value, reads as `stop`.
107
+ * since both reach the stream path. Anything else, including `stop` and an
108
+ * absent value, reads as `stop`. A wire `error` finish never gets here: the SSE
109
+ * parser throws on it, and on a stream that ended with no terminal marker.
109
110
  */
110
111
  const toUnifiedFinishReason = (reason) => {
111
112
  switch (reason) {
@@ -14,6 +14,8 @@
14
14
  * module is to be the native replacement for the AI SDK's OpenAI wrapper.
15
15
  */
16
16
  import { createParser } from "eventsource-parser";
17
+ import { ErrorCategory, ErrorSeverity } from "../constants/enums.js";
18
+ import { NeuroLinkError } from "../utils/errorHandling.js";
17
19
  import { sanitizeToolName } from "../mcp/toolConverter.js";
18
20
  import { resolveSamplingParams } from "../models/modelRegistry.js";
19
21
  import { convertZodToJsonSchema, normalizeWireToolSchema, } from "../utils/schemaConversion.js";
@@ -725,13 +727,24 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
725
727
  };
726
728
  const decoder = new TextDecoder();
727
729
  let parseErr;
730
+ // An upstream error frame or `finish_reason: "error"`.
731
+ let streamErr;
732
+ // True once the upstream said it was done: `[DONE]` or any finish_reason.
733
+ let sawTerminal = false;
728
734
  // Key of the tool call the previous delta wrote to (for unindexed deltas).
729
735
  let lastToolCallKey;
730
736
  let nextToolCallKey = 0;
731
737
  const toolCallKeysById = new Map();
732
738
  const handleEvent = (msg) => {
739
+ if (streamErr) {
740
+ return;
741
+ }
733
742
  const data = msg.data;
734
- if (!data || data === "[DONE]") {
743
+ if (data === "[DONE]") {
744
+ sawTerminal = true;
745
+ return;
746
+ }
747
+ if (!data) {
735
748
  return;
736
749
  }
737
750
  let chunk;
@@ -742,6 +755,13 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
742
755
  parseErr = err instanceof Error ? err : new Error(String(err));
743
756
  return;
744
757
  }
758
+ if (chunk.error) {
759
+ streamErr ??= streamFailure("OPENAI_COMPAT_STREAM_ERROR_FRAME", `Upstream sent an error frame mid-stream: ${String(chunk.error.message ?? JSON.stringify(chunk.error)).slice(0, 500)}`, {
760
+ upstreamError: JSON.stringify(chunk.error).slice(0, 500),
761
+ partialTextLength: result.text.length,
762
+ });
763
+ return;
764
+ }
745
765
  if (chunk.usage) {
746
766
  result.usage = chunk.usage;
747
767
  }
@@ -828,7 +848,12 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
828
848
  }
829
849
  }
830
850
  }
851
+ if (choice.finish_reason === "error") {
852
+ streamErr ??= streamFailure("OPENAI_COMPAT_STREAM_FINISH_ERROR", 'Upstream ended the stream with finish_reason "error".', { partialTextLength: result.text.length });
853
+ return;
854
+ }
831
855
  if (choice.finish_reason) {
856
+ sawTerminal = true;
832
857
  result.finishReason = choice.finish_reason;
833
858
  }
834
859
  };
@@ -841,6 +866,15 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
841
866
  break;
842
867
  }
843
868
  parser.feed(decoder.decode(value, { stream: true }));
869
+ if (streamErr) {
870
+ try {
871
+ await reader.cancel();
872
+ }
873
+ catch {
874
+ // Keep the original upstream error when reader cleanup fails.
875
+ }
876
+ break;
877
+ }
844
878
  }
845
879
  parser.feed(decoder.decode());
846
880
  }
@@ -850,8 +884,26 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
850
884
  if (parseErr) {
851
885
  throw parseErr;
852
886
  }
887
+ if (streamErr) {
888
+ throw streamErr;
889
+ }
890
+ // The body closed without `[DONE]` or a finish_reason: truncated stream.
891
+ // Not retriable (same as ANTHROPIC_STREAM_TRUNCATED).
892
+ if (!sawTerminal) {
893
+ throw streamFailure("OPENAI_COMPAT_STREAM_TRUNCATED", "Stream ended before [DONE] or a finish_reason; the response is incomplete.", { partialTextLength: result.text.length });
894
+ }
853
895
  return result;
854
896
  };
897
+ function streamFailure(code, message, context) {
898
+ return new NeuroLinkError({
899
+ code,
900
+ message,
901
+ category: ErrorCategory.NETWORK,
902
+ severity: ErrorSeverity.HIGH,
903
+ retriable: false,
904
+ context,
905
+ });
906
+ }
855
907
  function extractOpenAICompatErrorMessage(parsed) {
856
908
  const message = parsed?.error?.message;
857
909
  if (typeof message === "string" && message.trim().length > 0) {
@@ -1,10 +1,13 @@
1
1
  /**
2
2
  * Enhanced proxy-aware fetch implementation for AI SDK providers
3
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
3
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
4
+ * SOCKS proxy URLs are recognized but not supported: a request that selects
5
+ * one falls back to a direct connection, or fails under strict mode
6
+ * (NEUROLINK_PROXY_STRICT, or `createProxyFetch({ strict: true })`).
4
7
  * Lightweight implementation extracted from research of major proxy packages
5
8
  */
6
9
  import type { Dispatcher, ProxyAgent } from "undici";
7
- import type { GoogleGenAIHttpOptions, ProxyTimeouts } from "../types/index.js";
10
+ import type { GoogleGenAIHttpOptions, ProxyTimeouts, ProxyFetchOptions } from "../types/index.js";
8
11
  /**
9
12
  * Classify a fetch failure as a transient network error worth retrying.
10
13
  *
@@ -39,11 +42,32 @@ export declare function getProxyDispatcherForUrl(targetUrl: string, timeouts?: P
39
42
  * The optional dispatcher preserves callers' direct-connection tuning.
40
43
  */
41
44
  export declare function fetchProxyAware(url: string | URL, init?: RequestInit, directDispatcher?: Dispatcher, proxyTimeouts?: ProxyTimeouts): Promise<Response>;
45
+ /**
46
+ * Whether NEUROLINK_PROXY_STRICT asks for "proxy or nothing": `true`, `1`,
47
+ * `yes` or `on` (any case). Any other value, or none, keeps the default of
48
+ * retrying a failed proxy attempt over a direct connection.
49
+ */
50
+ export declare function isProxyStrictMode(): boolean;
51
+ /**
52
+ * The WebSocket clients (`ws`) are built without a proxy agent, so they always
53
+ * connect directly. Call this before opening one: when a proxy is configured
54
+ * for `wsUrl` (and NO_PROXY does not exempt it), strict mode refuses the
55
+ * connection, and otherwise a warning says the socket bypasses the proxy.
56
+ * `label` names the client in the message; the URL itself is never logged,
57
+ * since some carry an API key in the query string.
58
+ */
59
+ export declare function assertWebSocketProxyPolicy(wsUrl: string, label: string): void;
42
60
  /**
43
61
  * Create a proxy-aware fetch function with enhanced capabilities
44
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
62
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
63
+ *
64
+ * By default a request whose proxy attempt fails is retried once over a
65
+ * direct connection, with a warning. Strict mode (`options.strict`, or
66
+ * NEUROLINK_PROXY_STRICT when the option is omitted) fails it instead. Strict
67
+ * mode never blocks a request NO_PROXY exempts, or one sent while no proxy is
68
+ * configured: those go direct by design.
45
69
  */
46
- export declare function createProxyFetch(): typeof fetch;
70
+ export declare function createProxyFetch(options?: ProxyFetchOptions): typeof fetch;
47
71
  /**
48
72
  * Mask credentials in a proxy URL for safe logging/reporting.
49
73
  *
@@ -63,6 +87,7 @@ export declare function getProxyStatus(): {
63
87
  allProxy: string | null;
64
88
  socksProxy: string | null;
65
89
  noProxy: string | null;
90
+ strict: boolean;
66
91
  method: string;
67
92
  capabilities: string[];
68
93
  };
@@ -1,6 +1,9 @@
1
1
  /**
2
2
  * Enhanced proxy-aware fetch implementation for AI SDK providers
3
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
3
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
4
+ * SOCKS proxy URLs are recognized but not supported: a request that selects
5
+ * one falls back to a direct connection, or fails under strict mode
6
+ * (NEUROLINK_PROXY_STRICT, or `createProxyFetch({ strict: true })`).
4
7
  * Lightweight implementation extracted from research of major proxy packages
5
8
  */
6
9
  import { logger } from "../utils/logger.js";
@@ -285,9 +288,11 @@ function getDefaultPort(protocol) {
285
288
  return 8080;
286
289
  case "https:":
287
290
  return 8080;
291
+ case "socks:":
288
292
  case "socks4:":
289
- return 1080;
293
+ case "socks4a:":
290
294
  case "socks5:":
295
+ case "socks5h:":
291
296
  return 1080;
292
297
  default:
293
298
  return 8080;
@@ -347,10 +352,14 @@ async function createProxyAgent(proxyUrl, timeouts = {}) {
347
352
  return new ProxyAgent({ uri: proxyUrl, ...timeouts });
348
353
  }
349
354
  case "socks4:":
350
- case "socks5:": {
351
- // SOCKS proxy support is not included in the build to avoid optional dependencies
352
- throw new Error(`SOCKS proxy support requires 'proxy-agent' package. ` +
353
- `Install it with: npm install proxy-agent`);
355
+ case "socks4a:":
356
+ case "socks5:":
357
+ case "socks5h:":
358
+ case "socks:": {
359
+ // No SOCKS client ships with the package, and installing one does not
360
+ // change that: this module never loads it.
361
+ throw new Error(`SOCKS proxies (${parsed.protocol}//) are not supported. ` +
362
+ `Use an HTTP(S) proxy, or an HTTP-to-SOCKS bridge in front of the SOCKS proxy`);
354
363
  }
355
364
  default:
356
365
  throw new Error(`Unsupported proxy protocol: ${parsed.protocol}`);
@@ -410,6 +419,46 @@ export async function fetchProxyAware(url, init, directDispatcher, proxyTimeouts
410
419
  }));
411
420
  return response;
412
421
  }
422
+ /**
423
+ * Whether NEUROLINK_PROXY_STRICT asks for "proxy or nothing": `true`, `1`,
424
+ * `yes` or `on` (any case). Any other value, or none, keeps the default of
425
+ * retrying a failed proxy attempt over a direct connection.
426
+ */
427
+ export function isProxyStrictMode() {
428
+ return /^(true|1|yes|on)$/i.test(process.env.NEUROLINK_PROXY_STRICT?.trim() ?? "");
429
+ }
430
+ /**
431
+ * The WebSocket clients (`ws`) are built without a proxy agent, so they always
432
+ * connect directly. Call this before opening one: when a proxy is configured
433
+ * for `wsUrl` (and NO_PROXY does not exempt it), strict mode refuses the
434
+ * connection, and otherwise a warning says the socket bypasses the proxy.
435
+ * `label` names the client in the message; the URL itself is never logged,
436
+ * since some carry an API key in the query string.
437
+ */
438
+ export function assertWebSocketProxyPolicy(wsUrl, label) {
439
+ let host;
440
+ let httpEquivalent;
441
+ try {
442
+ const url = new URL(wsUrl);
443
+ host = url.host;
444
+ url.protocol =
445
+ url.protocol === "wss:" || url.protocol === "https:" ? "https:" : "http:";
446
+ url.search = "";
447
+ httpEquivalent = url.toString();
448
+ }
449
+ catch {
450
+ return;
451
+ }
452
+ if (!selectProxyUrl(httpEquivalent)) {
453
+ return;
454
+ }
455
+ if (isProxyStrictMode()) {
456
+ throw new Error(`[Proxy] ${label} WebSocket to ${host} cannot be sent through the configured proxy, ` +
457
+ `and NEUROLINK_PROXY_STRICT forbids a direct connection`);
458
+ }
459
+ logger.warn(`[Proxy] ${label} WebSocket to ${host} connects directly: WebSocket clients do not use the configured proxy. ` +
460
+ `Set NEUROLINK_PROXY_STRICT=true to refuse the connection instead.`);
461
+ }
413
462
  function sanitizeProxyUrl(url) {
414
463
  return maskProxyUrl(url) ?? "NOT_SET";
415
464
  }
@@ -465,7 +514,7 @@ function createDirectFetchHandler() {
465
514
  }
466
515
  };
467
516
  }
468
- async function executeProxiedFetch(input, init, proxyEnv) {
517
+ async function executeProxiedFetch(input, init, proxyEnv, strict) {
469
518
  const { httpsProxy, httpProxy, allProxy, socksProxy, noProxy } = proxyEnv;
470
519
  init = injectTraceContext(input, init);
471
520
  const requestId = `req-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
@@ -529,10 +578,19 @@ async function executeProxiedFetch(input, init, proxyEnv) {
529
578
  let fetchInit = { ...init };
530
579
  if (input instanceof Request) {
531
580
  fetchInput = input.url;
581
+ // A Request's body is a ReadableStream, and undici refuses a stream
582
+ // body without `duplex: "half"`. Default mode keeps its long-standing
583
+ // behaviour: that TypeError sends the request down the direct
584
+ // fallback. Strict mode has no fallback, so there the stream is sent
585
+ // through the proxy. A caller's own `duplex` in `init` still wins.
586
+ // The Request's own signal rides along so aborting it cancels the
587
+ // proxied attempt; an `init.signal` still wins.
532
588
  fetchInit = {
533
589
  method: input.method,
534
590
  headers: input.headers,
535
591
  body: input.body,
592
+ signal: input.signal,
593
+ ...(strict && input.body ? { duplex: "half" } : {}),
536
594
  ...init,
537
595
  };
538
596
  }
@@ -585,10 +643,23 @@ async function executeProxiedFetch(input, init, proxyEnv) {
585
643
  requestId,
586
644
  error: errorMessage,
587
645
  errorType: error instanceof Error ? error.constructor.name : typeof error,
588
- willFallback: true,
646
+ willFallback: !strict,
589
647
  timestamp: new Date().toISOString(),
590
648
  });
591
- logger.warn(`[Proxy Fetch] Enhanced proxy failed (${errorMessage}), falling back to direct connection`);
649
+ if (strict) {
650
+ let host = "[unknown-host]";
651
+ try {
652
+ host = new URL(targetUrl).host;
653
+ }
654
+ catch {
655
+ // keep the placeholder
656
+ }
657
+ logger.warn(`[Proxy Fetch] Request to ${host} through the proxy failed (${errorMessage}); strict proxy mode is on, so it is not retried over a direct connection`);
658
+ // The original error, unwrapped: callers classify it (abort, transient
659
+ // network codes on `cause`) exactly as they would any fetch failure.
660
+ throw error;
661
+ }
662
+ logger.warn(`[Proxy Fetch] Enhanced proxy failed (${errorMessage}), falling back to direct connection. Set NEUROLINK_PROXY_STRICT=true to fail instead.`);
592
663
  }
593
664
  logger.debug(`[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH`, {
594
665
  requestId,
@@ -630,15 +701,22 @@ async function executeProxiedFetch(input, init, proxyEnv) {
630
701
  throw fallbackError;
631
702
  }
632
703
  }
633
- function createProxiedFetchHandler(proxyEnv) {
634
- return async (input, init) => executeProxiedFetch(input, init, proxyEnv);
704
+ function createProxiedFetchHandler(proxyEnv, strict) {
705
+ return async (input, init) => executeProxiedFetch(input, init, proxyEnv, strict);
635
706
  }
636
707
  // ==================== ENHANCED PROXY FETCH FUNCTION ====================
637
708
  /**
638
709
  * Create a proxy-aware fetch function with enhanced capabilities
639
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
710
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
711
+ *
712
+ * By default a request whose proxy attempt fails is retried once over a
713
+ * direct connection, with a warning. Strict mode (`options.strict`, or
714
+ * NEUROLINK_PROXY_STRICT when the option is omitted) fails it instead. Strict
715
+ * mode never blocks a request NO_PROXY exempts, or one sent while no proxy is
716
+ * configured: those go direct by design.
640
717
  */
641
- export function createProxyFetch() {
718
+ export function createProxyFetch(options) {
719
+ const strict = options?.strict ?? isProxyStrictMode();
642
720
  // Detect ALL proxy-related environment variables
643
721
  const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
644
722
  const httpProxy = process.env.HTTP_PROXY || process.env.http_proxy;
@@ -683,7 +761,8 @@ export function createProxyFetch() {
683
761
  logger.debug(`[Proxy Fetch] ALL_PROXY: ${sanitizeProxyUrl(allProxy)}`);
684
762
  logger.debug(`[Proxy Fetch] SOCKS_PROXY: ${sanitizeProxyUrl(socksProxy)}`);
685
763
  logger.debug(`[Proxy Fetch] NO_PROXY: ${noProxy || "not set"}`);
686
- return createProxiedFetchHandler(proxyEnv);
764
+ logger.debug(`[Proxy Fetch] Strict mode: ${strict}`);
765
+ return createProxiedFetchHandler(proxyEnv, strict);
687
766
  }
688
767
  /**
689
768
  * Mask credentials in a proxy URL for safe logging/reporting.
@@ -725,11 +804,12 @@ export function getProxyStatus() {
725
804
  allProxy: maskProxyUrl(allProxy),
726
805
  socksProxy: maskProxyUrl(socksProxy),
727
806
  noProxy: noProxy || null,
807
+ strict: isProxyStrictMode(),
728
808
  method: "enhanced-proxy-agent",
729
809
  capabilities: [
730
810
  "HTTP/HTTPS Proxy",
731
- "SOCKS4/SOCKS5 Proxy",
732
811
  "Proxy Authentication",
812
+ "Strict (fail-closed) Mode",
733
813
  "NO_PROXY Bypass",
734
814
  "CIDR Range Matching",
735
815
  "Wildcard Domain Matching",
@@ -10,6 +10,7 @@ import { NeuroLink } from "../../neurolink.js";
10
10
  import { logger } from "../../utils/logger.js";
11
11
  import { withTimeout } from "../../utils/async/withTimeout.js";
12
12
  import { getCartesiaWsUrl } from "../../adapters/tts/cartesiaHandler.js";
13
+ import { assertWebSocketProxyPolicy } from "../../proxy/proxyFetch.js";
13
14
  const __filename = fileURLToPath(import.meta.url);
14
15
  const __dirname = path.dirname(__filename);
15
16
  /**
@@ -185,8 +186,10 @@ async function warmup() {
185
186
  try {
186
187
  const { default: WebSocket } = await import("ws");
187
188
  const apiKey = process.env.CARTESIA_API_KEY;
189
+ const cartesiaWsUrl = getCartesiaWsUrl();
190
+ assertWebSocketProxyPolicy(cartesiaWsUrl, "Cartesia TTS warmup");
188
191
  await new Promise((resolve) => {
189
- const ws = new WebSocket(getCartesiaWsUrl(), {
192
+ const ws = new WebSocket(cartesiaWsUrl, {
190
193
  headers: apiKey ? { "X-API-Key": apiKey } : undefined,
191
194
  });
192
195
  const timeout = setTimeout(() => {
@@ -2,9 +2,10 @@ import WebSocket, { WebSocketServer } from "ws";
2
2
  import { FrameBus } from "./frameBus.js";
3
3
  import { TurnManager, TurnState } from "./turnManager.js";
4
4
  import { timingSafeEqualString } from "./tokenCompare.js";
5
- import { CartesiaStream } from "../../adapters/tts/cartesiaHandler.js";
5
+ import { CartesiaStream, getCartesiaWsUrl, } from "../../adapters/tts/cartesiaHandler.js";
6
6
  import { NeuroLink } from "../../neurolink.js";
7
7
  import { logger } from "../../utils/logger.js";
8
+ import { assertWebSocketProxyPolicy, isProxyStrictMode, } from "../../proxy/proxyFetch.js";
8
9
  import { tryImport } from "../../utils/tryImport.js";
9
10
  import { withTimeout } from "../../utils/async/withTimeout.js";
10
11
  async function loadCobra(accessKey) {
@@ -408,6 +409,21 @@ function handleClientBinaryAudio(data, clientWs, s) {
408
409
  async function handleVoiceConnection(clientWs, ctx) {
409
410
  const { neurolink, accessKey } = ctx;
410
411
  logger.info("[WS] Client connected");
412
+ // Under NEUROLINK_PROXY_STRICT, a session whose Soniox or Cartesia WebSocket
413
+ // would be refused cannot transcribe or speak. Refuse it here, before Cobra
414
+ // or any turn's LLM stream is allocated, and close the client with a visible
415
+ // failure instead of leaving it connected to a session that never answers.
416
+ if (isProxyStrictMode()) {
417
+ try {
418
+ assertWebSocketProxyPolicy(SONIOX_URL, "Soniox STT");
419
+ assertWebSocketProxyPolicy(getCartesiaWsUrl(), "Cartesia TTS");
420
+ }
421
+ catch (err) {
422
+ logger.error("[WS] Refusing voice session:", err.message);
423
+ clientWs.close(1011, "Voice upstream refused by proxy policy");
424
+ return;
425
+ }
426
+ }
411
427
  // --- Per-session Cobra instance ---
412
428
  // Use definite-assignment via early return on catch — avoids dead initial
413
429
  // values that ESLint flags as `no-useless-assignment` and matches the
@@ -561,6 +577,19 @@ async function handleVoiceConnection(clientWs, ctx) {
561
577
  }
562
578
  }
563
579
  function connectSoniox() {
580
+ try {
581
+ assertWebSocketProxyPolicy(SONIOX_URL, "Soniox STT");
582
+ }
583
+ catch (err) {
584
+ // Reached on a reconnect when the policy changed mid-session; the
585
+ // session start check covers the first connection. Without Soniox the
586
+ // session cannot transcribe, so it is closed rather than left silent.
587
+ logger.error("[SONIOX] Not connecting:", err.message);
588
+ if (!s.sessionClosed) {
589
+ clientWs.close(1011, "Soniox STT unavailable");
590
+ }
591
+ return;
592
+ }
564
593
  const ws = new WebSocket(SONIOX_URL);
565
594
  s.sonioxWs = ws;
566
595
  ws.on("open", () => {
@@ -0,0 +1,3 @@
1
+ import type { JevRoutingAuditEvidence, ToolRoutingCatalogEntry, ToolRoutingDecision } from "../types/index.js";
2
+ /** Create a native child only after the actual routing exclusions are applied. */
3
+ export declare const recordJevRoutingAudit: (evidence: JevRoutingAuditEvidence | null, decision: ToolRoutingDecision | undefined, catalog: ToolRoutingCatalogEntry[], finalExcludedTools: string[], preExistingExcludedTools?: string[]) => void;