@juspay/neurolink 13.12.6 → 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.
- package/CHANGELOG.md +6 -2
- package/dist/adapters/tts/cartesiaHandler.js +4 -1
- package/dist/browser/neurolink.min.js +444 -444
- package/dist/core/constants.d.ts +11 -0
- package/dist/core/constants.js +11 -0
- package/dist/neurolink.d.ts +3 -0
- package/dist/neurolink.js +78 -2
- package/dist/proxy/proxyFetch.d.ts +29 -4
- package/dist/proxy/proxyFetch.js +95 -15
- package/dist/server/voice/voiceServerApp.js +4 -1
- package/dist/server/voice/voiceWebSocketHandler.js +30 -1
- package/dist/telemetry/jevRoutingAudit.d.ts +3 -0
- package/dist/telemetry/jevRoutingAudit.js +55 -0
- package/dist/types/proxy.d.ts +11 -0
- package/dist/types/toolRouting.d.ts +36 -0
- package/dist/utils/jevRoutingAudit.d.ts +5 -0
- package/dist/utils/jevRoutingAudit.js +145 -0
- package/dist/voice/livekit/realtimeModel.js +34 -0
- package/dist/voice/livekit/voiceAgent.js +7 -0
- package/dist/voice/providers/DeepgramSTT.js +2 -0
- package/dist/voice/providers/GeminiLive.js +2 -0
- package/dist/voice/providers/OpenAIRealtime.js +2 -0
- package/docs-site/static/search-index.json +10 -7
- package/package.json +4 -2
package/dist/core/constants.d.ts
CHANGED
|
@@ -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;
|
package/dist/core/constants.js
CHANGED
|
@@ -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: (() => {
|
package/dist/neurolink.d.ts
CHANGED
|
@@ -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) =>
|
|
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)) {
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Enhanced proxy-aware fetch implementation for AI SDK providers
|
|
3
|
-
* Supports HTTP/HTTPS
|
|
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
|
|
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
|
};
|
package/dist/proxy/proxyFetch.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Enhanced proxy-aware fetch implementation for AI SDK providers
|
|
3
|
-
* Supports HTTP/HTTPS
|
|
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
|
-
|
|
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 "
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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:
|
|
646
|
+
willFallback: !strict,
|
|
589
647
|
timestamp: new Date().toISOString(),
|
|
590
648
|
});
|
|
591
|
-
|
|
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
|
|
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
|
-
|
|
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(
|
|
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;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { trace } from "@opentelemetry/api";
|
|
2
|
+
import { JEV_ROUTING_AUDIT_OBSERVATION_NAME, JEV_ROUTING_AUDIT_PROVIDER, JEV_ROUTING_AUDIT_SCHEMA_VERSION, } from "../core/constants.js";
|
|
3
|
+
import { buildJevRoutingAuditSelection, logJevRoutingAuditFailure, } from "../utils/jevRoutingAudit.js";
|
|
4
|
+
import { observe } from "./observation.js";
|
|
5
|
+
import { tracers } from "./tracers.js";
|
|
6
|
+
/** Create a native child only after the actual routing exclusions are applied. */
|
|
7
|
+
export const recordJevRoutingAudit = (evidence, decision, catalog, finalExcludedTools, preExistingExcludedTools = []) => {
|
|
8
|
+
try {
|
|
9
|
+
if (evidence === null || evidence.provider !== JEV_ROUTING_AUDIT_PROVIDER) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
if (decision === undefined) {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const serverRoutingWasApplied = decision.strategy === "decision" &&
|
|
16
|
+
decision.outcome === "applied" &&
|
|
17
|
+
decision.granularity !== "tool";
|
|
18
|
+
if (!serverRoutingWasApplied) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const parent = trace.getActiveSpan();
|
|
22
|
+
if (!parent?.isRecording()) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const selection = buildJevRoutingAuditSelection(evidence.input.candidateServers, catalog, finalExcludedTools, preExistingExcludedTools);
|
|
26
|
+
let evaluable = false;
|
|
27
|
+
if (evidence.input.evidenceComplete && selection.selectionComplete) {
|
|
28
|
+
evaluable = true;
|
|
29
|
+
}
|
|
30
|
+
const output = {
|
|
31
|
+
retainedServers: selection.retainedServers,
|
|
32
|
+
excludedServers: selection.excludedServers,
|
|
33
|
+
routingStrategy: decision.strategy,
|
|
34
|
+
outcome: decision.outcome,
|
|
35
|
+
evaluable: evaluable,
|
|
36
|
+
excludedToolCount: selection.excludedToolCount,
|
|
37
|
+
};
|
|
38
|
+
const span = tracers.decision.startSpan(JEV_ROUTING_AUDIT_OBSERVATION_NAME, {
|
|
39
|
+
attributes: {
|
|
40
|
+
"jev.audit.schema_version": JEV_ROUTING_AUDIT_SCHEMA_VERSION,
|
|
41
|
+
"jev.audit.evaluable": evaluable,
|
|
42
|
+
"jev.audit.provider": evidence.provider,
|
|
43
|
+
"jev.audit.model": evidence.model,
|
|
44
|
+
"jev.audit.decision_succeeded": true,
|
|
45
|
+
"jev.audit.source_span_id": parent.spanContext().spanId,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
// observe() masks credentials and omits input when NEUROLINK_RECORD_INPUTS=false.
|
|
49
|
+
observe(span, "span", { input: evidence.input, output: output });
|
|
50
|
+
span.end();
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
logJevRoutingAuditFailure(error);
|
|
54
|
+
}
|
|
55
|
+
};
|
package/dist/types/proxy.d.ts
CHANGED
|
@@ -2061,6 +2061,17 @@ export type ProxyTimeouts = {
|
|
|
2061
2061
|
headersTimeout?: number;
|
|
2062
2062
|
bodyTimeout?: number;
|
|
2063
2063
|
};
|
|
2064
|
+
/** Options for `createProxyFetch`. */
|
|
2065
|
+
export type ProxyFetchOptions = {
|
|
2066
|
+
/**
|
|
2067
|
+
* `true`: a request whose proxy attempt fails (the proxy is unreachable or
|
|
2068
|
+
* refuses it, its URL is unparsable, or it is a SOCKS URL, which is not
|
|
2069
|
+
* supported) fails with that error instead of being retried over a direct
|
|
2070
|
+
* connection. Omitted: `NEUROLINK_PROXY_STRICT` decides, and with that unset
|
|
2071
|
+
* the request falls back to a direct connection, as it always has.
|
|
2072
|
+
*/
|
|
2073
|
+
strict?: boolean;
|
|
2074
|
+
};
|
|
2064
2075
|
/** Result of a traffic-quiet check. */
|
|
2065
2076
|
export type QuietStatus = {
|
|
2066
2077
|
isQuiet: boolean;
|
|
@@ -114,6 +114,15 @@ export type ToolRoutingConfig = {
|
|
|
114
114
|
generateFn?: (options: GenerateOptions) => Promise<GenerateResult>;
|
|
115
115
|
/** Master switch. Routing runs only when true AND the server catalog is non-empty. */
|
|
116
116
|
enabled: boolean;
|
|
117
|
+
/**
|
|
118
|
+
* Record bounded JEV routing evidence through the existing tracing exporter.
|
|
119
|
+
* Defaults off because queries and descriptions may contain user data.
|
|
120
|
+
* Hosts can pass true directly; a feature flag is not required.
|
|
121
|
+
* No extra inference calls. Cache hits and non-JEV routing are omitted.
|
|
122
|
+
*/
|
|
123
|
+
audit?: {
|
|
124
|
+
enabled: boolean;
|
|
125
|
+
};
|
|
117
126
|
/**
|
|
118
127
|
* Routable server catalog. Hosts that only know their servers after
|
|
119
128
|
* constructing NeuroLink can supply it later via
|
|
@@ -197,6 +206,33 @@ export type ToolRoutingCatalogEntry = {
|
|
|
197
206
|
/** Registered tool names for this server, i.e. `${serverId}_${toolName}`. */
|
|
198
207
|
toolNames: string[];
|
|
199
208
|
};
|
|
209
|
+
export type JevRoutingAuditAvailableServer = {
|
|
210
|
+
name: string;
|
|
211
|
+
does: string;
|
|
212
|
+
};
|
|
213
|
+
export type JevRoutingAuditCandidate = {
|
|
214
|
+
id: string;
|
|
215
|
+
capability: string;
|
|
216
|
+
};
|
|
217
|
+
/** Bounded server-level evidence consumed by routing evaluators. */
|
|
218
|
+
export type JevRoutingAuditInput = {
|
|
219
|
+
queryWithRoutingContext: string;
|
|
220
|
+
candidateServers: JevRoutingAuditCandidate[];
|
|
221
|
+
catalogueVersion: string;
|
|
222
|
+
evidenceComplete: boolean;
|
|
223
|
+
};
|
|
224
|
+
/** Per-call snapshot; never stored on the NeuroLink instance or in a cache. */
|
|
225
|
+
export type JevRoutingAuditEvidence = {
|
|
226
|
+
input: JevRoutingAuditInput;
|
|
227
|
+
provider: string;
|
|
228
|
+
model: string;
|
|
229
|
+
};
|
|
230
|
+
export type JevRoutingAuditSelection = {
|
|
231
|
+
retainedServers: string[];
|
|
232
|
+
excludedServers: string[];
|
|
233
|
+
selectionComplete: boolean;
|
|
234
|
+
excludedToolCount: number;
|
|
235
|
+
};
|
|
200
236
|
/** Internal cache entry for `ToolRoutingCache`. */
|
|
201
237
|
export type ToolRoutingCacheEntry = {
|
|
202
238
|
excludedToolNames: string[];
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { JevRoutingAuditCandidate, JevRoutingAuditInput, JevRoutingAuditSelection, ToolRoutingCatalogEntry } from "../types/index.js";
|
|
2
|
+
/** Never log the query, catalogue or provider error body. */
|
|
3
|
+
export declare const logJevRoutingAuditFailure: (error: unknown) => void;
|
|
4
|
+
export declare const buildJevRoutingAuditInput: (state: unknown) => JevRoutingAuditInput | null;
|
|
5
|
+
export declare const buildJevRoutingAuditSelection: (candidates: JevRoutingAuditCandidate[], catalog: ToolRoutingCatalogEntry[], finalExcludedTools: string[], preExistingExcludedTools: string[]) => JevRoutingAuditSelection;
|