@juspay/neurolink 10.10.6 → 10.10.7
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 +8 -0
- package/dist/browser/neurolink.min.js +399 -399
- package/dist/constants/contextWindows.js +10 -1
- package/dist/context/anthropicLoopGuard.d.ts +1 -0
- package/dist/context/anthropicLoopGuard.js +30 -12
- package/dist/context/contextCompactor.js +19 -0
- package/dist/context/geminiLoopGuard.d.ts +54 -0
- package/dist/context/geminiLoopGuard.js +140 -0
- package/dist/core/redisConversationMemoryManager.d.ts +27 -0
- package/dist/core/redisConversationMemoryManager.js +146 -25
- package/dist/lib/constants/contextWindows.js +10 -1
- package/dist/lib/context/anthropicLoopGuard.d.ts +1 -0
- package/dist/lib/context/anthropicLoopGuard.js +30 -12
- package/dist/lib/context/contextCompactor.js +19 -0
- package/dist/lib/context/geminiLoopGuard.d.ts +54 -0
- package/dist/lib/context/geminiLoopGuard.js +141 -0
- package/dist/lib/core/redisConversationMemoryManager.d.ts +27 -0
- package/dist/lib/core/redisConversationMemoryManager.js +146 -25
- package/dist/lib/providers/googleAiStudio/client.d.ts +0 -31
- package/dist/lib/providers/googleAiStudio/client.js +118 -1
- package/dist/lib/providers/googleNativeGemini3/utils.d.ts +9 -0
- package/dist/lib/providers/googleNativeGemini3/utils.js +12 -0
- package/dist/lib/providers/googleVertex/client.d.ts +0 -45
- package/dist/lib/providers/googleVertex/client.js +201 -21
- package/dist/lib/types/context.d.ts +9 -0
- package/dist/lib/utils/redis.d.ts +60 -1
- package/dist/lib/utils/redis.js +143 -12
- package/dist/providers/googleAiStudio/client.d.ts +0 -31
- package/dist/providers/googleAiStudio/client.js +118 -1
- package/dist/providers/googleNativeGemini3/utils.d.ts +9 -0
- package/dist/providers/googleNativeGemini3/utils.js +12 -0
- package/dist/providers/googleVertex/client.d.ts +0 -45
- package/dist/providers/googleVertex/client.js +201 -21
- package/dist/types/context.d.ts +9 -0
- package/dist/utils/redis.d.ts +60 -1
- package/dist/utils/redis.js +143 -12
- package/package.json +3 -1
|
@@ -376,7 +376,16 @@ export const MODEL_CONTEXT_WINDOWS = {
|
|
|
376
376
|
* `lm-studio` -> `lmstudio`, `nvidia-nim` -> `nvidianim`, `llama.cpp` -> `llamacpp`.
|
|
377
377
|
*/
|
|
378
378
|
const PROVIDER_ALIAS_MAP = {
|
|
379
|
-
|
|
379
|
+
// Both spellings resolve to `google-ai`, the ONLY key this table holds for
|
|
380
|
+
// AI Studio. `google-ai-studio` was never a key, so every realistic spelling
|
|
381
|
+
// ("googleAiStudio" from the native client, "google-ai-studio", "googleai")
|
|
382
|
+
// missed the table and fell back to DEFAULT_CONTEXT_WINDOW — reporting
|
|
383
|
+
// 128K for a 1,048,576-token Gemini. That understated the loop-guard budget
|
|
384
|
+
// by ~8x, so AI Studio agent loops reclaimed tool history that still fitted
|
|
385
|
+
// comfortably. `google-ai` itself only resolved via the raw-provider
|
|
386
|
+
// fallback below, which the normalized lookup now covers directly.
|
|
387
|
+
googleaistudio: "google-ai",
|
|
388
|
+
googleai: "google-ai",
|
|
380
389
|
lmstudio: "lm-studio",
|
|
381
390
|
llamacpp: "llamacpp",
|
|
382
391
|
nvidianim: "nvidia-nim",
|
|
@@ -125,25 +125,43 @@ export function isAnthropicToolResultMessage(message) {
|
|
|
125
125
|
* `cache_control` prefix this path depends on.
|
|
126
126
|
*/
|
|
127
127
|
export function planAnthropicLoopReclaim(args) {
|
|
128
|
-
const { conversation, availableInputTokens, fixedOverheadTokens, provider, observedPromptTokens, previousSentEstimate, onSentEstimate, } = args;
|
|
128
|
+
const { conversation, availableInputTokens, fixedOverheadTokens, provider, observedPromptTokens, previousSentEstimate, onSentEstimate, observedDescribesCurrentPayload = false, } = args;
|
|
129
129
|
const entries = toEntries(conversation, provider);
|
|
130
130
|
const rawEstimate = fixedOverheadTokens + entries.reduce((sum, e) => sum + e.tokens, 0);
|
|
131
|
-
// Calibration
|
|
132
|
-
//
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
//
|
|
131
|
+
// Calibration divides a real prompt-token count by THIS guard's estimate for
|
|
132
|
+
// the payload that count describes. Both halves must describe the SAME
|
|
133
|
+
// payload, and there are two legitimate pairings:
|
|
134
|
+
//
|
|
135
|
+
// - A caller that plans on EVERY step passes the provider's count for the
|
|
136
|
+
// previous request together with `previousSentEstimate`, the estimate
|
|
137
|
+
// recorded for that same request. Dividing that count by the estimate for
|
|
138
|
+
// the CURRENT conversation would be a category error — the loop has since
|
|
139
|
+
// appended an assistant tool_use message plus its tool_result, so the
|
|
140
|
+
// denominator is always the larger of the two, the ratio reads below 1 and
|
|
141
|
+
// the `Math.max(1, …)` floor pins calibration at 1. The correction then
|
|
142
|
+
// silently never applies, which is exactly when a dense-code run overflows.
|
|
143
|
+
//
|
|
144
|
+
// - A caller that plans only when a real-token guard trips has no estimate
|
|
145
|
+
// for an earlier request, but its trigger (`projectedNextPromptTokens`) is
|
|
146
|
+
// already a projection of the payload ABOUT TO BE SENT. It sets
|
|
147
|
+
// `observedDescribesCurrentPayload`, and the denominator is this module's
|
|
148
|
+
// estimate of the current history — the same payload again.
|
|
149
|
+
//
|
|
150
|
+
// Without the flag such a caller gets calibration 1, which makes its reclaim
|
|
151
|
+
// inert: the guard trips on real tokens at the same ratio this planner tests
|
|
152
|
+
// its (smaller) char estimate against, so the plan never fires and the loop
|
|
153
|
+
// falls back to stopping the turn.
|
|
154
|
+
const sentEstimate = observedDescribesCurrentPayload
|
|
155
|
+
? rawEstimate
|
|
156
|
+
: previousSentEstimate;
|
|
139
157
|
let calibration = 1;
|
|
140
158
|
if (observedPromptTokens &&
|
|
141
159
|
observedPromptTokens > 0 &&
|
|
142
|
-
|
|
143
|
-
|
|
160
|
+
sentEstimate &&
|
|
161
|
+
sentEstimate > 0) {
|
|
144
162
|
// Clamped: real tokenizers run up to ~1.3x the char estimate on dense
|
|
145
163
|
// code, and an unbounded ratio would compact the loop into uselessness.
|
|
146
|
-
calibration = Math.min(3, Math.max(1, observedPromptTokens /
|
|
164
|
+
calibration = Math.min(3, Math.max(1, observedPromptTokens / sentEstimate));
|
|
147
165
|
}
|
|
148
166
|
const plan = planLoopGuardReclaim(entries, {
|
|
149
167
|
availableInputTokens,
|
|
@@ -200,6 +200,25 @@ export class ContextCompactor {
|
|
|
200
200
|
stagesUsed,
|
|
201
201
|
durationMs: Date.now() - spanStartTime,
|
|
202
202
|
});
|
|
203
|
+
// A compaction that was ASKED to reclaim and reclaimed nothing is the
|
|
204
|
+
// signature of a mis-aimed target: the caller decided the request was
|
|
205
|
+
// over budget, but every stage gate compared against a number that
|
|
206
|
+
// said otherwise, so the pipeline no-opped and the request went out
|
|
207
|
+
// oversized anyway. That is exactly how the history-budget defect hid
|
|
208
|
+
// in production — silently, because "Complete" looked healthy. Warn
|
|
209
|
+
// loudly and stamp the span so it is greppable and alertable.
|
|
210
|
+
const reclaimedNothing = stagesUsed.length === 0;
|
|
211
|
+
if (reclaimedNothing) {
|
|
212
|
+
logger.warn("[Compaction] No-op — invoked but reclaimed nothing", {
|
|
213
|
+
requestId,
|
|
214
|
+
tokensBefore,
|
|
215
|
+
targetTokens,
|
|
216
|
+
messageCount: currentMessages.length,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
span = SpanSerializer.updateAttributes(span, {
|
|
220
|
+
"context.noop": reclaimedNothing,
|
|
221
|
+
});
|
|
203
222
|
const result = {
|
|
204
223
|
compacted: stagesUsed.length > 0,
|
|
205
224
|
stagesUsed,
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-turn context guard for Gemini-shaped agent loops (native Vertex + AI
|
|
3
|
+
* Studio + Gemini 3).
|
|
4
|
+
*
|
|
5
|
+
* These loops already had `createContextGuard`, but it is **stop-only**: once
|
|
6
|
+
* the projected prompt crosses the threshold it breaks the loop and synthesizes
|
|
7
|
+
* an answer from whatever it has. That avoids a provider rejection, but it also
|
|
8
|
+
* ends the turn early — the model stops doing work it was mid-way through.
|
|
9
|
+
*
|
|
10
|
+
* This module brings them to parity with the other loops: reclaim budget and
|
|
11
|
+
* CONTINUE, falling back to the existing stop only when reclaiming cannot get
|
|
12
|
+
* back under the line. The reclaim policy is shared with every other provider
|
|
13
|
+
* via `loopGuardCore`; this module owns only the Gemini shape mapping.
|
|
14
|
+
*
|
|
15
|
+
* Gemini history is `{ role, parts[] }`, where a part is a `functionCall`
|
|
16
|
+
* (tool invocation) or `functionResponse` (its result). One model turn can
|
|
17
|
+
* carry several `functionCall` parts and the following user turn carries the
|
|
18
|
+
* matching `functionResponse` parts, so the CONTENT is the batch unit —
|
|
19
|
+
* dropping a call turn together with its response turn can never orphan a part,
|
|
20
|
+
* which Gemini rejects.
|
|
21
|
+
*/
|
|
22
|
+
import type { GeminiGuardContent, LoopGuardPlan } from "../types/index.js";
|
|
23
|
+
/** Marker left where dropped history used to be. */
|
|
24
|
+
export declare const GEMINI_ELISION_NOTE = "[Earlier tool exchanges were removed to fit the context window.]";
|
|
25
|
+
/** True when this content carries tool results worth previewing. */
|
|
26
|
+
export declare function isGeminiToolResponseContent(content: GeminiGuardContent): boolean;
|
|
27
|
+
/** Head/tail preview for an oversized tool response payload. */
|
|
28
|
+
export declare function previewGeminiToolResponseText(text: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Decide what to reclaim from a Gemini agent loop.
|
|
31
|
+
*
|
|
32
|
+
* Returns `undefined` when the history still fits, in which case the caller
|
|
33
|
+
* must leave it byte-identical — any rewrite invalidates the provider's cached
|
|
34
|
+
* prefix, so "no change" has to mean no change.
|
|
35
|
+
*
|
|
36
|
+
* `observedPromptTokens` must be a count for the payload ABOUT TO BE SENT —
|
|
37
|
+
* every Gemini-shaped loop plans only when its `createContextGuard` trips, and
|
|
38
|
+
* that guard's `projectedNextPromptTokens` is exactly that: the provider's real
|
|
39
|
+
* count for the last request plus the growth measured since. Dividing it by
|
|
40
|
+
* this module's estimate of the current history therefore compares two views of
|
|
41
|
+
* one payload, which is what makes the correction meaningful. A count for an
|
|
42
|
+
* EARLIER request must not be passed here: the loop has appended a model turn
|
|
43
|
+
* and its tool turn since, so the denominator would always be the larger of the
|
|
44
|
+
* two, the ratio would read below 1 and the `Math.max(1, …)` floor would pin
|
|
45
|
+
* calibration at 1 — silently disabling the correction. `planAnthropicLoopReclaim`
|
|
46
|
+
* carries `previousSentEstimate` for callers in that other position.
|
|
47
|
+
*/
|
|
48
|
+
export declare function planGeminiLoopReclaim(args: {
|
|
49
|
+
contents: readonly GeminiGuardContent[];
|
|
50
|
+
availableInputTokens: number;
|
|
51
|
+
fixedOverheadTokens?: number;
|
|
52
|
+
provider?: string;
|
|
53
|
+
observedPromptTokens?: number;
|
|
54
|
+
}): LoopGuardPlan | undefined;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-turn context guard for Gemini-shaped agent loops (native Vertex + AI
|
|
3
|
+
* Studio + Gemini 3).
|
|
4
|
+
*
|
|
5
|
+
* These loops already had `createContextGuard`, but it is **stop-only**: once
|
|
6
|
+
* the projected prompt crosses the threshold it breaks the loop and synthesizes
|
|
7
|
+
* an answer from whatever it has. That avoids a provider rejection, but it also
|
|
8
|
+
* ends the turn early — the model stops doing work it was mid-way through.
|
|
9
|
+
*
|
|
10
|
+
* This module brings them to parity with the other loops: reclaim budget and
|
|
11
|
+
* CONTINUE, falling back to the existing stop only when reclaiming cannot get
|
|
12
|
+
* back under the line. The reclaim policy is shared with every other provider
|
|
13
|
+
* via `loopGuardCore`; this module owns only the Gemini shape mapping.
|
|
14
|
+
*
|
|
15
|
+
* Gemini history is `{ role, parts[] }`, where a part is a `functionCall`
|
|
16
|
+
* (tool invocation) or `functionResponse` (its result). One model turn can
|
|
17
|
+
* carry several `functionCall` parts and the following user turn carries the
|
|
18
|
+
* matching `functionResponse` parts, so the CONTENT is the batch unit —
|
|
19
|
+
* dropping a call turn together with its response turn can never orphan a part,
|
|
20
|
+
* which Gemini rejects.
|
|
21
|
+
*/
|
|
22
|
+
import { estimateTokens, TOKENS_PER_MESSAGE, } from "../utils/tokenEstimation.js";
|
|
23
|
+
import { generateToolOutputPreview } from "./toolOutputLimits.js";
|
|
24
|
+
import { planLoopGuardReclaim } from "./loopGuardCore.js";
|
|
25
|
+
import { logger } from "../utils/logger.js";
|
|
26
|
+
/** Preview budget for an old tool output. Matches the other loop guards. */
|
|
27
|
+
const OLD_TOOL_OUTPUT_PREVIEW_BYTES = 2_048;
|
|
28
|
+
const OLD_TOOL_OUTPUT_PREVIEW_LINES = 60;
|
|
29
|
+
/** Marker left where dropped history used to be. */
|
|
30
|
+
export const GEMINI_ELISION_NOTE = "[Earlier tool exchanges were removed to fit the context window.]";
|
|
31
|
+
/** Serialize any value for estimation. Never throws. */
|
|
32
|
+
function toText(value) {
|
|
33
|
+
if (typeof value === "string") {
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
if (value === null || value === undefined) {
|
|
37
|
+
return "";
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
return JSON.stringify(value) ?? "";
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Past V8's string cap: enormous by definition, so charge a large fixed
|
|
44
|
+
// size rather than aborting the estimate and with it the turn.
|
|
45
|
+
return "x".repeat(200_000);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function hasPart(content, key) {
|
|
49
|
+
return (Array.isArray(content.parts) &&
|
|
50
|
+
content.parts.some((part) => part && typeof part === "object" && key in part));
|
|
51
|
+
}
|
|
52
|
+
/** True when this content carries tool results worth previewing. */
|
|
53
|
+
export function isGeminiToolResponseContent(content) {
|
|
54
|
+
return hasPart(content, "functionResponse");
|
|
55
|
+
}
|
|
56
|
+
/** Head/tail preview for an oversized tool response payload. */
|
|
57
|
+
export function previewGeminiToolResponseText(text) {
|
|
58
|
+
const { preview } = generateToolOutputPreview(text, {
|
|
59
|
+
maxBytes: OLD_TOOL_OUTPUT_PREVIEW_BYTES,
|
|
60
|
+
maxLines: OLD_TOOL_OUTPUT_PREVIEW_LINES,
|
|
61
|
+
});
|
|
62
|
+
return preview;
|
|
63
|
+
}
|
|
64
|
+
function contentTokens(content, provider) {
|
|
65
|
+
return estimateTokens(toText(content.parts), provider) + TOKENS_PER_MESSAGE;
|
|
66
|
+
}
|
|
67
|
+
/** Map Gemini history onto the neutral view the shared policy operates on. */
|
|
68
|
+
function toEntries(contents, provider) {
|
|
69
|
+
return contents.map((content) => {
|
|
70
|
+
const tokens = contentTokens(content, provider);
|
|
71
|
+
if (isGeminiToolResponseContent(content)) {
|
|
72
|
+
// Only advertise a preview when it actually saves something: an
|
|
73
|
+
// already-small response must fall through to stage 2 rather than look
|
|
74
|
+
// shrinkable and stall the reclaim.
|
|
75
|
+
const previewed = toText(content.parts);
|
|
76
|
+
const previewTokens = previewed.length > OLD_TOOL_OUTPUT_PREVIEW_BYTES
|
|
77
|
+
? estimateTokens(previewGeminiToolResponseText(previewed), provider) +
|
|
78
|
+
TOKENS_PER_MESSAGE
|
|
79
|
+
: tokens;
|
|
80
|
+
return {
|
|
81
|
+
kind: "toolResult",
|
|
82
|
+
tokens,
|
|
83
|
+
...(previewTokens < tokens ? { previewTokens } : {}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (hasPart(content, "functionCall")) {
|
|
87
|
+
return { kind: "toolCall", tokens };
|
|
88
|
+
}
|
|
89
|
+
return { kind: "other", tokens };
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Decide what to reclaim from a Gemini agent loop.
|
|
94
|
+
*
|
|
95
|
+
* Returns `undefined` when the history still fits, in which case the caller
|
|
96
|
+
* must leave it byte-identical — any rewrite invalidates the provider's cached
|
|
97
|
+
* prefix, so "no change" has to mean no change.
|
|
98
|
+
*
|
|
99
|
+
* `observedPromptTokens` must be a count for the payload ABOUT TO BE SENT —
|
|
100
|
+
* every Gemini-shaped loop plans only when its `createContextGuard` trips, and
|
|
101
|
+
* that guard's `projectedNextPromptTokens` is exactly that: the provider's real
|
|
102
|
+
* count for the last request plus the growth measured since. Dividing it by
|
|
103
|
+
* this module's estimate of the current history therefore compares two views of
|
|
104
|
+
* one payload, which is what makes the correction meaningful. A count for an
|
|
105
|
+
* EARLIER request must not be passed here: the loop has appended a model turn
|
|
106
|
+
* and its tool turn since, so the denominator would always be the larger of the
|
|
107
|
+
* two, the ratio would read below 1 and the `Math.max(1, …)` floor would pin
|
|
108
|
+
* calibration at 1 — silently disabling the correction. `planAnthropicLoopReclaim`
|
|
109
|
+
* carries `previousSentEstimate` for callers in that other position.
|
|
110
|
+
*/
|
|
111
|
+
export function planGeminiLoopReclaim(args) {
|
|
112
|
+
const { contents, availableInputTokens, fixedOverheadTokens = 0, provider, observedPromptTokens, } = args;
|
|
113
|
+
const entries = toEntries(contents, provider);
|
|
114
|
+
let calibration = 1;
|
|
115
|
+
if (observedPromptTokens && observedPromptTokens > 0) {
|
|
116
|
+
const rawEstimate = fixedOverheadTokens + entries.reduce((sum, e) => sum + e.tokens, 0);
|
|
117
|
+
if (rawEstimate > 0) {
|
|
118
|
+
// Clamped: real tokenizers run up to ~1.3x the char estimate on dense
|
|
119
|
+
// code, and an unbounded ratio would compact the loop into uselessness.
|
|
120
|
+
calibration = Math.min(3, Math.max(1, observedPromptTokens / rawEstimate));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const plan = planLoopGuardReclaim(entries, {
|
|
124
|
+
availableInputTokens,
|
|
125
|
+
fixedOverheadTokens,
|
|
126
|
+
calibration,
|
|
127
|
+
});
|
|
128
|
+
if (!plan.fire) {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
logger.info("[GeminiLoopGuard] Reclaiming agent-loop context", {
|
|
132
|
+
provider,
|
|
133
|
+
contents: contents.length,
|
|
134
|
+
toolResponsesTruncated: plan.truncate.length,
|
|
135
|
+
contentsDropped: plan.drop.length,
|
|
136
|
+
projectedTokens: plan.projectedTokens,
|
|
137
|
+
calibration,
|
|
138
|
+
});
|
|
139
|
+
return plan;
|
|
140
|
+
}
|
|
@@ -93,6 +93,33 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
|
|
|
93
93
|
* Check if summarization is needed based on token count
|
|
94
94
|
*/
|
|
95
95
|
private checkAndSummarize;
|
|
96
|
+
/**
|
|
97
|
+
* True only for keys holding a conversation BLOB — the sole key type these
|
|
98
|
+
* scan-then-GET paths may read.
|
|
99
|
+
*
|
|
100
|
+
* `${keyPrefix}*` also matches the companion message LISTs and, when a
|
|
101
|
+
* custom key prefix does not end in `conversation:`, the user-index SETs
|
|
102
|
+
* (whose derived prefix then collapses onto `keyPrefix`). `GET` against
|
|
103
|
+
* either raises WRONGTYPE, and counting them would inflate session totals.
|
|
104
|
+
*/
|
|
105
|
+
private isConversationBlobKey;
|
|
106
|
+
/**
|
|
107
|
+
* Hydrate a deserialized blob's messages from the companion LIST when the
|
|
108
|
+
* session uses split storage. Legacy blobs (messages inline) pass through
|
|
109
|
+
* untouched — that is what makes the migration backward compatible.
|
|
110
|
+
*/
|
|
111
|
+
private hydrateMessages;
|
|
112
|
+
/** Message count without materializing them — LLEN for split sessions. */
|
|
113
|
+
private countMessages;
|
|
114
|
+
/** Load a session, messages included, regardless of storage format. */
|
|
115
|
+
private loadConversation;
|
|
116
|
+
/**
|
|
117
|
+
* Persist a conversation, splitting messages into the companion LIST.
|
|
118
|
+
* `appendFrom` appends only messages from that index onward (the per-turn
|
|
119
|
+
* fast path); omit it to rewrite the LIST wholesale, which is also how a
|
|
120
|
+
* legacy blob gets converted.
|
|
121
|
+
*/
|
|
122
|
+
private persistConversation;
|
|
96
123
|
/**
|
|
97
124
|
* Build context messages for AI prompt injection (TOKEN-BASED)
|
|
98
125
|
* Returns messages from pointer onwards (or all if no pointer)
|
|
@@ -15,7 +15,7 @@ import { withTimeout } from "../utils/errorHandling.js";
|
|
|
15
15
|
import { buildContextFromPointer, getEffectiveTokenThreshold, } from "../utils/conversationMemory.js";
|
|
16
16
|
import { runWithCurrentLangfuseContext } from "../services/server/ai/observability/instrumentation.js";
|
|
17
17
|
import { logger } from "../utils/logger.js";
|
|
18
|
-
import { deserializeConversation, getNormalizedConfig, getPooledRedisClient, getSessionKey, getUserSessionsKey, releasePooledRedisClient, scanKeys, serializeConversation, } from "../utils/redis.js";
|
|
18
|
+
import { deserializeConversation, encodeStoredMessages, getSessionMessagesKey, MESSAGES_KEY_SUFFIX, isSessionMessagesKey, parseStoredMessages, serializeConversationMetadata, usesSplitMessageStorage, getNormalizedConfig, getPooledRedisClient, getSessionKey, getUserSessionsKey, releasePooledRedisClient, scanKeys, serializeConversation, } from "../utils/redis.js";
|
|
19
19
|
const redisTracer = tracers.redis;
|
|
20
20
|
const REDIS_TIMEOUT_MS = 5000;
|
|
21
21
|
/**
|
|
@@ -140,7 +140,7 @@ export class RedisConversationMemoryManager {
|
|
|
140
140
|
try {
|
|
141
141
|
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
142
142
|
const conversationData = await withTimeout(redisClient.get(redisKey), REDIS_TIMEOUT_MS);
|
|
143
|
-
const conversation = deserializeConversation(conversationData || null);
|
|
143
|
+
const conversation = await this.hydrateMessages(deserializeConversation(conversationData || null), redisKey);
|
|
144
144
|
if (!conversation) {
|
|
145
145
|
span.setAttribute("session.found", false);
|
|
146
146
|
return undefined;
|
|
@@ -221,7 +221,7 @@ export class RedisConversationMemoryManager {
|
|
|
221
221
|
}
|
|
222
222
|
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
223
223
|
const conversationData = await this.redisClient.get(redisKey);
|
|
224
|
-
return deserializeConversation(conversationData || null);
|
|
224
|
+
return this.hydrateMessages(deserializeConversation(conversationData || null), redisKey);
|
|
225
225
|
}
|
|
226
226
|
catch (error) {
|
|
227
227
|
logger.error("[RedisConversationMemoryManager] Failed to get raw session", {
|
|
@@ -391,7 +391,13 @@ export class RedisConversationMemoryManager {
|
|
|
391
391
|
}
|
|
392
392
|
const redisKey = getSessionKey(this.redisConfig, options.sessionId, options.userId);
|
|
393
393
|
const conversationData = await this.redisClient.get(redisKey);
|
|
394
|
-
let conversation = deserializeConversation(conversationData);
|
|
394
|
+
let conversation = await this.hydrateMessages(deserializeConversation(conversationData), redisKey);
|
|
395
|
+
// Split-storage bookkeeping: whether this session already keeps its
|
|
396
|
+
// messages in the companion LIST, and how many it held before this
|
|
397
|
+
// turn — so only the new ones are appended rather than rewriting the
|
|
398
|
+
// whole conversation on every turn.
|
|
399
|
+
const wasSplitStorage = usesSplitMessageStorage(conversation);
|
|
400
|
+
const messageCountBeforeTurn = conversation?.messages.length ?? 0;
|
|
395
401
|
const currentTime = new Date().toISOString();
|
|
396
402
|
const normalizedUserId = options.userId || "randomUser";
|
|
397
403
|
if (!conversation) {
|
|
@@ -486,6 +492,16 @@ export class RedisConversationMemoryManager {
|
|
|
486
492
|
const shouldSummarize = options.enableSummarization !== undefined
|
|
487
493
|
? options.enableSummarization
|
|
488
494
|
: this.config.enableSummarization;
|
|
495
|
+
// Append-only: push just this turn's messages and persist a SMALL
|
|
496
|
+
// metadata blob. A session not yet using split storage (new, or a
|
|
497
|
+
// legacy blob) is converted once here, then every later turn appends.
|
|
498
|
+
await this.persistConversation(conversation, options.sessionId, options.userId, wasSplitStorage ? messageCountBeforeTurn : undefined);
|
|
499
|
+
// Scheduled AFTER the write, never before it. On the single turn that
|
|
500
|
+
// converts a legacy session, `checkAndSummarize` re-reads the blob and
|
|
501
|
+
// writes it back; observing the pre-conversion blob would make it
|
|
502
|
+
// re-serialize the record WITHOUT the split marker, so a later SET
|
|
503
|
+
// would strip the marker while the companion LIST already held the
|
|
504
|
+
// messages — the next read would then serve the stale inline copy.
|
|
489
505
|
if (shouldSummarize) {
|
|
490
506
|
const normalizedUserId = options.userId || "randomUser";
|
|
491
507
|
const summarizationKey = `${options.sessionId}:${normalizedUserId}`;
|
|
@@ -514,10 +530,8 @@ export class RedisConversationMemoryManager {
|
|
|
514
530
|
});
|
|
515
531
|
}
|
|
516
532
|
}
|
|
517
|
-
const serializedData = serializeConversation(conversation);
|
|
518
|
-
await this.redisClient.set(redisKey, serializedData);
|
|
519
533
|
// Log turn storage metadata for observability
|
|
520
|
-
const blobSizeBytes = Buffer.byteLength(
|
|
534
|
+
const blobSizeBytes = Buffer.byteLength(serializeConversationMetadata(conversation), "utf8");
|
|
521
535
|
logger.info("[ConversationMemory] Turn stored", {
|
|
522
536
|
requestId: options.requestId,
|
|
523
537
|
sessionId: options.sessionId,
|
|
@@ -611,7 +625,14 @@ export class RedisConversationMemoryManager {
|
|
|
611
625
|
conversation.summarizedMessage;
|
|
612
626
|
latestConversation.lastTokenCount = conversation.lastTokenCount;
|
|
613
627
|
latestConversation.lastCountedAt = conversation.lastCountedAt;
|
|
614
|
-
|
|
628
|
+
// Only summarization metadata changed, so the companion LIST is
|
|
629
|
+
// left alone. Critical: this re-read was NOT hydrated, so for a
|
|
630
|
+
// split session `messages` is empty — writing it with
|
|
631
|
+
// serializeConversation would drop the marker and make the record
|
|
632
|
+
// look like a legacy blob with zero messages (silent data loss).
|
|
633
|
+
const freshSerialized = usesSplitMessageStorage(latestConversation)
|
|
634
|
+
? serializeConversationMetadata(latestConversation)
|
|
635
|
+
: serializeConversation(latestConversation);
|
|
615
636
|
await this.redisClient.set(redisKey, freshSerialized);
|
|
616
637
|
if (this.redisConfig.ttl > 0) {
|
|
617
638
|
await this.redisClient.expire(redisKey, this.redisConfig.ttl);
|
|
@@ -631,6 +652,95 @@ export class RedisConversationMemoryManager {
|
|
|
631
652
|
this.summarizationInProgress.delete(summarizationKey);
|
|
632
653
|
}
|
|
633
654
|
}
|
|
655
|
+
/**
|
|
656
|
+
* True only for keys holding a conversation BLOB — the sole key type these
|
|
657
|
+
* scan-then-GET paths may read.
|
|
658
|
+
*
|
|
659
|
+
* `${keyPrefix}*` also matches the companion message LISTs and, when a
|
|
660
|
+
* custom key prefix does not end in `conversation:`, the user-index SETs
|
|
661
|
+
* (whose derived prefix then collapses onto `keyPrefix`). `GET` against
|
|
662
|
+
* either raises WRONGTYPE, and counting them would inflate session totals.
|
|
663
|
+
*/
|
|
664
|
+
isConversationBlobKey(key) {
|
|
665
|
+
return (!isSessionMessagesKey(key) &&
|
|
666
|
+
!key.endsWith(":sessions") &&
|
|
667
|
+
!key.startsWith(this.redisConfig.userSessionsKeyPrefix));
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Hydrate a deserialized blob's messages from the companion LIST when the
|
|
671
|
+
* session uses split storage. Legacy blobs (messages inline) pass through
|
|
672
|
+
* untouched — that is what makes the migration backward compatible.
|
|
673
|
+
*/
|
|
674
|
+
async hydrateMessages(conversation, redisKey) {
|
|
675
|
+
if (!conversation || !usesSplitMessageStorage(conversation)) {
|
|
676
|
+
return conversation;
|
|
677
|
+
}
|
|
678
|
+
if (!this.redisClient) {
|
|
679
|
+
return conversation;
|
|
680
|
+
}
|
|
681
|
+
// `getSession` and `buildContextMessages` guard their own GET with
|
|
682
|
+
// `withTimeout`; both now also depend on this read, so leaving it unguarded
|
|
683
|
+
// would let a hung LIST read block the request thread anyway.
|
|
684
|
+
const entries = await withTimeout(this.redisClient.lRange(`${redisKey}${MESSAGES_KEY_SUFFIX}`, 0, -1), REDIS_TIMEOUT_MS);
|
|
685
|
+
// `lRange` is typed `(string | Buffer)[]` — the client returns Buffers when
|
|
686
|
+
// a connection is opened in binary mode. Normalize rather than assert, so
|
|
687
|
+
// a binary-mode client reads its history instead of throwing on parse.
|
|
688
|
+
conversation.messages = parseStoredMessages(entries.map((entry) => entry.toString()));
|
|
689
|
+
return conversation;
|
|
690
|
+
}
|
|
691
|
+
/** Message count without materializing them — LLEN for split sessions. */
|
|
692
|
+
async countMessages(conversation, redisKey) {
|
|
693
|
+
if (!usesSplitMessageStorage(conversation) || !this.redisClient) {
|
|
694
|
+
return conversation.messages.length;
|
|
695
|
+
}
|
|
696
|
+
// `lLen` is typed `number | \`${number}\`` (RESP3 can deliver it as a
|
|
697
|
+
// string), and callers add it to numbers — coerce so the count never
|
|
698
|
+
// concatenates instead of summing.
|
|
699
|
+
return Number(await withTimeout(this.redisClient.lLen(`${redisKey}${MESSAGES_KEY_SUFFIX}`), REDIS_TIMEOUT_MS));
|
|
700
|
+
}
|
|
701
|
+
/** Load a session, messages included, regardless of storage format. */
|
|
702
|
+
async loadConversation(sessionId, userId) {
|
|
703
|
+
if (!this.redisClient) {
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
707
|
+
return this.hydrateMessages(deserializeConversation(await this.redisClient.get(redisKey)), redisKey);
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Persist a conversation, splitting messages into the companion LIST.
|
|
711
|
+
* `appendFrom` appends only messages from that index onward (the per-turn
|
|
712
|
+
* fast path); omit it to rewrite the LIST wholesale, which is also how a
|
|
713
|
+
* legacy blob gets converted.
|
|
714
|
+
*/
|
|
715
|
+
async persistConversation(conversation, sessionId, userId, appendFrom) {
|
|
716
|
+
if (!this.redisClient) {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
720
|
+
const messagesKey = getSessionMessagesKey(this.redisConfig, sessionId, userId);
|
|
721
|
+
// One MULTI, not four to six independent commands. The replace path is a
|
|
722
|
+
// DEL followed by an RPUSH, and on the legacy-conversion path the inline
|
|
723
|
+
// blob is the only copy of the history until the SET lands — so a failure
|
|
724
|
+
// between any two of them leaves the session either empty or unrecoverable.
|
|
725
|
+
// Grouping them also collapses the round trips, which is the point of the
|
|
726
|
+
// append-only layout.
|
|
727
|
+
const tx = this.redisClient.multi();
|
|
728
|
+
if (appendFrom === undefined) {
|
|
729
|
+
tx.del(messagesKey);
|
|
730
|
+
}
|
|
731
|
+
const toPush = appendFrom === undefined
|
|
732
|
+
? conversation.messages
|
|
733
|
+
: conversation.messages.slice(appendFrom);
|
|
734
|
+
if (toPush.length > 0) {
|
|
735
|
+
tx.rPush(messagesKey, encodeStoredMessages(toPush));
|
|
736
|
+
}
|
|
737
|
+
tx.set(redisKey, serializeConversationMetadata(conversation));
|
|
738
|
+
if (this.redisConfig.ttl > 0) {
|
|
739
|
+
tx.expire(redisKey, this.redisConfig.ttl);
|
|
740
|
+
tx.expire(messagesKey, this.redisConfig.ttl);
|
|
741
|
+
}
|
|
742
|
+
await withTimeout(tx.exec(), REDIS_TIMEOUT_MS);
|
|
743
|
+
}
|
|
634
744
|
/**
|
|
635
745
|
* Build context messages for AI prompt injection (TOKEN-BASED)
|
|
636
746
|
* Returns messages from pointer onwards (or all if no pointer)
|
|
@@ -664,7 +774,7 @@ export class RedisConversationMemoryManager {
|
|
|
664
774
|
});
|
|
665
775
|
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
666
776
|
const conversationData = await withTimeout(redisClient.get(redisKey), REDIS_TIMEOUT_MS);
|
|
667
|
-
const conversation = deserializeConversation(conversationData || null);
|
|
777
|
+
const conversation = await this.hydrateMessages(deserializeConversation(conversationData || null), redisKey);
|
|
668
778
|
logger.debug("[RedisConversationMemoryManager] Retrieved conversation for context building", {
|
|
669
779
|
sessionId,
|
|
670
780
|
userId,
|
|
@@ -895,7 +1005,7 @@ export class RedisConversationMemoryManager {
|
|
|
895
1005
|
return null;
|
|
896
1006
|
}
|
|
897
1007
|
// Deserialize the complete conversation object
|
|
898
|
-
const conversation = deserializeConversation(conversationData);
|
|
1008
|
+
const conversation = await this.hydrateMessages(deserializeConversation(conversationData), sessionKey);
|
|
899
1009
|
if (!conversation) {
|
|
900
1010
|
logger.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data", {
|
|
901
1011
|
userId,
|
|
@@ -1014,7 +1124,7 @@ User message: "${userMessage}"`;
|
|
|
1014
1124
|
try {
|
|
1015
1125
|
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
1016
1126
|
const conversationData = await this.redisClient.get(redisKey);
|
|
1017
|
-
const conversation = deserializeConversation(conversationData || null);
|
|
1127
|
+
const conversation = await this.hydrateMessages(deserializeConversation(conversationData || null), redisKey);
|
|
1018
1128
|
return conversation?.messages ?? [];
|
|
1019
1129
|
}
|
|
1020
1130
|
catch (error) {
|
|
@@ -1050,11 +1160,8 @@ User message: "${userMessage}"`;
|
|
|
1050
1160
|
conversation.summarizedMessage = undefined;
|
|
1051
1161
|
conversation.lastTokenCount = undefined;
|
|
1052
1162
|
conversation.lastCountedAt = undefined;
|
|
1053
|
-
|
|
1054
|
-
await this.
|
|
1055
|
-
if (this.redisConfig.ttl > 0) {
|
|
1056
|
-
await this.redisClient.expire(redisKey, this.redisConfig.ttl);
|
|
1057
|
-
}
|
|
1163
|
+
// Wholesale replacement: rewrite the LIST rather than appending.
|
|
1164
|
+
await this.persistConversation(conversation, sessionId, userId);
|
|
1058
1165
|
logger.debug("[RedisConversationMemoryManager] Session messages replaced", {
|
|
1059
1166
|
sessionId,
|
|
1060
1167
|
userId,
|
|
@@ -1097,11 +1204,16 @@ User message: "${userMessage}"`;
|
|
|
1097
1204
|
pattern,
|
|
1098
1205
|
keyCount: keys.length,
|
|
1099
1206
|
});
|
|
1207
|
+
// Companion message LISTs share the session key prefix, so the SCAN above
|
|
1208
|
+
// returns them too. GET on a LIST raises WRONGTYPE, and counting them as
|
|
1209
|
+
// sessions would double `totalSessions` — filter them out exactly as the
|
|
1210
|
+
// session listing already skips `:sessions` index keys.
|
|
1211
|
+
const sessionKeys = keys.filter((key) => this.isConversationBlobKey(key));
|
|
1100
1212
|
// Count messages in each session
|
|
1101
1213
|
let totalTurns = 0;
|
|
1102
|
-
for (const key of
|
|
1214
|
+
for (const key of sessionKeys) {
|
|
1103
1215
|
const conversationData = await this.redisClient.get(key);
|
|
1104
|
-
const conversation = deserializeConversation(conversationData);
|
|
1216
|
+
const conversation = await this.hydrateMessages(deserializeConversation(conversationData), key);
|
|
1105
1217
|
if (conversation?.messages) {
|
|
1106
1218
|
// Pinned skill messages are extra rows inside a turn — exclude them
|
|
1107
1219
|
// so a skill-activating turn still counts as one turn.
|
|
@@ -1110,7 +1222,7 @@ User message: "${userMessage}"`;
|
|
|
1110
1222
|
}
|
|
1111
1223
|
}
|
|
1112
1224
|
return {
|
|
1113
|
-
totalSessions:
|
|
1225
|
+
totalSessions: sessionKeys.length,
|
|
1114
1226
|
totalTurns,
|
|
1115
1227
|
};
|
|
1116
1228
|
}
|
|
@@ -1133,7 +1245,9 @@ User message: "${userMessage}"`;
|
|
|
1133
1245
|
}, async (span) => {
|
|
1134
1246
|
try {
|
|
1135
1247
|
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
1136
|
-
|
|
1248
|
+
// Delete the companion message LIST as well: leaving it behind would
|
|
1249
|
+
// leak the messages and let a re-created session inherit them.
|
|
1250
|
+
const result = await withTimeout(redisClient.del([redisKey, `${redisKey}${MESSAGES_KEY_SUFFIX}`]), REDIS_TIMEOUT_MS);
|
|
1137
1251
|
if (Number(result) > 0) {
|
|
1138
1252
|
// Remove session from user's session set
|
|
1139
1253
|
if (userId) {
|
|
@@ -1307,8 +1421,9 @@ User message: "${userMessage}"`;
|
|
|
1307
1421
|
// List all sessions across all users by scanning Redis keys
|
|
1308
1422
|
const keys = await scanKeys(this.redisClient, `${this.redisConfig.keyPrefix}*`);
|
|
1309
1423
|
for (const key of keys) {
|
|
1310
|
-
// Skip user session index keys (they end with :sessions)
|
|
1311
|
-
|
|
1424
|
+
// Skip user session index keys (they end with :sessions) and the
|
|
1425
|
+
// companion message LISTs — GET on a LIST raises WRONGTYPE.
|
|
1426
|
+
if (!this.isConversationBlobKey(key)) {
|
|
1312
1427
|
continue;
|
|
1313
1428
|
}
|
|
1314
1429
|
const raw = await this.redisClient.get(key);
|
|
@@ -1325,7 +1440,9 @@ User message: "${userMessage}"`;
|
|
|
1325
1440
|
createdAt: session.createdAt,
|
|
1326
1441
|
updatedAt: session.updatedAt,
|
|
1327
1442
|
userId: session.userId,
|
|
1328
|
-
|
|
1443
|
+
// LLEN for split sessions: the blob's inline array is empty here
|
|
1444
|
+
// because this branch reads the raw key without hydrating.
|
|
1445
|
+
messageCount: await this.countMessages(session, key),
|
|
1329
1446
|
lastActive: this.formatTimeAgo(now - new Date(session.updatedAt).getTime()),
|
|
1330
1447
|
});
|
|
1331
1448
|
}
|
|
@@ -1571,8 +1688,12 @@ User message: "${userMessage}"`;
|
|
|
1571
1688
|
logger.debug("[RedisConversationMemoryManager] Added new agentic loop report", { sessionId, reportId: report.reportId });
|
|
1572
1689
|
}
|
|
1573
1690
|
conversation.updatedAt = new Date().toISOString();
|
|
1574
|
-
// Write back to Redis
|
|
1575
|
-
|
|
1691
|
+
// Write back to Redis. Metadata-only change, so the companion LIST is
|
|
1692
|
+
// untouched — but the split marker must survive (see the summarization
|
|
1693
|
+
// writeback above for why dropping it loses messages).
|
|
1694
|
+
const serializedData = usesSplitMessageStorage(conversation)
|
|
1695
|
+
? serializeConversationMetadata(conversation)
|
|
1696
|
+
: serializeConversation(conversation);
|
|
1576
1697
|
await withTimeout(this.redisClient.set(redisKey, serializedData), 5000);
|
|
1577
1698
|
if (this.redisConfig.ttl > 0) {
|
|
1578
1699
|
await withTimeout(this.redisClient.expire(redisKey, this.redisConfig.ttl), 5000);
|