@redis/vercel-ai-sdk 0.1.1 → 0.3.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 +47 -36
- package/README.md +13 -8
- package/TOOLS.md +264 -31
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +5 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +167 -33
- package/dist/index.js.map +1 -1
- package/dist/ingestion.d.ts +6 -0
- package/dist/ingestion.d.ts.map +1 -0
- package/dist/ingestion.js +148 -0
- package/dist/ingestion.js.map +1 -0
- package/dist/instructions.d.ts +1 -1
- package/dist/instructions.d.ts.map +1 -1
- package/dist/instructions.js +8 -4
- package/dist/instructions.js.map +1 -1
- package/dist/namespaces.d.ts +2 -0
- package/dist/namespaces.d.ts.map +1 -1
- package/dist/namespaces.js +70 -15
- package/dist/namespaces.js.map +1 -1
- package/dist/provider.js +2 -2
- package/dist/provider.js.map +1 -1
- package/dist/schemas.d.ts +32 -33
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +24 -11
- package/dist/schemas.js.map +1 -1
- package/dist/scoped-memory.d.ts +11 -9
- package/dist/scoped-memory.d.ts.map +1 -1
- package/dist/scoped-memory.js +80 -56
- package/dist/scoped-memory.js.map +1 -1
- package/dist/session-event-hook.js +1 -1
- package/dist/session-event-hook.js.map +1 -1
- package/dist/summary-views.d.ts +9 -0
- package/dist/summary-views.d.ts.map +1 -0
- package/dist/summary-views.js +276 -0
- package/dist/summary-views.js.map +1 -0
- package/package.json +2 -2
- package/src/errors.ts +6 -1
- package/src/index.ts +162 -33
- package/src/ingestion.ts +160 -0
- package/src/instructions.ts +8 -4
- package/src/namespaces.ts +81 -14
- package/src/provider.ts +2 -2
- package/src/schemas.ts +28 -11
- package/src/scoped-memory.ts +88 -48
- package/src/session-event-hook.ts +1 -1
- package/src/summary-views.ts +300 -0
package/dist/scoped-memory.js
CHANGED
|
@@ -20,7 +20,9 @@ export function resolveAgentMemoryClient(serverUrl, storeId, apiKey, timeoutMs =
|
|
|
20
20
|
throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');
|
|
21
21
|
if (!resolvedStoreId?.trim())
|
|
22
22
|
throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');
|
|
23
|
-
const serverURL = serverUrl ?? env.AGENT_MEMORY_URL
|
|
23
|
+
const serverURL = serverUrl ?? env.AGENT_MEMORY_URL;
|
|
24
|
+
if (!serverURL?.trim())
|
|
25
|
+
throw new Error('Set AGENT_MEMORY_URL or pass serverUrl; each store has its own endpoint URL.');
|
|
24
26
|
const url = new URL(serverURL);
|
|
25
27
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
26
28
|
throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');
|
|
@@ -29,7 +31,19 @@ export function resolveAgentMemoryClient(serverUrl, storeId, apiKey, timeoutMs =
|
|
|
29
31
|
throw new Error('timeoutMs must be positive.');
|
|
30
32
|
return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });
|
|
31
33
|
}
|
|
32
|
-
|
|
34
|
+
const SCOPE_KEYS = new Set(['userId', 'sessionId', 'namespaceId']);
|
|
35
|
+
/** Unknown keys would be ignored, silently dropping a boundary the caller meant to enforce. */
|
|
36
|
+
function assertKnownScopeKeys(scope, label) {
|
|
37
|
+
for (const key of Object.keys(scope)) {
|
|
38
|
+
if (SCOPE_KEYS.has(key))
|
|
39
|
+
continue;
|
|
40
|
+
throw new Error(key === 'namespace'
|
|
41
|
+
? `${label}.namespace was removed; use ${label}.namespaceId.`
|
|
42
|
+
: `Unknown ${label} field: ${key}.`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function copyMemoryScope(scope, _options = {}) {
|
|
46
|
+
assertKnownScopeKeys(scope, 'scope');
|
|
33
47
|
const copied = Object.freeze({ ...scope });
|
|
34
48
|
if (copied.userId !== undefined)
|
|
35
49
|
s.ownerId.parse(copied.userId);
|
|
@@ -37,17 +51,12 @@ export function copyMemoryScope(scope, options = {}) {
|
|
|
37
51
|
s.sessionId.parse(copied.sessionId);
|
|
38
52
|
if (copied.namespaceId !== undefined)
|
|
39
53
|
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
54
|
return copied;
|
|
47
55
|
}
|
|
48
56
|
export function extendMemoryScope(scope, context) {
|
|
57
|
+
assertKnownScopeKeys(context, 'context scope');
|
|
49
58
|
const extended = { ...scope };
|
|
50
|
-
for (const name of ['userId', 'sessionId', '
|
|
59
|
+
for (const name of ['userId', 'sessionId', 'namespaceId']) {
|
|
51
60
|
const value = context[name];
|
|
52
61
|
if (value === undefined)
|
|
53
62
|
continue;
|
|
@@ -63,31 +72,18 @@ export function extendMemoryScope(scope, context) {
|
|
|
63
72
|
*/
|
|
64
73
|
export function createScopedMemory(client, inputScope) {
|
|
65
74
|
const scope = copyMemoryScope(inputScope);
|
|
66
|
-
const hasResourceScope = Boolean(scope.userId || scope.
|
|
75
|
+
const hasResourceScope = Boolean(scope.userId || scope.namespaceId);
|
|
67
76
|
const checkPlacement = (value) => {
|
|
68
|
-
if (
|
|
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) {
|
|
77
|
+
if (scope.namespaceId !== undefined && value.namespaceId !== scope.namespaceId) {
|
|
73
78
|
fail('Resource is outside the configured namespace resource.');
|
|
74
79
|
}
|
|
75
80
|
};
|
|
76
81
|
const place = (input) => {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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;
|
|
82
|
+
if (scope.namespaceId === undefined)
|
|
83
|
+
return { ...input };
|
|
84
|
+
if (input.namespaceId !== undefined && input.namespaceId !== scope.namespaceId)
|
|
85
|
+
fail('Cannot override namespace scope.');
|
|
86
|
+
return { ...input, namespaceId: scope.namespaceId };
|
|
91
87
|
};
|
|
92
88
|
const resolveSession = (value) => {
|
|
93
89
|
if (scope.sessionId && value && value !== scope.sessionId)
|
|
@@ -125,11 +121,11 @@ export function createScopedMemory(client, inputScope) {
|
|
|
125
121
|
return memory;
|
|
126
122
|
};
|
|
127
123
|
const assertPlacementOwner = async (value, options) => {
|
|
128
|
-
if (!scope.userId || !value.
|
|
124
|
+
if (!scope.userId || !value.namespaceId)
|
|
129
125
|
return;
|
|
130
126
|
const signal = options?.signal ?? undefined;
|
|
131
127
|
throwIfAborted(signal);
|
|
132
|
-
const { namespace } = await client.getNamespace(value.
|
|
128
|
+
const { namespace } = await client.getNamespace(value.namespaceId, options);
|
|
133
129
|
throwIfAborted(signal);
|
|
134
130
|
const root = namespace.rootId === namespace.namespaceId ? namespace
|
|
135
131
|
: (await client.getNamespace(namespace.rootId, options)).namespace;
|
|
@@ -140,13 +136,11 @@ export function createScopedMemory(client, inputScope) {
|
|
|
140
136
|
};
|
|
141
137
|
const scopeSearch = (input) => {
|
|
142
138
|
const filter = { ...input.filter };
|
|
143
|
-
if (filter.
|
|
144
|
-
fail('Supply namespace or namespaceRef, never both.');
|
|
145
|
-
if (filter.unnamespaced !== undefined && (filter.namespace || filter.namespaceRef)) {
|
|
139
|
+
if (filter.unnamespaced !== undefined && filter.namespaceId) {
|
|
146
140
|
fail('unnamespaced cannot be combined with namespace selectors.');
|
|
147
141
|
}
|
|
148
|
-
if (hasResourceScope &&
|
|
149
|
-
fail('Scoped searches require
|
|
142
|
+
if (hasResourceScope && filter.op?.toUpperCase() === 'ANY')
|
|
143
|
+
fail('Scoped searches require filter.op ALL to preserve isolation.');
|
|
150
144
|
const fixed = (name, value) => {
|
|
151
145
|
const existing = filter[name];
|
|
152
146
|
if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {
|
|
@@ -156,25 +150,16 @@ export function createScopedMemory(client, inputScope) {
|
|
|
156
150
|
};
|
|
157
151
|
if (scope.userId)
|
|
158
152
|
fixed('ownerId', scope.userId);
|
|
159
|
-
if (scope.
|
|
153
|
+
if (scope.namespaceId) {
|
|
160
154
|
if (filter.unnamespaced !== undefined)
|
|
161
155
|
fail('Cannot search unnamespaced records within a namespace scope.');
|
|
162
|
-
|
|
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
|
-
}
|
|
156
|
+
fixed('namespaceId', scope.namespaceId);
|
|
172
157
|
}
|
|
173
|
-
return { ...input, filter
|
|
158
|
+
return { ...input, filter: hasResourceScope ? { ...filter, op: 'ALL' } : filter };
|
|
174
159
|
};
|
|
175
160
|
const searchLongTermMemory = (input, options) => client.searchLongTermMemory(scopeSearch(input), options);
|
|
176
161
|
const searchPersonalMemories = async (text, limit, options) => {
|
|
177
|
-
const result = await searchLongTermMemory({ text, limit }, options);
|
|
162
|
+
const result = await searchLongTermMemory({ query: text, limit }, options);
|
|
178
163
|
for (const memory of result.items) {
|
|
179
164
|
if (scope.userId && memory.ownerId !== scope.userId)
|
|
180
165
|
fail('Memory is outside the configured user scope.');
|
|
@@ -182,11 +167,40 @@ export function createScopedMemory(client, inputScope) {
|
|
|
182
167
|
}
|
|
183
168
|
return result;
|
|
184
169
|
};
|
|
170
|
+
async function scopeIdempotencyKey(key, ...target) {
|
|
171
|
+
if (key === undefined)
|
|
172
|
+
return undefined;
|
|
173
|
+
const input = new TextEncoder().encode(JSON.stringify([
|
|
174
|
+
key, scope.userId ?? null, scope.sessionId ?? null, scope.namespaceId ?? null, target,
|
|
175
|
+
]));
|
|
176
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));
|
|
177
|
+
return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
178
|
+
}
|
|
179
|
+
const findStartEvent = async (sessionId, input, options) => {
|
|
180
|
+
const { events, namespaceId } = await client.getSessionMemory(sessionId, true, options);
|
|
181
|
+
if (input.namespaceId !== undefined && namespaceId !== input.namespaceId) {
|
|
182
|
+
fail('This session already exists in a different namespace than requested; use add_session_event.');
|
|
183
|
+
}
|
|
184
|
+
// createdAt is caller-supplied and a later append may be backdated; systemTimestamp is the store's own clock.
|
|
185
|
+
// The store gives events no creation marker, so every event tied for the earliest clock reading is a candidate.
|
|
186
|
+
const earliest = Math.min(...events.map(event => event.systemTimestamp.getTime()));
|
|
187
|
+
const sameText = (event) => event.content.length === input.content.length
|
|
188
|
+
&& event.content.every((part, index) => part.text === input.content[index].text);
|
|
189
|
+
return events.find(event => event.systemTimestamp.getTime() === earliest
|
|
190
|
+
&& event.actorId === input.actorId && event.role === input.role && sameText(event)
|
|
191
|
+
&& (input.createdAt === undefined || event.createdAt.getTime() === Date.parse(input.createdAt)));
|
|
192
|
+
};
|
|
185
193
|
const appendSessionEvent = async (input, options = {}) => {
|
|
186
194
|
const { start = false, postflightNewSession = false, onPostStatus, validateResponse = false, ...requestOptions } = options;
|
|
187
195
|
const requestSignal = requestOptions.signal ?? undefined;
|
|
188
196
|
const placed = place(input);
|
|
189
197
|
const sessionId = input.sessionId ?? scope.sessionId;
|
|
198
|
+
if (start && input.idempotencyKey !== undefined) {
|
|
199
|
+
if (!sessionId)
|
|
200
|
+
fail('A keyed start_session needs a sessionId, so a retry can find the session it created.');
|
|
201
|
+
if (input.createdAt === undefined)
|
|
202
|
+
fail('A keyed start_session needs createdAt, so a retry sends the identical request.');
|
|
203
|
+
}
|
|
190
204
|
let newSession = false;
|
|
191
205
|
if (sessionId) {
|
|
192
206
|
resolveSession(sessionId);
|
|
@@ -195,8 +209,15 @@ export function createScopedMemory(client, inputScope) {
|
|
|
195
209
|
try {
|
|
196
210
|
await assertSession(sessionId, requestOptions, validateResponse);
|
|
197
211
|
throwIfAborted(requestSignal);
|
|
198
|
-
if (start)
|
|
199
|
-
|
|
212
|
+
if (start) {
|
|
213
|
+
if (!input.idempotencyKey)
|
|
214
|
+
fail('This session already exists; use add_session_event.');
|
|
215
|
+
// The store answers a repeated createSession with 409 even for the same key, so the replay happens here.
|
|
216
|
+
const first = await findStartEvent(sessionId, input, requestOptions);
|
|
217
|
+
if (!first)
|
|
218
|
+
fail('This session already exists and its first event differs from this request; use add_session_event.');
|
|
219
|
+
return { event: first };
|
|
220
|
+
}
|
|
200
221
|
}
|
|
201
222
|
catch (error) {
|
|
202
223
|
if (memoryErrorStatus(error) !== 404)
|
|
@@ -215,11 +236,13 @@ export function createScopedMemory(client, inputScope) {
|
|
|
215
236
|
await assertPlacementOwner(placed, requestOptions);
|
|
216
237
|
throwIfAborted(requestSignal);
|
|
217
238
|
onPostStatus?.('started');
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
239
|
+
const { sessionId: _sessionId, ...eventFields } = placed;
|
|
240
|
+
const idempotencyKey = await scopeIdempotencyKey(input.idempotencyKey, sessionId ?? '');
|
|
241
|
+
const body = { ...eventFields, idempotencyKey, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };
|
|
242
|
+
// createSession refuses an existing ID with 409; addSessionEvent appends and creates a missing session.
|
|
243
|
+
const result = sessionId && !start
|
|
244
|
+
? await client.addSessionEvent(sessionId, body, requestOptions)
|
|
245
|
+
: await client.createSession({ ...body, sessionId }, requestOptions);
|
|
223
246
|
onPostStatus?.('acknowledged');
|
|
224
247
|
if (validateResponse && (result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role)) {
|
|
225
248
|
fail('Saved event is outside the configured session or actor scope.');
|
|
@@ -246,6 +269,7 @@ export function createScopedMemory(client, inputScope) {
|
|
|
246
269
|
scopeSearch,
|
|
247
270
|
searchLongTermMemory,
|
|
248
271
|
searchPersonalMemories,
|
|
272
|
+
scopeIdempotencyKey,
|
|
249
273
|
appendSessionEvent,
|
|
250
274
|
});
|
|
251
275
|
}
|
|
@@ -1 +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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,EAAE,cAAc,CAAC,CAAC;QACnB,YAAY,EAAE,CAAC,cAAc,CAAC,CAAC;QAC/B,IAAI,gBAAgB,IAAI,CACtB,MAAM,CAAC,KAAK,CAAC,SAAS,KAAK,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"]}
|
|
1
|
+
{"version":3,"file":"sc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tB,MAAM,CAAC,KAAK,CAAC,SAAS,KAAK,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,mBAAmB;QACnB,kBAAkB;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter, SessionEvent } 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 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 = { namespaceId?: string };\n\nexport interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {\n /** Create the session. An existing one is refused unless the request is keyed and matches its first event. */\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;\n if (!serverURL?.trim()) throw new Error('Set AGENT_MEMORY_URL or pass serverUrl; each store has its own endpoint URL.');\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\nconst SCOPE_KEYS: ReadonlySet<string> = new Set(['userId', 'sessionId', 'namespaceId']);\n\n/** Unknown keys would be ignored, silently dropping a boundary the caller meant to enforce. */\nfunction assertKnownScopeKeys(scope: object, label: string): void {\n for (const key of Object.keys(scope)) {\n if (SCOPE_KEYS.has(key)) continue;\n throw new Error(key === 'namespace'\n ? `${label}.namespace was removed; use ${label}.namespaceId.`\n : `Unknown ${label} field: ${key}.`);\n }\n}\n\nexport function copyMemoryScope(\n scope: RedisAgentMemoryScope,\n _options: ScopeValidationOptions = {},\n): Readonly<RedisAgentMemoryScope> {\n assertKnownScopeKeys(scope, 'scope');\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 return copied;\n}\n\nexport function extendMemoryScope(\n scope: RedisAgentMemoryScope,\n context: RedisAgentMemoryScope,\n): RedisAgentMemoryScope {\n assertKnownScopeKeys(context, 'context scope');\n const extended = { ...scope };\n for (const name of ['userId', 'sessionId', '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.namespaceId);\n\n const checkPlacement = (value: Placement) => {\n if (scope.namespaceId !== undefined && value.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 if (scope.namespaceId === undefined) return { ...input };\n if (input.namespaceId !== undefined && input.namespaceId !== scope.namespaceId) fail('Cannot override namespace scope.');\n return { ...input, namespaceId: scope.namespaceId };\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.namespaceId) return;\n const signal = options?.signal ?? undefined;\n throwIfAborted(signal);\n const { namespace } = await client.getNamespace(value.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.unnamespaced !== undefined && filter.namespaceId) {\n fail('unnamespaced cannot be combined with namespace selectors.');\n }\n if (hasResourceScope && filter.op?.toUpperCase() === 'ANY') fail('Scoped searches require filter.op ALL to preserve isolation.');\n const fixed = (name: 'ownerId' | 'namespaceId', 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.namespaceId) {\n if (filter.unnamespaced !== undefined) fail('Cannot search unnamespaced records within a namespace scope.');\n fixed('namespaceId', scope.namespaceId);\n }\n return { ...input, filter: hasResourceScope ? { ...filter, op: 'ALL' } : filter };\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({ query: 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 /**\n * The store treats an idempotency key as store-wide, so two users whose models both pick a generic key would collide.\n * Hashing the fixed scope and the request target into the key keeps retries identical and isolates everyone else.\n */\n function scopeIdempotencyKey(key: string, ...target: string[]): Promise<string>;\n function scopeIdempotencyKey(key: string | undefined, ...target: string[]): Promise<string | undefined>;\n async function scopeIdempotencyKey(key: string | undefined, ...target: string[]) {\n if (key === undefined) return undefined;\n const input = new TextEncoder().encode(JSON.stringify([\n key, scope.userId ?? null, scope.sessionId ?? null, scope.namespaceId ?? null, target,\n ]));\n const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));\n return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');\n }\n\n const findStartEvent = async (\n sessionId: string,\n input: SessionEventInput,\n options: ScopedMemoryRequestOptions,\n ) => {\n const { events, namespaceId } = await client.getSessionMemory(sessionId, true, options);\n if (input.namespaceId !== undefined && namespaceId !== input.namespaceId) {\n fail('This session already exists in a different namespace than requested; use add_session_event.');\n }\n // createdAt is caller-supplied and a later append may be backdated; systemTimestamp is the store's own clock.\n // The store gives events no creation marker, so every event tied for the earliest clock reading is a candidate.\n const earliest = Math.min(...events.map(event => event.systemTimestamp.getTime()));\n const sameText = (event: SessionEvent) => event.content.length === input.content.length\n && event.content.every((part, index) => part.text === input.content[index]!.text);\n return events.find(event => event.systemTimestamp.getTime() === earliest\n && event.actorId === input.actorId && event.role === input.role && sameText(event)\n && (input.createdAt === undefined || event.createdAt.getTime() === Date.parse(input.createdAt)));\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 if (start && input.idempotencyKey !== undefined) {\n if (!sessionId) fail('A keyed start_session needs a sessionId, so a retry can find the session it created.');\n if (input.createdAt === undefined) fail('A keyed start_session needs createdAt, so a retry sends the identical request.');\n }\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) {\n if (!input.idempotencyKey) fail('This session already exists; use add_session_event.');\n // The store answers a repeated createSession with 409 even for the same key, so the replay happens here.\n const first = await findStartEvent(sessionId, input, requestOptions);\n if (!first) fail('This session already exists and its first event differs from this request; use add_session_event.');\n return { event: first };\n }\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 { sessionId: _sessionId, ...eventFields } = placed;\n const idempotencyKey = await scopeIdempotencyKey(input.idempotencyKey, sessionId ?? '');\n const body = { ...eventFields, idempotencyKey, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };\n // createSession refuses an existing ID with 409; addSessionEvent appends and creates a missing session.\n const result = sessionId && !start\n ? await client.addSessionEvent(sessionId, body, requestOptions)\n : await client.createSession({ ...body, sessionId }, 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 scopeIdempotencyKey,\n appendSessionEvent,\n });\n}\n\nexport type ScopedMemory = ReturnType<typeof createScopedMemory>;\n"]}
|
|
@@ -40,7 +40,7 @@ export function createSessionEventHook(scope, write, options) {
|
|
|
40
40
|
const { role, onError, onEventStart, onEventSaved } = options;
|
|
41
41
|
if (role !== 'USER' && role !== 'ASSISTANT')
|
|
42
42
|
throw new Error('createSessionEventHook requires role USER or ASSISTANT.');
|
|
43
|
-
const actorId = s.
|
|
43
|
+
const actorId = s.actorId.parse(options.actorId);
|
|
44
44
|
if (role === 'USER' && actorId !== scope.userId) {
|
|
45
45
|
throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');
|
|
46
46
|
}
|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,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.actorId.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"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ToolSet } from 'ai';
|
|
2
|
+
import type { AgentMemory } from '@redis-iris/agent-memory';
|
|
3
|
+
import type { ScopedMemory } from './scoped-memory.js';
|
|
4
|
+
export interface SummaryViewToolOptions {
|
|
5
|
+
allowDeletes: boolean;
|
|
6
|
+
}
|
|
7
|
+
/** Optional Summary View tools. Scoped toolsets only reach views whose partitions they can prove are theirs. */
|
|
8
|
+
export declare function createSummaryViewTools(client: AgentMemory, ctx: ScopedMemory, options: SummaryViewToolOptions): ToolSet;
|
|
9
|
+
//# sourceMappingURL=summary-views.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"summary-views.d.ts","sourceRoot":"","sources":["../src/summary-views.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,IAAI,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAK5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,OAAO,CAAC;CACvB;AA2DD,gHAAgH;AAChH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,WAAW,EACnB,GAAG,EAAE,YAAY,EACjB,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAiOT"}
|