@juspay/neurolink 9.10.1 → 9.12.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.
- package/CHANGELOG.md +16 -0
- package/dist/agent/directTools.d.ts +3 -3
- package/dist/cli/commands/config.d.ts +9 -9
- package/dist/cli/loop/optionsSchema.d.ts +1 -1
- package/dist/constants/contextWindows.d.ts +6 -3
- package/dist/constants/contextWindows.js +30 -3
- package/dist/constants/index.d.ts +3 -3
- package/dist/constants/retry.d.ts +4 -4
- package/dist/constants/retry.js +1 -1
- package/dist/context/contextCompactor.d.ts +1 -1
- package/dist/context/contextCompactor.js +59 -1
- package/dist/context/summarizationEngine.d.ts +2 -2
- package/dist/context/summarizationEngine.js +44 -18
- package/dist/context/toolOutputLimits.d.ts +22 -13
- package/dist/context/toolOutputLimits.js +58 -64
- package/dist/core/baseProvider.d.ts +11 -2
- package/dist/core/baseProvider.js +16 -1
- package/dist/core/conversationMemoryManager.d.ts +13 -1
- package/dist/core/conversationMemoryManager.js +36 -5
- package/dist/core/modules/GenerationHandler.d.ts +6 -0
- package/dist/core/modules/GenerationHandler.js +192 -7
- package/dist/core/modules/MessageBuilder.js +42 -4
- package/dist/core/modules/TelemetryHandler.js +4 -1
- package/dist/core/redisConversationMemoryManager.d.ts +19 -3
- package/dist/core/redisConversationMemoryManager.js +253 -58
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/lib/agent/directTools.d.ts +7 -7
- package/dist/lib/constants/contextWindows.d.ts +6 -3
- package/dist/lib/constants/contextWindows.js +30 -3
- package/dist/lib/constants/index.d.ts +3 -3
- package/dist/lib/constants/retry.d.ts +4 -4
- package/dist/lib/constants/retry.js +1 -1
- package/dist/lib/context/contextCompactor.d.ts +1 -1
- package/dist/lib/context/contextCompactor.js +59 -1
- package/dist/lib/context/summarizationEngine.d.ts +2 -2
- package/dist/lib/context/summarizationEngine.js +44 -18
- package/dist/lib/context/toolOutputLimits.d.ts +22 -13
- package/dist/lib/context/toolOutputLimits.js +58 -64
- package/dist/lib/core/baseProvider.d.ts +11 -2
- package/dist/lib/core/baseProvider.js +16 -1
- package/dist/lib/core/conversationMemoryManager.d.ts +13 -1
- package/dist/lib/core/conversationMemoryManager.js +36 -5
- package/dist/lib/core/modules/GenerationHandler.d.ts +6 -0
- package/dist/lib/core/modules/GenerationHandler.js +192 -7
- package/dist/lib/core/modules/MessageBuilder.js +42 -4
- package/dist/lib/core/modules/TelemetryHandler.js +4 -1
- package/dist/lib/core/redisConversationMemoryManager.d.ts +19 -3
- package/dist/lib/core/redisConversationMemoryManager.js +253 -58
- package/dist/lib/files/fileTools.d.ts +3 -3
- package/dist/lib/index.d.ts +2 -0
- package/dist/lib/index.js +3 -0
- package/dist/lib/mcp/externalServerManager.js +46 -10
- package/dist/lib/memory/memoryRetrievalTools.d.ts +166 -0
- package/dist/lib/memory/memoryRetrievalTools.js +145 -0
- package/dist/lib/neurolink.d.ts +35 -1
- package/dist/lib/neurolink.js +476 -16
- package/dist/lib/providers/amazonBedrock.d.ts +1 -1
- package/dist/lib/providers/amazonBedrock.js +78 -45
- package/dist/lib/providers/amazonSagemaker.d.ts +1 -1
- package/dist/lib/providers/amazonSagemaker.js +1 -1
- package/dist/lib/providers/anthropic.d.ts +1 -1
- package/dist/lib/providers/anthropic.js +7 -7
- package/dist/lib/providers/anthropicBaseProvider.d.ts +1 -1
- package/dist/lib/providers/anthropicBaseProvider.js +7 -6
- package/dist/lib/providers/azureOpenai.d.ts +1 -1
- package/dist/lib/providers/azureOpenai.js +1 -1
- package/dist/lib/providers/googleAiStudio.d.ts +1 -1
- package/dist/lib/providers/googleAiStudio.js +5 -5
- package/dist/lib/providers/googleVertex.d.ts +1 -1
- package/dist/lib/providers/googleVertex.js +74 -17
- package/dist/lib/providers/huggingFace.d.ts +1 -1
- package/dist/lib/providers/huggingFace.js +1 -1
- package/dist/lib/providers/litellm.d.ts +1 -1
- package/dist/lib/providers/litellm.js +18 -16
- package/dist/lib/providers/mistral.d.ts +1 -1
- package/dist/lib/providers/mistral.js +1 -1
- package/dist/lib/providers/ollama.d.ts +1 -1
- package/dist/lib/providers/ollama.js +8 -7
- package/dist/lib/providers/openAI.d.ts +1 -1
- package/dist/lib/providers/openAI.js +6 -6
- package/dist/lib/providers/openRouter.d.ts +1 -1
- package/dist/lib/providers/openRouter.js +6 -2
- package/dist/lib/providers/openaiCompatible.d.ts +1 -1
- package/dist/lib/providers/openaiCompatible.js +1 -1
- package/dist/lib/proxy/proxyFetch.js +291 -65
- package/dist/lib/server/utils/validation.d.ts +4 -4
- package/dist/lib/services/server/ai/observability/instrumentation.js +12 -3
- package/dist/lib/telemetry/telemetryService.d.ts +2 -1
- package/dist/lib/telemetry/telemetryService.js +8 -1
- package/dist/lib/types/contextTypes.d.ts +26 -2
- package/dist/lib/types/conversation.d.ts +72 -40
- package/dist/lib/types/conversationMemoryInterface.d.ts +5 -1
- package/dist/lib/types/generateTypes.d.ts +26 -0
- package/dist/lib/types/modelTypes.d.ts +2 -2
- package/dist/lib/types/multimodal.d.ts +2 -0
- package/dist/lib/types/observability.d.ts +10 -0
- package/dist/lib/types/sdkTypes.d.ts +1 -1
- package/dist/lib/utils/conversationMemory.d.ts +4 -3
- package/dist/lib/utils/conversationMemory.js +44 -6
- package/dist/lib/utils/errorHandling.d.ts +5 -0
- package/dist/lib/utils/errorHandling.js +7 -2
- package/dist/lib/utils/logger.d.ts +8 -0
- package/dist/lib/utils/logger.js +56 -1
- package/dist/lib/utils/messageBuilder.js +74 -4
- package/dist/lib/utils/redis.js +6 -1
- package/dist/lib/utils/tokenEstimation.d.ts +2 -2
- package/dist/lib/utils/tokenEstimation.js +16 -1
- package/dist/lib/workflow/config.d.ts +110 -110
- package/dist/mcp/externalServerManager.js +46 -10
- package/dist/memory/memoryRetrievalTools.d.ts +166 -0
- package/dist/memory/memoryRetrievalTools.js +144 -0
- package/dist/neurolink.d.ts +35 -1
- package/dist/neurolink.js +476 -16
- package/dist/providers/amazonBedrock.d.ts +1 -1
- package/dist/providers/amazonBedrock.js +78 -45
- package/dist/providers/amazonSagemaker.d.ts +1 -1
- package/dist/providers/amazonSagemaker.js +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/anthropic.js +7 -7
- package/dist/providers/anthropicBaseProvider.d.ts +1 -1
- package/dist/providers/anthropicBaseProvider.js +7 -6
- package/dist/providers/azureOpenai.d.ts +1 -1
- package/dist/providers/azureOpenai.js +1 -1
- package/dist/providers/googleAiStudio.d.ts +1 -1
- package/dist/providers/googleAiStudio.js +5 -5
- package/dist/providers/googleVertex.d.ts +1 -1
- package/dist/providers/googleVertex.js +74 -17
- package/dist/providers/huggingFace.d.ts +1 -1
- package/dist/providers/huggingFace.js +1 -1
- package/dist/providers/litellm.d.ts +1 -1
- package/dist/providers/litellm.js +18 -16
- package/dist/providers/mistral.d.ts +1 -1
- package/dist/providers/mistral.js +1 -1
- package/dist/providers/ollama.d.ts +1 -1
- package/dist/providers/ollama.js +8 -7
- package/dist/providers/openAI.d.ts +1 -1
- package/dist/providers/openAI.js +6 -6
- package/dist/providers/openRouter.d.ts +1 -1
- package/dist/providers/openRouter.js +6 -2
- package/dist/providers/openaiCompatible.d.ts +1 -1
- package/dist/providers/openaiCompatible.js +1 -1
- package/dist/proxy/proxyFetch.js +291 -65
- package/dist/services/server/ai/observability/instrumentation.js +12 -3
- package/dist/telemetry/telemetryService.d.ts +2 -1
- package/dist/telemetry/telemetryService.js +8 -1
- package/dist/types/contextTypes.d.ts +26 -2
- package/dist/types/conversation.d.ts +72 -40
- package/dist/types/conversationMemoryInterface.d.ts +5 -1
- package/dist/types/generateTypes.d.ts +26 -0
- package/dist/types/modelTypes.d.ts +10 -10
- package/dist/types/multimodal.d.ts +2 -0
- package/dist/types/observability.d.ts +10 -0
- package/dist/types/sdkTypes.d.ts +1 -1
- package/dist/utils/conversationMemory.d.ts +4 -3
- package/dist/utils/conversationMemory.js +44 -6
- package/dist/utils/errorHandling.d.ts +5 -0
- package/dist/utils/errorHandling.js +7 -2
- package/dist/utils/logger.d.ts +8 -0
- package/dist/utils/logger.js +56 -1
- package/dist/utils/messageBuilder.js +74 -4
- package/dist/utils/redis.js +6 -1
- package/dist/utils/tokenEstimation.d.ts +2 -2
- package/dist/utils/tokenEstimation.js +16 -1
- package/dist/workflow/config.d.ts +12 -12
- package/package.json +1 -1
|
@@ -76,25 +76,44 @@ export class MessageBuilder {
|
|
|
76
76
|
messages = await buildMessagesArray(options);
|
|
77
77
|
}
|
|
78
78
|
// Convert messages to Vercel AI SDK format
|
|
79
|
+
// Preserve providerOptions (e.g. Anthropic cache_control) through conversion
|
|
79
80
|
return messages.map((msg) => {
|
|
81
|
+
const providerOptions = msg
|
|
82
|
+
.providerOptions;
|
|
80
83
|
if (typeof msg.content === "string") {
|
|
81
84
|
return {
|
|
82
85
|
role: msg.role,
|
|
83
86
|
content: msg.content,
|
|
87
|
+
...(providerOptions && { providerOptions }),
|
|
84
88
|
};
|
|
85
89
|
}
|
|
86
90
|
else {
|
|
87
91
|
return {
|
|
88
92
|
role: msg.role,
|
|
89
93
|
content: msg.content.map((item) => {
|
|
94
|
+
const itemProviderOptions = item
|
|
95
|
+
.providerOptions;
|
|
90
96
|
if (item.type === "text") {
|
|
91
|
-
return {
|
|
97
|
+
return {
|
|
98
|
+
type: "text",
|
|
99
|
+
text: item.text || "",
|
|
100
|
+
...(itemProviderOptions && {
|
|
101
|
+
providerOptions: itemProviderOptions,
|
|
102
|
+
}),
|
|
103
|
+
};
|
|
92
104
|
}
|
|
93
105
|
else if (item.type === "image") {
|
|
94
|
-
return {
|
|
106
|
+
return {
|
|
107
|
+
type: "image",
|
|
108
|
+
image: item.image || "",
|
|
109
|
+
...(itemProviderOptions && {
|
|
110
|
+
providerOptions: itemProviderOptions,
|
|
111
|
+
}),
|
|
112
|
+
};
|
|
95
113
|
}
|
|
96
114
|
return item;
|
|
97
115
|
}),
|
|
116
|
+
...(providerOptions && { providerOptions }),
|
|
98
117
|
};
|
|
99
118
|
}
|
|
100
119
|
});
|
|
@@ -159,25 +178,44 @@ export class MessageBuilder {
|
|
|
159
178
|
messages = await buildMessagesArray(options);
|
|
160
179
|
}
|
|
161
180
|
// Convert messages to Vercel AI SDK format
|
|
181
|
+
// Preserve providerOptions (e.g. Anthropic cache_control) through conversion
|
|
162
182
|
return messages.map((msg) => {
|
|
183
|
+
const providerOptions = msg
|
|
184
|
+
.providerOptions;
|
|
163
185
|
if (typeof msg.content === "string") {
|
|
164
186
|
return {
|
|
165
187
|
role: msg.role,
|
|
166
188
|
content: msg.content,
|
|
189
|
+
...(providerOptions && { providerOptions }),
|
|
167
190
|
};
|
|
168
191
|
}
|
|
169
192
|
else {
|
|
170
193
|
return {
|
|
171
194
|
role: msg.role,
|
|
172
195
|
content: msg.content.map((item) => {
|
|
196
|
+
const itemProviderOptions = item
|
|
197
|
+
.providerOptions;
|
|
173
198
|
if (item.type === "text") {
|
|
174
|
-
return {
|
|
199
|
+
return {
|
|
200
|
+
type: "text",
|
|
201
|
+
text: item.text || "",
|
|
202
|
+
...(itemProviderOptions && {
|
|
203
|
+
providerOptions: itemProviderOptions,
|
|
204
|
+
}),
|
|
205
|
+
};
|
|
175
206
|
}
|
|
176
207
|
else if (item.type === "image") {
|
|
177
|
-
return {
|
|
208
|
+
return {
|
|
209
|
+
type: "image",
|
|
210
|
+
image: item.image || "",
|
|
211
|
+
...(itemProviderOptions && {
|
|
212
|
+
providerOptions: itemProviderOptions,
|
|
213
|
+
}),
|
|
214
|
+
};
|
|
178
215
|
}
|
|
179
216
|
return item;
|
|
180
217
|
}),
|
|
218
|
+
...(providerOptions && { providerOptions }),
|
|
181
219
|
};
|
|
182
220
|
}
|
|
183
221
|
});
|
|
@@ -17,6 +17,7 @@ import { nanoid } from "nanoid";
|
|
|
17
17
|
import { logger } from "../../utils/logger.js";
|
|
18
18
|
import { getPerformanceOptimizedProvider, recordProviderPerformanceFromMetrics, } from "../evaluationProviders.js";
|
|
19
19
|
import { modelConfig } from "../modelConfiguration.js";
|
|
20
|
+
import { TelemetryService } from "../../telemetry/telemetryService.js";
|
|
20
21
|
/**
|
|
21
22
|
* TelemetryHandler class - Handles analytics and telemetry for AI providers
|
|
22
23
|
*/
|
|
@@ -79,6 +80,8 @@ export class TelemetryHandler {
|
|
|
79
80
|
cost: actualCost,
|
|
80
81
|
success: true,
|
|
81
82
|
});
|
|
83
|
+
// Wire TelemetryService metrics so OTEL counters/histograms are populated
|
|
84
|
+
TelemetryService.getInstance().recordAIRequest(this.providerName, this.modelName, usage?.totalTokens || 0, responseTime, actualCost > 0 ? actualCost : undefined);
|
|
82
85
|
const optimizedProvider = getPerformanceOptimizedProvider("speed");
|
|
83
86
|
logger.debug(`🚀 Performance recorded for ${this.providerName}:`, {
|
|
84
87
|
responseTime: `${responseTime}ms`,
|
|
@@ -147,7 +150,7 @@ export class TelemetryHandler {
|
|
|
147
150
|
isEnabled: true,
|
|
148
151
|
functionId,
|
|
149
152
|
metadata,
|
|
150
|
-
recordInputs:
|
|
153
|
+
recordInputs: process.env.NEUROLINK_RECORD_INPUTS?.toLowerCase() === "true",
|
|
151
154
|
recordOutputs: true,
|
|
152
155
|
};
|
|
153
156
|
}
|
|
@@ -48,7 +48,13 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
|
|
|
48
48
|
/**
|
|
49
49
|
* Get session by ID, reconstructing a SessionMemory from Redis storage.
|
|
50
50
|
*/
|
|
51
|
-
getSession(sessionId: string, userId?: string): Promise<SessionMemory | undefined>;
|
|
51
|
+
getSession(sessionId: string, userId?: string, requestId?: string): Promise<SessionMemory | undefined>;
|
|
52
|
+
/**
|
|
53
|
+
* Get raw session data without any filtering or transformation.
|
|
54
|
+
* Used by the memory retrieval tool and internal APIs that need
|
|
55
|
+
* access to full message data including unmodified tool outputs.
|
|
56
|
+
*/
|
|
57
|
+
getSessionRaw(sessionId: string, userId?: string): Promise<RedisConversationObject | null>;
|
|
52
58
|
/**
|
|
53
59
|
* Get all sessions for a specific user
|
|
54
60
|
*/
|
|
@@ -90,9 +96,9 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
|
|
|
90
96
|
/**
|
|
91
97
|
* Build context messages for AI prompt injection (TOKEN-BASED)
|
|
92
98
|
* Returns messages from pointer onwards (or all if no pointer)
|
|
93
|
-
*
|
|
99
|
+
* Applies sendToolPreview toggle and hydrates result.result for backward compat
|
|
94
100
|
*/
|
|
95
|
-
buildContextMessages(sessionId: string, userId?: string, enableSummarization?: boolean): Promise<ChatMessage[]>;
|
|
101
|
+
buildContextMessages(sessionId: string, userId?: string, enableSummarization?: boolean, requestId?: string): Promise<ChatMessage[]>;
|
|
96
102
|
/**
|
|
97
103
|
* Get session metadata for a specific user session (optimized for listing)
|
|
98
104
|
* Fetches only essential metadata without heavy message arrays
|
|
@@ -131,6 +137,16 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
|
|
|
131
137
|
* Create summary system message
|
|
132
138
|
*/
|
|
133
139
|
createSummarySystemMessage(content: string, summarizesFrom?: string, summarizesTo?: string): ChatMessage;
|
|
140
|
+
/**
|
|
141
|
+
* Get the raw messages array for a session.
|
|
142
|
+
* Returns the full messages list without context filtering or summarization.
|
|
143
|
+
*/
|
|
144
|
+
getSessionMessages(sessionId: string, userId?: string): Promise<ChatMessage[]>;
|
|
145
|
+
/**
|
|
146
|
+
* Replace the entire messages array for a session.
|
|
147
|
+
* The session must already exist in Redis.
|
|
148
|
+
*/
|
|
149
|
+
setSessionMessages(sessionId: string, messages: ChatMessage[], userId?: string): Promise<void>;
|
|
134
150
|
/**
|
|
135
151
|
* Close Redis connection
|
|
136
152
|
*/
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { randomUUID } from "crypto";
|
|
6
6
|
import { MESSAGES_PER_TURN } from "../config/conversationMemory.js";
|
|
7
|
+
import { generateToolOutputPreview } from "../context/toolOutputLimits.js";
|
|
7
8
|
import { SummarizationEngine } from "../context/summarizationEngine.js";
|
|
8
9
|
import { NeuroLink } from "../neurolink.js";
|
|
9
10
|
import { ConversationMemoryError } from "../types/conversation.js";
|
|
@@ -102,7 +103,7 @@ export class RedisConversationMemoryManager {
|
|
|
102
103
|
/**
|
|
103
104
|
* Get session by ID, reconstructing a SessionMemory from Redis storage.
|
|
104
105
|
*/
|
|
105
|
-
async getSession(sessionId, userId) {
|
|
106
|
+
async getSession(sessionId, userId, requestId) {
|
|
106
107
|
await this.ensureInitialized();
|
|
107
108
|
if (!this.redisClient) {
|
|
108
109
|
return undefined;
|
|
@@ -114,6 +115,34 @@ export class RedisConversationMemoryManager {
|
|
|
114
115
|
if (!conversation) {
|
|
115
116
|
return undefined;
|
|
116
117
|
}
|
|
118
|
+
// Log session load metadata for observability
|
|
119
|
+
const blobSizeBytes = conversationData
|
|
120
|
+
? Buffer.byteLength(conversationData, "utf8")
|
|
121
|
+
: 0;
|
|
122
|
+
const messageCount = conversation.messages.length;
|
|
123
|
+
const hasSummary = !!conversation.summarizedUpToMessageId;
|
|
124
|
+
const pointerIndex = hasSummary
|
|
125
|
+
? conversation.messages.findIndex((msg) => msg.id === conversation.summarizedUpToMessageId)
|
|
126
|
+
: -1;
|
|
127
|
+
const recentMessageCount = hasSummary && pointerIndex !== -1
|
|
128
|
+
? messageCount - pointerIndex - 1
|
|
129
|
+
: messageCount;
|
|
130
|
+
logger.info("[ConversationMemory] Session loaded", {
|
|
131
|
+
requestId,
|
|
132
|
+
sessionId,
|
|
133
|
+
blobSizeBytes,
|
|
134
|
+
messageCount,
|
|
135
|
+
hasSummary,
|
|
136
|
+
recentMessageCount,
|
|
137
|
+
});
|
|
138
|
+
if (blobSizeBytes > 512 * 1024) {
|
|
139
|
+
logger.warn("[ConversationMemory] Large session blob", {
|
|
140
|
+
requestId,
|
|
141
|
+
sessionId,
|
|
142
|
+
blobSizeBytes,
|
|
143
|
+
messageCount,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
117
146
|
return {
|
|
118
147
|
sessionId: conversation.sessionId,
|
|
119
148
|
userId: conversation.userId,
|
|
@@ -137,6 +166,30 @@ export class RedisConversationMemoryManager {
|
|
|
137
166
|
return undefined;
|
|
138
167
|
}
|
|
139
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* Get raw session data without any filtering or transformation.
|
|
171
|
+
* Used by the memory retrieval tool and internal APIs that need
|
|
172
|
+
* access to full message data including unmodified tool outputs.
|
|
173
|
+
*/
|
|
174
|
+
async getSessionRaw(sessionId, userId) {
|
|
175
|
+
try {
|
|
176
|
+
await this.ensureInitialized();
|
|
177
|
+
if (!this.redisClient) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
181
|
+
const conversationData = await this.redisClient.get(redisKey);
|
|
182
|
+
return deserializeConversation(conversationData || null);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
logger.error("[RedisConversationMemoryManager] Failed to get raw session", {
|
|
186
|
+
sessionId,
|
|
187
|
+
userId,
|
|
188
|
+
error: error instanceof Error ? error.message : String(error),
|
|
189
|
+
});
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
140
193
|
/**
|
|
141
194
|
* Get all sessions for a specific user
|
|
142
195
|
*/
|
|
@@ -377,7 +430,7 @@ export class RedisConversationMemoryManager {
|
|
|
377
430
|
if (!this.summarizationInProgress.has(summarizationKey)) {
|
|
378
431
|
setImmediate(async () => {
|
|
379
432
|
try {
|
|
380
|
-
await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId);
|
|
433
|
+
await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId, options.requestId);
|
|
381
434
|
}
|
|
382
435
|
catch (error) {
|
|
383
436
|
logger.error("Background summarization failed", {
|
|
@@ -396,6 +449,24 @@ export class RedisConversationMemoryManager {
|
|
|
396
449
|
}
|
|
397
450
|
const serializedData = serializeConversation(conversation);
|
|
398
451
|
await this.redisClient.set(redisKey, serializedData);
|
|
452
|
+
// Log turn storage metadata for observability
|
|
453
|
+
const blobSizeBytes = Buffer.byteLength(serializedData, "utf8");
|
|
454
|
+
logger.info("[ConversationMemory] Turn stored", {
|
|
455
|
+
requestId: options.requestId,
|
|
456
|
+
sessionId: options.sessionId,
|
|
457
|
+
blobSizeBytes,
|
|
458
|
+
totalMessages: conversation.messages.length,
|
|
459
|
+
userMsgChars: options.userMessage.length,
|
|
460
|
+
assistantMsgChars: options.aiResponse.length,
|
|
461
|
+
});
|
|
462
|
+
if (blobSizeBytes > 512 * 1024) {
|
|
463
|
+
logger.warn("[ConversationMemory] Large session blob", {
|
|
464
|
+
requestId: options.requestId,
|
|
465
|
+
sessionId: options.sessionId,
|
|
466
|
+
blobSizeBytes,
|
|
467
|
+
messageCount: conversation.messages.length,
|
|
468
|
+
});
|
|
469
|
+
}
|
|
399
470
|
if (this.redisConfig.ttl > 0) {
|
|
400
471
|
await this.redisClient.expire(redisKey, this.redisConfig.ttl);
|
|
401
472
|
}
|
|
@@ -418,7 +489,7 @@ export class RedisConversationMemoryManager {
|
|
|
418
489
|
/**
|
|
419
490
|
* Check if summarization is needed based on token count
|
|
420
491
|
*/
|
|
421
|
-
async checkAndSummarize(conversation, threshold, sessionId, userId) {
|
|
492
|
+
async checkAndSummarize(conversation, threshold, sessionId, userId, requestId) {
|
|
422
493
|
const normalizedUserId = userId || "randomUser";
|
|
423
494
|
const summarizationKey = `${sessionId}:${normalizedUserId}`;
|
|
424
495
|
if (this.summarizationInProgress.has(summarizationKey)) {
|
|
@@ -442,7 +513,7 @@ export class RedisConversationMemoryManager {
|
|
|
442
513
|
createdAt: new Date(conversation.createdAt).getTime(),
|
|
443
514
|
lastActivity: new Date(conversation.updatedAt).getTime(),
|
|
444
515
|
};
|
|
445
|
-
const summarized = await this.summarizationEngine.checkAndSummarize(session, threshold, this.config, "[RedisConversationMemoryManager]");
|
|
516
|
+
const summarized = await this.summarizationEngine.checkAndSummarize(session, threshold, this.config, "[RedisConversationMemoryManager]", requestId);
|
|
446
517
|
conversation.lastTokenCount = session.lastTokenCount;
|
|
447
518
|
conversation.lastCountedAt = session.lastCountedAt;
|
|
448
519
|
if (summarized) {
|
|
@@ -471,9 +542,9 @@ export class RedisConversationMemoryManager {
|
|
|
471
542
|
/**
|
|
472
543
|
* Build context messages for AI prompt injection (TOKEN-BASED)
|
|
473
544
|
* Returns messages from pointer onwards (or all if no pointer)
|
|
474
|
-
*
|
|
545
|
+
* Applies sendToolPreview toggle and hydrates result.result for backward compat
|
|
475
546
|
*/
|
|
476
|
-
async buildContextMessages(sessionId, userId, enableSummarization) {
|
|
547
|
+
async buildContextMessages(sessionId, userId, enableSummarization, requestId) {
|
|
477
548
|
logger.info("[RedisConversationMemoryManager] Building context messages", {
|
|
478
549
|
sessionId,
|
|
479
550
|
userId,
|
|
@@ -497,14 +568,34 @@ export class RedisConversationMemoryManager {
|
|
|
497
568
|
createdAt: new Date(conversation.createdAt).getTime(),
|
|
498
569
|
lastActivity: new Date(conversation.updatedAt).getTime(),
|
|
499
570
|
};
|
|
500
|
-
const contextMessages = buildContextFromPointer(session);
|
|
501
|
-
const
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
571
|
+
const contextMessages = buildContextFromPointer(session, requestId);
|
|
572
|
+
const sendToolPreview = this.config?.contextCompaction?.sendToolPreview === true;
|
|
573
|
+
// Map tool_result messages: apply preview toggle + hydrate result.result
|
|
574
|
+
const finalMessages = contextMessages.map((msg) => {
|
|
575
|
+
if (msg.role !== "tool_result") {
|
|
576
|
+
return msg;
|
|
577
|
+
}
|
|
578
|
+
// Toggle: swap content to preview if enabled AND a preview exists
|
|
579
|
+
const content = sendToolPreview && msg.metadata?.toolOutputPreview
|
|
580
|
+
? msg.metadata.toolOutputPreview
|
|
581
|
+
: msg.content;
|
|
582
|
+
// Hydrate result.result from content for backward compatibility
|
|
583
|
+
// (result.result is no longer stored — inferred from content at read time)
|
|
584
|
+
let hydratedResult = msg.result;
|
|
585
|
+
if (msg.result && msg.result.result === undefined) {
|
|
586
|
+
let parsedResult = content;
|
|
587
|
+
try {
|
|
588
|
+
parsedResult = JSON.parse(content);
|
|
589
|
+
}
|
|
590
|
+
catch {
|
|
591
|
+
/* plain text — use as-is */
|
|
592
|
+
}
|
|
593
|
+
hydratedResult = { ...msg.result, result: parsedResult };
|
|
594
|
+
}
|
|
595
|
+
return { ...msg, content, result: hydratedResult };
|
|
596
|
+
});
|
|
597
|
+
// Tool messages now have real content and participate in context properly.
|
|
598
|
+
// The tool output pruner (Stage 1) handles bounding old tool outputs.
|
|
508
599
|
logger.info("[RedisConversationMemoryManager] Retrieved context messages", {
|
|
509
600
|
sessionId,
|
|
510
601
|
userId,
|
|
@@ -756,6 +847,75 @@ User message: "${userMessage}"`;
|
|
|
756
847
|
},
|
|
757
848
|
};
|
|
758
849
|
}
|
|
850
|
+
/**
|
|
851
|
+
* Get the raw messages array for a session.
|
|
852
|
+
* Returns the full messages list without context filtering or summarization.
|
|
853
|
+
*/
|
|
854
|
+
async getSessionMessages(sessionId, userId) {
|
|
855
|
+
await this.ensureInitialized();
|
|
856
|
+
if (!this.redisClient) {
|
|
857
|
+
return [];
|
|
858
|
+
}
|
|
859
|
+
try {
|
|
860
|
+
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
861
|
+
const conversationData = await this.redisClient.get(redisKey);
|
|
862
|
+
const conversation = deserializeConversation(conversationData || null);
|
|
863
|
+
return conversation?.messages ?? [];
|
|
864
|
+
}
|
|
865
|
+
catch (error) {
|
|
866
|
+
logger.error("[RedisConversationMemoryManager] Failed to get session messages", {
|
|
867
|
+
sessionId,
|
|
868
|
+
userId,
|
|
869
|
+
error: error instanceof Error ? error.message : String(error),
|
|
870
|
+
});
|
|
871
|
+
return [];
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Replace the entire messages array for a session.
|
|
876
|
+
* The session must already exist in Redis.
|
|
877
|
+
*/
|
|
878
|
+
async setSessionMessages(sessionId, messages, userId) {
|
|
879
|
+
await this.ensureInitialized();
|
|
880
|
+
if (!this.redisClient) {
|
|
881
|
+
throw new ConversationMemoryError("Redis client not initialized", "STORAGE_ERROR", { sessionId });
|
|
882
|
+
}
|
|
883
|
+
try {
|
|
884
|
+
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
885
|
+
const conversationData = await this.redisClient.get(redisKey);
|
|
886
|
+
const conversation = deserializeConversation(conversationData || null);
|
|
887
|
+
if (!conversation) {
|
|
888
|
+
throw new ConversationMemoryError(`Session ${sessionId} not found`, "STORAGE_ERROR", { sessionId });
|
|
889
|
+
}
|
|
890
|
+
conversation.messages = messages;
|
|
891
|
+
conversation.updatedAt = new Date().toISOString();
|
|
892
|
+
// Reset summarization pointers — the old summary no longer applies
|
|
893
|
+
// to the replaced messages array
|
|
894
|
+
conversation.summarizedUpToMessageId = undefined;
|
|
895
|
+
conversation.summarizedMessage = undefined;
|
|
896
|
+
conversation.lastTokenCount = undefined;
|
|
897
|
+
conversation.lastCountedAt = undefined;
|
|
898
|
+
const serializedData = serializeConversation(conversation);
|
|
899
|
+
await this.redisClient.set(redisKey, serializedData);
|
|
900
|
+
if (this.redisConfig.ttl > 0) {
|
|
901
|
+
await this.redisClient.expire(redisKey, this.redisConfig.ttl);
|
|
902
|
+
}
|
|
903
|
+
logger.debug("[RedisConversationMemoryManager] Session messages replaced", {
|
|
904
|
+
sessionId,
|
|
905
|
+
userId,
|
|
906
|
+
messageCount: messages.length,
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
catch (error) {
|
|
910
|
+
if (error instanceof ConversationMemoryError) {
|
|
911
|
+
throw error;
|
|
912
|
+
}
|
|
913
|
+
throw new ConversationMemoryError(`Failed to set session messages for session ${sessionId}`, "STORAGE_ERROR", {
|
|
914
|
+
sessionId,
|
|
915
|
+
error: error instanceof Error ? error.message : String(error),
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
}
|
|
759
919
|
/**
|
|
760
920
|
* Close Redis connection
|
|
761
921
|
*/
|
|
@@ -966,52 +1126,87 @@ User message: "${userMessage}"`;
|
|
|
966
1126
|
toolCallsCount: pendingData.toolCalls.length,
|
|
967
1127
|
toolResultsCount: pendingData.toolResults.length,
|
|
968
1128
|
});
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
const
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
toolCall.
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
const
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
result
|
|
1129
|
+
try {
|
|
1130
|
+
// Create a mapping from toolCallId to toolName for matching tool results
|
|
1131
|
+
const toolCallMap = new Map();
|
|
1132
|
+
// Create separate messages for tool calls and build the mapping
|
|
1133
|
+
for (const toolCall of pendingData.toolCalls) {
|
|
1134
|
+
const toolCallId = toolCall.toolCallId ?? "";
|
|
1135
|
+
const toolName = toolCall.toolName ?? "";
|
|
1136
|
+
// Store in mapping for tool results
|
|
1137
|
+
toolCallMap.set(toolCallId, toolName);
|
|
1138
|
+
const toolCallMessage = {
|
|
1139
|
+
id: randomUUID(),
|
|
1140
|
+
timestamp: toolCall.timestamp?.toISOString() || this.generateTimestamp(),
|
|
1141
|
+
role: "tool_call",
|
|
1142
|
+
content: "", // Can be empty for tool calls
|
|
1143
|
+
tool: toolName,
|
|
1144
|
+
args: (toolCall.args ||
|
|
1145
|
+
toolCall.arguments ||
|
|
1146
|
+
toolCall.parameters ||
|
|
1147
|
+
{}),
|
|
1148
|
+
};
|
|
1149
|
+
conversation.messages.push(toolCallMessage);
|
|
1150
|
+
}
|
|
1151
|
+
// Create separate messages for tool results using the mapping
|
|
1152
|
+
for (const toolResult of pendingData.toolResults) {
|
|
1153
|
+
const toolCallId = String(toolResult.toolCallId || toolResult.id || "unknown");
|
|
1154
|
+
const toolName = toolCallMap.get(toolCallId) || "unknown";
|
|
1155
|
+
// Serialize the tool result to string for content field
|
|
1156
|
+
let serializedResult;
|
|
1157
|
+
if (typeof toolResult.result === "string") {
|
|
1158
|
+
serializedResult = toolResult.result;
|
|
1159
|
+
}
|
|
1160
|
+
else if (toolResult.result === undefined ||
|
|
1161
|
+
toolResult.result === null) {
|
|
1162
|
+
serializedResult = String(toolResult.result ?? "null");
|
|
1163
|
+
}
|
|
1164
|
+
else {
|
|
1165
|
+
try {
|
|
1166
|
+
serializedResult = JSON.stringify(toolResult.result, null, 2);
|
|
1167
|
+
}
|
|
1168
|
+
catch (serializeError) {
|
|
1169
|
+
serializedResult = `[Serialization failed: ${serializeError instanceof Error ? serializeError.message : String(serializeError)}]`;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
// Generate preview (uses existing config fields that were previously unused)
|
|
1173
|
+
const { preview, truncated, originalSize } = generateToolOutputPreview(serializedResult, {
|
|
1174
|
+
maxBytes: this.config?.contextCompaction?.maxToolOutputBytes,
|
|
1175
|
+
maxLines: this.config?.contextCompaction?.maxToolOutputLines,
|
|
1176
|
+
});
|
|
1177
|
+
// Build metadata — only store preview when truncation occurred (no duplication)
|
|
1178
|
+
const metadata = {
|
|
1179
|
+
truncated,
|
|
1180
|
+
...(truncated && { toolOutputPreview: preview }),
|
|
1181
|
+
...(truncated && { originalSize }),
|
|
1182
|
+
};
|
|
1183
|
+
// Build result — success/error metadata only, NOT the output data
|
|
1184
|
+
const result = {
|
|
1001
1185
|
success: !toolResult.error,
|
|
1002
|
-
result
|
|
1186
|
+
// result.result intentionally NOT stored — inferred from content at read time
|
|
1003
1187
|
error: toolResult.error ? String(toolResult.error) : undefined,
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1188
|
+
};
|
|
1189
|
+
const toolResultMessage = {
|
|
1190
|
+
id: randomUUID(),
|
|
1191
|
+
timestamp: toolResult.timestamp?.toISOString() || this.generateTimestamp(),
|
|
1192
|
+
role: "tool_result",
|
|
1193
|
+
content: serializedResult, // Full output (was "")
|
|
1194
|
+
tool: toolName,
|
|
1195
|
+
result,
|
|
1196
|
+
metadata,
|
|
1197
|
+
};
|
|
1198
|
+
conversation.messages.push(toolResultMessage);
|
|
1199
|
+
}
|
|
1200
|
+
logger.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data", {
|
|
1201
|
+
sessionId,
|
|
1202
|
+
userId,
|
|
1203
|
+
toolMessagesAdded: pendingData.toolCalls.length + pendingData.toolResults.length,
|
|
1204
|
+
totalMessages: conversation.messages.length,
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
finally {
|
|
1208
|
+
// Always clean up pending data, even on failure, to prevent infinite retry loops
|
|
1209
|
+
this.pendingToolExecutions.delete(pendingKey);
|
|
1007
1210
|
}
|
|
1008
|
-
// Remove the pending data now that it's been flushed
|
|
1009
|
-
this.pendingToolExecutions.delete(pendingKey);
|
|
1010
|
-
logger.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data", {
|
|
1011
|
-
sessionId,
|
|
1012
|
-
userId,
|
|
1013
|
-
toolMessagesAdded: pendingData.toolCalls.length + pendingData.toolResults.length,
|
|
1014
|
-
totalMessages: conversation.messages.length,
|
|
1015
|
-
});
|
|
1016
1211
|
}
|
|
1017
1212
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -42,6 +42,8 @@ export type { DynamicModelConfig, ModelRegistry } from "./types/modelTypes.js";
|
|
|
42
42
|
export { getAvailableProviders, getBestProvider, isValidProvider, } from "./utils/providerUtils.js";
|
|
43
43
|
export { calculateCost, hasPricing } from "./utils/pricing.js";
|
|
44
44
|
export { isAbortError } from "./utils/errorHandling.js";
|
|
45
|
+
export { TTSProcessor } from "./utils/ttsProcessor.js";
|
|
46
|
+
export { GoogleTTSHandler } from "./adapters/tts/googleTTSHandler.js";
|
|
45
47
|
import { NeuroLink } from "./neurolink.js";
|
|
46
48
|
export { NeuroLink };
|
|
47
49
|
export type { MCPServerInfo } from "./types/mcpTypes.js";
|
package/dist/index.js
CHANGED
|
@@ -49,6 +49,9 @@ export { getAvailableProviders, getBestProvider, isValidProvider, } from "./util
|
|
|
49
49
|
export { calculateCost, hasPricing } from "./utils/pricing.js";
|
|
50
50
|
// Error utilities
|
|
51
51
|
export { isAbortError } from "./utils/errorHandling.js";
|
|
52
|
+
// TTS utilities
|
|
53
|
+
export { TTSProcessor } from "./utils/ttsProcessor.js";
|
|
54
|
+
export { GoogleTTSHandler } from "./adapters/tts/googleTTSHandler.js";
|
|
52
55
|
// Main NeuroLink wrapper class and diagnostic types
|
|
53
56
|
import { NeuroLink } from "./neurolink.js";
|
|
54
57
|
export { NeuroLink };
|
|
@@ -221,11 +221,11 @@ export declare const directAgentTools: {
|
|
|
221
221
|
}, "strip", z.ZodTypeAny, {
|
|
222
222
|
content: string;
|
|
223
223
|
path: string;
|
|
224
|
-
mode: "create" | "
|
|
224
|
+
mode: "create" | "overwrite" | "append";
|
|
225
225
|
}, {
|
|
226
226
|
content: string;
|
|
227
227
|
path: string;
|
|
228
|
-
mode?: "create" | "
|
|
228
|
+
mode?: "create" | "overwrite" | "append" | undefined;
|
|
229
229
|
}>, {
|
|
230
230
|
success: boolean;
|
|
231
231
|
error: string;
|
|
@@ -236,7 +236,7 @@ export declare const directAgentTools: {
|
|
|
236
236
|
} | {
|
|
237
237
|
success: boolean;
|
|
238
238
|
path: string;
|
|
239
|
-
mode: "create" | "
|
|
239
|
+
mode: "create" | "overwrite" | "append";
|
|
240
240
|
size: number;
|
|
241
241
|
written: number;
|
|
242
242
|
error?: undefined;
|
|
@@ -251,7 +251,7 @@ export declare const directAgentTools: {
|
|
|
251
251
|
execute: (args: {
|
|
252
252
|
content: string;
|
|
253
253
|
path: string;
|
|
254
|
-
mode: "create" | "
|
|
254
|
+
mode: "create" | "overwrite" | "append";
|
|
255
255
|
}, options: import("ai").ToolExecutionOptions) => PromiseLike<{
|
|
256
256
|
success: boolean;
|
|
257
257
|
error: string;
|
|
@@ -262,7 +262,7 @@ export declare const directAgentTools: {
|
|
|
262
262
|
} | {
|
|
263
263
|
success: boolean;
|
|
264
264
|
path: string;
|
|
265
|
-
mode: "create" | "
|
|
265
|
+
mode: "create" | "overwrite" | "append";
|
|
266
266
|
size: number;
|
|
267
267
|
written: number;
|
|
268
268
|
error?: undefined;
|
|
@@ -282,8 +282,8 @@ export declare const directAgentTools: {
|
|
|
282
282
|
maxRows: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
283
283
|
}, "strip", z.ZodTypeAny, {
|
|
284
284
|
operation: "count_by_column" | "sum_by_column" | "average_by_column" | "min_max_by_column" | "describe";
|
|
285
|
-
filePath: string;
|
|
286
285
|
maxRows: number;
|
|
286
|
+
filePath: string;
|
|
287
287
|
column: string;
|
|
288
288
|
}, {
|
|
289
289
|
operation: "count_by_column" | "sum_by_column" | "average_by_column" | "min_max_by_column" | "describe";
|
|
@@ -309,8 +309,8 @@ export declare const directAgentTools: {
|
|
|
309
309
|
}> & {
|
|
310
310
|
execute: (args: {
|
|
311
311
|
operation: "count_by_column" | "sum_by_column" | "average_by_column" | "min_max_by_column" | "describe";
|
|
312
|
-
filePath: string;
|
|
313
312
|
maxRows: number;
|
|
313
|
+
filePath: string;
|
|
314
314
|
column: string;
|
|
315
315
|
}, options: import("ai").ToolExecutionOptions) => PromiseLike<{
|
|
316
316
|
success: boolean;
|
|
@@ -25,9 +25,12 @@ export declare const MODEL_CONTEXT_WINDOWS: Record<string, Record<string, number
|
|
|
25
25
|
* Resolve context window size for a provider/model combination.
|
|
26
26
|
*
|
|
27
27
|
* Priority:
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
28
|
+
* 0. Dynamic model registry (DynamicModelProvider) — resolves cross-provider
|
|
29
|
+
* models (e.g. Claude on Vertex) that the static table cannot handle
|
|
30
|
+
* 1. Exact model match under provider in static registry
|
|
31
|
+
* 2. Prefix match under provider in static registry
|
|
32
|
+
* 3. Provider's _default in static registry
|
|
33
|
+
* 4. Global DEFAULT_CONTEXT_WINDOW
|
|
31
34
|
*/
|
|
32
35
|
export declare function getContextWindowSize(provider: string, model?: string): number;
|
|
33
36
|
/**
|