@juspay/neurolink 13.12.6 → 13.13.1
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 +2 -2
- package/dist/adapters/tts/cartesiaHandler.js +4 -1
- package/dist/auth/tokenStore.d.ts +10 -0
- package/dist/auth/tokenStore.js +36 -0
- package/dist/browser/neurolink.min.js +444 -444
- package/dist/cli/commands/auth.d.ts +14 -1
- package/dist/cli/commands/auth.js +101 -25
- package/dist/cli/factories/authCommandFactory.js +5 -0
- 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/routes/codexProxyRoutes.d.ts +2 -2
- package/dist/server/routes/codexProxyRoutes.js +83 -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/codex.d.ts +16 -0
- package/dist/types/proxy.d.ts +19 -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
|
@@ -116,17 +116,42 @@ function readCodexRequestRefusal(status, errorText) {
|
|
|
116
116
|
*/
|
|
117
117
|
const codexRefreshInFlight = new Map();
|
|
118
118
|
async function refreshCodexTokenOnceWithDependencies(key, refreshToken, store, refresh) {
|
|
119
|
-
|
|
119
|
+
// Re-read the stored token instead of trusting the caller's snapshot. A
|
|
120
|
+
// request that captured the pool just before a previous refresh completed
|
|
121
|
+
// holds a token that has since been rotated; using it would spend a real
|
|
122
|
+
// attempt on a grant the server has already invalidated.
|
|
123
|
+
const latest = await store.peekTokens(key).catch(() => null);
|
|
124
|
+
const current = latest?.refreshToken ?? refreshToken;
|
|
125
|
+
// Flights are keyed by the token that is actually spent, read from the store
|
|
126
|
+
// rather than from the caller. Every caller for one account therefore
|
|
127
|
+
// shares one flight whatever snapshot it holds, and accounts that share a
|
|
128
|
+
// refresh token share it too. Nothing awaits between this lookup and the
|
|
129
|
+
// set below, so two callers cannot both start a flight.
|
|
130
|
+
const flightKey = current || key;
|
|
131
|
+
const existing = codexRefreshInFlight.get(flightKey);
|
|
120
132
|
if (existing) {
|
|
121
|
-
|
|
133
|
+
const resolved = await existing;
|
|
134
|
+
// Normally the owner's fan-out already persisted this key; this repairs
|
|
135
|
+
// the case where that write failed, and only while the stored token is
|
|
136
|
+
// still the one that was rotated.
|
|
137
|
+
await saveRotatedIfCurrent(store, key, current, resolved, latest?.scope);
|
|
138
|
+
return resolved;
|
|
122
139
|
}
|
|
123
140
|
const pending = (async () => {
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
//
|
|
128
|
-
|
|
129
|
-
|
|
141
|
+
// The peek above ran outside any flight. If a flight for this token ended
|
|
142
|
+
// between that peek and this point, `current` has already been rotated;
|
|
143
|
+
// spending it would be an invalid_grant. Re-read inside the flight and use
|
|
144
|
+
// what the finished flight stored instead of refreshing again.
|
|
145
|
+
if (latest) {
|
|
146
|
+
const fresh = await store.peekTokens(key).catch(() => null);
|
|
147
|
+
if (fresh?.refreshToken && fresh.refreshToken !== current) {
|
|
148
|
+
return {
|
|
149
|
+
accessToken: fresh.accessToken,
|
|
150
|
+
refreshToken: fresh.refreshToken,
|
|
151
|
+
expiresAt: fresh.expiresAt ?? latest.expiresAt ?? Date.now(),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
130
155
|
const refreshed = await refresh(current);
|
|
131
156
|
const resolved = {
|
|
132
157
|
accessToken: refreshed.accessToken,
|
|
@@ -138,19 +163,62 @@ async function refreshCodexTokenOnceWithDependencies(key, refreshToken, store, r
|
|
|
138
163
|
// rotating refresh token, receive an invalid_grant, and disable an account
|
|
139
164
|
// another request has already healed.
|
|
140
165
|
if (latest) {
|
|
141
|
-
await store
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
166
|
+
const saved = await saveRotatedIfCurrent(store, key, current, resolved, latest.scope);
|
|
167
|
+
if (!saved) {
|
|
168
|
+
logger.warn(`[codex] ${key} changed during refresh; kept the stored credential instead of the rotated token`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (store.getProviderSnapshot) {
|
|
172
|
+
let snapshot = {};
|
|
173
|
+
try {
|
|
174
|
+
snapshot = await store.getProviderSnapshot();
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
logger.warn(`[codex] could not read sibling accounts to propagate the rotated token: ${error instanceof Error ? error.message : String(error)}`);
|
|
178
|
+
}
|
|
179
|
+
for (const [siblingKey, entry] of Object.entries(snapshot)) {
|
|
180
|
+
if (!siblingKey.startsWith("codex:") ||
|
|
181
|
+
siblingKey === key ||
|
|
182
|
+
entry?.tokens?.refreshToken !== current) {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
await saveRotatedIfCurrent(store, siblingKey, current, resolved, entry.tokens?.scope);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
logger.warn(`[codex] could not propagate the rotated token to ${siblingKey}: ${error instanceof Error ? error.message : String(error)}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
146
192
|
}
|
|
147
193
|
return resolved;
|
|
148
194
|
})().finally(() => {
|
|
149
|
-
codexRefreshInFlight.delete(
|
|
195
|
+
codexRefreshInFlight.delete(flightKey);
|
|
150
196
|
});
|
|
151
|
-
codexRefreshInFlight.set(
|
|
197
|
+
codexRefreshInFlight.set(flightKey, pending);
|
|
152
198
|
return pending;
|
|
153
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Persist a rotated token for `key` only while its stored refresh token is
|
|
202
|
+
* still `rotatedFrom`, so a concurrent `auth login --force` import is never
|
|
203
|
+
* overwritten. Atomic under the token store's lock when it offers
|
|
204
|
+
* `saveTokensIf`; otherwise a best-effort peek-then-save.
|
|
205
|
+
*/
|
|
206
|
+
async function saveRotatedIfCurrent(store, key, rotatedFrom, resolved, scope) {
|
|
207
|
+
const tokens = {
|
|
208
|
+
...resolved,
|
|
209
|
+
tokenType: "Bearer",
|
|
210
|
+
...(scope ? { scope } : {}),
|
|
211
|
+
};
|
|
212
|
+
if (store.saveTokensIf) {
|
|
213
|
+
return store.saveTokensIf(key, tokens, (providers) => providers[key]?.tokens?.refreshToken === rotatedFrom);
|
|
214
|
+
}
|
|
215
|
+
const stored = await store.peekTokens(key).catch(() => null);
|
|
216
|
+
if (stored?.refreshToken !== rotatedFrom) {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
await store.saveTokens(key, tokens);
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
154
222
|
/** Refresh an account's token at most once at a time. */
|
|
155
223
|
async function refreshCodexTokenOnce(key, refreshToken) {
|
|
156
224
|
return refreshCodexTokenOnceWithDependencies(key, refreshToken, tokenStore, refreshCodexToken);
|
|
@@ -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/codex.d.ts
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* maps onto the session fields and its secondary window onto the weekly fields.
|
|
13
13
|
*/
|
|
14
14
|
import type { AccountCoolingReason, AccountQuota, ClaudeContentBlock, ClaudeTool, InternalResult } from "./proxy.js";
|
|
15
|
+
import type { StoredOAuthTokens } from "./auth.js";
|
|
15
16
|
/** Token block inside `~/.codex/auth.json`. */
|
|
16
17
|
export type CodexAuthFileTokens = {
|
|
17
18
|
id_token?: string;
|
|
@@ -40,6 +41,21 @@ export type CodexImportedCredential = {
|
|
|
40
41
|
/** Account email decoded from the id token, for the account label. */
|
|
41
42
|
email?: string;
|
|
42
43
|
};
|
|
44
|
+
/** Provider inventory as seen by a Codex credential import. */
|
|
45
|
+
export type CodexImportProviders = Record<string, {
|
|
46
|
+
tokens?: StoredOAuthTokens;
|
|
47
|
+
}>;
|
|
48
|
+
/** Token-store operations needed to import a Codex credential into the pool. */
|
|
49
|
+
export type CodexImportTokenStore = {
|
|
50
|
+
getProviderSnapshot: () => Promise<Record<string, {
|
|
51
|
+
tokens?: StoredOAuthTokens;
|
|
52
|
+
}>>;
|
|
53
|
+
saveTokensIf: (key: string, tokens: StoredOAuthTokens, guard: (providers: Record<string, {
|
|
54
|
+
tokens?: StoredOAuthTokens;
|
|
55
|
+
}>) => boolean, options?: {
|
|
56
|
+
enable?: boolean;
|
|
57
|
+
}) => Promise<boolean>;
|
|
58
|
+
};
|
|
43
59
|
/** Raw OpenAI OAuth token endpoint response. */
|
|
44
60
|
export type CodexTokenResponse = {
|
|
45
61
|
access_token?: string;
|
package/dist/types/proxy.d.ts
CHANGED
|
@@ -1076,6 +1076,14 @@ export type CodexRotationFailure = {
|
|
|
1076
1076
|
export type CodexRefreshTokenStore = {
|
|
1077
1077
|
peekTokens(provider: string): Promise<StoredOAuthTokens | null>;
|
|
1078
1078
|
saveTokens(provider: string, tokens: StoredOAuthTokens): Promise<void>;
|
|
1079
|
+
/** Compare-and-set save under the store's lock; the real token store has it. */
|
|
1080
|
+
saveTokensIf?(provider: string, tokens: StoredOAuthTokens, guard: (providers: Record<string, {
|
|
1081
|
+
tokens?: StoredOAuthTokens;
|
|
1082
|
+
}>) => boolean): Promise<boolean>;
|
|
1083
|
+
/** Present on the real token store; lets a refresh also reach sibling labels. */
|
|
1084
|
+
getProviderSnapshot?(): Promise<Record<string, {
|
|
1085
|
+
tokens?: StoredOAuthTokens;
|
|
1086
|
+
}>>;
|
|
1079
1087
|
};
|
|
1080
1088
|
/** Result contract for a Codex OAuth refresh operation. */
|
|
1081
1089
|
export type CodexTokenRefresher = (refreshToken: string) => Promise<{
|
|
@@ -2061,6 +2069,17 @@ export type ProxyTimeouts = {
|
|
|
2061
2069
|
headersTimeout?: number;
|
|
2062
2070
|
bodyTimeout?: number;
|
|
2063
2071
|
};
|
|
2072
|
+
/** Options for `createProxyFetch`. */
|
|
2073
|
+
export type ProxyFetchOptions = {
|
|
2074
|
+
/**
|
|
2075
|
+
* `true`: a request whose proxy attempt fails (the proxy is unreachable or
|
|
2076
|
+
* refuses it, its URL is unparsable, or it is a SOCKS URL, which is not
|
|
2077
|
+
* supported) fails with that error instead of being retried over a direct
|
|
2078
|
+
* connection. Omitted: `NEUROLINK_PROXY_STRICT` decides, and with that unset
|
|
2079
|
+
* the request falls back to a direct connection, as it always has.
|
|
2080
|
+
*/
|
|
2081
|
+
strict?: boolean;
|
|
2082
|
+
};
|
|
2064
2083
|
/** Result of a traffic-quiet check. */
|
|
2065
2084
|
export type QuietStatus = {
|
|
2066
2085
|
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;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { diag } from "@opentelemetry/api";
|
|
3
|
+
import { decodeArray, decodeString } from "type-decoder/dist/index.js";
|
|
4
|
+
import { JEV_ROUTING_AUDIT_COMPONENT, JEV_ROUTING_AUDIT_LIMITS, } from "../core/constants.js";
|
|
5
|
+
import { logger } from "./logger.js";
|
|
6
|
+
import { isPlainObject } from "./typeUtils.js";
|
|
7
|
+
/** Never log the query, catalogue or provider error body. */
|
|
8
|
+
export const logJevRoutingAuditFailure = (error) => {
|
|
9
|
+
let errorType = "UnknownError";
|
|
10
|
+
if (error instanceof Error) {
|
|
11
|
+
errorType = error.name;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
logger.warn(`${JEV_ROUTING_AUDIT_COMPONENT} Evidence recording failed`, {
|
|
15
|
+
errorType: errorType,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
try {
|
|
20
|
+
diag.warn(JEV_ROUTING_AUDIT_COMPONENT, "Audit failure logging failed");
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const decodeAvailableServer = (value) => {
|
|
28
|
+
if (!isPlainObject(value)) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const name = decodeString(value.name);
|
|
32
|
+
const does = decodeString(value.does);
|
|
33
|
+
if (name === null || does === null) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
return { name: name, does: does };
|
|
37
|
+
};
|
|
38
|
+
export const buildJevRoutingAuditInput = (state) => {
|
|
39
|
+
try {
|
|
40
|
+
if (!isPlainObject(state)) {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const request = decodeString(state.request);
|
|
44
|
+
if (request === null) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
if (!Array.isArray(state.available_servers) ||
|
|
48
|
+
state.available_servers.length === 0) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const availableServers = decodeArray(state.available_servers.slice(0, JEV_ROUTING_AUDIT_LIMITS.candidateServers), decodeAvailableServer);
|
|
52
|
+
if (availableServers === null) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
let evidenceComplete = true;
|
|
56
|
+
if (request.trim().length === 0 ||
|
|
57
|
+
request.length > JEV_ROUTING_AUDIT_LIMITS.queryCharacters) {
|
|
58
|
+
evidenceComplete = false;
|
|
59
|
+
}
|
|
60
|
+
if (state.available_servers.length > JEV_ROUTING_AUDIT_LIMITS.candidateServers) {
|
|
61
|
+
evidenceComplete = false;
|
|
62
|
+
}
|
|
63
|
+
const candidateServers = availableServers.map((server) => {
|
|
64
|
+
const serverIdIsComplete = server.name.trim().length > 0 &&
|
|
65
|
+
server.name.length <= JEV_ROUTING_AUDIT_LIMITS.serverIdCharacters;
|
|
66
|
+
const capabilityIsComplete = server.does.trim().length > 0 &&
|
|
67
|
+
server.does.length <= JEV_ROUTING_AUDIT_LIMITS.capabilityCharacters;
|
|
68
|
+
if (!serverIdIsComplete || !capabilityIsComplete) {
|
|
69
|
+
evidenceComplete = false;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
id: server.name.slice(0, JEV_ROUTING_AUDIT_LIMITS.serverIdCharacters),
|
|
73
|
+
capability: server.does.slice(0, JEV_ROUTING_AUDIT_LIMITS.capabilityCharacters),
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
const catalogueVersion = createHash("sha256")
|
|
77
|
+
.update(JSON.stringify({
|
|
78
|
+
total: state.available_servers.length,
|
|
79
|
+
candidates: availableServers,
|
|
80
|
+
}))
|
|
81
|
+
.digest("hex");
|
|
82
|
+
const input = {
|
|
83
|
+
queryWithRoutingContext: request.slice(0, JEV_ROUTING_AUDIT_LIMITS.queryCharacters),
|
|
84
|
+
candidateServers: candidateServers,
|
|
85
|
+
catalogueVersion: catalogueVersion,
|
|
86
|
+
evidenceComplete: evidenceComplete,
|
|
87
|
+
};
|
|
88
|
+
if (JSON.stringify(input).length >
|
|
89
|
+
JEV_ROUTING_AUDIT_LIMITS.serializedInputCharacters) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
return input;
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
logJevRoutingAuditFailure(error);
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
export const buildJevRoutingAuditSelection = (candidates, catalog, finalExcludedTools, preExistingExcludedTools) => {
|
|
100
|
+
const excludedTools = new Set(finalExcludedTools);
|
|
101
|
+
const candidateIds = new Set(candidates.map((server) => server.id));
|
|
102
|
+
const candidateToolNames = catalog
|
|
103
|
+
.filter((server) => candidateIds.has(server.id))
|
|
104
|
+
.flatMap((server) => server.toolNames);
|
|
105
|
+
const candidateTools = new Set(candidateToolNames);
|
|
106
|
+
const retainedServers = [];
|
|
107
|
+
const excludedServers = [];
|
|
108
|
+
let selectionComplete = true;
|
|
109
|
+
// Policy exclusions must not be scored as JEV mistakes.
|
|
110
|
+
if (preExistingExcludedTools.some((name) => candidateTools.has(name))) {
|
|
111
|
+
selectionComplete = false;
|
|
112
|
+
}
|
|
113
|
+
if (candidateIds.size !== candidates.length) {
|
|
114
|
+
selectionComplete = false;
|
|
115
|
+
}
|
|
116
|
+
for (const candidate of candidates) {
|
|
117
|
+
const matchingServers = catalog.filter((server) => server.id === candidate.id);
|
|
118
|
+
if (matchingServers.length !== 1) {
|
|
119
|
+
selectionComplete = false;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const server = matchingServers[0];
|
|
123
|
+
if (server.toolNames.length === 0) {
|
|
124
|
+
selectionComplete = false;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const allToolsExcluded = server.toolNames.every((name) => excludedTools.has(name));
|
|
128
|
+
if (allToolsExcluded) {
|
|
129
|
+
excludedServers.push(candidate.id);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
retainedServers.push(candidate.id);
|
|
133
|
+
const someToolsExcluded = server.toolNames.some((name) => excludedTools.has(name));
|
|
134
|
+
if (someToolsExcluded) {
|
|
135
|
+
selectionComplete = false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const excludedToolCount = candidateToolNames.filter((name) => excludedTools.has(name)).length;
|
|
139
|
+
return {
|
|
140
|
+
retainedServers: retainedServers,
|
|
141
|
+
excludedServers: excludedServers,
|
|
142
|
+
selectionComplete: selectionComplete,
|
|
143
|
+
excludedToolCount: excludedToolCount,
|
|
144
|
+
};
|
|
145
|
+
};
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*
|
|
14
14
|
* See docs/features/livekit-voice-agent.md.
|
|
15
15
|
*/
|
|
16
|
+
import { assertWebSocketProxyPolicy } from "../../proxy/proxyFetch.js";
|
|
16
17
|
import { requireWebSocketUrl } from "./config.js";
|
|
17
18
|
import { observeXaiSession } from "./xaiSessionWatch.js";
|
|
18
19
|
/**
|
|
@@ -28,7 +29,37 @@ export function requireXaiApiKey() {
|
|
|
28
29
|
throw new Error("XAI_API_KEY is not set; the xai realtime backend reads its key from that environment variable");
|
|
29
30
|
}
|
|
30
31
|
}
|
|
32
|
+
/** The xAI realtime endpoint the plugin connects to when no base URL is set. */
|
|
33
|
+
const XAI_REALTIME_DEFAULT_URL = "wss://api.x.ai/v1";
|
|
34
|
+
/**
|
|
35
|
+
* The Vertex AI Live endpoint the Google plugin connects to for `cfg`. The
|
|
36
|
+
* plugin resolves the location as `cfg.location`, then
|
|
37
|
+
* `GOOGLE_CLOUD_LOCATION`, then `us-central1`, and `@google/genai` maps it to
|
|
38
|
+
* a host. Only the host matters here: it is what proxy and NO_PROXY rules
|
|
39
|
+
* match against.
|
|
40
|
+
*/
|
|
41
|
+
function vertexLiveWebSocketUrl(cfg) {
|
|
42
|
+
// `@google/genai` and the Vertex provider both let GOOGLE_VERTEX_BASE_URL
|
|
43
|
+
// replace the regional host, so a policy check on the canonical host alone
|
|
44
|
+
// would let a custom endpoint bypass strict mode.
|
|
45
|
+
const baseURL = process.env.GOOGLE_VERTEX_BASE_URL?.trim();
|
|
46
|
+
if (baseURL) {
|
|
47
|
+
return baseURL;
|
|
48
|
+
}
|
|
49
|
+
const location = cfg.location || process.env.GOOGLE_CLOUD_LOCATION || "us-central1";
|
|
50
|
+
if (location === "global") {
|
|
51
|
+
return "wss://aiplatform.googleapis.com";
|
|
52
|
+
}
|
|
53
|
+
if (location === "us" || location === "eu") {
|
|
54
|
+
return `wss://aiplatform.${location}.rep.googleapis.com`;
|
|
55
|
+
}
|
|
56
|
+
return `wss://${location}-aiplatform.googleapis.com`;
|
|
57
|
+
}
|
|
31
58
|
async function createGeminiRealtimeLlm(cfg) {
|
|
59
|
+
// The plugin's WebSocket does not go through the configured proxy, so the
|
|
60
|
+
// proxy policy is checked before the plugin is loaded: it warns, or under
|
|
61
|
+
// NEUROLINK_PROXY_STRICT refuses before any session can connect.
|
|
62
|
+
assertWebSocketProxyPolicy(vertexLiveWebSocketUrl(cfg), "Gemini Live (LiveKit realtime)");
|
|
32
63
|
const google = await import("@livekit/agents-plugin-google");
|
|
33
64
|
const { Modality } = await import("@google/genai");
|
|
34
65
|
const modality = Object.values(Modality).find((value) => value === cfg.responseModality);
|
|
@@ -62,6 +93,9 @@ async function createXaiRealtimeLlm(cfg) {
|
|
|
62
93
|
if (cfg.xaiBaseURL) {
|
|
63
94
|
requireWebSocketUrl(cfg.xaiBaseURL, "xaiBaseURL");
|
|
64
95
|
}
|
|
96
|
+
// As for gemini: checked before the plugin loads, so a refusal under
|
|
97
|
+
// NEUROLINK_PROXY_STRICT leaves no model that could open a session.
|
|
98
|
+
assertWebSocketProxyPolicy(cfg.xaiBaseURL || XAI_REALTIME_DEFAULT_URL, "xAI realtime (LiveKit)");
|
|
65
99
|
const xai = await import("@livekit/agents-plugin-xai");
|
|
66
100
|
// Keys are added only when set. The plugin spreads these options over its
|
|
67
101
|
// own defaults, so a key holding `undefined` would erase the default: a
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* See docs/features/livekit-voice-agent.md.
|
|
16
16
|
*/
|
|
17
17
|
import { ReadableStream } from "node:stream/web";
|
|
18
|
+
import { assertWebSocketProxyPolicy } from "../../proxy/proxyFetch.js";
|
|
18
19
|
import { logger } from "../../utils/logger.js";
|
|
19
20
|
import { markAgentDefinition } from "./agentDefinition.js";
|
|
20
21
|
import { createVoiceBrain } from "./brain.js";
|
|
@@ -146,6 +147,9 @@ async function loadVad(config) {
|
|
|
146
147
|
*/
|
|
147
148
|
async function buildStt(config) {
|
|
148
149
|
if (config.provider === "soniox") {
|
|
150
|
+
// The STT and TTS plugins open their WebSockets without the configured
|
|
151
|
+
// proxy, so each checks the proxy policy for its endpoint before it loads.
|
|
152
|
+
assertWebSocketProxyPolicy("wss://stt-rt.soniox.com/transcribe-websocket", "Soniox STT (LiveKit)");
|
|
149
153
|
const soniox = await import("@livekit/agents-plugin-soniox");
|
|
150
154
|
const opts = {};
|
|
151
155
|
if (config.model !== undefined) {
|
|
@@ -165,6 +169,7 @@ async function buildStt(config) {
|
|
|
165
169
|
return new soniox.STT(opts);
|
|
166
170
|
}
|
|
167
171
|
if (config.provider === "deepgram") {
|
|
172
|
+
assertWebSocketProxyPolicy("wss://api.deepgram.com/v1/listen", "Deepgram STT (LiveKit)");
|
|
168
173
|
const deepgram = await import("@livekit/agents-plugin-deepgram");
|
|
169
174
|
const opts = {};
|
|
170
175
|
if (config.language !== undefined) {
|
|
@@ -182,6 +187,7 @@ async function buildStt(config) {
|
|
|
182
187
|
*/
|
|
183
188
|
async function buildTts(config) {
|
|
184
189
|
if (config.provider === "cartesia") {
|
|
190
|
+
assertWebSocketProxyPolicy("wss://api.cartesia.ai/tts/websocket", "Cartesia TTS (LiveKit)");
|
|
185
191
|
const cartesia = await import("@livekit/agents-plugin-cartesia");
|
|
186
192
|
const opts = {};
|
|
187
193
|
if (config.voice !== undefined) {
|
|
@@ -193,6 +199,7 @@ async function buildTts(config) {
|
|
|
193
199
|
return new cartesia.TTS(opts);
|
|
194
200
|
}
|
|
195
201
|
if (config.provider === "elevenlabs") {
|
|
202
|
+
assertWebSocketProxyPolicy("wss://api.elevenlabs.io/v1", "ElevenLabs TTS (LiveKit)");
|
|
196
203
|
const elevenlabs = await import("@livekit/agents-plugin-elevenlabs");
|
|
197
204
|
const opts = {};
|
|
198
205
|
if (config.voice !== undefined) {
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* @module voice/providers/DeepgramSTT
|
|
7
7
|
*/
|
|
8
8
|
import { logger } from "../../utils/logger.js";
|
|
9
|
+
import { assertWebSocketProxyPolicy } from "../../proxy/proxyFetch.js";
|
|
9
10
|
import { STTError } from "../errors.js";
|
|
10
11
|
const DEFAULT_BASE_URL = "https://api.deepgram.com/v1";
|
|
11
12
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
@@ -393,6 +394,7 @@ export class DeepgramSTT {
|
|
|
393
394
|
// Indicate interim results
|
|
394
395
|
params.set("interim_results", "true");
|
|
395
396
|
const wsUrl = `${this.wsBaseUrl}/listen?${params.toString()}`;
|
|
397
|
+
assertWebSocketProxyPolicy(wsUrl, "Deepgram STT");
|
|
396
398
|
// Create WebSocket connection
|
|
397
399
|
const WebSocket = (await import("ws")).default;
|
|
398
400
|
const ws = new WebSocket(wsUrl, {
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { logger } from "../../utils/logger.js";
|
|
9
9
|
import { redactUrlsInText } from "../../utils/logSanitize.js";
|
|
10
|
+
import { assertWebSocketProxyPolicy } from "../../proxy/proxyFetch.js";
|
|
10
11
|
import { RealtimeError } from "../errors.js";
|
|
11
12
|
import { BaseRealtimeHandler } from "../RealtimeVoiceAPI.js";
|
|
12
13
|
/**
|
|
@@ -69,6 +70,7 @@ export class GeminiLive extends BaseRealtimeHandler {
|
|
|
69
70
|
// key as a query parameter; every error below is scrubbed with
|
|
70
71
|
// `redactUrlsInText` so that URL never reaches a log or a caller.
|
|
71
72
|
const wsUrl = `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key=${this.apiKey}`;
|
|
73
|
+
assertWebSocketProxyPolicy(wsUrl, "Gemini Live");
|
|
72
74
|
this.ws = new WebSocket(wsUrl);
|
|
73
75
|
// Issue 9: capture a local reference so the closure below doesn't need
|
|
74
76
|
// a non-null assertion on `this.ws`. The local `ws` survives even if a
|