@juspay/neurolink 13.9.0 → 13.10.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.
@@ -10,15 +10,19 @@ import { generateToolOutputPreview } from "../context/toolOutputLimits.js";
10
10
  import { NEUROLINK_ARTIFACT_ID_KEY } from "../mcp/mcpOutputNormalizer.js";
11
11
  import { SummarizationEngine } from "../context/summarizationEngine.js";
12
12
  import { NeuroLink } from "../neurolink.js";
13
- import { ConversationMemoryError } from "../types/index.js";
13
+ import { ConversationMemoryError, ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
14
14
  import { withTimeout } from "../utils/errorHandling.js";
15
15
  import { buildContextFromPointer, getEffectiveTokenThreshold, } from "../utils/conversationMemory.js";
16
16
  import { logger } from "../utils/logger.js";
17
+ import { conversationErasureWriterStatus, eraseSessionPermanently as erasePermanently, fencedSessionIndexWrite, fencedSessionMetadataWrite, fencedSessionPersist, prepareConversationWriteContext, } from "./conversationErasureFence.js";
17
18
  import { assistantTurnIdentity, isTurnAlreadyStored, turnMessageFields, userTurnIdentity, } from "../utils/conversationTurnIdentity.js";
18
19
  import { extractIsErrorText } from "../utils/toolResultStatus.js";
19
- import { addToSetWithTtl, deserializeConversation, encodeStoredMessages, getSessionMessagesKey, MESSAGES_KEY_SUFFIX, isSessionMessagesKey, parseStoredMessages, serializeConversationMetadata, usesSplitMessageStorage, getNormalizedConfig, getPooledRedisClient, getSessionKey, getUserSessionsKey, releasePooledRedisClient, scanKeys, serializeConversation, setWithTtl, } from "../utils/redis.js";
20
+ import { deserializeConversation, encodeStoredMessages, MESSAGES_KEY_SUFFIX, isSessionMessagesKey, parseStoredMessages, serializeConversationMetadata, usesSplitMessageStorage, getNormalizedConfig, getPooledRedisClient, getSessionKey, getUserSessionsKey, releasePooledRedisClient, scanKeys, serializeConversation, } from "../utils/redis.js";
20
21
  const redisTracer = tracers.redis;
21
22
  const REDIS_TIMEOUT_MS = 5000;
23
+ /** A fence refusal must reach the caller; a swallowed one reads as a stored write. */
24
+ const isErasureFenceRefusal = (error) => error instanceof ConversationSessionErasedError ||
25
+ error instanceof ConversationWriterEpochError;
22
26
  /**
23
27
  * Redis-based implementation of the ConversationMemoryManager
24
28
  * Uses the same interface but stores data in Redis
@@ -29,6 +33,12 @@ export class RedisConversationMemoryManager {
29
33
  summarizationEngine = new SummarizationEngine();
30
34
  redisConfig;
31
35
  redisClient = null;
36
+ /**
37
+ * Resolved once per initialization, before any write is admitted. Every
38
+ * write reads it up front so an in-flight write keeps the epoch it started
39
+ * under.
40
+ */
41
+ erasureWriteContext;
32
42
  /**
33
43
  * Receives `conversation:titleGenerated` once a new conversation's title is
34
44
  * stored. Optional because the manager can be constructed standalone.
@@ -62,6 +72,7 @@ export class RedisConversationMemoryManager {
62
72
  logger.debug("[RedisConversationMemoryManager] Already initialized, skipping");
63
73
  return;
64
74
  }
75
+ this.erasureWriteContext = undefined;
65
76
  await redisTracer.startActiveSpan("memory.initialize", {
66
77
  kind: SpanKind.CLIENT,
67
78
  attributes: {
@@ -78,6 +89,7 @@ export class RedisConversationMemoryManager {
78
89
  ttl: this.redisConfig.ttl,
79
90
  });
80
91
  this.redisClient = await getPooledRedisClient(this.redisConfig);
92
+ this.erasureWriteContext = await prepareConversationWriteContext(this.redisClient, this.redisConfig, this.config.erasureWriteProtocol === "conversation-erasure-v1");
81
93
  this.isInitialized = true;
82
94
  logger.info("RedisConversationMemoryManager initialized", {
83
95
  storage: "redis",
@@ -92,6 +104,15 @@ export class RedisConversationMemoryManager {
92
104
  });
93
105
  }
94
106
  catch (error) {
107
+ if (this.redisClient && !this.isInitialized) {
108
+ this.redisClient = null;
109
+ try {
110
+ await releasePooledRedisClient(this.redisConfig);
111
+ }
112
+ catch {
113
+ // The initialization error below stays authoritative.
114
+ }
115
+ }
95
116
  span.setStatus({
96
117
  code: SpanStatusCode.ERROR,
97
118
  message: error instanceof Error ? error.message : String(error),
@@ -105,6 +126,12 @@ export class RedisConversationMemoryManager {
105
126
  port: this.redisConfig.port,
106
127
  },
107
128
  });
129
+ // A strict writer the server cannot admit (cluster, an evicting
130
+ // policy, no readable epoch) is a typed refusal callers can match;
131
+ // wrapping it as a generic CONFIG_ERROR would hide which it was.
132
+ if (error instanceof ConversationWriterEpochError) {
133
+ throw error;
134
+ }
108
135
  throw new ConversationMemoryError("Failed to initialize Redis conversation memory", "CONFIG_ERROR", {
109
136
  error: error instanceof Error ? error.message : String(error),
110
137
  });
@@ -265,15 +292,18 @@ export class RedisConversationMemoryManager {
265
292
  /**
266
293
  * Add a session to user's session set (private method)
267
294
  */
268
- async addUserSession(userId, sessionId) {
295
+ async addUserSession(userId, sessionId, writeContext = this
296
+ .erasureWriteContext) {
269
297
  if (!this.redisClient || !userId) {
270
298
  return;
271
299
  }
272
300
  try {
273
- const userSessionsKey = getUserSessionsKey(this.redisConfig, userId);
274
- await addToSetWithTtl(this.redisClient, userSessionsKey, sessionId, this.redisConfig.ttl);
301
+ await fencedSessionIndexWrite(this.redisClient, this.redisConfig, sessionId, userId, writeContext);
275
302
  }
276
303
  catch (error) {
304
+ if (isErasureFenceRefusal(error)) {
305
+ throw error;
306
+ }
277
307
  logger.error("[RedisConversationMemoryManager] Failed to add session to user set", {
278
308
  userId,
279
309
  sessionId,
@@ -381,6 +411,7 @@ export class RedisConversationMemoryManager {
381
411
  userId: options.userId,
382
412
  });
383
413
  await this.ensureInitialized();
414
+ const writeContext = this.erasureWriteContext;
384
415
  // NLK-GAP-012: Add span for storeTurn CRUD operation
385
416
  return redisTracer.startActiveSpan("memory.storeTurn", {
386
417
  kind: SpanKind.CLIENT,
@@ -408,46 +439,7 @@ export class RedisConversationMemoryManager {
408
439
  const currentTime = new Date().toISOString();
409
440
  const normalizedUserId = options.userId || "randomUser";
410
441
  if (!conversation) {
411
- const titleGenerationKey = `${options.sessionId}:${normalizedUserId}`;
412
- const generateTitleWithContext = context.bind(context.active(), async () => {
413
- if (this.titleGenerationInProgress.has(titleGenerationKey)) {
414
- return;
415
- }
416
- this.titleGenerationInProgress.add(titleGenerationKey);
417
- try {
418
- const title = await this.generateConversationTitle(options.userMessage);
419
- const updatedRedisKey = getSessionKey(this.redisConfig, options.sessionId, options.userId || undefined);
420
- const updatedConversationData = await this.redisClient?.get(updatedRedisKey);
421
- const updatedConversation = deserializeConversation(updatedConversationData || null);
422
- if (updatedConversation) {
423
- updatedConversation.title = title;
424
- updatedConversation.updatedAt = new Date().toISOString();
425
- const serializedData = serializeConversation(updatedConversation);
426
- if (this.redisClient) {
427
- await setWithTtl(this.redisClient, updatedRedisKey, serializedData, this.redisConfig.ttl);
428
- this.emitTitleGenerated({
429
- sessionId: options.sessionId,
430
- userId: normalizedUserId,
431
- title,
432
- timestamp: Date.now(),
433
- });
434
- }
435
- }
436
- }
437
- catch (titleError) {
438
- logger.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background", {
439
- sessionId: options.sessionId,
440
- userId: normalizedUserId,
441
- error: titleError instanceof Error
442
- ? titleError.message
443
- : String(titleError),
444
- });
445
- }
446
- finally {
447
- this.titleGenerationInProgress.delete(titleGenerationKey);
448
- }
449
- });
450
- setImmediate(generateTitleWithContext);
442
+ this.scheduleTitleGeneration(options, normalizedUserId, writeContext);
451
443
  conversation = {
452
444
  id: randomUUID(),
453
445
  title: "New Conversation", // Temporary title until generated
@@ -501,7 +493,7 @@ export class RedisConversationMemoryManager {
501
493
  // Append-only: push just this turn's messages and persist a SMALL
502
494
  // metadata blob. A session not yet using split storage (new, or a
503
495
  // legacy blob) is converted once here, then every later turn appends.
504
- await this.persistConversation(conversation, options.sessionId, options.userId, wasSplitStorage ? messageCountBeforeTurn : undefined);
496
+ await this.persistConversation(conversation, options.sessionId, options.userId, wasSplitStorage ? messageCountBeforeTurn : undefined, writeContext);
505
497
  // Scheduled AFTER the write, never before it. On the single turn that
506
498
  // converts a legacy session, `checkAndSummarize` re-reads the blob and
507
499
  // writes it back; observing the pre-conversion blob would make it
@@ -509,50 +501,11 @@ export class RedisConversationMemoryManager {
509
501
  // would strip the marker while the companion LIST already held the
510
502
  // messages — the next read would then serve the stale inline copy.
511
503
  if (shouldSummarize) {
512
- const normalizedUserId = options.userId || "randomUser";
513
- const summarizationKey = `${options.sessionId}:${normalizedUserId}`;
514
- // Only trigger summarization if not already in progress for this session
515
- if (!this.summarizationInProgress.has(summarizationKey)) {
516
- const summarizeWithContext = context.bind(context.active(), async () => {
517
- try {
518
- await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId, options.requestId);
519
- }
520
- catch (error) {
521
- logger.error("Background summarization failed", {
522
- sessionId: conversation.sessionId,
523
- error: error instanceof Error ? error.message : String(error),
524
- });
525
- }
526
- });
527
- setImmediate(summarizeWithContext);
528
- }
529
- else {
530
- logger.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping", {
531
- sessionId: options.sessionId,
532
- userId: normalizedUserId,
533
- });
534
- }
535
- }
536
- // Log turn storage metadata for observability
537
- const blobSizeBytes = Buffer.byteLength(serializeConversationMetadata(conversation), "utf8");
538
- logger.info("[ConversationMemory] Turn stored", {
539
- requestId: options.requestId,
540
- sessionId: options.sessionId,
541
- blobSizeBytes,
542
- totalMessages: conversation.messages.length,
543
- userMsgChars: options.userMessage.length,
544
- assistantMsgChars: options.aiResponse.length,
545
- });
546
- if (blobSizeBytes > 512 * 1024) {
547
- logger.warn("[ConversationMemory] Large session blob", {
548
- requestId: options.requestId,
549
- sessionId: options.sessionId,
550
- blobSizeBytes,
551
- messageCount: conversation.messages.length,
552
- });
504
+ this.scheduleSummarization(conversation, tokenThreshold, options, writeContext);
553
505
  }
506
+ this.logTurnStored(conversation, options);
554
507
  if (options.userId) {
555
- await this.addUserSession(options.userId, options.sessionId);
508
+ await this.addUserSession(options.userId, options.sessionId, writeContext);
556
509
  }
557
510
  span.setAttribute("message.count", conversation.messages.length);
558
511
  span.setStatus({ code: SpanStatusCode.OK });
@@ -578,10 +531,107 @@ export class RedisConversationMemoryManager {
578
531
  }
579
532
  });
580
533
  }
534
+ /**
535
+ * Generate a title for a new session in the background and write it back.
536
+ */
537
+ scheduleTitleGeneration(options, normalizedUserId, writeContext) {
538
+ const titleGenerationKey = `${options.sessionId}:${normalizedUserId}`;
539
+ const generateTitleWithContext = context.bind(context.active(), async () => {
540
+ if (this.titleGenerationInProgress.has(titleGenerationKey)) {
541
+ return;
542
+ }
543
+ this.titleGenerationInProgress.add(titleGenerationKey);
544
+ try {
545
+ const title = await this.generateConversationTitle(options.userMessage);
546
+ const updatedRedisKey = getSessionKey(this.redisConfig, options.sessionId, options.userId || undefined);
547
+ const updatedConversationData = await this.redisClient?.get(updatedRedisKey);
548
+ const updatedConversation = deserializeConversation(updatedConversationData || null);
549
+ if (updatedConversation) {
550
+ updatedConversation.title = title;
551
+ updatedConversation.updatedAt = new Date().toISOString();
552
+ const serializedData = serializeConversation(updatedConversation);
553
+ if (this.redisClient) {
554
+ await fencedSessionMetadataWrite(this.redisClient, this.redisConfig, options.sessionId, options.userId || undefined, serializedData, writeContext);
555
+ this.emitTitleGenerated({
556
+ sessionId: options.sessionId,
557
+ userId: normalizedUserId,
558
+ title,
559
+ timestamp: Date.now(),
560
+ });
561
+ }
562
+ }
563
+ }
564
+ catch (titleError) {
565
+ logger.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background", {
566
+ sessionId: options.sessionId,
567
+ userId: normalizedUserId,
568
+ error: titleError instanceof Error
569
+ ? titleError.message
570
+ : String(titleError),
571
+ });
572
+ }
573
+ finally {
574
+ this.titleGenerationInProgress.delete(titleGenerationKey);
575
+ }
576
+ });
577
+ setImmediate(generateTitleWithContext);
578
+ }
579
+ /**
580
+ * Summarize in the background when the session is not already being
581
+ * summarized.
582
+ */
583
+ scheduleSummarization(conversation, tokenThreshold, options, writeContext) {
584
+ const normalizedUserId = options.userId || "randomUser";
585
+ const summarizationKey = `${options.sessionId}:${normalizedUserId}`;
586
+ // Only trigger summarization if not already in progress for this session
587
+ if (!this.summarizationInProgress.has(summarizationKey)) {
588
+ const summarizeWithContext = context.bind(context.active(), async () => {
589
+ try {
590
+ await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId, options.requestId, writeContext);
591
+ }
592
+ catch (error) {
593
+ logger.error("Background summarization failed", {
594
+ sessionId: conversation.sessionId,
595
+ error: error instanceof Error ? error.message : String(error),
596
+ });
597
+ }
598
+ });
599
+ setImmediate(summarizeWithContext);
600
+ }
601
+ else {
602
+ logger.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping", {
603
+ sessionId: options.sessionId,
604
+ userId: normalizedUserId,
605
+ });
606
+ }
607
+ }
608
+ /**
609
+ * Log turn storage metadata for observability.
610
+ */
611
+ logTurnStored(conversation, options) {
612
+ const blobSizeBytes = Buffer.byteLength(serializeConversationMetadata(conversation), "utf8");
613
+ logger.info("[ConversationMemory] Turn stored", {
614
+ requestId: options.requestId,
615
+ sessionId: options.sessionId,
616
+ blobSizeBytes,
617
+ totalMessages: conversation.messages.length,
618
+ userMsgChars: options.userMessage.length,
619
+ assistantMsgChars: options.aiResponse.length,
620
+ });
621
+ if (blobSizeBytes > 512 * 1024) {
622
+ logger.warn("[ConversationMemory] Large session blob", {
623
+ requestId: options.requestId,
624
+ sessionId: options.sessionId,
625
+ blobSizeBytes,
626
+ messageCount: conversation.messages.length,
627
+ });
628
+ }
629
+ }
581
630
  /**
582
631
  * Check if summarization is needed based on token count
583
632
  */
