@juspay/neurolink 9.73.0 → 9.74.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.
@@ -0,0 +1,155 @@
1
+ /**
2
+ * LRU+TTL cache for pre-call tool routing decisions, plus session stickiness
3
+ * tracking to reduce turn-to-turn server flapping.
4
+ *
5
+ * The cache is keyed by a caller-supplied string (typically a normalized hash
6
+ * of sessionId + routing query). On a hit the cached exclusion list is
7
+ * returned, skipping the router LLM entirely. On a miss the caller resolves
8
+ * normally, stores the result, and `recordSelection` is called with the
9
+ * selected server ids so stickiness can suppress their exclusion for the next
10
+ * N turns.
11
+ *
12
+ * All operations are synchronous and pure (no I/O). The clock is injected via
13
+ * `now` so tests can control time without `Date.now` side effects.
14
+ */
15
+ const DEFAULT_TTL_MS = 60_000;
16
+ const DEFAULT_MAX_ENTRIES = 256;
17
+ const DEFAULT_STICKY_TURNS = 3;
18
+ /**
19
+ * Internal cap on the number of sessions tracked in the sticky map.
20
+ * Not configurable via public API — avoids unbounded memory growth when many
21
+ * ephemeral session ids are generated. Oldest entry (Map insertion order) is
22
+ * evicted when the cap is reached.
23
+ */
24
+ const MAX_STICKY_ENTRIES = 1024;
25
+ export class ToolRoutingCache {
26
+ ttlMs;
27
+ maxEntries;
28
+ stickyTurns;
29
+ now;
30
+ /** Main LRU+TTL store keyed by routing key. */
31
+ store = new Map();
32
+ /** Per-session stickiness tracking keyed by session id. */
33
+ sticky = new Map();
34
+ /** Monotonic counter for LRU ordering — incremented on each access. */
35
+ accessCounter = 0;
36
+ constructor(opts = {}) {
37
+ // Fall back to defaults for invalid (<=0 or NaN) values so callers cannot
38
+ // accidentally disable the cache by passing bad config.
39
+ const validOrDefault = (v, def) => v !== undefined && Number.isFinite(v) && v > 0 ? v : def;
40
+ this.ttlMs = validOrDefault(opts.ttlMs, DEFAULT_TTL_MS);
41
+ this.maxEntries = validOrDefault(opts.maxEntries, DEFAULT_MAX_ENTRIES);
42
+ this.stickyTurns = validOrDefault(opts.stickyTurns, DEFAULT_STICKY_TURNS);
43
+ this.now = opts.now ?? Date.now;
44
+ }
45
+ /**
46
+ * Returns the cached routing result for the given key, or `undefined` on a
47
+ * miss or expiry. Expired entries are deleted on access (lazy eviction).
48
+ */
49
+ get(key) {
50
+ const entry = this.store.get(key);
51
+ if (!entry) {
52
+ return undefined;
53
+ }
54
+ if (this.now() >= entry.expiresAt) {
55
+ this.store.delete(key);
56
+ return undefined;
57
+ }
58
+ // Bump access order for LRU.
59
+ entry.accessOrder = ++this.accessCounter;
60
+ // Return shallow copies so callers cannot mutate cached state.
61
+ return {
62
+ excludedToolNames: [...entry.excludedToolNames],
63
+ selectedServerIds: [...entry.selectedServerIds],
64
+ };
65
+ }
66
+ /**
67
+ * Stores a routing result under the given key. Evicts the least-recently-
68
+ * used entry when the store is at capacity. Silently no-ops on any error
69
+ * (caller is responsible for fail-open behaviour).
70
+ */
71
+ set(key, value) {
72
+ try {
73
+ if (this.store.size >= this.maxEntries && !this.store.has(key)) {
74
+ this.evictLRU();
75
+ }
76
+ // Defensive copies: guard against callers mutating arrays after storing.
77
+ this.store.set(key, {
78
+ excludedToolNames: [...value.excludedToolNames],
79
+ selectedServerIds: [...value.selectedServerIds],
80
+ expiresAt: this.now() + this.ttlMs,
81
+ accessOrder: ++this.accessCounter,
82
+ });
83
+ }
84
+ catch {
85
+ // Silently no-ops on any error — cache writes are non-fatal.
86
+ }
87
+ }
88
+ /**
89
+ * Records the server ids selected by the router for a session so they stay
90
+ * warm for the next `stickyTurns` turns. Called after a successful
91
+ * (non-cached) routing resolution.
92
+ */
93
+ recordSelection(sessionId, serverIds) {
94
+ if (!sessionId || serverIds.length === 0) {
95
+ return;
96
+ }
97
+ // Evict the oldest session when at the internal cap (Map preserves insertion
98
+ // order, so the first key is always the oldest).
99
+ if (this.sticky.size >= MAX_STICKY_ENTRIES && !this.sticky.has(sessionId)) {
100
+ const oldestKey = this.sticky.keys().next().value;
101
+ if (oldestKey !== undefined) {
102
+ this.sticky.delete(oldestKey);
103
+ }
104
+ }
105
+ this.sticky.set(sessionId, {
106
+ serverIds: [...serverIds],
107
+ turnsRemaining: this.stickyTurns,
108
+ });
109
+ }
110
+ /**
111
+ * Returns the server ids that should be kept warm (not excluded) for the
112
+ * given session due to stickiness. Decrements the turn counter; when it
113
+ * reaches zero the entry is removed. Returns an empty array when there is no
114
+ * active sticky state for the session.
115
+ */
116
+ getStickyServerIds(sessionId) {
117
+ if (!sessionId) {
118
+ return [];
119
+ }
120
+ const entry = this.sticky.get(sessionId);
121
+ if (!entry) {
122
+ return [];
123
+ }
124
+ const ids = [...entry.serverIds];
125
+ if (entry.turnsRemaining <= 1) {
126
+ this.sticky.delete(sessionId);
127
+ }
128
+ else {
129
+ entry.turnsRemaining -= 1;
130
+ }
131
+ return ids;
132
+ }
133
+ // ---------------------------------------------------------------------------
134
+ // Private helpers
135
+ // ---------------------------------------------------------------------------
136
+ /**
137
+ * Scans the store for the entry with the lowest accessOrder and removes it.
138
+ * O(n) scan is acceptable at the default maxEntries (256); very large caches
139
+ * should consider an O(1) doubly-linked-list approach instead.
140
+ */
141
+ evictLRU() {
142
+ let lruKey;
143
+ let lruOrder = Infinity;
144
+ for (const [key, entry] of this.store) {
145
+ if (entry.accessOrder < lruOrder) {
146
+ lruOrder = entry.accessOrder;
147
+ lruKey = key;
148
+ }
149
+ }
150
+ if (lruKey !== undefined) {
151
+ this.store.delete(lruKey);
152
+ }
153
+ }
154
+ }
155
+ //# sourceMappingURL=toolRoutingCache.js.map
@@ -216,6 +216,8 @@ export declare function createBestAIProvider(requestedProvider?: string, modelNa
216
216
  export { CircuitBreakerManager, calculateExpiresAt, createMCPServer, createOAuthProviderFromConfig, DEFAULT_HTTP_RETRY_CONFIG, DEFAULT_RATE_LIMIT_CONFIG, executeMCP, FileTokenStorage, getMCPStats, getServerInfo, globalCircuitBreakerManager, globalRateLimiterManager, HTTPRateLimiter, InMemoryTokenStorage, initializeMCPEcosystem, isRetryableHTTPError, isRetryableStatusCode, isTokenExpired, listMCPs, CircuitBreakerOpenError, MCPCircuitBreaker, mcpLogger, NeuroLinkOAuthProvider, RateLimiterManager, validateServerTools, validateTool as validateMCPTool, withHTTPRetry, MCPToolRegistry, ExternalServerManager, MCPClientFactory, ToolRouter, createToolRouter, DEFAULT_ROUTER_CONFIG, ToolCache, createToolCache, DEFAULT_CACHE_CONFIG, ToolResultCache, createToolResultCache, RequestBatcher, ToolCallBatcher, createRequestBatcher, createToolCallBatcher, DEFAULT_BATCH_CONFIG, inferAnnotations, createAnnotatedTool, validateAnnotations, filterToolsByAnnotations, mergeAnnotations, getAnnotationSummary, requiresConfirmation, isSafeToRetry, getToolSafetyLevel, ElicitationManager, globalElicitationManager, EnhancedToolDiscovery, MCPRegistryClient, globalMCPRegistryClient, getWellKnownServer, getAllWellKnownServers, MCPServerBase, MultiServerManager, globalMultiServerManager, AgentExposureManager, exposeAgentAsTool, exposeAgentsAsTools, exposeWorkflowAsTool, exposeWorkflowsAsTools, globalAgentExposureManager, ServerCapabilitiesManager, createTextResource, createJsonResource, createPrompt, neuroLinkToolToMCP, mcpToolToNeuroLink, batchConvertToMCP, batchConvertToNeuroLink, sanitizeToolName, validateToolName, createToolFromFunction, mcpProtocolToolToServerTool, serverToolToMCPProtocol, TOOL_COMPATIBILITY, ToolIntegrationManager, globalToolIntegrationManager, wrapToolWithElicitation, wrapToolsWithElicitation, createElicitationContext, confirmationMiddleware, validationMiddleware, loggingMiddleware, createRetryMiddleware, createTimeoutMiddleware, createToolMiddlewareChain, ElicitationProtocolAdapter, globalElicitationProtocol, isElicitationProtocolMessage, protocolMessageToElicitation, elicitationResponseToProtocol, createElicitationRequest, createElicitationResponse, createElicitationCancel, createTextInputRequest, createSelectRequest, createConfirmationRequest, createFormRequest, } from "./mcp/index.js";
217
217
  export { logger } from "./utils/logger.js";
218
218
  export { getPoolStats } from "./utils/redis.js";
219
+ export { ToolRoutingCache } from "./core/toolRoutingCache.js";
220
+ export { resolveToolRoutingExclusions, buildToolRoutingCatalog, buildRoutingQueryFromHistory, DEFAULT_ROUTER_PROMPT_PREFIX, } from "./core/toolRouting.js";
219
221
  export declare function initializeTelemetry(): Promise<boolean>;
220
222
  export declare function getTelemetryStatus(): Promise<{
221
223
  enabled: boolean;
package/dist/lib/index.js CHANGED
@@ -356,6 +356,10 @@ ToolIntegrationManager, globalToolIntegrationManager, wrapToolWithElicitation, w
356
356
  ElicitationProtocolAdapter, globalElicitationProtocol, isElicitationProtocolMessage, protocolMessageToElicitation, elicitationResponseToProtocol, createElicitationRequest, createElicitationResponse, createElicitationCancel, createTextInputRequest, createSelectRequest, createConfirmationRequest, createFormRequest, } from "./mcp/index.js";
357
357
  export { logger } from "./utils/logger.js";
358
358
  export { getPoolStats } from "./utils/redis.js";
359
+ // Pre-call tool routing cache (ITEM C: LRU+TTL cache + session stickiness)
360
+ export { ToolRoutingCache } from "./core/toolRoutingCache.js";
361
+ // Pre-call tool routing resolver — exported for host integrations and testing
362
+ export { resolveToolRoutingExclusions, buildToolRoutingCatalog, buildRoutingQueryFromHistory, DEFAULT_ROUTER_PROMPT_PREFIX, } from "./core/toolRouting.js";
359
363
  // ============================================================================
360
364
  // REAL-TIME SERVICES & TELEMETRY - Enterprise Platform Features
361
365
  // ============================================================================
@@ -101,6 +101,7 @@ export declare class NeuroLink {
101
101
  private conversationMemoryNeedsInit;
102
102
  private conversationMemoryConfig?;
103
103
  private toolRoutingConfig?;
104
+ private toolRoutingCacheInstance?;
104
105
  private enableOrchestration;
105
106
  private authProvider?;
106
107
  private pendingAuthConfig?;
@@ -805,12 +806,13 @@ export declare class NeuroLink {
805
806
  private streamWithIterationFallback;
806
807
  private executeStreamRequest;
807
808
  /**
808
- * Pre-call tool routing for stream(): runs the router LLM once per turn
809
- * and appends the unpicked servers' registered tool names to
810
- * `options.excludeTools` — the per-call denylist enforced by
811
- * `baseProvider.applyToolFiltering`. No-op unless `toolRouting.enabled`
812
- * is true and a non-empty server catalog has been supplied. Never throws
813
- * (the resolver fails open to an empty exclusion list).
809
+ * Pre-call tool routing for both stream() and generate() turns: runs the
810
+ * router LLM once per turn and appends the unpicked servers' registered tool
811
+ * names to `options.excludeTools` — the per-call denylist enforced by
812
+ * `baseProvider.applyToolFiltering`. No-op unless `toolRouting.enabled` is
813
+ * true and a non-empty server catalog has been supplied. Never throws (the
814
+ * resolver fails open to an empty exclusion list). Accepts both StreamOptions
815
+ * and GenerateOptions since both share the required fields.
814
816
  */
815
817
  private applyToolRoutingExclusions;
816
818
  /**
@@ -31,6 +31,7 @@ import { repairToolPairs } from "./context/toolPairRepair.js";
31
31
  import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, } from "./core/constants.js";
32
32
  import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
33
33
  import { buildToolRoutingCatalog, buildRoutingQueryFromHistory, resolveToolRoutingExclusions, } from "./core/toolRouting.js";
34
+ import { ToolRoutingCache } from "./core/toolRoutingCache.js";
34
35
  import { AIProviderFactory } from "./core/factory.js";
35
36
  import { createToolEventPayload } from "./core/toolEvents.js";
36
37
  import { ProviderRegistry } from "./factories/providerRegistry.js";
@@ -59,7 +60,7 @@ import { SpanSerializer } from "./observability/utils/spanSerializer.js";
59
60
  import { flushOpenTelemetry, getLangfuseContext, getLangfuseHealthStatus, initializeOpenTelemetry, isOpenTelemetryInitialized, runWithCurrentLangfuseContext, setLangfuseContext, shutdownOpenTelemetry, stampGuestRescueIdentity, } from "./services/server/ai/observability/instrumentation.js";
60
61
  import { TaskManager } from "./tasks/taskManager.js";
61
62
  import { createTaskTools } from "./tasks/tools/taskTools.js";
62
- import { ATTR } from "./telemetry/attributes.js";
63
+ import { ATTR, spanJsonAttribute } from "./telemetry/attributes.js";
63
64
  import { tracers } from "./telemetry/tracers.js";
64
65
  import { getConversationMessages, storeConversationTurn, } from "./utils/conversationMemory.js";
65
66
  // Enhanced error handling imports
@@ -441,6 +442,9 @@ export class NeuroLink {
441
442
  // The server catalog inside it can be supplied/replaced later via
442
443
  // setToolRoutingServers() for hosts that register tools after construction.
443
444
  toolRoutingConfig;
445
+ // Lazy-initialized routing decision cache (ITEM C). Created on first use so
446
+ // instances that don't use routing pay no overhead.
447
+ toolRoutingCacheInstance;
444
448
  // Add orchestration property
445
449
  enableOrchestration;
446
450
  // Authentication provider for secure access control
@@ -3019,7 +3023,14 @@ Current user's request: ${currentInput}`;
3019
3023
  generateSpan.setStatus({ code: SpanStatusCode.OK });
3020
3024
  return earlyResult;
3021
3025
  }
3022
- const result = await this.setLangfuseContextFromOptions(options, () => this.runStandardGenerateRequest(options, originalPrompt, generateSpan));
3026
+ // Pre-call tool routing for generate(): mirrors the stream() routing path.
3027
+ // Runs inside the generate's Langfuse context (setLangfuseContextFromOptions)
3028
+ // so the router's own generation span nests under this turn's trace.
3029
+ // After the early-result short-circuit so workflow/media turns skip it.
3030
+ const result = await this.setLangfuseContextFromOptions(options, async () => {
3031
+ await this.applyToolRoutingExclusions(options, options.input?.text ?? "");
3032
+ return this.runStandardGenerateRequest(options, originalPrompt, generateSpan);
3033
+ });
3023
3034
  generateSpan.setStatus({ code: SpanStatusCode.OK });
3024
3035
  return result;
3025
3036
  }
@@ -5688,12 +5699,13 @@ Current user's request: ${currentInput}`;
5688
5699
  }
5689
5700
  }
5690
5701
  /**
5691
- * Pre-call tool routing for stream(): runs the router LLM once per turn
5692
- * and appends the unpicked servers' registered tool names to
5693
- * `options.excludeTools` — the per-call denylist enforced by
5694
- * `baseProvider.applyToolFiltering`. No-op unless `toolRouting.enabled`
5695
- * is true and a non-empty server catalog has been supplied. Never throws
5696
- * (the resolver fails open to an empty exclusion list).
5702
+ * Pre-call tool routing for both stream() and generate() turns: runs the
5703
+ * router LLM once per turn and appends the unpicked servers' registered tool
5704
+ * names to `options.excludeTools` — the per-call denylist enforced by
5705
+ * `baseProvider.applyToolFiltering`. No-op unless `toolRouting.enabled` is
5706
+ * true and a non-empty server catalog has been supplied. Never throws (the
5707
+ * resolver fails open to an empty exclusion list). Accepts both StreamOptions
5708
+ * and GenerateOptions since both share the required fields.
5697
5709
  */
5698
5710
  async applyToolRoutingExclusions(options, userQuery) {
5699
5711
  const routingConfig = this.toolRoutingConfig;
@@ -5706,8 +5718,8 @@ Current user's request: ${currentInput}`;
5706
5718
  }
5707
5719
  // Whole setup is fail-open: catalog building (getCustomTools /
5708
5720
  // buildToolRoutingCatalog) and the router call degrade to no exclusions
5709
- // rather than killing the stream, honoring this method's "never throws"
5710
- // contract. Genuine stream cancellations still propagate.
5721
+ // rather than killing the stream/generate turn, honoring this method's
5722
+ // "never throws" contract. Genuine cancellations still propagate.
5711
5723
  try {
5712
5724
  const registeredToolNames = Array.from(this.getCustomTools().keys());
5713
5725
  const catalog = buildToolRoutingCatalog(servers, registeredToolNames);
@@ -5724,44 +5736,180 @@ Current user's request: ${currentInput}`;
5724
5736
  const routingQuery = recentMessages.length > 0
5725
5737
  ? buildRoutingQueryFromHistory(recentMessages, userQuery)
5726
5738
  : userQuery;
5727
- // The router call below re-enters the public generate(), whose finally
5728
- // block resets _disableToolCacheForCurrentRequest to false. That flag is
5729
- // stream-scoped (set at the top of this turn) and read by the main tool
5730
- // execution path that runs after routing, so save it before the router
5731
- // call and restore it afterward to keep the turn's cache setting intact.
5732
- const cacheDisabledForCurrentRequest = this._disableToolCacheForCurrentRequest;
5739
+ // --- ITEM C: routing decision cache ---
5740
+ const cacheConfig = routingConfig.cache;
5741
+ const cacheEnabled = cacheConfig?.enabled === true;
5742
+ const stickinessEnabled = routingConfig.stickiness?.enabled === true;
5743
+ // Lazy-init the cache instance once per NeuroLink instance.
5744
+ if ((cacheEnabled || stickinessEnabled) &&
5745
+ !this.toolRoutingCacheInstance) {
5746
+ this.toolRoutingCacheInstance = new ToolRoutingCache({
5747
+ ttlMs: cacheConfig?.ttlMs,
5748
+ maxEntries: cacheConfig?.maxEntries,
5749
+ stickyTurns: routingConfig.stickiness?.turns,
5750
+ });
5751
+ }
5752
+ const cache = this.toolRoutingCacheInstance;
5753
+ // Derive sessionId for stickiness — same extraction path as
5754
+ // fetchRecentRoutingHistory.
5755
+ const requestContext = options.context;
5756
+ const sessionId = typeof requestContext?.sessionId === "string"
5757
+ ? requestContext.sessionId
5758
+ : "";
5759
+ // Cache key: session + normalized routing query.
5760
+ // Require a non-empty sessionId to avoid anonymous sessions sharing a
5761
+ // ":query" namespace (cross-session cache leak).
5762
+ const cacheKey = cacheEnabled && sessionId ? `${sessionId}:${routingQuery}` : undefined;
5763
+ // --- ITEM E: build the emitDecision callback ---
5764
+ const emitDecision = (decision) => {
5765
+ try {
5766
+ const activeSpan = trace.getActiveSpan();
5767
+ if (!activeSpan) {
5768
+ return;
5769
+ }
5770
+ activeSpan.setAttribute("tool_routing.outcome", decision.outcome);
5771
+ activeSpan.setAttribute("tool_routing.routable_server_count", decision.routableServerCount);
5772
+ activeSpan.setAttribute("tool_routing.selected_server_ids", spanJsonAttribute(decision.selectedServerIds));
5773
+ activeSpan.setAttribute("tool_routing.excluded_server_ids", spanJsonAttribute(decision.excludedServerIds));
5774
+ activeSpan.setAttribute("tool_routing.hallucinated_ids", spanJsonAttribute(decision.hallucinatedIds));
5775
+ activeSpan.setAttribute("tool_routing.excluded_tool_count", decision.excludedToolCount);
5776
+ activeSpan.setAttribute("tool_routing.cache_hit", decision.cacheHit);
5777
+ activeSpan.setAttribute("tool_routing.duration_ms", decision.durationMs);
5778
+ }
5779
+ catch {
5780
+ // Telemetry must never affect routing behaviour.
5781
+ }
5782
+ };
5783
+ // Unified hit/miss block: always produces raw (pre-stickiness) exclusions
5784
+ // so stickiness can be applied identically on both paths below.
5733
5785
  let routedExcludeTools;
5734
- try {
5735
- routedExcludeTools = await resolveToolRoutingExclusions({
5736
- catalog,
5737
- alwaysIncludeServerIds: routingConfig.alwaysIncludeServerIds ?? [],
5738
- userQuery: routingQuery,
5739
- routerPromptPrefix: routingConfig.routerPromptPrefix,
5740
- routerModel: {
5741
- provider: routingConfig.routerModel?.provider ??
5742
- options.provider,
5743
- model: routingConfig.routerModel?.model ?? options.model,
5744
- region: routingConfig.routerModel?.region ?? options.region,
5745
- temperature: routingConfig.routerModel?.temperature,
5746
- },
5747
- timeoutMs: routingConfig.timeoutMs ?? DEFAULT_TOOL_ROUTING_TIMEOUT_MS,
5748
- // Forward the stream's abort signal so a cancelled stream aborts the
5749
- // router call promptly instead of waiting out the routing timeout.
5750
- generateFn: (generateOptions) => this.generate({
5751
- ...generateOptions,
5752
- abortSignal: options.abortSignal,
5753
- }),
5786
+ let selectedServerIds = [];
5787
+ let resolvedDecision;
5788
+ let fromCache = false;
5789
+ const cached = cacheEnabled && cache && cacheKey !== undefined
5790
+ ? cache.get(cacheKey)
5791
+ : undefined;
5792
+ if (cached) {
5793
+ // Cache HIT — use stored raw exclusions (pre-stickiness).
5794
+ fromCache = true;
5795
+ routedExcludeTools = [...cached.excludedToolNames];
5796
+ selectedServerIds = [...cached.selectedServerIds];
5797
+ logger.debug("[ToolRouting] Cache hit, skipping router LLM", {
5798
+ cacheKey,
5754
5799
  });
5800
+ // Emit cache-hit telemetry with full parity to the miss path.
5801
+ try {
5802
+ const activeSpan = trace.getActiveSpan();
5803
+ if (activeSpan) {
5804
+ const routableCount = catalog.filter((s) => !(routingConfig.alwaysIncludeServerIds ?? []).includes(s.id)).length;
5805
+ activeSpan.setAttribute("tool_routing.outcome", "cache-hit");
5806
+ activeSpan.setAttribute("tool_routing.routable_server_count", routableCount);
5807
+ activeSpan.setAttribute("tool_routing.cache_hit", true);
5808
+ activeSpan.setAttribute("tool_routing.selected_server_ids", spanJsonAttribute(selectedServerIds));
5809
+ activeSpan.setAttribute("tool_routing.excluded_tool_count", routedExcludeTools.length);
5810
+ }
5811
+ }
5812
+ catch {
5813
+ // Telemetry must never affect routing behaviour.
5814
+ }
5755
5815
  }
5756
- finally {
5757
- this._disableToolCacheForCurrentRequest =
5758
- cacheDisabledForCurrentRequest;
5816
+ else {
5817
+ // Cache MISS — run the router LLM.
5818
+ // The router call re-enters the public generate(), whose finally block
5819
+ // resets _disableToolCacheForCurrentRequest to false. That flag is
5820
+ // turn-scoped and read by the main tool execution path after routing, so
5821
+ // save it before the router call and restore it afterward.
5822
+ const cacheDisabledForCurrentRequest = this._disableToolCacheForCurrentRequest;
5823
+ try {
5824
+ // Intercept the decision so we can store it in the cache.
5825
+ const captureDecision = (decision) => {
5826
+ resolvedDecision = decision;
5827
+ emitDecision(decision);
5828
+ };
5829
+ routedExcludeTools = await resolveToolRoutingExclusions({
5830
+ catalog,
5831
+ alwaysIncludeServerIds: routingConfig.alwaysIncludeServerIds ?? [],
5832
+ userQuery: routingQuery,
5833
+ routerPromptPrefix: routingConfig.routerPromptPrefix,
5834
+ routerModel: {
5835
+ provider: routingConfig.routerModel?.provider ??
5836
+ options.provider,
5837
+ model: routingConfig.routerModel?.model ?? options.model,
5838
+ region: routingConfig.routerModel?.region ?? options.region,
5839
+ temperature: routingConfig.routerModel?.temperature,
5840
+ },
5841
+ timeoutMs: routingConfig.timeoutMs ?? DEFAULT_TOOL_ROUTING_TIMEOUT_MS,
5842
+ // Forward the abort signal so a cancelled turn aborts the router
5843
+ // call promptly instead of waiting out the routing timeout.
5844
+ generateFn: (generateOptions) => this.generate({
5845
+ ...generateOptions,
5846
+ abortSignal: options.abortSignal,
5847
+ }),
5848
+ emitDecision: captureDecision,
5849
+ });
5850
+ }
5851
+ finally {
5852
+ this._disableToolCacheForCurrentRequest =
5853
+ cacheDisabledForCurrentRequest;
5854
+ }
5855
+ if (resolvedDecision?.outcome === "applied") {
5856
+ selectedServerIds = resolvedDecision.selectedServerIds;
5857
+ }
5759
5858
  }
5760
5859
  // Aborted during the router call — skip applying now-stale exclusions;
5761
5860
  // the main generation path enforces the abort itself.
5762
5861
  if (options.abortSignal?.aborted) {
5763
5862
  return;
5764
5863
  }
5864
+ // Capture raw (pre-stickiness) exclusions for cache storage on MISS path.
5865
+ const rawExclusions = [...routedExcludeTools];
5866
+ // Apply stickiness on BOTH hit and miss paths: the sticky ids were
5867
+ // recorded on a prior turn and represent servers that should stay warm for
5868
+ // the current turn. Consuming (decrementing) them before recordSelection
5869
+ // ensures the window covers the correct set of future turns rather than
5870
+ // burning one count on the same turn the selection is recorded
5871
+ // (off-by-one fix).
5872
+ if (stickinessEnabled && cache && sessionId) {
5873
+ try {
5874
+ const stickyIds = cache.getStickyServerIds(sessionId);
5875
+ if (stickyIds.length > 0) {
5876
+ // Remove from routedExcludeTools any tool belonging to a sticky server.
5877
+ // Precompute prefixes to avoid rebuilding the set inside the predicate.
5878
+ const stickyPrefixes = stickyIds.map((id) => `${id}_`);
5879
+ routedExcludeTools = routedExcludeTools.filter((toolName) => !stickyPrefixes.some((prefix) => toolName.startsWith(prefix)));
5880
+ }
5881
+ }
5882
+ catch {
5883
+ // Stickiness failure is non-fatal.
5884
+ }
5885
+ }
5886
+ // --- ITEM C: store result for future turns (MISS path only) ---
5887
+ // Cache stores RAW (pre-stickiness) exclusions so the cached value is
5888
+ // correct regardless of which sessions hit it on subsequent turns.
5889
+ if (!fromCache && resolvedDecision?.outcome === "applied" && cache) {
5890
+ if (cacheEnabled && cacheKey !== undefined) {
5891
+ try {
5892
+ cache.set(cacheKey, {
5893
+ excludedToolNames: rawExclusions,
5894
+ selectedServerIds,
5895
+ });
5896
+ }
5897
+ catch {
5898
+ // Cache write failure is non-fatal.
5899
+ }
5900
+ }
5901
+ // Record selected servers for stickiness on subsequent turns. This must
5902
+ // come after getStickyServerIds so the window count is not consumed on
5903
+ // the same turn it is set (the off-by-one fix above).
5904
+ if (stickinessEnabled && sessionId) {
5905
+ try {
5906
+ cache.recordSelection(sessionId, selectedServerIds);
5907
+ }
5908
+ catch {
5909
+ // Stickiness failure is non-fatal.
5910
+ }
5911
+ }
5912
+ }
5765
5913
  if (routedExcludeTools.length > 0) {
5766
5914
  options.excludeTools = [
5767
5915
  ...(options.excludeTools ?? []),
@@ -64,6 +64,30 @@ export type ToolRoutingConfig = {
64
64
  * always appended by the SDK regardless of this value.
65
65
  */
66
66
  routerPromptPrefix?: string;
67
+ /**
68
+ * LRU+TTL cache for routing decisions. When enabled, identical routing
69
+ * queries within the TTL window skip the router LLM entirely and reuse
70
+ * the cached exclusion list.
71
+ */
72
+ cache?: {
73
+ /** Whether the cache is active. Default: false. */
74
+ enabled?: boolean;
75
+ /** Time-to-live in milliseconds for each cached entry. Default: 60000. */
76
+ ttlMs?: number;
77
+ /** Maximum number of entries in the LRU cache. Default: 256. */
78
+ maxEntries?: number;
79
+ };
80
+ /**
81
+ * Session stickiness: once the router picks a set of servers for a session,
82
+ * those servers are kept warm (not excluded) for the next N turns to prevent
83
+ * flapping.
84
+ */
85
+ stickiness?: {
86
+ /** Whether session stickiness is active. Default: false. */
87
+ enabled?: boolean;
88
+ /** Number of turns for which a previously-selected server stays warm. Default: 3. */
89
+ turns?: number;
90
+ };
67
91
  };
68
92
  /** Catalog entry pairing a server descriptor with its registered tool names. */
69
93
  export type ToolRoutingCatalogEntry = {
@@ -72,6 +96,63 @@ export type ToolRoutingCatalogEntry = {
72
96
  /** Registered tool names for this server, i.e. `${serverId}_${toolName}`. */
73
97
  toolNames: string[];
74
98
  };
99
+ /** Internal cache entry for `ToolRoutingCache`. */
100
+ export type ToolRoutingCacheEntry = {
101
+ excludedToolNames: string[];
102
+ selectedServerIds: string[];
103
+ /** Absolute expiry timestamp (from the injected `now()` clock). */
104
+ expiresAt: number;
105
+ /** LRU eviction order — lower = older. Bumped on each get/set. */
106
+ accessOrder: number;
107
+ };
108
+ /** Internal stickiness entry for `ToolRoutingCache`. */
109
+ export type ToolRoutingStickiness = {
110
+ serverIds: string[];
111
+ /** Turn counter — decremented on each routing turn, removed when it hits 0. */
112
+ turnsRemaining: number;
113
+ };
114
+ /** Constructor options for `ToolRoutingCache`. */
115
+ export type ToolRoutingCacheOptions = {
116
+ /** Time-to-live in milliseconds for each cached entry. Default: 60_000. */
117
+ ttlMs?: number;
118
+ /** Maximum number of entries kept in the LRU before eviction. Default: 256. */
119
+ maxEntries?: number;
120
+ /** Number of turns a selected server remains sticky per session. Default: 3. */
121
+ stickyTurns?: number;
122
+ /**
123
+ * Clock function for TTL calculations. Defaults to `Date.now`.
124
+ * Inject a deterministic function in tests to control time.
125
+ */
126
+ now?: () => number;
127
+ };
128
+ /**
129
+ * Outcome classifier for a single routing resolution. Used in
130
+ * `ToolRoutingDecision` and emitted as an OTel span attribute.
131
+ */
132
+ export type ToolRoutingOutcome = "applied" | "skipped-no-query" | "skipped-single-server" | "empty-pick" | "failed-open-parse" | "failed-open-timeout" | "failed-open-error" | "cache-hit";
133
+ /**
134
+ * Machine-readable summary of one routing resolution. Emitted via the
135
+ * `emitDecision` callback so the caller can attach it as OTel span attributes
136
+ * or record it in any other telemetry sink.
137
+ */
138
+ export type ToolRoutingDecision = {
139
+ /** How the routing turn concluded. */
140
+ outcome: ToolRoutingOutcome;
141
+ /** Server ids the router kept (selected as relevant). */
142
+ selectedServerIds: string[];
143
+ /** Server ids whose tools were excluded (router considered them irrelevant). */
144
+ excludedServerIds: string[];
145
+ /** Server ids the router returned that did not exist in the catalog. */
146
+ hallucinatedIds: string[];
147
+ /** Total number of individual tool names added to the exclusion list. */
148
+ excludedToolCount: number;
149
+ /** Number of servers that were offered to the router (always-include excluded). */
150
+ routableServerCount: number;
151
+ /** True when the result was served from cache, skipping the router LLM. */
152
+ cacheHit: boolean;
153
+ /** Wall-clock time spent in the routing resolution in milliseconds. */
154
+ durationMs: number;
155
+ };
75
156
  /** Parameters for `resolveToolRoutingExclusions()`. */
76
157
  export type ToolRoutingResolutionParams = {
77
158
  /** Full catalog; always-include servers are filtered out internally. */
@@ -88,4 +169,11 @@ export type ToolRoutingResolutionParams = {
88
169
  timeoutMs: number;
89
170
  /** Invokes the router LLM — `NeuroLink.generate` bound by the caller. */
90
171
  generateFn: (options: GenerateOptions) => Promise<GenerateResult>;
172
+ /**
173
+ * Optional callback invoked once per resolution with a structured summary of
174
+ * the routing decision. Called on every return path (applied, skipped,
175
+ * failed-open). Must never throw — any error inside is swallowed by
176
+ * the resolver.
177
+ */
178
+ emitDecision?: (decision: ToolRoutingDecision) => void;
91
179
  };
@@ -101,6 +101,7 @@ export declare class NeuroLink {
101
101
  private conversationMemoryNeedsInit;
102
102
  private conversationMemoryConfig?;
103
103
  private toolRoutingConfig?;
104
+ private toolRoutingCacheInstance?;
104
105
  private enableOrchestration;
105
106
  private authProvider?;
106
107
  private pendingAuthConfig?;
@@ -805,12 +806,13 @@ export declare class NeuroLink {
805
806
  private streamWithIterationFallback;
806
807
  private executeStreamRequest;
807
808
  /**
808
- * Pre-call tool routing for stream(): runs the router LLM once per turn
809
- * and appends the unpicked servers' registered tool names to
810
- * `options.excludeTools` — the per-call denylist enforced by
811
- * `baseProvider.applyToolFiltering`. No-op unless `toolRouting.enabled`
812
- * is true and a non-empty server catalog has been supplied. Never throws
813
- * (the resolver fails open to an empty exclusion list).
809
+ * Pre-call tool routing for both stream() and generate() turns: runs the
810
+ * router LLM once per turn and appends the unpicked servers' registered tool
811
+ * names to `options.excludeTools` — the per-call denylist enforced by
812
+ * `baseProvider.applyToolFiltering`. No-op unless `toolRouting.enabled` is
813
+ * true and a non-empty server catalog has been supplied. Never throws (the
814
+ * resolver fails open to an empty exclusion list). Accepts both StreamOptions
815
+ * and GenerateOptions since both share the required fields.
814
816
  */
815
817
  private applyToolRoutingExclusions;
816
818
  /**