@juspay/neurolink 13.13.3 → 13.13.4

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.
@@ -38,7 +38,7 @@ import { z } from "zod";
38
38
  import { logger } from "../utils/logger.js";
39
39
  import { withTimeout } from "../utils/async/index.js";
40
40
  import { selectRelevantToolNames } from "./toolRoutingEmbedding.js";
41
- import { selectServersByDecision } from "./toolRoutingDecision.js";
41
+ import { selectServersByDecision, ToolRoutingDecisionTimeoutError, } from "./toolRoutingDecision.js";
42
42
  const routerOutputSchema = z.object({
43
43
  servers: z.array(z.string()),
44
44
  });
@@ -498,8 +498,9 @@ export async function resolveToolRoutingExclusions(params) {
498
498
  return excludedToolNames;
499
499
  }
500
500
  catch (error) {
501
- const isTimeout = error instanceof Error &&
502
- error.message.includes("Tool routing router call exceeded");
501
+ const isTimeout = error instanceof ToolRoutingDecisionTimeoutError ||
502
+ (error instanceof Error &&
503
+ error.message.includes("Tool routing router call exceeded"));
503
504
  const outcome = isTimeout
504
505
  ? "failed-open-timeout"
505
506
  : "failed-open-error";
@@ -22,6 +22,16 @@
22
22
  * @module core/toolRoutingDecision
23
23
  */
24
24
  import type { DecisionCallerFn, ToolRoutingCatalogEntry, ToolRoutingDecisionOutcome } from "../types/index.js";
25
+ /**
26
+ * Thrown by a host-bound `decideFn` when a configured decision provider did
27
+ * not answer inside `toolRouting.timeoutMs`. It is distinct from `null`
28
+ * ("no provider", which falls back to the generative router): after a timeout
29
+ * the router must add no exclusions, or a slow decision model would hand the
30
+ * turn to a second, unbounded model that can still drop tools.
31
+ */
32
+ export declare class ToolRoutingDecisionTimeoutError extends Error {
33
+ constructor(timeoutMs: number);
34
+ }
25
35
  /**
26
36
  * Ask one yes/no question per routable server and return the servers to keep.
27
37
  *
@@ -23,6 +23,19 @@
23
23
  */
24
24
  import { decisionKey, gateDecisionBoolean } from "../utils/decisionAnswers.js";
25
25
  import { logger } from "../utils/logger.js";
26
+ /**
27
+ * Thrown by a host-bound `decideFn` when a configured decision provider did
28
+ * not answer inside `toolRouting.timeoutMs`. It is distinct from `null`
29
+ * ("no provider", which falls back to the generative router): after a timeout
30
+ * the router must add no exclusions, or a slow decision model would hand the
31
+ * turn to a second, unbounded model that can still drop tools.
32
+ */
33
+ export class ToolRoutingDecisionTimeoutError extends Error {
34
+ constructor(timeoutMs) {
35
+ super(`Tool routing decision exceeded ${timeoutMs}ms`);
36
+ this.name = "ToolRoutingDecisionTimeoutError";
37
+ }
38
+ }
26
39
  /** Namespace for the per-server questions in the batch. */
27
40
  const SERVER_NAMESPACE = "server";
28
41
  /**
package/dist/neurolink.js CHANGED
@@ -37,6 +37,7 @@ import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, JEV_ROUTING_AUDIT_PROVI
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";
40
+ import { ToolRoutingDecisionTimeoutError } from "./core/toolRoutingDecision.js";
40
41
  import { DEFAULT_RECENT_TURNS, KnowledgeGroundingEngine, } from "./knowledge/index.js";
41
42
  import { AnthropicThreadStore } from "./providers/anthropic/threads.js";
42
43
  import { AIProviderFactory } from "./core/factory.js";
@@ -8185,7 +8186,112 @@ Current user's request: ${currentInput}`;
8185
8186
  if (auditEnabled) {
8186
8187
  auditInput = buildJevRoutingAuditInput(decisionOptions.state);
8187
8188
  }
8188
- const result = await this.siteDecide(decisionOptions, this.decisionSiteContext(options, sessionId || undefined));
8189
+ // One deadline for the whole provider call (every retry and
8190
+ // backoff included), enforced by aborting the in-flight request
8191
+ // and by not waiting for a wrapper that ignores the signal.
8192
+ // siteDecide starts it right before provider dispatch, so a slow
8193
+ // host `extendQuestions` hook keeps its own budget. A fraction
8194
+ // is floored to whole ms (AbortSignal.timeout rejects one) so
8195
+ // the ceiling is never extended. Unset, or a value that is not
8196
+ // a usable bound (<= 0, NaN, Infinity), keeps the provider's
8197
+ // own state-scaled default untouched.
8198
+ const configured = routingConfig.timeoutMs;
8199
+ const boundMs = typeof configured === "number" &&
8200
+ Number.isFinite(configured) &&
8201
+ configured > 0
8202
+ ? // Node's timers treat anything above 2^31-1 ms as 1 ms.
8203
+ Math.min(2_147_483_647, Math.max(1, Math.floor(configured)))
8204
+ : undefined;
8205
+ // Whether the provider's own call had already hit the deadline
8206
+ // when it returned; a slow host observer afterwards is not a
8207
+ // provider timeout.
8208
+ let deadlineHitAtReturn;
8209
+ let deadline;
8210
+ let onDeadlineStarted = () => { };
8211
+ const deadlineStarted = new Promise((resolve) => {
8212
+ onDeadlineStarted = resolve;
8213
+ });
8214
+ const decision = this.siteDecide(decisionOptions, {
8215
+ ...this.decisionSiteContext(options, sessionId || undefined),
8216
+ providerTimeoutMs: boundMs,
8217
+ onProviderDeadline: (signal) => {
8218
+ deadline = signal;
8219
+ onDeadlineStarted(signal);
8220
+ },
8221
+ onProviderReturned: () => {
8222
+ deadlineHitAtReturn = deadline?.aborted === true;
8223
+ },
8224
+ });
8225
+ const DECISION_DEADLINE = Symbol("decisionDeadline");
8226
+ let result;
8227
+ if (boundMs === undefined) {
8228
+ result = await decision;
8229
+ }
8230
+ else {
8231
+ // A host override of decide() may ignore the signal and never
8232
+ // settle: the deadline itself ends the wait, and whatever the
8233
+ // wrapped call returns later is dropped.
8234
+ decision.catch(() => undefined);
8235
+ const expired = deadlineStarted.then((signal) => new Promise((resolve) => {
8236
+ // Only the provider call is bounded: once it returned,
8237
+ // a slow host observer is not a provider timeout.
8238
+ const fire = () => {
8239
+ if (deadlineHitAtReturn === undefined) {
8240
+ resolve(DECISION_DEADLINE);
8241
+ }
8242
+ };
8243
+ if (signal.aborted) {
8244
+ fire();
8245
+ return;
8246
+ }
8247
+ signal.addEventListener("abort", fire, { once: true });
8248
+ }));
8249
+ // The caller's own cancellation is raced separately, so an
8250
+ // unresponsive decide() cannot hold a cancelled turn until the
8251
+ // deadline. A late answer is dropped, never applied.
8252
+ const callerSignal = options.abortSignal;
8253
+ const CALLER_ABORTED = Symbol("callerAborted");
8254
+ let removeAbortListener = () => { };
8255
+ const cancelled = new Promise((resolve) => {
8256
+ if (callerSignal === undefined) {
8257
+ return;
8258
+ }
8259
+ if (callerSignal.aborted) {
8260
+ resolve(CALLER_ABORTED);
8261
+ return;
8262
+ }
8263
+ const onAbort = () => resolve(CALLER_ABORTED);
8264
+ callerSignal.addEventListener("abort", onAbort, {
8265
+ once: true,
8266
+ });
8267
+ removeAbortListener = () => callerSignal.removeEventListener("abort", onAbort);
8268
+ });
8269
+ let winner;
8270
+ try {
8271
+ winner = await Promise.race([decision, expired, cancelled]);
8272
+ }
8273
+ finally {
8274
+ removeAbortListener();
8275
+ }
8276
+ if (winner === CALLER_ABORTED) {
8277
+ throw new DOMException("The operation was aborted", "AbortError");
8278
+ }
8279
+ if (winner === DECISION_DEADLINE) {
8280
+ if (callerSignal?.aborted) {
8281
+ throw new DOMException("The operation was aborted", "AbortError");
8282
+ }
8283
+ throw new ToolRoutingDecisionTimeoutError(boundMs);
8284
+ }
8285
+ result = winner;
8286
+ }
8287
+ // A late or aborted answer is never applied. A missed deadline
8288
+ // means a provider was configured and too slow, unlike the
8289
+ // no-provider null that falls back to the generative router.
8290
+ if ((deadlineHitAtReturn ?? deadline?.aborted) &&
8291
+ boundMs !== undefined &&
8292
+ !options.abortSignal?.aborted) {
8293
+ throw new ToolRoutingDecisionTimeoutError(boundMs);
8294
+ }
8189
8295
  if (auditInput !== null && result !== null) {
8190
8296
  try {
8191
8297
  if (result.provider === JEV_ROUTING_AUDIT_PROVIDER) {
@@ -14780,16 +14886,35 @@ Current user's request: ${currentInput}`;
14780
14886
  sessionId: outer?.sessionId ?? request.sessionId,
14781
14887
  requestId: outer?.requestId ?? request.requestId,
14782
14888
  };
14889
+ let providerDeadline;
14890
+ const runWire = async (wireRequest) => {
14891
+ // Started here, not at the caller, so host hooks that ran first spend
14892
+ // their own budget; shared by every wire call this siteDecide makes.
14893
+ if (outer?.providerTimeoutMs !== undefined && !providerDeadline) {
14894
+ providerDeadline = AbortSignal.timeout(outer.providerTimeoutMs);
14895
+ outer.onProviderDeadline?.(providerDeadline);
14896
+ }
14897
+ const wireResult = await this.tryRunDecide(providerDeadline
14898
+ ? {
14899
+ ...wireRequest,
14900
+ signal: wireRequest.signal
14901
+ ? AbortSignal.any([wireRequest.signal, providerDeadline])
14902
+ : providerDeadline,
14903
+ }
14904
+ : wireRequest);
14905
+ outer?.onProviderReturned?.();
14906
+ return wireResult;
14907
+ };
14783
14908
  const site = merged.site;
14784
14909
  if (!site) {
14785
- return this.tryRunDecide(merged);
14910
+ return runWire(merged);
14786
14911
  }
14787
14912
  // No host hook or event without a decision provider: a hook must not sit
14788
14913
  // on the request path of a tenant that has no decision model to reach, and
14789
14914
  // an event for a call that could never be made would only mislead. The
14790
14915
  // plain call still runs, so the WARNING observation it records is kept.
14791
14916
  if (!this.resolveDecisionProviderName(merged.provider, merged.credentials)) {
14792
- return this.tryRunDecide(merged);
14917
+ return runWire(merged);
14793
14918
  }
14794
14919
  // Wire id → the host's own id, so answers can be handed back under the
14795
14920
  // ids the host used, and NeuroLink's consumers never see a host id. A Map,
@@ -14899,7 +15024,7 @@ Current user's request: ${currentInput}`;
14899
15024
  this.emitDecisionEvent("decision:before", beforeEvent);
14900
15025
  }
14901
15026
  const startedAt = Date.now();
14902
- const result = await this.tryRunDecide({ ...merged, questions });
15027
+ const result = await runWire({ ...merged, questions });
14903
15028
  obtained = result;
14904
15029
  // Null-prototype maps: a host id such as `__proto__` or `constructor`
14905
15030
  // must land as an own key, not fall into the prototype and vanish.
@@ -14961,7 +15086,7 @@ Current user's request: ${currentInput}`;
14961
15086
  ? "deciding with NeuroLink's own questions"
14962
15087
  : "handing the consumer the answers already obtained"}`, { error: error instanceof Error ? error.message : String(error) });
14963
15088
  if (obtained === undefined) {
14964
- return this.tryRunDecide(merged);
15089
+ return runWire(merged);
14965
15090
  }
14966
15091
  return obtained ? stripHostAnswers(obtained, hostIdByWireId) : null;
14967
15092
  }
@@ -82,9 +82,8 @@ function isRedirectRefusal(error) {
82
82
  /**
83
83
  * Rejects with the signal's reason when it aborts, so a caller tearing a turn
84
84
  * down is not held, nor its process kept alive, for the length of a vendor's
85
- * Retry-After wait. The half-second backoff after a transport error is waited
86
- * out without a signal: a rejection there would leave the catch block that is
87
- * already handling that error.
85
+ * Retry-After wait. The transport-error backoff passes the request signal
86
+ * too and turns a rejection into a non-retryable error.
88
87
  */
89
88
  const sleep = (ms, signal) => new Promise((resolve, reject) => {
90
89
  if (signal?.aborted) {
@@ -316,7 +315,16 @@ export class SystemOneDecisionProvider extends BaseProvider {
316
315
  const requestId = this.readRequestId(response.headers);
317
316
  const upstreamMs = Number(response.headers.get("x-envoy-upstream-service-time")) ||
318
317
  undefined;
319
- const payload = await response.json().catch(() => null);
318
+ const payload = await response
319
+ .json()
320
+ .catch((error) => {
321
+ // A deadline or abort that cuts the body read short is a timeout,
322
+ // not a response without answers; the catch below classifies it.
323
+ if (signal.aborted) {
324
+ throw error;
325
+ }
326
+ return null;
327
+ });
320
328
  if (!response.ok) {
321
329
  lastError = this.parseDecisionError(response.status, payload, requestId);
322
330
  if (lastError.kind === "authentication") {
@@ -401,9 +409,13 @@ export class SystemOneDecisionProvider extends BaseProvider {
401
409
  // turn is already being torn down.
402
410
  const aborted = request.signal?.aborted === true;
403
411
  const isTimeout = error instanceof Error && error.name === "TimeoutError";
412
+ // The caller's deadline is an AbortSignal.timeout, so its reason is a
413
+ // TimeoutError; a cancellation is not, and stays a network failure.
414
+ const reason = request.signal?.reason;
415
+ const deadlineHit = aborted && reason instanceof Error && reason.name === "TimeoutError";
404
416
  const redirected = isRedirectRefusal(error);
405
417
  lastError = {
406
- kind: aborted ? "network" : isTimeout ? "timeout" : "network",
418
+ kind: deadlineHit || (!aborted && isTimeout) ? "timeout" : "network",
407
419
  // `fetch` words a refused redirect as "fetch failed", which says
408
420
  // nothing about why, and asking again meets the same answer. The
409
421
  // address it points at is the server's to choose, so it is not quoted.
@@ -415,7 +427,22 @@ export class SystemOneDecisionProvider extends BaseProvider {
415
427
  if (!lastError.retryable || attempt === this.maxRetries) {
416
428
  throw this.decisionError(lastError);
417
429
  }
418
- await sleep(2 ** attempt * 250 + Math.random() * 250);
430
+ try {
431
+ await sleep(2 ** attempt * 250 + Math.random() * 250, request.signal);
432
+ }
433
+ catch (sleepError) {
434
+ // The caller's deadline or abort landed during the backoff. Record
435
+ // that, not the earlier network error, so the span matches what the
436
+ // caller sees; a deadline stays a timeout, a cancellation does not.
437
+ const deadlineHit = sleepError instanceof Error && sleepError.name === "TimeoutError";
438
+ throw this.decisionError({
439
+ kind: deadlineHit ? "timeout" : "network",
440
+ message: redactCredentials(redactUrlsInText(sleepError instanceof Error
441
+ ? sleepError.message
442
+ : `${label} request was cancelled.`), this.decisionApiKey()),
443
+ retryable: false,
444
+ });
445
+ }
419
446
  }
420
447
  }
421
448
  throw this.decisionError(lastError ?? {
@@ -116,6 +116,13 @@ export function isTransientNetworkError(error) {
116
116
  */
117
117
  async function fetchWithRetry(url, init, maxRetries = 3, baseDelay = 500) {
118
118
  const hostname = extractHostname(url);
119
+ // The signal fetch itself observes: an explicit init.signal (null included)
120
+ // overrides the one carried by a Request.
121
+ const effectiveSignal = init?.signal !== undefined
122
+ ? init.signal
123
+ : url instanceof Request
124
+ ? url.signal
125
+ : undefined;
119
126
  return fetchTracer.startActiveSpan("http.fetchWithRetry", async (span) => {
120
127
  span.setAttribute("http.request.max_retries", maxRetries);
121
128
  span.setAttribute("http.request.hostname", hostname);
@@ -136,7 +143,10 @@ async function fetchWithRetry(url, init, maxRetries = 3, baseDelay = 500) {
136
143
  catch (error) {
137
144
  const isRetryable = isTransientNetworkError(error);
138
145
  const err = error;
139
- if (!isRetryable || attempt === maxRetries) {
146
+ // A caller whose signal has fired is done waiting; retrying (and
147
+ // backing off) past it would outlive its deadline.
148
+ const callerGaveUp = effectiveSignal?.aborted === true;
149
+ if (!isRetryable || attempt === maxRetries || callerGaveUp) {
140
150
  // Final failure — record on span and rethrow
141
151
  span.setAttribute("http.request.total_attempts", totalAttempts);
142
152
  span.setStatus({
@@ -154,7 +164,16 @@ async function fetchWithRetry(url, init, maxRetries = 3, baseDelay = 500) {
154
164
  "retry.error": (err?.code || err?.message || String(error)).slice(0, 256),
155
165
  });
156
166
  logger.debug(`[fetchWithRetry] Transient error (${err?.code || err?.message}), retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
157
- await new Promise((r) => setTimeout(r, delay));
167
+ await new Promise((resolve) => {
168
+ const timer = setTimeout(done, delay);
169
+ const signal = effectiveSignal ?? undefined;
170
+ function done() {
171
+ clearTimeout(timer);
172
+ signal?.removeEventListener("abort", done);
173
+ resolve();
174
+ }
175
+ signal?.addEventListener("abort", done, { once: true });
176
+ });
158
177
  }
159
178
  }
160
179
  throw new Error("fetchWithRetry exhausted"); // unreachable
@@ -476,6 +476,20 @@ export type DecisionSiteContext = {
476
476
  signal?: AbortSignal;
477
477
  sessionId?: string;
478
478
  requestId?: string;
479
+ /**
480
+ * Called each time the wire call returns, before any host hook runs, so the
481
+ * caller can tell whether the provider itself met a deadline apart from the
482
+ * time a host observer then spent.
483
+ */
484
+ onProviderReturned?: () => void;
485
+ /**
486
+ * A deadline, in whole milliseconds, for the provider call alone. It starts
487
+ * right before the first wire dispatch (after any host `extendQuestions`
488
+ * hook) and is shared by every attempt and backoff of this call.
489
+ */
490
+ providerTimeoutMs?: number;
491
+ /** Receives the deadline signal when it starts. */
492
+ onProviderDeadline?: (signal: AbortSignal) => void;
479
493
  };
480
494
  /** What a site call adds to its decision span beyond the request itself. */
481
495
  export type DecisionSiteAttributes = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.13.3",
3
+ "version": "13.13.4",
4
4
  "packageManager": "pnpm@10.34.9+sha512.f49b5a8ea0fdedb44bb3c0c1d6575092a53c2950d95b7ad15df11f17974877a2de3a01c07e934e9b28ce716e51c09a94962c7306d09be2e1e4b18a8c8762fd32",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {
@@ -284,7 +284,7 @@
284
284
  "test:reasoning-parity-live": "pnpm exec tsx test/continuous-test-suite-reasoning-parity-live.ts",
285
285
  "test:ci": "pnpm run test && pnpm run test:client && pnpm run test:hitl",
286
286
  "// CI tier — fast, no live AI calls, safe for every commit (test:unit; also see the separate provider-safety-net CI job, which runs build + test:providers-mocked + test:provider-structure + test:error-classifier-contract on every PR)": "",
287
- "test:tool-routing": "pnpm exec tsx test/continuous-test-suite-tool-routing.ts && pnpm run test:jev-routing-audit",
287
+ "test:tool-routing": "pnpm exec tsx test/continuous-test-suite-tool-routing.ts && pnpm run test:jev-routing-audit && pnpm exec tsx test/continuous-test-suite-tool-routing-decide-timeout.ts",
288
288
  "test:jev-routing-audit": "pnpm exec tsx test/continuous-test-suite-jev-routing-audit.ts && pnpm exec tsx test/continuous-test-suite-jev-routing-audit-privacy.ts",
289
289
  "test:tool-routing-semantic": "pnpm exec tsx test/continuous-test-suite-tool-routing-semantic.ts",
290
290
  "test:unit": "pnpm run test:bugfixes && pnpm run test:mcp:infra && pnpm run test:mcp:registry && pnpm run test:mcp:spans && pnpm run test:tool-routing && pnpm run test:tool-routing-cli && pnpm run test:tool-dedup && pnpm run test:model-pool && pnpm run test:classifier-router && pnpm run test:tool-routing-semantic && pnpm run test:mcp-result-cache && pnpm run test:mcp-direct-name-repair && pnpm run test:mcp-breaker-resolved-errors && pnpm run test:archive:security && pnpm run test:office && pnpm run test:office:security && pnpm run test:image-exif && pnpm run test:vector-chroma && pnpm run test:vector-pgvector && pnpm run test:vector-pinecone && pnpm run test:provider-wiring && pnpm run test:docs-mcp && pnpm run test:retired-model-defaults && pnpm run test:cli-fallback && pnpm run test:embedding-response-validation && pnpm run test:xiaomi-mimo-pilot && pnpm run test:rag-bounds && pnpm run test:longcat-pilot && pnpm run test:runinfra-pilot && pnpm run test:catalog-output-ceiling && pnpm run test:package-declarations && pnpm run test:realtime-voice",