584
- async checkAndSummarize(conversation, threshold, sessionId, userId, requestId) {
633
+ async checkAndSummarize(conversation, threshold, sessionId, userId, requestId, writeContext = this
634
+ .erasureWriteContext) {
585
635
  const normalizedUserId = userId || "randomUser";
586
636
  const summarizationKey = `${sessionId}:${normalizedUserId}`;
587
637
  if (this.summarizationInProgress.has(summarizationKey)) {
@@ -633,7 +683,7 @@ export class RedisConversationMemoryManager {
633
683
  const freshSerialized = usesSplitMessageStorage(latestConversation)
634
684
  ? serializeConversationMetadata(latestConversation)
635
685
  : serializeConversation(latestConversation);
636
- await setWithTtl(this.redisClient, redisKey, freshSerialized, this.redisConfig.ttl);
686
+ await fencedSessionMetadataWrite(this.redisClient, this.redisConfig, sessionId, userId, freshSerialized, writeContext);
637
687
  }
638
688
  }
639
689
  }
@@ -709,34 +759,25 @@ export class RedisConversationMemoryManager {
709
759
  * fast path); omit it to rewrite the LIST wholesale, which is also how a
710
760
  * legacy blob gets converted.
711
761
  */
712
- async persistConversation(conversation, sessionId, userId, appendFrom) {
762
+ async persistConversation(conversation, sessionId, userId, appendFrom, writeContext = this
763
+ .erasureWriteContext) {
713
764
  if (!this.redisClient) {
714
765
  return;
715
766
  }
716
- const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
717
- const messagesKey = getSessionMessagesKey(this.redisConfig, sessionId, userId);
718
767
  // One MULTI, not four to six independent commands. The replace path is a
719
768
  // DEL followed by an RPUSH, and on the legacy-conversion path the inline
720
769
  // blob is the only copy of the history until the SET lands — so a failure
721
770
  // between any two of them leaves the session either empty or unrecoverable.
722
771
  // Grouping them also collapses the round trips, which is the point of the
723
772
  // append-only layout.
724
- const tx = this.redisClient.multi();
725
- if (appendFrom === undefined) {
726
- tx.del(messagesKey);
727
- }
728
773
  const toPush = appendFrom === undefined
729
774
  ? conversation.messages
730
775
  : conversation.messages.slice(appendFrom);
731
- if (toPush.length > 0) {
732
- tx.rPush(messagesKey, encodeStoredMessages(toPush));
733
- }
734
- tx.set(redisKey, serializeConversationMetadata(conversation));
735
- if (this.redisConfig.ttl > 0) {
736
- tx.expire(redisKey, this.redisConfig.ttl);
737
- tx.expire(messagesKey, this.redisConfig.ttl);
738
- }
739
- await withTimeout(tx.exec(), REDIS_TIMEOUT_MS);
776
+ await withTimeout(fencedSessionPersist(this.redisClient, this.redisConfig, sessionId, userId, {
777
+ mode: appendFrom === undefined ? "replace" : "append",
778
+ messages: toPush.length > 0 ? encodeStoredMessages(toPush) : [],
779
+ payload: serializeConversationMetadata(conversation),
780
+ }, writeContext), REDIS_TIMEOUT_MS);
740
781
  }
741
782
  /**
742
783
  * Build context messages for AI prompt injection (TOKEN-BASED)
@@ -1157,6 +1198,7 @@ User message: "${userMessage}"`;
1157
1198
  */
1158
1199
  async setSessionMessages(sessionId, messages, userId) {
1159
1200
  await this.ensureInitialized();
1201
+ const writeContext = this.erasureWriteContext;
1160
1202
  if (!this.redisClient) {
1161
1203
  throw new ConversationMemoryError("Redis client not initialized", "STORAGE_ERROR", { sessionId });
1162
1204
  }
@@ -1176,7 +1218,7 @@ User message: "${userMessage}"`;
1176
1218
  conversation.lastTokenCount = undefined;
1177
1219
  conversation.lastCountedAt = undefined;
1178
1220
  // Wholesale replacement: rewrite the LIST rather than appending.
1179
- await this.persistConversation(conversation, sessionId, userId);
1221
+ await this.persistConversation(conversation, sessionId, userId, undefined, writeContext);
1180
1222
  logger.debug("[RedisConversationMemoryManager] Session messages replaced", {
1181
1223
  sessionId,
1182
1224
  userId,
@@ -1184,6 +1226,9 @@ User message: "${userMessage}"`;
1184
1226
  });
1185
1227
  }
