@juspay/neurolink 13.10.0 → 13.10.2

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.
@@ -100,6 +100,19 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
100
100
  * Store a conversation turn for a session
101
101
  */
102
102
  storeConversationTurn(options: StoreConversationTurnOptions): Promise<void>;
103
+ /**
104
+ * Generate a title for a new session in the background and write it back.
105
+ */
106
+ private scheduleTitleGeneration;
107
+ /**
108
+ * Summarize in the background when the session is not already being
109
+ * summarized.
110
+ */
111
+ private scheduleSummarization;
112
+ /**
113
+ * Log turn storage metadata for observability.
114
+ */
115
+ private logTurnStored;
103
116
  /**
104
117
  * Check if summarization is needed based on token count
105
118
  */
@@ -439,46 +439,7 @@ export class RedisConversationMemoryManager {
439
439
  const currentTime = new Date().toISOString();
440
440
  const normalizedUserId = options.userId || "randomUser";
441
441
  if (!conversation) {
442
- const titleGenerationKey = `${options.sessionId}:${normalizedUserId}`;
443
- const generateTitleWithContext = context.bind(context.active(), async () => {
444
- if (this.titleGenerationInProgress.has(titleGenerationKey)) {
445
- return;
446
- }
447
- this.titleGenerationInProgress.add(titleGenerationKey);
448
- try {
449
- const title = await this.generateConversationTitle(options.userMessage);
450
- const updatedRedisKey = getSessionKey(this.redisConfig, options.sessionId, options.userId || undefined);
451
- const updatedConversationData = await this.redisClient?.get(updatedRedisKey);
452
- const updatedConversation = deserializeConversation(updatedConversationData || null);
453
- if (updatedConversation) {
454
- updatedConversation.title = title;
455
- updatedConversation.updatedAt = new Date().toISOString();
456
- const serializedData = serializeConversation(updatedConversation);
457
- if (this.redisClient) {
458
- await fencedSessionMetadataWrite(this.redisClient, this.redisConfig, options.sessionId, options.userId || undefined, serializedData, writeContext);
459
- this.emitTitleGenerated({
460
- sessionId: options.sessionId,
461
- userId: normalizedUserId,
462
- title,
463
- timestamp: Date.now(),
464
- });
465
- }
466
- }
467
- }
468
- catch (titleError) {
469
- logger.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background", {
470
- sessionId: options.sessionId,
471
- userId: normalizedUserId,
472
- error: titleError instanceof Error
473
- ? titleError.message
474
- : String(titleError),
475
- });
476
- }
477
- finally {
478
- this.titleGenerationInProgress.delete(titleGenerationKey);
479
- }
480
- });
481
- setImmediate(generateTitleWithContext);
442
+ this.scheduleTitleGeneration(options, normalizedUserId, writeContext);
482
443
  conversation = {
483
444
  id: randomUUID(),
484
445
  title: "New Conversation", // Temporary title until generated
@@ -540,48 +501,9 @@ export class RedisConversationMemoryManager {
540
501
  // would strip the marker while the companion LIST already held the
541
502
  // messages — the next read would then serve the stale inline copy.
542
503
  if (shouldSummarize) {
543
- const normalizedUserId = options.userId || "randomUser";
544
- const summarizationKey = `${options.sessionId}:${normalizedUserId}`;
545
- // Only trigger summarization if not already in progress for this session
546
- if (!this.summarizationInProgress.has(summarizationKey)) {
547
- const summarizeWithContext = context.bind(context.active(), async () => {
548
- try {
549
- await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId, options.requestId, writeContext);
550
- }
551
- catch (error) {
552
- logger.error("Background summarization failed", {
553
- sessionId: conversation.sessionId,
554
- error: error instanceof Error ? error.message : String(error),
555
- });
556
- }
557
- });
558
- setImmediate(summarizeWithContext);
559
- }
560
- else {
561
- logger.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping", {
562
- sessionId: options.sessionId,
563
- userId: normalizedUserId,
564
- });
565
- }
566
- }
567
- // Log turn storage metadata for observability
568
- const blobSizeBytes = Buffer.byteLength(serializeConversationMetadata(conversation), "utf8");
569
- logger.info("[ConversationMemory] Turn stored", {
570
- requestId: options.requestId,
571
- sessionId: options.sessionId,
572
- blobSizeBytes,
573
- totalMessages: conversation.messages.length,
574
- userMsgChars: options.userMessage.length,
575
- assistantMsgChars: options.aiResponse.length,
576
- });
577
- if (blobSizeBytes > 512 * 1024) {
578
- logger.warn("[ConversationMemory] Large session blob", {
579
- requestId: options.requestId,
580
- sessionId: options.sessionId,
581
- blobSizeBytes,
582
- messageCount: conversation.messages.length,
583
- });
504
+ this.scheduleSummarization(conversation, tokenThreshold, options, writeContext);
584
505
  }
506
+ this.logTurnStored(conversation, options);
585
507
  if (options.userId) {
586
508
  await this.addUserSession(options.userId, options.sessionId, writeContext);
587
509
  }
@@ -609,6 +531,102 @@ export class RedisConversationMemoryManager {
609
531
  }
610
532
  });
611
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
+ }
612
630
  /**
613
631
  * Check if summarization is needed based on token count
614
632
  */
@@ -180,8 +180,11 @@ export class MCPToolRegistry extends MCPRegistry {
180
180
  tools: toolsObject,
181
181
  configuration: {},
182
182
  };
183
- // Call the parent register method
184
- this.register(plugin);
183
+ // Key by the server id, the same key unregisterServer() removes by.
184
+ // metadata.name is display text: two servers may share it, and the
185
+ // parent register() would let the second silently replace the first.
186
+ this.plugins.set(serverId, plugin);
187
+ registryLogger.debug(`Registered plugin: ${plugin.metadata.name}`);
185
188
  // Use MCPServerInfo.tools array directly - ZERO conversions!
186
189
  const tools = serverInfo.tools;
187
190
  for (const tool of tools) {
@@ -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
  */