@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.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Conversation erasure write fence (`conversation-erasure-v1`).
3
+ *
4
+ * A writer that opts in is admitted once, at initialization, against a
5
+ * standalone Redis running `maxmemory-policy noeviction`. Each later write is
6
+ * one atomic script that refuses unless the server run id, the store epoch and
7
+ * the eviction counter still match what the writer was admitted under, and
8
+ * refuses a session whose erasure tombstone exists. A permanent erasure sets
9
+ * the tombstone, deletes the session's keys and index entry in the same script.
10
+ *
11
+ * Only participating writers are fenced. A writer that did not opt in keeps the
12
+ * ordinary storage behaviour (`legacy` mode) and cannot erase permanently.
13
+ */
14
+ import type { ConversationErasureProtocol, ConversationErasureResult, ConversationErasureWriteContext, ConversationErasureWriterStatus, RedisClient, RedisStorageConfig } from "../types/index.js";
15
+ export { ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
16
+ export declare const ERASURE_FENCE_PROTOCOL: ConversationErasureProtocol;
17
+ /** Key of the per-session erasure tombstone. */
18
+ export declare const erasureFenceKey: (sessionKey: string) => string;
19
+ /**
20
+ * Resolve the write context once, before the manager admits asynchronous work
21
+ * (not at the later commit of a write).
22
+ *
23
+ * Without `strict` the writer does not participate and stays `legacy`. With
24
+ * `strict`, anything short of a standalone, non-evicting Redis whose epoch
25
+ * could be read and pinned throws {@link ConversationWriterEpochError}.
26
+ */
27
+ export declare const prepareConversationWriteContext: (client: RedisClient, config: Required<RedisStorageConfig>, strict?: boolean) => Promise<ConversationErasureWriteContext>;
28
+ /** Write the session metadata blob (SET plus TTL). */
29
+ export declare const fencedSessionMetadataWrite: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string | undefined, payload: string, context: ConversationErasureWriteContext | undefined) => Promise<void>;
30
+ /** Add the session to the user's session index (SADD plus TTL). */
31
+ export declare const fencedSessionIndexWrite: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string, context: ConversationErasureWriteContext | undefined) => Promise<void>;
32
+ /**
33
+ * Write the message LIST and the metadata blob together. Resolves to 1 once
34
+ * the write landed; a refused write throws instead.
35
+ */
36
+ export declare const fencedSessionPersist: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string | undefined, write: {
37
+ mode: "replace" | "append";
38
+ messages: string[];
39
+ payload: string;
40
+ }, context: ConversationErasureWriteContext | undefined) => Promise<number>;
41
+ /**
42
+ * Permanently erase one session: tombstone, data keys and index entry in one
43
+ * atomic step. Requires a strict, fenced writer and an explicit session and
44
+ * user id.
45
+ */
46
+ export declare const eraseSessionPermanently: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string, context: ConversationErasureWriteContext | undefined) => Promise<ConversationErasureResult>;
47
+ /** Whether the writer that resolved `context` participates in the v1 fence. */
48
+ export declare const conversationErasureWriterStatus: (context: ConversationErasureWriteContext | undefined) => ConversationErasureWriterStatus;
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Conversation erasure write fence (`conversation-erasure-v1`).
3
+ *
4
+ * A writer that opts in is admitted once, at initialization, against a
5
+ * standalone Redis running `maxmemory-policy noeviction`. Each later write is
6
+ * one atomic script that refuses unless the server run id, the store epoch and
7
+ * the eviction counter still match what the writer was admitted under, and
8
+ * refuses a session whose erasure tombstone exists. A permanent erasure sets
9
+ * the tombstone, deletes the session's keys and index entry in the same script.
10
+ *
11
+ * Only participating writers are fenced. A writer that did not opt in keeps the
12
+ * ordinary storage behaviour (`legacy` mode) and cannot erase permanently.
13
+ */
14
+ import { createHash, randomUUID } from "node:crypto";
15
+ import { ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
16
+ import { addToSetWithTtl, getSessionKey, getSessionMessagesKey, getUserSessionsKey, setWithTtl, } from "../utils/redis.js";
17
+ export { ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
18
+ export const ERASURE_FENCE_PROTOCOL = "conversation-erasure-v1";
19
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
20
+ /** Key of the per-session erasure tombstone. */
21
+ export const erasureFenceKey = (sessionKey) => `neurolink-erasure-v1:${digest(sessionKey)}`;
22
+ const epochKey = (config) => `neurolink-erasure-epoch-v1:${digest(JSON.stringify([config.keyPrefix, config.userSessionsKeyPrefix]))}`;
23
+ const infoField = (info, name) => new RegExp(`(?:^|[\\r\\n])${name}:([^\\r\\n]+)`).exec(info)?.[1];
24
+ // Binds the epoch record to the current server run: a restarted server (whose
25
+ // data may have been lost) gets a fresh epoch, and an eviction-capable policy
26
+ // is refused outright.
27
+ const PREPARE_SCRIPT = String.raw `
28
+ local server=redis.call('INFO','server')
29
+ local current=string.match(server,'run_id:([^\r\n]+)')
30
+ if current~=ARGV[1] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
31
+ local memory=redis.call('INFO','memory')
32
+ if string.match(memory,'maxmemory_policy:([^\r\n]+)')~='noeviction' then return redis.error_reply('SESSION_WRITER_POLICY_UNSUPPORTED') end
33
+ local stored=redis.call('GET',KEYS[1])
34
+ if not stored or string.sub(stored,1,string.len(ARGV[1])+1)~=ARGV[1]..':' then
35
+ stored=ARGV[1]..':'..ARGV[2];redis.call('SET',KEYS[1],stored)
36
+ end
37
+ local stats=redis.call('INFO','stats')
38
+ local evicted=string.match(stats,'evicted_keys:(%d+)')
39
+ if not evicted then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
40
+ return {stored,evicted}`;
41
+ /**
42
+ * Resolve the write context once, before the manager admits asynchronous work
43
+ * (not at the later commit of a write).
44
+ *
45
+ * Without `strict` the writer does not participate and stays `legacy`. With
46
+ * `strict`, anything short of a standalone, non-evicting Redis whose epoch
47
+ * could be read and pinned throws {@link ConversationWriterEpochError}.
48
+ */
49
+ export const prepareConversationWriteContext = async (client, config, strict = false) => {
50
+ if (!strict) {
51
+ return Object.freeze({
52
+ mode: "legacy",
53
+ reason: "compatible-client",
54
+ strict: false,
55
+ });
56
+ }
57
+ try {
58
+ const cluster = await client.info("cluster");
59
+ if (infoField(cluster, "cluster_enabled") !== "0") {
60
+ throw new ConversationWriterEpochError();
61
+ }
62
+ const memory = await client.info("memory");
63
+ if (infoField(memory, "maxmemory_policy") !== "noeviction") {
64
+ throw new ConversationWriterEpochError();
65
+ }
66
+ const server = await client.info("server");
67
+ const runId = infoField(server, "run_id");
68
+ if (!runId) {
69
+ throw new ConversationWriterEpochError();
70
+ }
71
+ const result = await client.eval(PREPARE_SCRIPT, {
72
+ keys: [epochKey(config)],
73
+ arguments: [runId, randomUUID()],
74
+ });
75
+ if (!Array.isArray(result) ||
76
+ typeof result[0] !== "string" ||
77
+ !/^\d+$/.test(String(result[1]))) {
78
+ throw new ConversationWriterEpochError();
79
+ }
80
+ return Object.freeze({
81
+ mode: "fenced",
82
+ strict,
83
+ runId,
84
+ epoch: result[0],
85
+ evictedKeys: String(result[1]),
86
+ evictionPolicy: "noeviction",
87
+ });
88
+ }
89
+ catch {
90
+ throw new ConversationWriterEpochError();
91
+ }
92
+ };
93
+ // KEYS: 1 session blob, 2 messages LIST, 3 user index SET, 4 tombstone, 5 epoch
94
+ // ARGV: 1 mode, 2 session id, 3 ttl, 4 payload / append mode, 5 messages JSON,
95
+ // 6 metadata payload, 7 spare, 8 run id, 9 epoch, 10 eviction counter
96
+ const FENCED_SCRIPT = String.raw `
97
+ local server=redis.call('INFO','server')
98
+ if string.match(server,'run_id:([^\r\n]+)')~=ARGV[8] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
99
+ if redis.call('GET',KEYS[5])~=ARGV[9] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
100
+ local memory=redis.call('INFO','memory')
101
+ if string.match(memory,'maxmemory_policy:([^\r\n]+)')~='noeviction' then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
102
+ local stats=redis.call('INFO','stats')
103
+ if string.match(stats,'evicted_keys:(%d+)')~=ARGV[10] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
104
+ local mode=ARGV[1]
105
+ if mode=='erase' then
106
+ redis.call('SET',KEYS[4],'conversation-erasure-v1')
107
+ local deleted=redis.call('DEL',KEYS[1],KEYS[2])
108
+ local member=redis.call('SREM',KEYS[3],ARGV[2])
109
+ return {1,deleted,member}
110
+ end
111
+ if redis.call('EXISTS',KEYS[4])~=0 then return redis.error_reply('SESSION_ERASED') end
112
+ local ttl=tonumber(ARGV[3])
113
+ if mode=='index' then
114
+ redis.call('SADD',KEYS[3],ARGV[2]);if ttl>0 then redis.call('EXPIRE',KEYS[3],ttl) end;return 1
115
+ end
116
+ if mode=='persist' then
117
+ if ARGV[4]=='replace' then redis.call('DEL',KEYS[2]) end
118
+ for _,message in ipairs(cjson.decode(ARGV[5])) do redis.call('RPUSH',KEYS[2],message) end
119
+ redis.call('SET',KEYS[1],ARGV[6]);if ttl>0 then redis.call('EXPIRE',KEYS[1],ttl);redis.call('EXPIRE',KEYS[2],ttl) end;return 1
120
+ end
121
+ if mode=='metadata' then
122
+ redis.call('SET',KEYS[1],ARGV[4]);if ttl>0 then redis.call('EXPIRE',KEYS[1],ttl) end;return 1
123
+ end
124
+ return redis.error_reply('Unsupported erasure-fence mode')`;
125
+ const fenceKeys = (config, sessionId, userId) => {
126
+ const sessionKey = getSessionKey(config, sessionId, userId);
127
+ return [
128
+ sessionKey,
129
+ getSessionMessagesKey(config, sessionId, userId),
130
+ getUserSessionsKey(config, userId || "randomUser"),
131
+ erasureFenceKey(sessionKey),
132
+ epochKey(config),
133
+ ];
134
+ };
135
+ const errorText = (error) => error instanceof Error ? error.message : String(error);
136
+ const runFenced = async (client, config, sessionId, userId, scriptArguments, context) => {
137
+ if (context?.mode !== "fenced") {
138
+ throw new ConversationWriterEpochError();
139
+ }
140
+ const padded = [...scriptArguments];
141
+ while (padded.length < 7) {
142
+ padded.push("");
143
+ }
144
+ padded.push(context.runId, context.epoch, context.evictedKeys);
145
+ try {
146
+ return await client.eval(FENCED_SCRIPT, {
147
+ keys: fenceKeys(config, sessionId, userId),
148
+ arguments: padded,
149
+ });
150
+ }
151
+ catch (error) {
152
+ const text = errorText(error);
153
+ if (text.includes("SESSION_ERASED")) {
154
+ throw new ConversationSessionErasedError();
155
+ }
156
+ if (text.includes("SESSION_WRITER_EPOCH_LOST")) {
157
+ throw new ConversationWriterEpochError();
158
+ }
159
+ throw error;
160
+ }
161
+ };
162
+ /** Write the session metadata blob (SET plus TTL). */
163
+ export const fencedSessionMetadataWrite = async (client, config, sessionId, userId, payload, context) => {
164
+ if (context?.mode === "legacy") {
165
+ await setWithTtl(client, getSessionKey(config, sessionId, userId), payload, config.ttl);
166
+ return;
167
+ }
168
+ await runFenced(client, config, sessionId, userId, ["metadata", sessionId, String(config.ttl), payload], context);
169
+ };
170
+ /** Add the session to the user's session index (SADD plus TTL). */
171
+ export const fencedSessionIndexWrite = async (client, config, sessionId, userId, context) => {
172
+ if (context?.mode === "legacy") {
173
+ await addToSetWithTtl(client, getUserSessionsKey(config, userId), sessionId, config.ttl);
174
+ return;
175
+ }
176
+ await runFenced(client, config, sessionId, userId, ["index", sessionId, String(config.ttl)], context);
177
+ };
178
+ /**
179
+ * Write the message LIST and the metadata blob together. Resolves to 1 once
180
+ * the write landed; a refused write throws instead.
181
+ */
182
+ export const fencedSessionPersist = async (client, config, sessionId, userId, write, context) => {
183
+ const { mode, messages, payload } = write;
184
+ if (context?.mode === "legacy") {
185
+ const blobKey = getSessionKey(config, sessionId, userId);
186
+ const listKey = getSessionMessagesKey(config, sessionId, userId);
187
+ const transaction = client.multi();
188
+ if (mode === "replace") {
189
+ transaction.del(listKey);
190
+ }
191
+ if (messages.length > 0) {
192
+ transaction.rPush(listKey, messages);
193
+ }
194
+ transaction.set(blobKey, payload);
195
+ if (config.ttl > 0) {
196
+ transaction.expire(blobKey, config.ttl);
197
+ transaction.expire(listKey, config.ttl);
198
+ }
199
+ await transaction.exec();
200
+ return 1;
201
+ }
202
+ await runFenced(client, config, sessionId, userId, [
203
+ "persist",
204
+ sessionId,
205
+ String(config.ttl),
206
+ mode,
207
+ JSON.stringify(messages),
208
+ payload,
209
+ ], context);
210
+ return 1;
211
+ };
212
+ /**
213
+ * Permanently erase one session: tombstone, data keys and index entry in one
214
+ * atomic step. Requires a strict, fenced writer and an explicit session and
215
+ * user id.
216
+ */
217
+ export const eraseSessionPermanently = async (client, config, sessionId, userId, context) => {
218
+ if (typeof sessionId !== "string" ||
219
+ !sessionId.trim() ||
220
+ typeof userId !== "string" ||
221
+ !userId.trim()) {
222
+ throw new Error("Explicit sessionId and userId are required for permanent erasure");
223
+ }
224
+ if (context?.mode !== "fenced" || context.strict !== true) {
225
+ throw new ConversationWriterEpochError();
226
+ }
227
+ const result = await runFenced(client, config, sessionId, userId, ["erase", sessionId], context);
228
+ if (!Array.isArray(result) || Number(result[0]) !== 1) {
229
+ throw new Error("Erasure outcome unconfirmed");
230
+ }
231
+ return {
232
+ status: "erased",
233
+ backend: "redis-standalone",
234
+ protocol: ERASURE_FENCE_PROTOCOL,
235
+ participatingWritesFenced: true,
236
+ strictWriteProtocol: true,
237
+ legacyWritersFenced: false,
238
+ sessionId,
239
+ userId,
240
+ namespaceDigest: digest(getSessionKey(config, sessionId, userId)),
241
+ serverRunIdDigest: digest(context.runId),
242
+ storeEpochDigest: digest(context.epoch),
243
+ evictionPolicy: "noeviction",
244
+ evictionCounter: Number(context.evictedKeys),
245
+ deletedKeys: Number(result[1]),
246
+ removedIndexMembers: Number(result[2]),
247
+ tombstoneExpiry: null,
248
+ };
249
+ };
250
+ /** Whether the writer that resolved `context` participates in the v1 fence. */
251
+ export const conversationErasureWriterStatus = (context) => {
252
+ if (context?.mode !== "fenced") {
253
+ return {
254
+ status: "unsupported",
255
+ protocol: ERASURE_FENCE_PROTOCOL,
256
+ strict: false,
257
+ reason: context?.mode === "legacy" ? context.reason : "not-initialized",
258
+ };
259
+ }
260
+ return {
261
+ status: "participating",
262
+ strict: context.strict === true,
263
+ backend: "redis-standalone",
264
+ protocol: ERASURE_FENCE_PROTOCOL,
265
+ serverRunIdDigest: digest(context.runId),
266
+ storeEpochDigest: digest(context.epoch),
267
+ evictionPolicy: "noeviction",
268
+ evictionCounter: Number(context.evictedKeys),
269
+ };
270
+ };
@@ -2,6 +2,7 @@
2
2
  * Conversation Memory Initializer
3
3
  * Provides integration with Redis storage for conversation memory
4
4
  */
5
+ import { ConversationMemoryError } from "../types/index.js";
5
6
  import { applyConversationMemoryDefaults } from "../utils/conversationMemory.js";
6
7
  import { logger } from "../utils/logger.js";
7
8
  import { createConversationMemoryManager, getRedisConfigFromEnv, getStorageType, } from "./conversationMemoryFactory.js";
@@ -77,6 +78,12 @@ export async function initializeConversationMemory(config, eventEmitter) {
77
78
  }
78
79
  else {
79
80
  logger.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager");
81
+ // The erasure write protocol is a Redis-only fence. Handing back a
82
+ // process-local manager would let a writer that asked for it run with no
83
+ // fence and no permanent erasure, which is the downgrade it exists to refuse.
84
+ if (memoryConfig.erasureWriteProtocol === "conversation-erasure-v1") {
85
+ throw new ConversationMemoryError('erasureWriteProtocol "conversation-erasure-v1" requires Redis conversation storage', "CONFIG_ERROR", { storageType });
86
+ }
80
87
  // Create in-memory conversation memory manager
81
88
  logger.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");
82
89
  const memoryManager = createConversationMemoryManager(memoryConfig);
@@ -2,7 +2,7 @@
2
2
  * Redis Conversation Memory Manager for NeuroLink
3
3
  * Redis-based implementation of conversation storage with same interface as ConversationMemoryManager
4
4
  */
5
- import type { ChatMessage, ConversationMemoryConfig, ConversationMemoryStats, RedisConversationObject, RedisStorageConfig, SessionListItem, SessionMemory, SessionMetadata, StoreConversationTurnOptions, AgenticLoopReportMetadata, IConversationMemoryManager, NeuroLinkEvents, TypedEventEmitter } from "../types/index.js";
5
+ import type { ChatMessage, ConversationMemoryConfig, ConversationErasureResult, ConversationErasureWriterStatus, ConversationMemoryStats, RedisConversationObject, RedisStorageConfig, SessionListItem, SessionMemory, SessionMetadata, StoreConversationTurnOptions, AgenticLoopReportMetadata, IConversationMemoryManager, NeuroLinkEvents, TypedEventEmitter } from "../types/index.js";
6
6
  /**
7
7
  * Redis-based implementation of the ConversationMemoryManager
8
8
  * Uses the same interface but stores data in Redis
@@ -13,6 +13,12 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
13
13
  private summarizationEngine;
14
14
  private redisConfig;
15
15
  private redisClient;
16
+ /**
17
+ * Resolved once per initialization, before any write is admitted. Every
18
+ * write reads it up front so an in-flight write keeps the epoch it started
19
+ * under.
20
+ */
21
+ private erasureWriteContext;
16
22
  /**
17
23
  * Receives `conversation:titleGenerated` once a new conversation's title is
18
24
  * stored. Optional because the manager can be constructed standalone.
@@ -94,6 +100,19 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
94
100
  * Store a conversation turn for a session
95
101
  */
96
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;
97
116
  /**
98
117
  * Check if summarization is needed based on token count
99
118
  */
@@ -193,6 +212,17 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
193
212
  * Get statistics about conversation storage
194
213
  */
195
214
  getStats(): Promise<ConversationMemoryStats>;
215
+ /**
216
+ * Whether this writer participates in the `conversation-erasure-v1` fence.
217
+ * Only participating writers are fenced; others are NOT.
218
+ */
219
+ getConversationErasureWriterStatus(): ConversationErasureWriterStatus;
220
+ /**
221
+ * Permanently erase one session. Fences participating writers only, and
222
+ * needs a writer initialized with `erasureWriteProtocol:
223
+ * "conversation-erasure-v1"`.
224
+ */
225
+ eraseSessionPermanently(sessionId: string, userId: string): Promise<ConversationErasureResult>;
196
226
  /**
197
227
  * Clear a specific session
198
228
  */