1186
1228
  catch (error) {
1229
+ if (isErasureFenceRefusal(error)) {
1230
+ throw error;
1231
+ }
1187
1232
  if (error instanceof ConversationMemoryError) {
1188
1233
  throw error;
1189
1234
  }
@@ -1241,6 +1286,25 @@ User message: "${userMessage}"`;
1241
1286
  totalTurns,
1242
1287
  };
1243
1288
  }
1289
+ /**
1290
+ * Whether this writer participates in the `conversation-erasure-v1` fence.
1291
+ * Only participating writers are fenced; others are NOT.
1292
+ */
1293
+ getConversationErasureWriterStatus() {
1294
+ return conversationErasureWriterStatus(this.erasureWriteContext);
1295
+ }
1296
+ /**
1297
+ * Permanently erase one session. Fences participating writers only, and
1298
+ * needs a writer initialized with `erasureWriteProtocol:
1299
+ * "conversation-erasure-v1"`.
1300
+ */
1301
+ async eraseSessionPermanently(sessionId, userId) {
1302
+ await this.ensureInitialized();
1303
+ if (!this.redisClient) {
1304
+ throw new ConversationMemoryError("Redis unavailable; erasure unconfirmed", "STORAGE_ERROR", { sessionId });
1305
+ }
1306
+ return erasePermanently(this.redisClient, this.redisConfig, sessionId, userId, this.erasureWriteContext);
1307
+ }
1244
1308
  /**
1245
1309
  * Clear a specific session
1246
1310
  */
@@ -1674,6 +1738,7 @@ User message: "${userMessage}"`;
1674
1738
  reportStatus: report.reportStatus,
1675
1739
  });
