@redis/vercel-ai-sdk 0.0.0-stage → 0.1.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +185 -2
  4. package/TOOLS.md +359 -0
  5. package/dist/errors.d.ts +9 -0
  6. package/dist/errors.d.ts.map +1 -0
  7. package/dist/errors.js +21 -0
  8. package/dist/errors.js.map +1 -0
  9. package/dist/index.d.ts +53 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +239 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/instructions.d.ts +3 -0
  14. package/dist/instructions.d.ts.map +1 -0
  15. package/dist/instructions.js +16 -0
  16. package/dist/instructions.js.map +1 -0
  17. package/dist/namespaces.d.ts +11 -0
  18. package/dist/namespaces.d.ts.map +1 -0
  19. package/dist/namespaces.js +182 -0
  20. package/dist/namespaces.js.map +1 -0
  21. package/dist/provider.d.ts +54 -0
  22. package/dist/provider.d.ts.map +1 -0
  23. package/dist/provider.js +666 -0
  24. package/dist/provider.js.map +1 -0
  25. package/dist/schemas.d.ts +125 -0
  26. package/dist/schemas.d.ts.map +1 -0
  27. package/dist/schemas.js +54 -0
  28. package/dist/schemas.js.map +1 -0
  29. package/dist/scoped-memory.d.ts +63 -0
  30. package/dist/scoped-memory.d.ts.map +1 -0
  31. package/dist/scoped-memory.js +252 -0
  32. package/dist/scoped-memory.js.map +1 -0
  33. package/dist/session-event-hook.d.ts +49 -0
  34. package/dist/session-event-hook.d.ts.map +1 -0
  35. package/dist/session-event-hook.js +77 -0
  36. package/dist/session-event-hook.js.map +1 -0
  37. package/package.json +74 -4
  38. package/src/errors.ts +16 -0
  39. package/src/index.ts +310 -0
  40. package/src/instructions.ts +15 -0
  41. package/src/namespaces.ts +217 -0
  42. package/src/provider.ts +741 -0
  43. package/src/schemas.ts +55 -0
  44. package/src/scoped-memory.ts +298 -0
  45. package/src/session-event-hook.ts +120 -0
