@redis/vercel-ai-sdk 0.0.0-stage → 0.1.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 +38 -0
- package/LICENSE +21 -0
- package/README.md +185 -2
- package/TOOLS.md +359 -0
- package/dist/errors.d.ts +9 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +21 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +239 -0
- package/dist/index.js.map +1 -0
- package/dist/instructions.d.ts +3 -0
- package/dist/instructions.d.ts.map +1 -0
- package/dist/instructions.js +16 -0
- package/dist/instructions.js.map +1 -0
- package/dist/namespaces.d.ts +11 -0
- package/dist/namespaces.d.ts.map +1 -0
- package/dist/namespaces.js +182 -0
- package/dist/namespaces.js.map +1 -0
- package/dist/provider.d.ts +54 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +666 -0
- package/dist/provider.js.map +1 -0
- package/dist/schemas.d.ts +125 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +54 -0
- package/dist/schemas.js.map +1 -0
- package/dist/scoped-memory.d.ts +63 -0
- package/dist/scoped-memory.d.ts.map +1 -0
- package/dist/scoped-memory.js +252 -0
- package/dist/scoped-memory.js.map +1 -0
- package/dist/session-event-hook.d.ts +49 -0
- package/dist/session-event-hook.d.ts.map +1 -0
- package/dist/session-event-hook.js +77 -0
- package/dist/session-event-hook.js.map +1 -0
- package/package.json +74 -4
- package/src/errors.ts +16 -0
- package/src/index.ts +310 -0
- package/src/instructions.ts +15 -0
- package/src/namespaces.ts +217 -0
- package/src/provider.ts +741 -0
- package/src/schemas.ts +55 -0
- package/src/scoped-memory.ts +298 -0
- package/src/session-event-hook.ts +120 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { AgentMemory } from '@redis-iris/agent-memory';
|
|
2
|
+
import { RedisAgentMemoryToolError } from './errors.js';
|
|
3
|
+
import * as s from './schemas.js';
|
|
4
|
+
function throwIfAborted(signal) {
|
|
5
|
+
if (signal?.aborted)
|
|
6
|
+
throw signal.reason ?? new DOMException('Memory operation aborted.', 'AbortError');
|
|
7
|
+
}
|
|
8
|
+
function fail(message) {
|
|
9
|
+
throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);
|
|
10
|
+
}
|
|
11
|
+
export function memoryErrorStatus(error) {
|
|
12
|
+
return typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'
|
|
13
|
+
? error.statusCode : undefined;
|
|
14
|
+
}
|
|
15
|
+
/** Resolve and validate connection configuration without exposing credentials outside the SDK client. */
|
|
16
|
+
export function resolveAgentMemoryClient(serverUrl, storeId, apiKey, timeoutMs = 30_000, env = typeof process === 'undefined' ? {} : process.env) {
|
|
17
|
+
const key = apiKey ?? env.AGENT_MEMORY_API_KEY;
|
|
18
|
+
const resolvedStoreId = storeId ?? env.AGENT_MEMORY_STORE_ID;
|
|
19
|
+
if (!key?.trim())
|
|
20
|
+
throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');
|
|
21
|
+
if (!resolvedStoreId?.trim())
|
|
22
|
+
throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');
|
|
23
|
+
const serverURL = serverUrl ?? env.AGENT_MEMORY_URL ?? 'https://gcp-us-east4.memory.redis.io';
|
|
24
|
+
const url = new URL(serverURL);
|
|
25
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
26
|
+
throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');
|
|
27
|
+
}
|
|
28
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
|
|
29
|
+
throw new Error('timeoutMs must be positive.');
|
|
30
|
+
return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });
|
|
31
|
+
}
|
|
32
|
+
export function copyMemoryScope(scope, options = {}) {
|
|
33
|
+
const copied = Object.freeze({ ...scope });
|
|
34
|
+
if (copied.userId !== undefined)
|
|
35
|
+
s.ownerId.parse(copied.userId);
|
|
36
|
+
if (copied.sessionId !== undefined)
|
|
37
|
+
s.sessionId.parse(copied.sessionId);
|
|
38
|
+
if (copied.namespaceId !== undefined)
|
|
39
|
+
s.id.parse(copied.namespaceId);
|
|
40
|
+
if (copied.namespace !== undefined && !copied.namespace.trim())
|
|
41
|
+
throw new Error('scope.namespace must not be empty.');
|
|
42
|
+
if (copied.namespace !== undefined && copied.namespaceId !== undefined)
|
|
43
|
+
throw new Error('Choose scope.namespace or scope.namespaceId.');
|
|
44
|
+
if (options.namespaceTools && copied.namespace !== undefined)
|
|
45
|
+
throw new Error('Namespace resource tools cannot use a legacy namespace scope.');
|
|
46
|
+
return copied;
|
|
47
|
+
}
|
|
48
|
+
export function extendMemoryScope(scope, context) {
|
|
49
|
+
const extended = { ...scope };
|
|
50
|
+
for (const name of ['userId', 'sessionId', 'namespace', 'namespaceId']) {
|
|
51
|
+
const value = context[name];
|
|
52
|
+
if (value === undefined)
|
|
53
|
+
continue;
|
|
54
|
+
if (scope[name] !== undefined && scope[name] !== value)
|
|
55
|
+
fail(`Cannot override ${name} scope.`);
|
|
56
|
+
extended[name] = value;
|
|
57
|
+
}
|
|
58
|
+
return extended;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Security boundary shared by tools, hooks, and the provider wrapper.
|
|
62
|
+
* The client and validated scope are captured once and never exposed as enumerable state.
|
|
63
|
+
*/
|
|
64
|
+
export function createScopedMemory(client, inputScope) {
|
|
65
|
+
const scope = copyMemoryScope(inputScope);
|
|
66
|
+
const hasResourceScope = Boolean(scope.userId || scope.namespace !== undefined || scope.namespaceId);
|
|
67
|
+
const checkPlacement = (value) => {
|
|
68
|
+
if (value.namespace !== undefined && value.namespaceRef !== undefined)
|
|
69
|
+
fail('Supply namespace or namespaceRef, never both.');
|
|
70
|
+
if (scope.namespace !== undefined && value.namespace !== scope.namespace)
|
|
71
|
+
fail('Resource is outside the configured namespace.');
|
|
72
|
+
if (scope.namespaceId !== undefined && value.namespaceRef?.namespaceId !== scope.namespaceId) {
|
|
73
|
+
fail('Resource is outside the configured namespace resource.');
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const place = (input) => {
|
|
77
|
+
const value = { ...input };
|
|
78
|
+
if (value.namespace !== undefined && value.namespaceRef !== undefined)
|
|
79
|
+
fail('Supply namespace or namespaceRef, never both.');
|
|
80
|
+
if (scope.namespace !== undefined) {
|
|
81
|
+
if (value.namespaceRef || (value.namespace !== undefined && value.namespace !== scope.namespace))
|
|
82
|
+
fail('Cannot override namespace scope.');
|
|
83
|
+
value.namespace = scope.namespace;
|
|
84
|
+
}
|
|
85
|
+
if (scope.namespaceId !== undefined) {
|
|
86
|
+
if (value.namespace !== undefined || (value.namespaceRef && value.namespaceRef.namespaceId !== scope.namespaceId))
|
|
87
|
+
fail('Cannot override namespace scope.');
|
|
88
|
+
value.namespaceRef = { namespaceId: scope.namespaceId };
|
|
89
|
+
}
|
|
90
|
+
return value;
|
|
91
|
+
};
|
|
92
|
+
const resolveSession = (value) => {
|
|
93
|
+
if (scope.sessionId && value && value !== scope.sessionId)
|
|
94
|
+
fail('Cannot override session scope.');
|
|
95
|
+
const resolved = value ?? scope.sessionId;
|
|
96
|
+
if (!resolved)
|
|
97
|
+
fail('Supply sessionId or configure scope.sessionId.');
|
|
98
|
+
return resolved;
|
|
99
|
+
};
|
|
100
|
+
const resolveOwner = (value) => {
|
|
101
|
+
if (scope.userId && value && value !== scope.userId)
|
|
102
|
+
fail('Cannot override user scope.');
|
|
103
|
+
const resolved = value ?? scope.userId;
|
|
104
|
+
if (!resolved)
|
|
105
|
+
fail('Supply ownerId or configure scope.userId.');
|
|
106
|
+
return resolved;
|
|
107
|
+
};
|
|
108
|
+
const assertSession = async (sessionId, options, validateSessionId = false) => {
|
|
109
|
+
resolveSession(sessionId);
|
|
110
|
+
const session = await client.getSessionMemory(sessionId, false, options);
|
|
111
|
+
if (validateSessionId && session.sessionId !== sessionId)
|
|
112
|
+
fail('Session response does not match the configured session scope.');
|
|
113
|
+
if (scope.userId && session.ownerId !== scope.userId)
|
|
114
|
+
fail('Session is outside the configured user scope.');
|
|
115
|
+
checkPlacement(session);
|
|
116
|
+
return session;
|
|
117
|
+
};
|
|
118
|
+
const restoreSession = (options) => assertSession(resolveSession(), options);
|
|
119
|
+
const restoreScopedSession = (options) => assertSession(resolveSession(), options, true);
|
|
120
|
+
const assertMemory = async (id, options) => {
|
|
121
|
+
const memory = await client.getLongTermMemory(id, options);
|
|
122
|
+
if (scope.userId && memory.ownerId !== scope.userId)
|
|
123
|
+
fail('Memory is outside the configured user scope.');
|
|
124
|
+
checkPlacement(memory);
|
|
125
|
+
return memory;
|
|
126
|
+
};
|
|
127
|
+
const assertPlacementOwner = async (value, options) => {
|
|
128
|
+
if (!scope.userId || !value.namespaceRef)
|
|
129
|
+
return;
|
|
130
|
+
const signal = options?.signal ?? undefined;
|
|
131
|
+
throwIfAborted(signal);
|
|
132
|
+
const { namespace } = await client.getNamespace(value.namespaceRef.namespaceId, options);
|
|
133
|
+
throwIfAborted(signal);
|
|
134
|
+
const root = namespace.rootId === namespace.namespaceId ? namespace
|
|
135
|
+
: (await client.getNamespace(namespace.rootId, options)).namespace;
|
|
136
|
+
throwIfAborted(signal);
|
|
137
|
+
if (root.scope !== 'PERSONAL' || root.ownerId !== scope.userId) {
|
|
138
|
+
fail('Namespace placement is outside the configured user’s personal namespaces.');
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const scopeSearch = (input) => {
|
|
142
|
+
const filter = { ...input.filter };
|
|
143
|
+
if (filter.namespace && filter.namespaceRef)
|
|
144
|
+
fail('Supply namespace or namespaceRef, never both.');
|
|
145
|
+
if (filter.unnamespaced !== undefined && (filter.namespace || filter.namespaceRef)) {
|
|
146
|
+
fail('unnamespaced cannot be combined with namespace selectors.');
|
|
147
|
+
}
|
|
148
|
+
if (hasResourceScope && input.filterOp === 'any')
|
|
149
|
+
fail('Scoped searches require filterOp all to preserve isolation.');
|
|
150
|
+
const fixed = (name, value) => {
|
|
151
|
+
const existing = filter[name];
|
|
152
|
+
if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {
|
|
153
|
+
fail(`Cannot override ${name} scope.`);
|
|
154
|
+
}
|
|
155
|
+
filter[name] = { eq: value };
|
|
156
|
+
};
|
|
157
|
+
if (scope.userId)
|
|
158
|
+
fixed('ownerId', scope.userId);
|
|
159
|
+
if (scope.namespace !== undefined || scope.namespaceId) {
|
|
160
|
+
if (filter.unnamespaced !== undefined)
|
|
161
|
+
fail('Cannot search unnamespaced records within a namespace scope.');
|
|
162
|
+
if (scope.namespace !== undefined) {
|
|
163
|
+
if (filter.namespaceRef)
|
|
164
|
+
fail('Cannot override namespace scope.');
|
|
165
|
+
fixed('namespace', scope.namespace);
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
if (filter.namespace)
|
|
169
|
+
fail('Cannot override namespace scope.');
|
|
170
|
+
fixed('namespaceRef', scope.namespaceId);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { ...input, filter, filterOp: hasResourceScope ? 'all' : input.filterOp };
|
|
174
|
+
};
|
|
175
|
+
const searchLongTermMemory = (input, options) => client.searchLongTermMemory(scopeSearch(input), options);
|
|
176
|
+
const searchPersonalMemories = async (text, limit, options) => {
|
|
177
|
+
const result = await searchLongTermMemory({ text, limit }, options);
|
|
178
|
+
for (const memory of result.items) {
|
|
179
|
+
if (scope.userId && memory.ownerId !== scope.userId)
|
|
180
|
+
fail('Memory is outside the configured user scope.');
|
|
181
|
+
checkPlacement(memory);
|
|
182
|
+
}
|
|
183
|
+
return result;
|
|
184
|
+
};
|
|
185
|
+
const appendSessionEvent = async (input, options = {}) => {
|
|
186
|
+
const { start = false, postflightNewSession = false, onPostStatus, validateResponse = false, ...requestOptions } = options;
|
|
187
|
+
const requestSignal = requestOptions.signal ?? undefined;
|
|
188
|
+
const placed = place(input);
|
|
189
|
+
const sessionId = input.sessionId ?? scope.sessionId;
|
|
190
|
+
let newSession = false;
|
|
191
|
+
if (sessionId) {
|
|
192
|
+
resolveSession(sessionId);
|
|
193
|
+
if (hasResourceScope || start) {
|
|
194
|
+
throwIfAborted(requestSignal);
|
|
195
|
+
try {
|
|
196
|
+
await assertSession(sessionId, requestOptions, validateResponse);
|
|
197
|
+
throwIfAborted(requestSignal);
|
|
198
|
+
if (start)
|
|
199
|
+
fail('This session already exists; use add_session_event.');
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
if (memoryErrorStatus(error) !== 404)
|
|
203
|
+
throw error;
|
|
204
|
+
newSession = true;
|
|
205
|
+
if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {
|
|
206
|
+
fail('A new session must start with a USER event whose actorId is the configured userId.');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
else if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {
|
|
212
|
+
fail('A new session must start with a USER event whose actorId is the configured userId.');
|
|
213
|
+
}
|
|
214
|
+
throwIfAborted(requestSignal);
|
|
215
|
+
await assertPlacementOwner(placed, requestOptions);
|
|
216
|
+
throwIfAborted(requestSignal);
|
|
217
|
+
onPostStatus?.('started');
|
|
218
|
+
const result = await client.addSessionEvent({
|
|
219
|
+
...placed,
|
|
220
|
+
sessionId,
|
|
221
|
+
createdAt: input.createdAt ? new Date(input.createdAt) : new Date(),
|
|
222
|
+
}, requestOptions);
|
|
223
|
+
onPostStatus?.('acknowledged');
|
|
224
|
+
if (validateResponse && (result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role)) {
|
|
225
|
+
fail('Saved event is outside the configured session or actor scope.');
|
|
226
|
+
}
|
|
227
|
+
throwIfAborted(requestSignal);
|
|
228
|
+
if (postflightNewSession && newSession && sessionId) {
|
|
229
|
+
await assertSession(sessionId, requestOptions, validateResponse);
|
|
230
|
+
throwIfAborted(requestSignal);
|
|
231
|
+
}
|
|
232
|
+
return result;
|
|
233
|
+
};
|
|
234
|
+
return Object.freeze({
|
|
235
|
+
scope,
|
|
236
|
+
hasResourceScope,
|
|
237
|
+
checkPlacement,
|
|
238
|
+
place,
|
|
239
|
+
resolveSession,
|
|
240
|
+
resolveOwner,
|
|
241
|
+
assertSession,
|
|
242
|
+
restoreSession,
|
|
243
|
+
restoreScopedSession,
|
|
244
|
+
assertMemory,
|
|
245
|
+
assertPlacementOwner,
|
|
246
|
+
scopeSearch,
|
|
247
|
+
searchLongTermMemory,
|
|
248
|
+
searchPersonalMemories,
|
|
249
|
+
appendSessionEvent,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
//# sourceMappingURL=scoped-memory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scoped-memory.js","sourceRoot":"","sources":["../src/scoped-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAgClC,SAAS,cAAc,CAAC,MAAoB;IAC1C,IAAI,MAAM,EAAE,OAAO;QAAE,MAAM,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAAY,CAAC,CAAC;AAC1G,CAAC;AAED,SAAS,IAAI,CAAC,OAAe;IAC3B,MAAM,IAAI,yBAAyB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,YAAY,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ;QACjH,CAAC,CAAC,KAAK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K,SAAS,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CACnH,EAAE,CAAC;YACF,IAAI,CAAC,+DAA+D,CAAC,CAAC;QACxE,CAAC;QACD,cAAc,CAAC,aAAa,CAAC,CAAC;QAC9B,IAAI,oBAAoB,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;YACpD,MAAM,aAAa,CAAC,SAAS,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;YACjE,cAAc,CAAC,aAAa,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,KAAK;QACL,gBAAgB;QAChB,cAAc;QACd,KAAK;QACL,cAAc;QACd,YAAY;QACZ,aAAa;QACb,cAAc;QACd,oBAAoB;QACpB,YAAY;QACZ,oBAAoB;QACpB,WAAW;QACX,oBAAoB;QACpB,sBAAsB;QACtB,kBAAkB;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter } from '@redis-iris/agent-memory/models';\nimport type { z } from 'zod';\nimport { RedisAgentMemoryToolError } from './errors.js';\nimport * as s from './schemas.js';\n\nexport interface RedisAgentMemoryScope {\n /** Stable application user ID. Used as the memory owner and as the actor for USER events. */\n userId?: string;\n /** Locks session operations and associates new memories; recall still spans this user's sessions. */\n sessionId?: string;\n /** Deprecated label; prefer namespaceId for resource-backed namespaces. */\n namespace?: string;\n namespaceId?: string;\n}\n\nexport interface ScopeValidationOptions {\n namespaceTools?: boolean;\n}\n\nexport type ScopedMemoryRequestOptions = NonNullable<Parameters<AgentMemory['getSessionMemory']>[2]>;\ntype SessionEventInput = z.infer<typeof s.event>;\ntype SearchInput = NonNullable<Parameters<AgentMemory['searchLongTermMemory']>[0]>;\ntype Placement = { namespace?: string; namespaceRef?: { namespaceId: string } };\n\nexport interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {\n /** Reject when the named session already exists. Used by the legacy start_session tool. */\n start?: boolean;\n /** Re-read a session created by this append to verify its immutable owner and placement. */\n postflightNewSession?: boolean;\n /** @internal Reports whether the append POST started or was acknowledged. */\n onPostStatus?: (status: 'started' | 'acknowledged') => void;\n /** @internal Validates the echoed event identity for wrapper writes. */\n validateResponse?: boolean;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new DOMException('Memory operation aborted.', 'AbortError');\n}\n\nfunction fail(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);\n}\n\nexport function memoryErrorStatus(error: unknown): number | undefined {\n return typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'\n ? error.statusCode : undefined;\n}\n\n/** Resolve and validate connection configuration without exposing credentials outside the SDK client. */\nexport function resolveAgentMemoryClient(\n serverUrl?: string,\n storeId?: string,\n apiKey?: string,\n timeoutMs = 30_000,\n env: Readonly<Record<string, string | undefined>> = typeof process === 'undefined' ? {} : process.env,\n): AgentMemory {\n const key = apiKey ?? env.AGENT_MEMORY_API_KEY;\n const resolvedStoreId = storeId ?? env.AGENT_MEMORY_STORE_ID;\n if (!key?.trim()) throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');\n if (!resolvedStoreId?.trim()) throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');\n const serverURL = serverUrl ?? env.AGENT_MEMORY_URL ?? 'https://gcp-us-east4.memory.redis.io';\n const url = new URL(serverURL);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {\n throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('timeoutMs must be positive.');\n return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });\n}\n\nexport function copyMemoryScope(\n scope: RedisAgentMemoryScope,\n options: ScopeValidationOptions = {},\n): Readonly<RedisAgentMemoryScope> {\n const copied = Object.freeze({ ...scope });\n if (copied.userId !== undefined) s.ownerId.parse(copied.userId);\n if (copied.sessionId !== undefined) s.sessionId.parse(copied.sessionId);\n if (copied.namespaceId !== undefined) s.id.parse(copied.namespaceId);\n if (copied.namespace !== undefined && !copied.namespace.trim()) throw new Error('scope.namespace must not be empty.');\n if (copied.namespace !== undefined && copied.namespaceId !== undefined) throw new Error('Choose scope.namespace or scope.namespaceId.');\n if (options.namespaceTools && copied.namespace !== undefined) throw new Error('Namespace resource tools cannot use a legacy namespace scope.');\n return copied;\n}\n\nexport function extendMemoryScope(\n scope: RedisAgentMemoryScope,\n context: RedisAgentMemoryScope,\n): RedisAgentMemoryScope {\n const extended = { ...scope };\n for (const name of ['userId', 'sessionId', 'namespace', 'namespaceId'] as const) {\n const value = context[name];\n if (value === undefined) continue;\n if (scope[name] !== undefined && scope[name] !== value) fail(`Cannot override ${name} scope.`);\n extended[name] = value;\n }\n return extended;\n}\n\n/**\n * Security boundary shared by tools, hooks, and the provider wrapper.\n * The client and validated scope are captured once and never exposed as enumerable state.\n */\nexport function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMemoryScope) {\n const scope = copyMemoryScope(inputScope);\n const hasResourceScope = Boolean(scope.userId || scope.namespace !== undefined || scope.namespaceId);\n\n const checkPlacement = (value: Placement) => {\n if (value.namespace !== undefined && value.namespaceRef !== undefined) fail('Supply namespace or namespaceRef, never both.');\n if (scope.namespace !== undefined && value.namespace !== scope.namespace) fail('Resource is outside the configured namespace.');\n if (scope.namespaceId !== undefined && value.namespaceRef?.namespaceId !== scope.namespaceId) {\n fail('Resource is outside the configured namespace resource.');\n }\n };\n\n const place = <T extends Placement>(input: T): T => {\n const value = { ...input };\n if (value.namespace !== undefined && value.namespaceRef !== undefined) fail('Supply namespace or namespaceRef, never both.');\n if (scope.namespace !== undefined) {\n if (value.namespaceRef || (value.namespace !== undefined && value.namespace !== scope.namespace)) fail('Cannot override namespace scope.');\n value.namespace = scope.namespace;\n }\n if (scope.namespaceId !== undefined) {\n if (value.namespace !== undefined || (value.namespaceRef && value.namespaceRef.namespaceId !== scope.namespaceId)) fail('Cannot override namespace scope.');\n value.namespaceRef = { namespaceId: scope.namespaceId };\n }\n return value;\n };\n\n const resolveSession = (value?: string) => {\n if (scope.sessionId && value && value !== scope.sessionId) fail('Cannot override session scope.');\n const resolved = value ?? scope.sessionId;\n if (!resolved) fail('Supply sessionId or configure scope.sessionId.');\n return resolved;\n };\n\n const resolveOwner = (value?: string) => {\n if (scope.userId && value && value !== scope.userId) fail('Cannot override user scope.');\n const resolved = value ?? scope.userId;\n if (!resolved) fail('Supply ownerId or configure scope.userId.');\n return resolved;\n };\n\n const assertSession = async (\n sessionId: string,\n options?: ScopedMemoryRequestOptions,\n validateSessionId = false,\n ) => {\n resolveSession(sessionId);\n const session = await client.getSessionMemory(sessionId, false, options);\n if (validateSessionId && session.sessionId !== sessionId) fail('Session response does not match the configured session scope.');\n if (scope.userId && session.ownerId !== scope.userId) fail('Session is outside the configured user scope.');\n checkPlacement(session);\n return session;\n };\n\n const restoreSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options);\n const restoreScopedSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options, true);\n\n const assertMemory = async (id: string, options?: ScopedMemoryRequestOptions) => {\n const memory = await client.getLongTermMemory(id, options);\n if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');\n checkPlacement(memory);\n return memory;\n };\n\n const assertPlacementOwner = async (value: Placement, options?: ScopedMemoryRequestOptions) => {\n if (!scope.userId || !value.namespaceRef) return;\n const signal = options?.signal ?? undefined;\n throwIfAborted(signal);\n const { namespace } = await client.getNamespace(value.namespaceRef.namespaceId, options);\n throwIfAborted(signal);\n const root = namespace.rootId === namespace.namespaceId ? namespace\n : (await client.getNamespace(namespace.rootId, options)).namespace;\n throwIfAborted(signal);\n if (root.scope !== 'PERSONAL' || root.ownerId !== scope.userId) {\n fail('Namespace placement is outside the configured user’s personal namespaces.');\n }\n };\n\n const scopeSearch = (input: SearchInput): SearchInput => {\n const filter: LongTermMemoryFilter = { ...input.filter };\n if (filter.namespace && filter.namespaceRef) fail('Supply namespace or namespaceRef, never both.');\n if (filter.unnamespaced !== undefined && (filter.namespace || filter.namespaceRef)) {\n fail('unnamespaced cannot be combined with namespace selectors.');\n }\n if (hasResourceScope && input.filterOp === 'any') fail('Scoped searches require filterOp all to preserve isolation.');\n const fixed = (name: 'ownerId' | 'namespace' | 'namespaceRef', value: string) => {\n const existing = filter[name];\n if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {\n fail(`Cannot override ${name} scope.`);\n }\n filter[name] = { eq: value };\n };\n if (scope.userId) fixed('ownerId', scope.userId);\n if (scope.namespace !== undefined || scope.namespaceId) {\n if (filter.unnamespaced !== undefined) fail('Cannot search unnamespaced records within a namespace scope.');\n if (scope.namespace !== undefined) {\n if (filter.namespaceRef) fail('Cannot override namespace scope.');\n fixed('namespace', scope.namespace);\n } else {\n if (filter.namespace) fail('Cannot override namespace scope.');\n fixed('namespaceRef', scope.namespaceId!);\n }\n }\n return { ...input, filter, filterOp: hasResourceScope ? 'all' : input.filterOp };\n };\n\n const searchLongTermMemory = (\n input: SearchInput,\n options?: ScopedMemoryRequestOptions,\n ) => client.searchLongTermMemory(scopeSearch(input), options);\n\n const searchPersonalMemories = async (\n text: string,\n limit: number,\n options?: ScopedMemoryRequestOptions,\n ) => {\n const result = await searchLongTermMemory({ text, limit }, options);\n for (const memory of result.items) {\n if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');\n checkPlacement(memory);\n }\n return result;\n };\n\n const appendSessionEvent = async (\n input: SessionEventInput,\n options: AppendSessionEventOptions = {},\n ) => {\n const {\n start = false, postflightNewSession = false, onPostStatus, validateResponse = false, ...requestOptions\n } = options;\n const requestSignal = requestOptions.signal ?? undefined;\n const placed = place(input);\n const sessionId = input.sessionId ?? scope.sessionId;\n let newSession = false;\n if (sessionId) {\n resolveSession(sessionId);\n if (hasResourceScope || start) {\n throwIfAborted(requestSignal);\n try {\n await assertSession(sessionId, requestOptions, validateResponse);\n throwIfAborted(requestSignal);\n if (start) fail('This session already exists; use add_session_event.');\n } catch (error) {\n if (memoryErrorStatus(error) !== 404) throw error;\n newSession = true;\n if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {\n fail('A new session must start with a USER event whose actorId is the configured userId.');\n }\n }\n }\n } else if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {\n fail('A new session must start with a USER event whose actorId is the configured userId.');\n }\n throwIfAborted(requestSignal);\n await assertPlacementOwner(placed, requestOptions);\n throwIfAborted(requestSignal);\n onPostStatus?.('started');\n const result = await client.addSessionEvent({\n ...placed,\n sessionId,\n createdAt: input.createdAt ? new Date(input.createdAt) : new Date(),\n }, requestOptions);\n onPostStatus?.('acknowledged');\n if (validateResponse && (\n result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role\n )) {\n fail('Saved event is outside the configured session or actor scope.');\n }\n throwIfAborted(requestSignal);\n if (postflightNewSession && newSession && sessionId) {\n await assertSession(sessionId, requestOptions, validateResponse);\n throwIfAborted(requestSignal);\n }\n return result;\n };\n\n return Object.freeze({\n scope,\n hasResourceScope,\n checkPlacement,\n place,\n resolveSession,\n resolveOwner,\n assertSession,\n restoreSession,\n restoreScopedSession,\n assertMemory,\n assertPlacementOwner,\n scopeSearch,\n searchLongTermMemory,\n searchPersonalMemories,\n appendSessionEvent,\n });\n}\n\nexport type ScopedMemory = ReturnType<typeof createScopedMemory>;\n"]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { z } from 'zod';
|
|
3
|
+
import { RedisAgentMemoryToolError } from './errors.js';
|
|
4
|
+
import * as s from './schemas.js';
|
|
5
|
+
type SessionRole = 'USER' | 'ASSISTANT';
|
|
6
|
+
type ObserverResult = void | PromiseLike<void>;
|
|
7
|
+
type SessionEventInput = z.infer<typeof s.event>;
|
|
8
|
+
interface SessionEventHookInputs {
|
|
9
|
+
USER: {
|
|
10
|
+
readonly messages: ReadonlyArray<ModelMessage>;
|
|
11
|
+
};
|
|
12
|
+
ASSISTANT: {
|
|
13
|
+
readonly finalStep: {
|
|
14
|
+
readonly text: string;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** USER hooks consume onStart messages; ASSISTANT hooks consume onEnd final text. */
|
|
19
|
+
export type SessionEventHookInput<Role extends SessionRole = SessionRole> = SessionEventHookInputs[Role];
|
|
20
|
+
export type SessionEventHook<Role extends SessionRole = SessionRole> = (event: SessionEventHookInput<Role>) => Promise<void>;
|
|
21
|
+
/** Identity of an event about to be written or confirmed saved. Contains no message text. */
|
|
22
|
+
export interface SessionHookEvent {
|
|
23
|
+
readonly sessionId: string;
|
|
24
|
+
readonly role: SessionRole;
|
|
25
|
+
readonly actorId: string;
|
|
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
|
+
export interface SessionEventHookOptions<Role extends SessionRole = SessionRole> {
|
|
33
|
+
/** Record one USER event in onStart or one ASSISTANT event in onEnd. */
|
|
34
|
+
role: Role;
|
|
35
|
+
/** Event author. For USER events, this must match the scoped userId. */
|
|
36
|
+
actorId: string;
|
|
37
|
+
/** Required because the AI SDK ignores exceptions thrown by lifecycle callbacks. */
|
|
38
|
+
onError: (error: RedisAgentMemoryToolError, context: SessionEventHookErrorContext) => ObserverResult;
|
|
39
|
+
/** Optional observers are awaited; observer errors never change which events are written. */
|
|
40
|
+
onEventStart?: (event: SessionHookEvent) => ObserverResult;
|
|
41
|
+
onEventSaved?: (event: SessionHookEvent) => ObserverResult;
|
|
42
|
+
}
|
|
43
|
+
/** Internal adapter. The writer retains the toolset's immutable scope and shared SDK client. */
|
|
44
|
+
export declare function createSessionEventHook<Role extends SessionRole>(scope: {
|
|
45
|
+
readonly userId?: string;
|
|
46
|
+
readonly sessionId?: string;
|
|
47
|
+
}, write: (event: SessionEventInput) => Promise<unknown>, options: SessionEventHookOptions<Role>): SessionEventHook<Role>;
|
|
48
|
+
export {};
|
|
49
|
+
//# sourceMappingURL=session-event-hook.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-event-hook.d.ts","sourceRoot":"","sources":["../src/session-event-hook.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AACvC,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAuB,MAAM,aAAa,CAAC;AAC7E,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAElC,KAAK,WAAW,GAAG,MAAM,GAAG,WAAW,CAAC;AACxC,KAAK,cAAc,GAAG,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;AAC/C,KAAK,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;AAEjD,UAAU,sBAAsB;IAC9B,IAAI,EAAE;QAAE,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC,YAAY,CAAC,CAAA;KAAE,CAAC;IACzD,SAAS,EAAE;QAAE,QAAQ,CAAC,SAAS,EAAE;YAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;CAC9D;AAED,qFAAqF;AACrF,MAAM,MAAM,qBAAqB,CAAC,IAAI,SAAS,WAAW,GAAG,WAAW,IAAI,sBAAsB,CAAC,IAAI,CAAC,CAAC;AAEzG,MAAM,MAAM,gBAA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}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';
|
|
2
|
+
import * as s from './schemas.js';
|
|
3
|
+
function invalidInput(message) {
|
|
4
|
+
throw new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', message);
|
|
5
|
+
}
|
|
6
|
+
function extractEvent(event, role, actorId) {
|
|
7
|
+
if (role === 'USER') {
|
|
8
|
+
if (!('messages' in event) || !Array.isArray(event.messages)) {
|
|
9
|
+
invalidInput('USER session recording requires messages from an onStart event.');
|
|
10
|
+
}
|
|
11
|
+
const messages = event.messages;
|
|
12
|
+
const user = messages.at(-1);
|
|
13
|
+
if (user?.role !== 'user')
|
|
14
|
+
invalidInput('Session recording requires the current final input message to have role user.');
|
|
15
|
+
const content = typeof user.content === 'string'
|
|
16
|
+
? [{ text: user.content }]
|
|
17
|
+
: user.content.flatMap(part => part.type === 'text' && part.text.length > 0 ? [{ text: part.text }] : []);
|
|
18
|
+
return s.event.parse({ actorId, role, content });
|
|
19
|
+
}
|
|
20
|
+
if (!('finalStep' in event) || typeof event.finalStep?.text !== 'string') {
|
|
21
|
+
invalidInput('ASSISTANT session recording requires finalStep.text from an onEnd event.');
|
|
22
|
+
}
|
|
23
|
+
if (event.finalStep.text.length === 0)
|
|
24
|
+
return undefined;
|
|
25
|
+
return s.event.parse({ actorId, role, content: [{ text: event.finalStep.text }] });
|
|
26
|
+
}
|
|
27
|
+
async function observe(callback) {
|
|
28
|
+
try {
|
|
29
|
+
await callback();
|
|
30
|
+
}
|
|
31
|
+
catch { /* Observers must not interrupt recording or cause a write to be retried. */ }
|
|
32
|
+
}
|
|
33
|
+
/** Internal adapter. The writer retains the toolset's immutable scope and shared SDK client. */
|
|
34
|
+
export function createSessionEventHook(scope, write, options) {
|
|
35
|
+
if (!scope.userId || !scope.sessionId) {
|
|
36
|
+
throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'createSessionEventHook requires scope.userId and scope.sessionId.');
|
|
37
|
+
}
|
|
38
|
+
if (typeof options?.onError !== 'function')
|
|
39
|
+
throw new Error('createSessionEventHook requires an onError callback.');
|
|
40
|
+
const { role, onError, onEventStart, onEventSaved } = options;
|
|
41
|
+
if (role !== 'USER' && role !== 'ASSISTANT')
|
|
42
|
+
throw new Error('createSessionEventHook requires role USER or ASSISTANT.');
|
|
43
|
+
const actorId = s.id.parse(options.actorId);
|
|
44
|
+
if (role === 'USER' && actorId !== scope.userId) {
|
|
45
|
+
throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');
|
|
46
|
+
}
|
|
47
|
+
for (const [name, observer] of [['onEventStart', onEventStart], ['onEventSaved', onEventSaved]]) {
|
|
48
|
+
if (observer !== undefined && typeof observer !== 'function')
|
|
49
|
+
throw new Error(`${name} must be a function.`);
|
|
50
|
+
}
|
|
51
|
+
const userId = scope.userId;
|
|
52
|
+
const info = Object.freeze({ sessionId: scope.sessionId, role, actorId });
|
|
53
|
+
return async (event) => {
|
|
54
|
+
let input;
|
|
55
|
+
try {
|
|
56
|
+
input = extractEvent(event, role, actorId);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const safeError = error instanceof RedisAgentMemoryToolError ? error
|
|
60
|
+
: 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.`);
|
|
61
|
+
await observe(() => onError(safeError, Object.freeze({ ...info, userId, phase: 'validation' })));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (!input)
|
|
65
|
+
return;
|
|
66
|
+
await observe(() => onEventStart?.(info));
|
|
67
|
+
try {
|
|
68
|
+
await write(input);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
await observe(() => onError(sanitizeMemoryError(error), Object.freeze({ ...info, userId, phase: 'write' })));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await observe(() => onEventSaved?.(info));
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=session-event-hook.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-event-hook.js","sourceRoot":"","sources":["../src/session-event-hook.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAyClC,SAAS,YAAY,CAAC,OAAe;IACnC,MAAM,IAAI,yBAAyB,CAAC,6BAA6B,EAAE,OAAO,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,YAAY,CACnB,KAA4B,EAC5B,IAAiB,EACjB,OAAe;IAEf,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC;QACpB,IAAI,CAAC,CAAC,UAAU,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7D,YAAY,CAAC,iEAAiE,CAAC,CAAC;QAClF,CAAC;QACD,MAAM,QAAQ,GAAgC,KAAK,CAAC,QAAQ,CAAC;QAC7D,MAAM,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,IAAI,EAAE,IAAI,KAAK,MAAM;YAAE,YAAY,CAAC,+EAA+E,CAAC,CAAC;QACzH,MAAM,OAAO,GAAG,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ;YAC9C,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC;YAC1B,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CA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,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC;YACjG,OAAO;QACT,CAAC;QACD,IAAI,CAAC,KAAK;YAAE,OAAO;QAEnB,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1C,IAAI,CAAC;YACH,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ModelMessage } from 'ai';\nimport type { z } from 'zod';\nimport { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';\nimport * as s from './schemas.js';\n\ntype SessionRole = 'USER' | 'ASSISTANT';\ntype ObserverResult = void | PromiseLike<void>;\ntype SessionEventInput = z.infer<typeof s.event>;\n\ninterface SessionEventHookInputs {\n USER: { readonly messages: ReadonlyArray<ModelMessage> };\n ASSISTANT: { readonly finalStep: { readonly text: string } };\n}\n\n/** USER hooks consume onStart messages; ASSISTANT hooks consume onEnd final text. */\nexport type SessionEventHookInput<Role extends SessionRole = SessionRole> = SessionEventHookInputs[Role];\n\nexport type SessionEventHook<Role extends SessionRole = SessionRole> = (event: SessionEventHookInput<Role>) => Promise<void>;\n\n/** Identity of an event about to be written or confirmed saved. Contains no message text. */\nexport interface SessionHookEvent {\n readonly sessionId: string;\n readonly role: SessionRole;\n readonly actorId: string;\n}\n\nexport interface SessionEventHookErrorContext extends SessionHookEvent {\n readonly userId: string;\n /** A failed write may have committed; verify before retrying. */\n readonly phase: 'validation' | 'write';\n}\n\nexport interface SessionEventHookOptions<Role extends SessionRole = SessionRole> {\n /** Record one USER event in onStart or one ASSISTANT event in onEnd. */\n role: Role;\n /** Event author. For USER events, this must match the scoped userId. */\n actorId: string;\n /** Required because the AI SDK ignores exceptions thrown by lifecycle callbacks. */\n onError: (error: RedisAgentMemoryToolError, context: SessionEventHookErrorContext) => ObserverResult;\n /** Optional observers are awaited; observer errors never change which events are written. */\n onEventStart?: (event: SessionHookEvent) => ObserverResult;\n onEventSaved?: (event: SessionHookEvent) => ObserverResult;\n}\n\nfunction invalidInput(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', message);\n}\n\nfunction extractEvent(\n event: SessionEventHookInput,\n role: SessionRole,\n actorId: string,\n): SessionEventInput | undefined {\n if (role === 'USER') {\n if (!('messages' in event) || !Array.isArray(event.messages)) {\n invalidInput('USER session recording requires messages from an onStart event.');\n }\n const messages: ReadonlyArray<ModelMessage> = event.messages;\n const user = messages.at(-1);\n if (user?.role !== 'user') invalidInput('Session recording requires the current final input message to have role user.');\n const content = typeof user.content === 'string'\n ? [{ text: user.content }]\n : user.content.flatMap(part => part.type === 'text' && part.text.length > 0 ? [{ text: part.text }] : []);\n return s.event.parse({ actorId, role, content });\n }\n if (!('finalStep' in event) || typeof event.finalStep?.text !== 'string') {\n invalidInput('ASSISTANT session recording requires finalStep.text from an onEnd event.');\n }\n if (event.finalStep.text.length === 0) return undefined;\n return s.event.parse({ actorId, role, content: [{ text: event.finalStep.text }] });\n}\n\nasync function observe(callback: () => ObserverResult): Promise<void> {\n try { await callback(); } catch { /* Observers must not interrupt recording or cause a write to be retried. */ }\n}\n\n/** Internal adapter. The writer retains the toolset's immutable scope and shared SDK client. */\nexport function createSessionEventHook<Role extends SessionRole>(\n scope: { readonly userId?: string; readonly sessionId?: string },\n write: (event: SessionEventInput) => Promise<unknown>,\n options: SessionEventHookOptions<Role>,\n): SessionEventHook<Role> {\n if (!scope.userId || !scope.sessionId) {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'createSessionEventHook requires scope.userId and scope.sessionId.');\n }\n if (typeof options?.onError !== 'function') throw new Error('createSessionEventHook requires an onError callback.');\n const { role, onError, onEventStart, onEventSaved } = options;\n if (role !== 'USER' && role !== 'ASSISTANT') throw new Error('createSessionEventHook requires role USER or ASSISTANT.');\n const actorId = s.id.parse(options.actorId);\n if (role === 'USER' && actorId !== scope.userId) {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');\n }\n for (const [name, observer] of [['onEventStart', onEventStart], ['onEventSaved', onEventSaved]] as const) {\n if (observer !== undefined && typeof observer !== 'function') throw new Error(`${name} must be a function.`);\n }\n const userId = scope.userId;\n const info: SessionHookEvent = Object.freeze({ sessionId: scope.sessionId, role, actorId });\n\n return async event => {\n let input: SessionEventInput | undefined;\n try {\n input = extractEvent(event, role, actorId);\n } catch (error) {\n const safeError = error instanceof RedisAgentMemoryToolError ? error\n : 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.`);\n await observe(() => onError(safeError, Object.freeze({ ...info, userId, phase: 'validation' })));\n return;\n }\n if (!input) return;\n\n await observe(() => onEventStart?.(info));\n try {\n await write(input);\n } catch (error) {\n await observe(() => onError(sanitizeMemoryError(error), Object.freeze({ ...info, userId, phase: 'write' })));\n return;\n }\n await observe(() => onEventSaved?.(info));\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,76 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@redis/vercel-ai-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AI SDK tools for Redis Agent Memory: session history, persistent memories, and semantic search",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/redis/vercel-ai-sdk.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/redis/vercel-ai-sdk#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/redis/vercel-ai-sdk/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"ai",
|
|
17
|
+
"ai-sdk",
|
|
18
|
+
"redis",
|
|
19
|
+
"agent-memory",
|
|
20
|
+
"memory",
|
|
21
|
+
"provider",
|
|
22
|
+
"tools",
|
|
23
|
+
"typescript",
|
|
24
|
+
"vercel"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22"
|
|
28
|
+
},
|
|
29
|
+
"main": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"import": "./dist/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"src/**/*.ts",
|
|
40
|
+
"README.md",
|
|
41
|
+
"TOOLS.md",
|
|
42
|
+
"LICENSE",
|
|
43
|
+
"CHANGELOG.md"
|
|
44
|
+
],
|
|
45
|
+
"sideEffects": false,
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public",
|
|
48
|
+
"registry": "https://registry.npmjs.org/"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
52
|
+
"build": "npm run clean && tsc -p tsconfig.build.json",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"test": "vitest run --dir test",
|
|
55
|
+
"test:watch": "vitest --dir test",
|
|
56
|
+
"check:package": "npm run build && node scripts/check-package.mjs",
|
|
57
|
+
"check": "npm run typecheck && npm test && npm run check:package",
|
|
58
|
+
"prepack": "npm run build",
|
|
59
|
+
"prepublishOnly": "npm run check"
|
|
60
|
+
},
|
|
61
|
+
"dependencies": {
|
|
62
|
+
"@redis-iris/agent-memory": "~0.3.1",
|
|
63
|
+
"@types/json-schema": "^7.0.15"
|
|
64
|
+
},
|
|
65
|
+
"peerDependencies": {
|
|
66
|
+
"ai": "^7.0.114",
|
|
67
|
+
"zod": "^4.1.8"
|
|
68
|
+
},
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"@types/node": "^22.20.4",
|
|
71
|
+
"ai": "^7.0.114",
|
|
72
|
+
"typescript": "~5.9.3",
|
|
73
|
+
"vitest": "^4.1.11",
|
|
74
|
+
"zod": "^4.6.5"
|
|
75
|
+
}
|
|
76
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Safe error details suitable for an AI SDK tool result. Never attach upstream bodies or headers. */
|
|
2
|
+
export class RedisAgentMemoryToolError extends Error {
|
|
3
|
+
constructor(public readonly code: string, message: string, public readonly statusCode?: number) {
|
|
4
|
+
super(message); this.name = 'IrisToolError';
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Share safe SDK error handling between model tools and application hooks. */
|
|
9
|
+
export function sanitizeMemoryError(error: unknown): RedisAgentMemoryToolError {
|
|
10
|
+
if (error instanceof RedisAgentMemoryToolError) return error;
|
|
11
|
+
const code = typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'
|
|
12
|
+
? error.statusCode : undefined;
|
|
13
|
+
return new RedisAgentMemoryToolError(code ? `IRIS_HTTP_${code}` : 'IRIS_REQUEST_FAILED',
|
|
14
|
+
code ? `Iris request failed (HTTP ${code}). Check service configuration and request scope. Writes may have partially succeeded; verify before retrying.`
|
|
15
|
+
: 'Iris request failed. Check connectivity and service configuration. Verify writes before retrying.', code);
|
|
16
|
+
}
|