1676
1740
  await this.ensureInitialized();
1741
+ const writeContext = this.erasureWriteContext;
1677
1742
  if (!this.redisClient) {
1678
1743
  logger.warn("[RedisConversationMemoryManager] Redis client not available for report update", { sessionId, userId });
1679
1744
  return;
@@ -1715,7 +1780,7 @@ User message: "${userMessage}"`;
1715
1780
  const serializedData = usesSplitMessageStorage(conversation)
1716
1781
  ? serializeConversationMetadata(conversation)
1717
1782
  : serializeConversation(conversation);
1718
- await withTimeout(setWithTtl(this.redisClient, redisKey, serializedData, this.redisConfig.ttl), 5000);
1783
+ await withTimeout(fencedSessionMetadataWrite(this.redisClient, this.redisConfig, sessionId, userId || undefined, serializedData, writeContext), 5000);
1719
1784
  logger.info("[RedisConversationMemoryManager] Successfully updated agentic loop report", {
1720
1785
  sessionId,
1721
1786
  userId,
@@ -1724,6 +1789,9 @@ User message: "${userMessage}"`;
1724
1789
  });
1725
1790
  }
1726
1791
  catch (error) {
1792
+ if (isErasureFenceRefusal(error)) {
1793
+ throw error;
1794
+ }
1727
1795
  logger.error("[RedisConversationMemoryManager] Failed to update agentic loop report", {
1728
1796
  sessionId,
1729
1797
  userId,
@@ -1139,6 +1139,31 @@ export declare class NeuroLink {
1139
1139
  * orchestration preference is tried before the existing provider fallback list.
1140
1140
  */
1141
1141
  private directProviderGeneration;
1142
+ /**
1143
+ * Generate through the configured ModelPool, walking its members until one
1144
+ * answers. Always returns or throws; never falls through to the static
1145
+ * provider list.
1146
+ */
1147
+ private generateViaModelPool;
1148
+ /**
1149
+ * Map a provider's answer to the internal generation result.
1150
+ */
1151
+ private toDirectGenerationResult;
1152
+ /**
1153
+ * Pre-dispatch hard cap for a request over budget with nothing to compact:
1154
+ * window the prompt to fit when the prompt is what blew the budget, else
1155
+ * throw ContextBudgetExceededError.
1156
+ */
1157
+ private windowOrRefuseOversizedPrompt;
1158
+ /**
1159
+ * Compact the conversation history before dispatch, re-checking the budget
1160
+ * and truncating as a last resort. Returns the history to send.
1161
+ */
1162
+ private compactHistoryForDispatch;
1163
+ /**
1164
+ * The error thrown once every candidate provider has failed.
1165
+ */
1166
+ private buildAllProvidersFailedError;
1142
1167
  /**
1143
1168
  * Create tool-aware system prompt that informs AI about available tools
1144
1169
  */
@@ -1273,6 +1298,21 @@ export declare class NeuroLink {
1273
1298
  * and GenerateOptions since both share the required fields.
1274
1299
  */
1275
1300
  private applyToolRoutingExclusions;
1301
+ /**
1302
+ * Record a tool routing decision on the active span. Telemetry only.
1303
+ */
1304
+ private recordToolRoutingSpan;
1305
+ /**
1306
+ * Build the embedding function for the L2 routing fast-path, or undefined
1307
+ * when embedding is off or its provider cannot be set up. Fails open.
1308
+ */
1309
+ private buildToolRoutingEmbedFn;
1310
+ /**
1311
+ * Store an applied routing decision for later turns: the cache entry (under
1312
+ * `cacheKey`, when caching is on) and the sticky servers (for
1313
+ * `stickySessionId`, when stickiness is on).
1314
+ */
1315
+ private storeToolRoutingOutcome;
1276
1316
  /**
1277
1317
  * Loads a bounded window of prior conversation turns for the router so a
1278
1318
  * follow-up turn carries the context it needs to classify intent. Reads this
@@ -1352,6 +1392,18 @@ export declare class NeuroLink {
1352
1392
  * absent either, getBestProvider retains its normal automatic selection.
1353
1393
  */
1354
1394
  private createMCPStream;
1395
+ /**
1396
+ * Compact the history before a stream, re-checking the budget and
1397
+ * truncating as a last resort; keeps `options.conversationMessages` in sync.
1398
+ * Returns the history to send.
1399
+ */
1400
+ private compactStreamHistory;
1401
+ /**
1402
+ * Stream through the configured ModelPool, walking its members until one
1403
+ * yields a stream. Always returns or throws; never falls through to the
1404
+ * single-provider path.
1405
+ */
1406
+ private streamViaModelPool;
1355
1407
  /**
1356
1408
  * Process stream result
1357
1409
  */
@@ -1364,6 +1416,12 @@ export declare class NeuroLink {
1364
1416
  * Create stream response
1365
1417
  */
1366
1418
  private createStreamResponse;
1419
+ /**
1420
+ * Whether `error` is the refusal of a conversation memory writer that opted in
1421
+ * to the erasure write protocol: the typed epoch error, or the CONFIG_ERROR
1422
+ * that storage which is unreachable, or not Redis, raises while the protocol is on.
1423
+ */
1424
+ private isStrictConversationAdmissionFailure;
1367
1425
  /**
1368
1426
  * Handle stream error with fallback
1369
1427
  */