package/src/schemas.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod';
2
+
3
+ export const id = z.string().min(1).max(255);
4
+ export const sessionId = z.string().min(1).max(64).regex(/^[A-Za-z0-9-]+$/);
5
+ export const ownerId = sessionId.describe('Stable application user identifier. Reuse it across conversations.');
6
+ export const timestamp = z.iso.datetime({ offset: true });
7
+ export const text = z.string().min(1).max(50_000);
8
+ export const topics = z.array(z.string().min(1).max(100)).max(50);
9
+ export const namespaceRef = z.object({ namespaceId: id });
10
+ export const placement = { namespace: z.string().max(255).optional(), namespaceRef: namespaceRef.optional() };
11
+ export const page = { limit: z.number().int().min(1).max(100).optional(), pageToken: z.string().optional() };
12
+ export const event = z.object({
13
+ sessionId: sessionId.optional().describe('Reuse the current session ID. Omit only to create a new session.'),
14
+ actorId: id.describe('Author of this event: user ID for USER, agent ID for ASSISTANT.'),
15
+ role: z.enum(['USER', 'ASSISTANT', 'SYSTEM']),
16
+ content: z.array(z.object({ text })).min(1),
17
+ createdAt: timestamp.optional().describe('ISO 8601 timestamp; defaults to the current time.'),
18
+ metadata: z.unknown().optional().describe('Optional JSON metadata attached to the event.'),
19
+ ...placement,
20
+ });
21
+ export const memory = z.object({
22
+ text,
23
+ ownerId: ownerId.optional().describe('Memory owner’s user ID. Required unless the toolset has a fixed scope.userId.'),
24
+ sessionId: sessionId.optional(),
25
+ memoryType: z.string().min(1).optional().describe('Built-in or registered custom memory type.'),
26
+ topics: topics.optional(),
27
+ attributes: z.record(z.string(), z.unknown()).optional(),
28
+ ...placement,
29
+ });
30
+ export const memoryUpdate = z.object({
31
+ text: text.optional(), memoryType: z.string().min(1).optional(), topics: topics.optional(),
32
+ ownerId: ownerId.optional(), sessionId: z.union([sessionId, z.literal('')]).optional(), ...placement,
33
+ });
34
+ const comparison = z.object({
35
+ eq: z.string().optional(), ne: z.string().optional(),
36
+ in: z.array(z.string()).min(1).optional(), all: z.array(z.string()).min(1).optional(),
37
+ }).refine(value => Object.values(value).filter(v => v !== undefined).length === 1,
38
+ 'Supply exactly one of eq, ne, in, all.');
39
+ export const search = z.object({
40
+ text: text.optional(), similarityThreshold: z.number().min(0).max(1).optional(), ...page,
41
+ filterOp: z.enum(['all', 'any']).optional(),
42
+ filter: z.object({
43
+ sessionId: comparison.optional(), ownerId: comparison.optional(), namespace: comparison.optional(),
44
+ topics: comparison.optional(), memoryType: comparison.optional(),
45
+ namespaceRef: z.object({ eq: id.optional(), in: z.array(id).min(1).optional() })
46
+ .refine(v => (v.eq === undefined) !== (v.in === undefined), 'Supply exactly one of eq or in.').optional(),
47
+ unnamespaced: z.boolean().optional(),
48
+ createdAt: z.object({ gt: timestamp.optional(), gte: timestamp.optional(), lt: timestamp.optional(),
49
+ lte: timestamp.optional(), eq: timestamp.optional() }).optional(),
50
+ attributes: z.record(z.string(), z.union([
51
+ z.object({ string: z.string() }).strict(), z.object({ number: z.number() }).strict(),
52
+ z.object({ boolean: z.boolean() }).strict(), z.object({ list: z.array(z.string()) }).strict(),
53
+ ])).optional(),
54
+ }).optional(),
55
+ });
@@ -0,0 +1,298 @@
1
+ import { AgentMemory } from '@redis-iris/agent-memory';
2
+ import type { LongTermMemoryFilter } from '@redis-iris/agent-memory/models';
3
+ import type { z } from 'zod';
4
+ import { RedisAgentMemoryToolError } from './errors.js';
5
+ import * as s from './schemas.js';
6
+
7
+ export interface RedisAgentMemoryScope {
8
+ /** Stable application user ID. Used as the memory owner and as the actor for USER events. */
9
+ userId?: string;
10
+ /** Locks session operations and associates new memories; recall still spans this user's sessions. */
11
+ sessionId?: string;
12
+ /** Deprecated label; prefer namespaceId for resource-backed namespaces. */
13
+ namespace?: string;
14
+ namespaceId?: string;
15
+ }
16
+
17
+ export interface ScopeValidationOptions {
18
+ namespaceTools?: boolean;
19
+ }
20
+
21
+ export type ScopedMemoryRequestOptions = NonNullable<Parameters<AgentMemory['getSessionMemory']>[2]>;
22
+ type SessionEventInput = z.infer<typeof s.event>;
23
+ type SearchInput = NonNullable<Parameters<AgentMemory['searchLongTermMemory']>[0]>;
24
+ type Placement = { namespace?: string; namespaceRef?: { namespaceId: string } };
25
+
26
+ export interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {
27
+ /** Reject when the named session already exists. Used by the legacy start_session tool. */
28
+ start?: boolean;
29
+ /** Re-read a session created by this append to verify its immutable owner and placement. */
30
+ postflightNewSession?: boolean;
31
+ /** @internal Reports whether the append POST started or was acknowledged. */
32
+ onPostStatus?: (status: 'started' | 'acknowledged') => void;
33
+ /** @internal Validates the echoed event identity for wrapper writes. */
34
+ validateResponse?: boolean;
35
+ }
36
+
37
+ function throwIfAborted(signal?: AbortSignal): void {
38
+ if (signal?.aborted) throw signal.reason ?? new DOMException('Memory operation aborted.', 'AbortError');
39
+ }
40
+
41
+ function fail(message: string): never {
42
+ throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);
43
+ }
44
+
45
+ export function memoryErrorStatus(error: unknown): number | undefined {
46
+ return typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'
47
+ ? error.statusCode : undefined;
48
+ }
49
+
50
+ /** Resolve and validate connection configuration without exposing credentials outside the SDK client. */
51
+ export function resolveAgentMemoryClient(
52
+ serverUrl?: string,
53
+ storeId?: string,
54
+ apiKey?: string,
55
+ timeoutMs = 30_000,
56
+ env: Readonly<Record<string, string | undefined>> = typeof process === 'undefined' ? {} : process.env,
57
+ ): AgentMemory {
58
+ const key = apiKey ?? env.AGENT_MEMORY_API_KEY;
59
+ const resolvedStoreId = storeId ?? env.AGENT_MEMORY_STORE_ID;
60
+ if (!key?.trim()) throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');
61
+ if (!resolvedStoreId?.trim()) throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');
62
+ const serverURL = serverUrl ?? env.AGENT_MEMORY_URL ?? 'https://gcp-us-east4.memory.redis.io';
63
+ const url = new URL(serverURL);
64
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
65
+ throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');
66
+ }
67
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('timeoutMs must be positive.');
68
+ return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });
69
+ }
70
+
71
+ export function copyMemoryScope(
72
+ scope: RedisAgentMemoryScope,
73
+ options: ScopeValidationOptions = {},
74
+ ): Readonly<RedisAgentMemoryScope> {
75
+ const copied = Object.freeze({ ...scope });
76
+ if (copied.userId !== undefined) s.ownerId.parse(copied.userId);
77
+ if (copied.sessionId !== undefined) s.sessionId.parse(copied.sessionId);
78
+ if (copied.namespaceId !== undefined) s.id.parse(copied.namespaceId);
79
+ if (copied.namespace !== undefined && !copied.namespace.trim()) throw new Error('scope.namespace must not be empty.');
80
+ if (copied.namespace !== undefined && copied.namespaceId !== undefined) throw new Error('Choose scope.namespace or scope.namespaceId.');
81
+ if (options.namespaceTools && copied.namespace !== undefined) throw new Error('Namespace resource tools cannot use a legacy namespace scope.');
82
+ return copied;
83
+ }
84
+
85
+ export function extendMemoryScope(
86
+ scope: RedisAgentMemoryScope,
87
+ context: RedisAgentMemoryScope,
88
+ ): RedisAgentMemoryScope {
89
+ const extended = { ...scope };
90
+ for (const name of ['userId', 'sessionId', 'namespace', 'namespaceId'] as const) {
91
+ const value = context[name];
92
+ if (value === undefined) continue;
93
+ if (scope[name] !== undefined && scope[name] !== value) fail(`Cannot override ${name} scope.`);
94
+ extended[name] = value;
95
+ }
96
+ return extended;
97
+ }
98
+
99
+ /**
100
+ * Security boundary shared by tools, hooks, and the provider wrapper.
101
+ * The client and validated scope are captured once and never exposed as enumerable state.
102
+ */
103
+ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMemoryScope) {
104
+ const scope = copyMemoryScope(inputScope);
105
+ const hasResourceScope = Boolean(scope.userId || scope.namespace !== undefined || scope.namespaceId);
106
+
107
+ const checkPlacement = (value: Placement) => {
108
+ if (value.namespace !== undefined && value.namespaceRef !== undefined) fail('Supply namespace or namespaceRef, never both.');
109
+ if (scope.namespace !== undefined && value.namespace !== scope.namespace) fail('Resource is outside the configured namespace.');
110
+ if (scope.namespaceId !== undefined && value.namespaceRef?.namespaceId !== scope.namespaceId) {
111
+ fail('Resource is outside the configured namespace resource.');
112
+ }
113
+ };
114
+
115
+ const place = <T extends Placement>(input: T): T => {
116
+ const value = { ...input };
117
+ if (value.namespace !== undefined && value.namespaceRef !== undefined) fail('Supply namespace or namespaceRef, never both.');
118
+ if (scope.namespace !== undefined) {
119
+ if (value.namespaceRef || (value.namespace !== undefined && value.namespace !== scope.namespace)) fail('Cannot override namespace scope.');
120
+ value.namespace = scope.namespace;
121
+ }
122
+ if (scope.namespaceId !== undefined) {
123
+ if (value.namespace !== undefined || (value.namespaceRef && value.namespaceRef.namespaceId !== scope.namespaceId)) fail('Cannot override namespace scope.');
124
+ value.namespaceRef = { namespaceId: scope.namespaceId };
125
+ }
126
+ return value;
127
+ };
128
+
129
+ const resolveSession = (value?: string) => {
130
+ if (scope.sessionId && value && value !== scope.sessionId) fail('Cannot override session scope.');
131
+ const resolved = value ?? scope.sessionId;
132
+ if (!resolved) fail('Supply sessionId or configure scope.sessionId.');
133
+ return resolved;
134
+ };
135
+
136
+ const resolveOwner = (value?: string) => {
137
+ if (scope.userId && value && value !== scope.userId) fail('Cannot override user scope.');
138
+ const resolved = value ?? scope.userId;
139
+ if (!resolved) fail('Supply ownerId or configure scope.userId.');
140
+ return resolved;
141
+ };
142
+
143
+ const assertSession = async (
144
+ sessionId: string,
145
+ options?: ScopedMemoryRequestOptions,
146
+ validateSessionId = false,
147
+ ) => {
148
+ resolveSession(sessionId);
149
+ const session = await client.getSessionMemory(sessionId, false, options);
150
+ if (validateSessionId && session.sessionId !== sessionId) fail('Session response does not match the configured session scope.');
151
+ if (scope.userId && session.ownerId !== scope.userId) fail('Session is outside the configured user scope.');
152
+ checkPlacement(session);
153
+ return session;
154
+ };
155
+
156
+ const restoreSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options);
157
+ const restoreScopedSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options, true);
158
+
159
+ const assertMemory = async (id: string, options?: ScopedMemoryRequestOptions) => {
160
+ const memory = await client.getLongTermMemory(id, options);
161
+ if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');
162
+ checkPlacement(memory);
163
+ return memory;
164
+ };
165
+
166
+ const assertPlacementOwner = async (value: Placement, options?: ScopedMemoryRequestOptions) => {
167
+ if (!scope.userId || !value.namespaceRef) return;
168
+ const signal = options?.signal ?? undefined;
169
+ throwIfAborted(signal);
170
+ const { namespace } = await client.getNamespace(value.namespaceRef.namespaceId, options);
171
+ throwIfAborted(signal);
172
+ const root = namespace.rootId === namespace.namespaceId ? namespace
173
+ : (await client.getNamespace(namespace.rootId, options)).namespace;
174
+ throwIfAborted(signal);
175
+ if (root.scope !== 'PERSONAL' || root.ownerId !== scope.userId) {
176
+ fail('Namespace placement is outside the configured user’s personal namespaces.');
177
+ }
178
+ };
179
+
180
+ const scopeSearch = (input: SearchInput): SearchInput => {
181
+ const filter: LongTermMemoryFilter = { ...input.filter };
182
+ if (filter.namespace && filter.namespaceRef) fail('Supply namespace or namespaceRef, never both.');
183
+ if (filter.unnamespaced !== undefined && (filter.namespace || filter.namespaceRef)) {
184
+ fail('unnamespaced cannot be combined with namespace selectors.');
185
+ }
186
+ if (hasResourceScope && input.filterOp === 'any') fail('Scoped searches require filterOp all to preserve isolation.');
187
+ const fixed = (name: 'ownerId' | 'namespace' | 'namespaceRef', value: string) => {
188
+ const existing = filter[name];
189
+ if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {
190
+ fail(`Cannot override ${name} scope.`);
191
+ }
192
+ filter[name] = { eq: value };
193
+ };
194
+ if (scope.userId) fixed('ownerId', scope.userId);
195
+ if (scope.namespace !== undefined || scope.namespaceId) {
196
+ if (filter.unnamespaced !== undefined) fail('Cannot search unnamespaced records within a namespace scope.');
197
+ if (scope.namespace !== undefined) {
198
+ if (filter.namespaceRef) fail('Cannot override namespace scope.');
199
+ fixed('namespace', scope.namespace);
200
+ } else {
201
+ if (filter.namespace) fail('Cannot override namespace scope.');
202
+ fixed('namespaceRef', scope.namespaceId!);
203
+ }
204
+ }
205
+ return { ...input, filter, filterOp: hasResourceScope ? 'all' : input.filterOp };
206
+ };
207
+
208
+ const searchLongTermMemory = (
209
+ input: SearchInput,
210
+ options?: ScopedMemoryRequestOptions,
211
+ ) => client.searchLongTermMemory(scopeSearch(input), options);
212
+
213
+ const searchPersonalMemories = async (
214
+ text: string,
215
+ limit: number,
216
+ options?: ScopedMemoryRequestOptions,
217
+ ) => {
218
+ const result = await searchLongTermMemory({ text, limit }, options);
219
+ for (const memory of result.items) {
220
+ if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');
221
+ checkPlacement(memory);
222
+ }
223
+ return result;
224
+ };
225
+
226
+ const appendSessionEvent = async (
227
+ input: SessionEventInput,
228
+ options: AppendSessionEventOptions = {},
229
+ ) => {
230
+ const {
231
+ start = false, postflightNewSession = false, onPostStatus, validateResponse = false, ...requestOptions
232
+ } = options;
233
+ const requestSignal = requestOptions.signal ?? undefined;
234
+ const placed = place(input);
235
+ const sessionId = input.sessionId ?? scope.sessionId;
236
+ let newSession = false;
237
+ if (sessionId) {
238
+ resolveSession(sessionId);
239
+ if (hasResourceScope || start) {
240
+ throwIfAborted(requestSignal);
241
+ try {
242
+ await assertSession(sessionId, requestOptions, validateResponse);
243
+ throwIfAborted(requestSignal);
244
+ if (start) fail('This session already exists; use add_session_event.');
245
+ } catch (error) {
246
+ if (memoryErrorStatus(error) !== 404) throw error;
247
+ newSession = true;
248
+ if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {
249
+ fail('A new session must start with a USER event whose actorId is the configured userId.');
250
+ }
251
+ }
252
+ }
253
+ } else if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {
254
+ fail('A new session must start with a USER event whose actorId is the configured userId.');
255
+ }
256
+ throwIfAborted(requestSignal);
257
+ await assertPlacementOwner(placed, requestOptions);
258
+ throwIfAborted(requestSignal);
259
+ onPostStatus?.('started');
260
+ const result = await client.addSessionEvent({
261
+ ...placed,
262
+ sessionId,
263
+ createdAt: input.createdAt ? new Date(input.createdAt) : new Date(),
264
+ }, requestOptions);
265
+ onPostStatus?.('acknowledged');
266
+ if (validateResponse && (
267
+ result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role
268
+ )) {
269
+ fail('Saved event is outside the configured session or actor scope.');
270
+ }
271
+ throwIfAborted(requestSignal);
272
+ if (postflightNewSession && newSession && sessionId) {
273
+ await assertSession(sessionId, requestOptions, validateResponse);
274
+ throwIfAborted(requestSignal);
275
+ }
276
+ return result;
277
+ };
278
+
279
+ return Object.freeze({
280
+ scope,
281
+ hasResourceScope,
282
+ checkPlacement,
283
+ place,
284
+ resolveSession,
285
+ resolveOwner,
286
+ assertSession,
287
+ restoreSession,
288
+ restoreScopedSession,
289
+ assertMemory,
290
+ assertPlacementOwner,
291
+ scopeSearch,
292
+ searchLongTermMemory,
293
+ searchPersonalMemories,
294
+ appendSessionEvent,
295
+ });
296
+ }
297
+
298
+ export type ScopedMemory = ReturnType<typeof createScopedMemory>;
@@ -0,0 +1,120 @@
1
+ import type { ModelMessage } from 'ai';
2
+ import type { z } from 'zod';
3
+ import { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';
4
+ import * as s from './schemas.js';
5
+
6
+ type SessionRole = 'USER' | 'ASSISTANT';
7
+ type ObserverResult = void | PromiseLike<void>;
8
+ type SessionEventInput = z.infer<typeof s.event>;
9
+
10
+ interface SessionEventHookInputs {
11
+ USER: { readonly messages: ReadonlyArray<ModelMessage> };
12
+ ASSISTANT: { readonly finalStep: { readonly text: string } };
13
+ }
14
+
15
+ /** USER hooks consume onStart messages; ASSISTANT hooks consume onEnd final text. */
16
+ export type SessionEventHookInput<Role extends SessionRole = SessionRole> = SessionEventHookInputs[Role];
17
+
18
+ export type SessionEventHook<Role extends SessionRole = SessionRole> = (event: SessionEventHookInput<Role>) => Promise<void>;
19
+
20
+ /** Identity of an event about to be written or confirmed saved. Contains no message text. */
21
+ export interface SessionHookEvent {
22
+ readonly sessionId: string;
23
+ readonly role: SessionRole;
24
+ readonly actorId: string;
25
+ }
26
+
27
+ export interface SessionEventHookErrorContext extends SessionHookEvent {
28
+ readonly userId: string;
29
+ /** A failed write may have committed; verify before retrying. */
30
+ readonly phase: 'validation' | 'write';
31
+ }
32
+
33
+ export interface SessionEventHookOptions<Role extends SessionRole = SessionRole> {
34
+ /** Record one USER event in onStart or one ASSISTANT event in onEnd. */
35
+ role: Role;
36
+ /** Event author. For USER events, this must match the scoped userId. */
37
+ actorId: string;
38
+ /** Required because the AI SDK ignores exceptions thrown by lifecycle callbacks. */
39
+ onError: (error: RedisAgentMemoryToolError, context: SessionEventHookErrorContext) => ObserverResult;
40
+ /** Optional observers are awaited; observer errors never change which events are written. */
41
+ onEventStart?: (event: SessionHookEvent) => ObserverResult;
42
+ onEventSaved?: (event: SessionHookEvent) => ObserverResult;
43
+ }
44
+
45
+ function invalidInput(message: string): never {
46
+ throw new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', message);
47
+ }
48
+
49
+ function extractEvent(
50
+ event: SessionEventHookInput,
51
+ role: SessionRole,
52
+ actorId: string,
53
+ ): SessionEventInput | undefined {
54
+ if (role === 'USER') {
55
+ if (!('messages' in event) || !Array.isArray(event.messages)) {
56
+ invalidInput('USER session recording requires messages from an onStart event.');
57
+ }
58
+ const messages: ReadonlyArray<ModelMessage> = event.messages;
59
+ const user = messages.at(-1);
60
+ if (user?.role !== 'user') invalidInput('Session recording requires the current final input message to have role user.');
61
+ const content = typeof user.content === 'string'
62
+ ? [{ text: user.content }]
63
+ : user.content.flatMap(part => part.type === 'text' && part.text.length > 0 ? [{ text: part.text }] : []);
64
+ return s.event.parse({ actorId, role, content });
65
+ }
66
+ if (!('finalStep' in event) || typeof event.finalStep?.text !== 'string') {
67
+ invalidInput('ASSISTANT session recording requires finalStep.text from an onEnd event.');
68
+ }
69
+ if (event.finalStep.text.length === 0) return undefined;
70
+ return s.event.parse({ actorId, role, content: [{ text: event.finalStep.text }] });
71
+ }
72
+
73
+ async function observe(callback: () => ObserverResult): Promise<void> {
74
+ try { await callback(); } catch { /* Observers must not interrupt recording or cause a write to be retried. */ }
75
+ }
76
+
77
+ /** Internal adapter. The writer retains the toolset's immutable scope and shared SDK client. */
78
+ export function createSessionEventHook<Role extends SessionRole>(
79
+ scope: { readonly userId?: string; readonly sessionId?: string },
80
+ write: (event: SessionEventInput) => Promise<unknown>,
81
+ options: SessionEventHookOptions<Role>,
82
+ ): SessionEventHook<Role> {
83
+ if (!scope.userId || !scope.sessionId) {
84
+ throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'createSessionEventHook requires scope.userId and scope.sessionId.');
85
+ }
86
+ if (typeof options?.onError !== 'function') throw new Error('createSessionEventHook requires an onError callback.');
87
+ const { role, onError, onEventStart, onEventSaved } = options;
88
+ if (role !== 'USER' && role !== 'ASSISTANT') throw new Error('createSessionEventHook requires role USER or ASSISTANT.');
89
+ const actorId = s.id.parse(options.actorId);
90
+ if (role === 'USER' && actorId !== scope.userId) {
91
+ throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');
92
+ }
93
+ for (const [name, observer] of [['onEventStart', onEventStart], ['onEventSaved', onEventSaved]] as const) {
94
+ if (observer !== undefined && typeof observer !== 'function') throw new Error(`${name} must be a function.`);
95
+ }
96
+ const userId = scope.userId;
97
+ const info: SessionHookEvent = Object.freeze({ sessionId: scope.sessionId, role, actorId });
98
+
99
+ return async event => {
100
+ let input: SessionEventInput | undefined;
101
+ try {
102
+ input = extractEvent(event, role, actorId);
103
+ } catch (error) {
104
+ const safeError = error instanceof RedisAgentMemoryToolError ? error
105
+ : new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', `Session recording requires valid ${role} text. Each text part must be non-empty and at most 50,000 characters.`);
106
+ await observe(() => onError(safeError, Object.freeze({ ...info, userId, phase: 'validation' })));
107
+ return;
108
+ }
109
+ if (!input) return;
110
+
111
+ await observe(() => onEventStart?.(info));
112
+ try {
113
+ await write(input);
114
+ } catch (error) {
115
+ await observe(() => onError(sanitizeMemoryError(error), Object.freeze({ ...info, userId, phase: 'write' })));
116
+ return;
117
+ }
118
+ await observe(() => onEventSaved?.(info));
119
+ };
120
+ }