@redis/vercel-ai-sdk 0.2.0 → 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.
Files changed (49) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +8 -2
  3. package/TOOLS.md +256 -22
  4. package/dist/errors.d.ts.map +1 -1
  5. package/dist/errors.js +5 -1
  6. package/dist/errors.js.map +1 -1
  7. package/dist/index.d.ts +7 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +159 -29
  10. package/dist/index.js.map +1 -1
  11. package/dist/ingestion.d.ts +6 -0
  12. package/dist/ingestion.d.ts.map +1 -0
  13. package/dist/ingestion.js +148 -0
  14. package/dist/ingestion.js.map +1 -0
  15. package/dist/instructions.d.ts +1 -1
  16. package/dist/instructions.d.ts.map +1 -1
  17. package/dist/instructions.js +6 -2
  18. package/dist/instructions.js.map +1 -1
  19. package/dist/namespaces.d.ts +2 -0
  20. package/dist/namespaces.d.ts.map +1 -1
  21. package/dist/namespaces.js +64 -9
  22. package/dist/namespaces.js.map +1 -1
  23. package/dist/provider.js +1 -1
  24. package/dist/provider.js.map +1 -1
  25. package/dist/schemas.d.ts +20 -0
  26. package/dist/schemas.d.ts.map +1 -1
  27. package/dist/schemas.js +18 -4
  28. package/dist/schemas.js.map +1 -1
  29. package/dist/scoped-memory.d.ts +9 -2
  30. package/dist/scoped-memory.d.ts.map +1 -1
  31. package/dist/scoped-memory.js +41 -3
  32. package/dist/scoped-memory.js.map +1 -1
  33. package/dist/session-event-hook.js +1 -1
  34. package/dist/session-event-hook.js.map +1 -1
  35. package/dist/summary-views.d.ts +9 -0
  36. package/dist/summary-views.d.ts.map +1 -0
  37. package/dist/summary-views.js +276 -0
  38. package/dist/summary-views.js.map +1 -0
  39. package/package.json +1 -1
  40. package/src/errors.ts +6 -1
  41. package/src/index.ts +151 -28
  42. package/src/ingestion.ts +160 -0
  43. package/src/instructions.ts +6 -2
  44. package/src/namespaces.ts +74 -7
  45. package/src/provider.ts +1 -1
  46. package/src/schemas.ts +22 -4
  47. package/src/scoped-memory.ts +50 -4
  48. package/src/session-event-hook.ts +1 -1
  49. package/src/summary-views.ts +300 -0
package/dist/index.js CHANGED
@@ -2,13 +2,24 @@ import { tool } from 'ai';
2
2
  import { z } from 'zod';
3
3
  import * as s from './schemas.js';
4
4
  import { createNamespaceTools } from './namespaces.js';
5
+ import { createIngestionTools } from './ingestion.js';
6
+ import { createSummaryViewTools } from './summary-views.js';
5
7
  import { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';
6
8
  import { createSessionEventHook } from './session-event-hook.js';
7
- import { copyMemoryScope, createScopedMemory, extendMemoryScope, resolveAgentMemoryClient, } from './scoped-memory.js';
9
+ import { copyMemoryScope, createScopedMemory, extendMemoryScope, memoryErrorStatus, resolveAgentMemoryClient, } from './scoped-memory.js';
8
10
  import { assertConfiguredLanguageModel, createRedisAgentMemoryModel, } from './provider.js';
9
11
  export { instructions } from './instructions.js';
10
12
  export { RedisAgentMemoryToolError } from './errors.js';
11
13
  function fail(message) { throw new RedisAgentMemoryToolError('INVALID_SCOPE', message); }
14
+ /**
15
+ * A replayed idempotent batch must carry the same memory IDs, or the server rejects it as a different request.
16
+ * Deriving them from the scoped request key keeps their uniqueness scope equal to the key's.
17
+ */
18
+ async function retryStableMemoryId(scopedKey, index) {
19
+ const input = new TextEncoder().encode(JSON.stringify([scopedKey, index]));
20
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));
21
+ return Array.from(digest.subarray(0, 16), byte => byte.toString(16).padStart(2, '0')).join('');
22
+ }
12
23
  function buildTools(client, scope, options) {
13
24
  const deletes = options.allowDeletes ?? false;
14
25
  const scoped = createScopedMemory(client, scope);
@@ -29,12 +40,16 @@ function buildTools(client, scope, options) {
29
40
  }),
30
41
  }),
31
42
  start_session: tool({
32
- description: 'Start a conversation with the user’s first event. Redis Agent Memory generates and returns a session ID when none is provided. Retain the returned ID.',
33
- inputSchema: z.object({ sessionId: s.sessionId.optional(), actorId: s.id, text: s.text, ...s.placement }),
43
+ description: 'Start a conversation with the user’s first event. Redis Agent Memory generates and returns a session ID when none is provided. Retain the returned ID. Fails when the named session already exists. With idempotencyKey, supply sessionId and createdAt too; a retry whose actorId, text, and createdAt match the session’s first event returns that event instead.',
44
+ inputSchema: z.object({
45
+ sessionId: s.sessionId.optional(), actorId: s.actorId, text: s.text,
46
+ createdAt: s.timestamp.optional().describe('ISO 8601 timestamp; defaults to the current time. Required with idempotencyKey, so a retry sends the identical request.'),
47
+ idempotencyKey: s.sessionIdempotencyKey.optional(), ...s.placement,
48
+ }),
34
49
  execute: (input, { abortSignal }) => append({ ...input, role: 'USER', content: [{ text: input.text }] }, abortSignal, true),
35
50
  }),
36
51
  add_session_event: tool({
37
- description: 'Append a USER, ASSISTANT, or SYSTEM event. Reuse the conversation’s sessionId. actorId is the author. Do not duplicate application logging or blindly retry an uncertain append.',
52
+ description: 'Append a USER, ASSISTANT, or SYSTEM event. Reuse the conversation’s sessionId. actorId is the author. Do not duplicate application logging. The store may not deduplicate appends by idempotencyKey, so after an uncertain append read get_session_memory before retrying.',
38
53
  inputSchema: s.event, execute: (input, { abortSignal }) => append(input, abortSignal),
39
54
  }),
40
55
  get_session_event: tool({
@@ -58,42 +73,56 @@ function buildTools(client, scope, options) {
58
73
  },
59
74
  }),
60
75
  list_sessions: tool({
61
- description: 'List sessions for an owner, with pagination, within any fixed namespace scope. Unscoped callers must explicitly request includeAll to list the whole store.',
62
- inputSchema: z.object({ ownerId: s.ownerId.optional(), includeAll: z.boolean().optional(), ...s.page,
63
- limit: z.number().int().min(1).max(1000).optional() }),
76
+ description: 'List sessions for an owner or a namespace, with pagination, within any fixed scope. Unscoped callers must explicitly request includeAll to list the whole store. Sort by sessionId, createdAt, or updatedAt.',
77
+ inputSchema: z.object({
78
+ ownerId: s.ownerId.optional(), namespaceId: s.id.optional().describe('Only sessions placed in this namespace.'),
79
+ includeAll: z.boolean().optional(), ...s.page, limit: z.number().int().min(1).max(1000).optional(),
80
+ sortBy: z.enum(['sessionId', 'createdAt', 'updatedAt']).optional(), sortOrder: s.sortOrder.optional(),
81
+ }),
64
82
  execute: async (input, { abortSignal }) => {
83
+ const { namespaceId } = place({ namespaceId: input.namespaceId });
65
84
  if (scope.sessionId) {
66
85
  if (input.ownerId && scope.userId && input.ownerId !== scope.userId)
67
86
  fail('Cannot override user scope.');
68
87
  const session = await assertSession(scope.sessionId, abortSignal);
88
+ if (input.ownerId && session.ownerId !== input.ownerId)
89
+ return { items: [] };
90
+ if (namespaceId && session.namespaceId !== namespaceId)
91
+ return { items: [] };
69
92
  return { items: [{ sessionId: session.sessionId, ownerId: session.ownerId, namespaceId: session.namespaceId }] };
70
93
  }
71
- if (input.includeAll && (scope.userId || scope.namespaceId || input.ownerId)) {
72
- fail('includeAll cannot be combined with a user or namespace scope, or ownerId.');
94
+ if (input.includeAll && (scope.userId || namespaceId || input.ownerId)) {
95
+ fail('includeAll cannot be combined with a user or namespace scope, ownerId, or namespaceId.');
73
96
  }
74
97
  const owner = input.ownerId || scope.userId;
75
- if (!owner && !scope.namespaceId && !input.includeAll)
76
- fail('Supply ownerId or explicitly set includeAll: true.');
98
+ if (!owner && !namespaceId && !input.includeAll)
99
+ fail('Supply ownerId or namespaceId, or explicitly set includeAll: true.');
77
100
  if (owner)
78
101
  resolveOwner(owner);
79
- // The service rejects includeAll alongside any filter, so a namespace scope stands in for it.
80
- const filtered = owner || scope.namespaceId;
81
- const result = await client.listSessions(input.limit, input.cursor, owner, filtered ? undefined : true, { signal: abortSignal }, scope.namespaceId);
102
+ // The service rejects includeAll alongside any filter, so a namespace filter stands in for it.
103
+ const filtered = owner || namespaceId;
104
+ const result = await client.listSessions(input.limit, input.cursor, owner, filtered ? undefined : true, { signal: abortSignal }, namespaceId, input.sortBy, input.sortOrder);
82
105
  for (const item of result.items)
83
106
  checkPlacement(item);
84
107
  return result;
85
108
  },
86
109
  }),
87
110
  create_memories: tool({
88
- description: 'Create up to 100 durable memories in one batch. UUIDs are generated automatically; do not supply IDs. Use the user ID as ownerId; fixed scope.userId supplies it automatically. Returned memoryIds match input order; created and errors report outcomes. New calls generate new IDs, so reconcile uncertain writes before retrying.',
89
- inputSchema: z.object({ memories: z.array(s.memory).min(1).max(100) }),
90
- execute: async ({ memories }, { abortSignal }) => {
91
- const records = memories.map(memory => {
111
+ description: 'Create up to 100 durable memories in one batch. IDs are generated automatically; do not supply them. Use the user ID as ownerId; fixed scope.userId supplies it automatically. created and errors report per-record outcomes. Without idempotencyKey each call generates new IDs and memoryIds lists them all in input order, so reconcile uncertain writes before retrying. With idempotencyKey, a retry of the identical request replays the saved result with the same IDs, and memoryIds stays aligned with the input, holding null for a record the service rejected; that record also appears in errors.',
112
+ inputSchema: z.object({ memories: z.array(s.memory).min(1).max(100), idempotencyKey: s.idempotencyKey.optional() }),
113
+ execute: async ({ memories, idempotencyKey }, { abortSignal }) => {
114
+ const placed = memories.map(memory => {
92
115
  const sessionId = memory.sessionId ?? scope.sessionId;
93
116
  if (scope.sessionId && sessionId !== scope.sessionId)
94
117
  fail('Cannot override session association.');
95
- return { ...place(memory), memoryId: globalThis.crypto.randomUUID(), ownerId: resolveOwner(memory.ownerId), sessionId };
118
+ return { ...place(memory), ownerId: resolveOwner(memory.ownerId), sessionId };
96
119
  });
120
+ const owners = [...new Set(placed.map(record => record.ownerId))].sort();
121
+ const scopedKey = await scoped.scopeIdempotencyKey(idempotencyKey, ...owners);
122
+ const records = await Promise.all(placed.map(async (record, index) => ({
123
+ ...record,
124
+ memoryId: scopedKey === undefined ? globalThis.crypto.randomUUID() : await retryStableMemoryId(scopedKey, index),
125
+ })));
97
126
  const checkedNamespaces = new Set();
98
127
  for (const record of records) {
99
128
  const namespaceId = record.namespaceId;
@@ -102,27 +131,42 @@ function buildTools(client, scope, options) {
102
131
  checkedNamespaces.add(namespaceId);
103
132
  }
104
133
  }
105
- const result = await client.bulkCreateLongTermMemories({ memories: records }, { signal: abortSignal });
106
- return { ...result, memoryIds: records.map(record => record.memoryId) };
134
+ const result = await client.bulkCreateLongTermMemories({
135
+ memories: records, idempotencyKey: scopedKey,
136
+ }, { signal: abortSignal });
137
+ const all = records.map(record => record.memoryId);
138
+ if (idempotencyKey === undefined)
139
+ return { ...result, memoryIds: all };
140
+ // Keyed IDs are guessable, so another owner may already hold one; never hand back an ID the service did not create.
141
+ // Nulls keep each position tied to its input record, since an error names only the rejected ID.
142
+ const created = new Set(result.created);
143
+ return { ...result, memoryIds: all.map(id => created.has(id) ? id : null) };
107
144
  },
108
145
  }),
109
146
  get_memory: tool({
110
- description: 'Get a long-term memory by ID within the configured scope.', inputSchema: z.object({ memoryId: s.id }),
147
+ description: 'Get a long-term memory by ID within the configured scope. The record carries its revision, its first source links, and documentManaged when document ingestion produced it.',
148
+ inputSchema: z.object({ memoryId: s.id }),
111
149
  execute: ({ memoryId }, { abortSignal }) => assertMemory(memoryId, abortSignal),
112
150
  }),
113
151
  search_memories: tool({
114
- description: 'Search durable memories semantically or list with filters. Results are items plus optional nextCursor. Recall spans conversations. Scoped searches require filter.op ALL.',
152
+ description: 'Search durable memories semantically with query, or list them with filters only. Results are items plus optional nextCursor. Recall spans conversations. Scoped searches require filter.op ALL. sortBy and sortOrder order a filter-only listing and cannot be combined with query.',
115
153
  inputSchema: s.search,
116
154
  execute: async (input, { abortSignal }) => {
155
+ if (input.query !== undefined && (input.sortBy !== undefined || input.sortOrder !== undefined)) {
156
+ throw new RedisAgentMemoryToolError('INVALID_INPUT', 'sortBy and sortOrder apply only to filter-only listing. Omit query to sort.');
157
+ }
117
158
  const filter = { ...input.filter, createdAt: input.filter?.createdAt
118
159
  ? Object.fromEntries(Object.entries(input.filter.createdAt).filter(([, v]) => v !== undefined).map(([k, v]) => [k, new Date(v)])) : undefined };
119
160
  return scoped.searchLongTermMemory({ ...input, filter }, { signal: abortSignal });
120
161
  },
121
162
  }),
122
163
  update_memory: tool({
123
- description: 'Correct a memory’s text or organization. Supply at least one change. Custom attributes are supplied at creation; custom extraction-worker updates are outside this toolset.',
124
- inputSchema: z.object({ memoryId: s.id, changes: s.memoryUpdate }),
125
- execute: async ({ memoryId, changes }, { abortSignal }) => {
164
+ description: 'Partially correct a memory’s text or organization. Supply at least one change; omitted fields stay unchanged. Document-managed memories accept only namespace changes. Use update_memory_fields for custom attributes or upsert_memory for a full replacement.',
165
+ inputSchema: z.object({
166
+ memoryId: s.id, changes: s.memoryUpdate,
167
+ expectedRevision: s.expectedRevision.optional(), idempotencyKey: s.idempotencyKey.optional(),
168
+ }),
169
+ execute: async ({ memoryId, changes, expectedRevision, idempotencyKey }, { abortSignal }) => {
126
170
  if (!Object.values(changes).some(v => v !== undefined))
127
171
  fail('Supply at least one change.');
128
172
  if (hasResourceScope)
@@ -133,14 +177,92 @@ function buildTools(client, scope, options) {
133
177
  fail('Cannot override session association.');
134
178
  const placed = place(changes);
135
179
  await assertPlacementOwner(placed, abortSignal);
136
- return client.updateLongTermMemory(memoryId, placed, { signal: abortSignal });
180
+ return client.updateLongTermMemory(memoryId, {
181
+ ...placed, expectedRevision, idempotencyKey: await scoped.scopeIdempotencyKey(idempotencyKey, memoryId),
182
+ }, { signal: abortSignal });
183
+ },
184
+ }),
185
+ upsert_memory: tool({
186
+ description: 'Create or fully replace one manually managed memory by ID, including custom attributes. Omitted optional fields are cleared and memoryType defaults to semantic. Read the memory first and send every field to keep. Pass expectedRevision to guard against concurrent changes. Document-managed memories cannot be replaced.',
187
+ inputSchema: s.memory.extend({
188
+ memoryId: s.memoryId.describe('ID of the memory to replace, or a new ID to create one.'),
189
+ expectedRevision: s.expectedRevision.optional(), idempotencyKey: s.idempotencyKey.optional(),
190
+ }),
191
+ execute: async ({ memoryId, ...input }, { abortSignal }) => {
192
+ if (hasResourceScope) {
193
+ try {
194
+ await assertMemory(memoryId, abortSignal);
195
+ }
196
+ catch (error) {
197
+ if (memoryErrorStatus(error) !== 404)
198
+ throw error;
199
+ }
200
+ }
201
+ const sessionId = input.sessionId ?? scope.sessionId;
202
+ if (scope.sessionId && sessionId !== scope.sessionId)
203
+ fail('Cannot override session association.');
204
+ const placed = { ...place(input), ownerId: resolveOwner(input.ownerId), sessionId };
205
+ await assertPlacementOwner(placed, abortSignal);
206
+ return client.upsertLongTermMemory(memoryId, {
207
+ ...placed, idempotencyKey: await scoped.scopeIdempotencyKey(input.idempotencyKey, memoryId),
208
+ }, { signal: abortSignal });
209
+ },
210
+ }),
211
+ update_memory_fields: tool({
212
+ description: 'Atomically update the text and/or attributes of a custom-typed memory. memoryType must match the stored type. Pass the memory’s current namespaceId; omitting it asserts the memory has no namespace.',
213
+ inputSchema: z.object({
214
+ memoryId: s.id, memoryType: z.string().min(1).describe('The stored custom memory type.'),
215
+ text: s.text.optional(), attributes: s.attributes.optional().describe('Field name to value, matching the custom type’s declared fields.'),
216
+ expectedRevision: s.expectedRevision.optional(), idempotencyKey: s.idempotencyKey.optional(), ...s.placement,
217
+ }),
218
+ execute: async ({ memoryId, ...input }, { abortSignal }) => {
219
+ if (input.text === undefined && input.attributes === undefined)
220
+ fail('Supply text or attributes.');
221
+ if (hasResourceScope)
222
+ await assertMemory(memoryId, abortSignal);
223
+ const placed = place(input);
224
+ await assertPlacementOwner(placed, abortSignal);
225
+ await client.updateLongTermMemoryFields(memoryId, {
226
+ ...placed, idempotencyKey: await scoped.scopeIdempotencyKey(input.idempotencyKey, memoryId),
227
+ }, { signal: abortSignal });
228
+ return { updated: true, memoryId };
229
+ },
230
+ }),
231
+ list_memory_sources: tool({
232
+ description: 'List where a memory came from: document revisions or sessions, with their first evidence. Follow nextCursor for more links.',
233
+ inputSchema: z.object({ memoryId: s.id, ...s.page }),
234
+ execute: async ({ memoryId, limit, cursor }, { abortSignal }) => {
235
+ if (hasResourceScope)
236
+ await assertMemory(memoryId, abortSignal);
237
+ return client.listMemorySourceLinks(memoryId, limit, cursor, { signal: abortSignal });
238
+ },
239
+ }),
240
+ list_memory_source_evidence: tool({
241
+ description: 'Page the extraction evidence for one source of a memory: document chunks or the session event IDs supplied to extraction. Evidence attributes input, not cited facts. Get sourceId from list_memory_sources.',
242
+ inputSchema: z.object({ memoryId: s.id, sourceId: s.id, ...s.page }),
243
+ execute: async ({ memoryId, sourceId, limit, cursor }, { abortSignal }) => {
244
+ if (hasResourceScope)
245
+ await assertMemory(memoryId, abortSignal);
246
+ return client.listMemorySourceEvidence(memoryId, sourceId, limit, cursor, { signal: abortSignal });
247
+ },
248
+ }),
249
+ list_source_memories: tool({
250
+ description: 'List one owner’s memories derived from a source. Get sourceId from list_memory_sources. Follow nextCursor for more. Memories outside a fixed namespace scope are omitted.',
251
+ inputSchema: z.object({ sourceId: s.id, ownerId: s.ownerId.optional(), ...s.page }),
252
+ execute: async ({ sourceId, ownerId, limit, cursor }, { abortSignal }) => {
253
+ const owner = resolveOwner(ownerId);
254
+ const result = await client.listSourceMemories(sourceId, owner, limit, cursor, { signal: abortSignal });
255
+ if (result.items.some(item => item.ownerId !== owner))
256
+ fail('Memory is outside the requested owner.');
257
+ return scope.namespaceId === undefined ? result
258
+ : { ...result, items: result.items.filter(item => item.namespaceId === scope.namespaceId) };
137
259
  },
138
260
  }),
139
261
  };
140
262
  if (deletes)
141
263
  Object.assign(tools, {
142
264
  delete_memories: tool({
143
- description: 'Delete 1–100 long-term memories by ID. Use for explicit forget requests. Inspect deleted and per-record errors.',
265
+ description: 'Delete 1 to 100 long-term memories by ID. Use for explicit forget requests. Inspect deleted and per-record errors before claiming success.',
144
266
  inputSchema: z.object({ memoryIds: z.array(s.id).min(1).max(100) }),
145
267
  execute: async ({ memoryIds }, { abortSignal }) => {
146
268
  if (hasResourceScope)
@@ -172,8 +294,13 @@ function buildTools(client, scope, options) {
172
294
  });
173
295
  if (options.namespaceTools)
174
296
  Object.assign(tools, createNamespaceTools(client, {
175
- ownerId: scope.userId, namespaceId: scope.namespaceId, allowDeletes: deletes, assertMemory,
297
+ ownerId: scope.userId, namespaceId: scope.namespaceId, allowDeletes: deletes,
298
+ allowRoutingWrites: options.routingPolicyWrites === true, assertMemory,
176
299
  }));
300
+ if (options.ingestionTools)
301
+ Object.assign(tools, createIngestionTools(client, scoped));
302
+ if (options.summaryViewTools)
303
+ Object.assign(tools, createSummaryViewTools(client, scoped, { allowDeletes: deletes }));
177
304
  // Errors from the generated SDK may contain response bodies and headers. Never expose these to the model.
178
305
  for (const entry of Object.values(tools)) {
179
306
  const execute = entry.execute;
@@ -211,6 +338,9 @@ export function createRedisAgentMemory(input) {
211
338
  const toolOptions = Object.freeze({
212
339
  allowDeletes: options.allowDeletes,
213
340
  namespaceTools: options.namespaceTools,
341
+ routingPolicyWrites: options.routingPolicyWrites,
342
+ ingestionTools: options.ingestionTools,
343
+ summaryViewTools: options.summaryViewTools,
214
344
  timeoutMs: options.timeoutMs,
215
345
  });
216
346
  let client;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAgB,MAAM,IAAI,CAAC;AACxC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAuD,MAAM,yBAAyB,CAAC;AACtH,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,wBAAwB,GAEzB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,GAI5B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AA8CxD,SAAS,IAAI,CAAC,OAAe,IAAW,MAAM,IAAI,yBAAyB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K,CAAC,OAAO,CAAC,CAAC,CAAC,yDAAyD,CACnG,CAAC;IACJ,CAAC;IACD,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC;IACnC,MAAM,MAAM,GAAG;QACb,KAAK,CAAC,cAA4C,EAAE;YAClD,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,KAAK,SAAS;gBAC3C,CAAC,CAAC,YAAY;gBACd,CAAC,CAAC,eAAe,CAAC,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;YACpD,OAAO,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;QAChD,CAAC;QACD,KAAK,CAAC,cAA4C,EAAE;YAClD,MAAM,aAAa,GAAG,WAAW,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;YACzF,6BAA6B,CAAC,aAAa,CAAC,CAAC;YAC7C,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,KAAK,SAAS;gBAC3C,CAAC,CAAC,YAAY;gBACd,CAAC,CAAC,eAAe,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YACvC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,cAAc,EAAE,GAAG,WAAW,CAAC;YACzD,OAAO,2BAA2B,CAAC,MAAM,EAAE,aAAa,EAAE,EAAE,GAAG,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1F,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAmC,CAAC;AACjE,CAAC","sourcesContent":["import type { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter } from '@redis-iris/agent-memory/models';\nimport { tool, type ToolSet } from 'ai';\nimport { z } from 'zod';\nimport * as s from './schemas.js';\nimport { createNamespaceTools } from './namespaces.js';\nimport { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';\nimport { createSessionEventHook, type SessionEventHook, type SessionEventHookOptions } from './session-event-hook.js';\nimport {\n copyMemoryScope,\n createScopedMemory,\n extendMemoryScope,\n resolveAgentMemoryClient,\n type RedisAgentMemoryScope,\n} from './scoped-memory.js';\nimport {\n assertConfiguredLanguageModel,\n createRedisAgentMemoryModel,\n type ConfiguredLanguageModel,\n type RedisAgentMemoryModel,\n type RedisAgentMemoryModelOptions,\n} from './provider.js';\nexport { instructions } from './instructions.js';\nexport { RedisAgentMemoryToolError } from './errors.js';\nexport type {\n ConfiguredLanguageModel,\n RedisAgentMemoryDiagnostic, RedisAgentMemoryDiagnosticError,\n RedisAgentMemoryLimits, RedisAgentMemoryModel, RedisAgentMemoryModelOptions,\n RedisAgentMemoryProvenance, RedisAgentMemoryProvenanceEntry,\n} from './provider.js';\nexport type {\n SessionEventHook, SessionEventHookInput, SessionEventHookOptions,\n SessionHookEvent, SessionEventHookErrorContext,\n} from './session-event-hook.js';\nexport type { RedisAgentMemoryScope } from './scoped-memory.js';\ninterface RedisAgentMemoryToolOptions {\n /** Expose deletion tools. Defaults to false. */\n allowDeletes?: boolean;\n /** Expose namespace administration tools. Defaults to false. */\n namespaceTools?: boolean;\n /** HTTP request timeout in milliseconds. Defaults to 30,000. Must be positive and finite. */\n timeoutMs?: number;\n}\n\ninterface RedisAgentMemoryBaseOptions extends RedisAgentMemoryToolOptions {\n serverUrl?: string;\n storeId?: string;\n apiKey?: string;\n /** Overridable default. Derive scopes and overrides from trusted, authenticated application state. */\n scope?: RedisAgentMemoryScope;\n}\n\nexport type RedisAgentMemoryOptions<DefaultModel extends ConfiguredLanguageModel | undefined = undefined> =\n RedisAgentMemoryBaseOptions & (undefined extends DefaultModel\n ? { /** Optional configured AI SDK model default. Model-name strings are not accepted. */ model?: DefaultModel }\n : { /** Configured AI SDK model default. Model-name strings are not accepted. */ model: DefaultModel });\n\nexport interface RedisAgentMemoryToolsOptions {\n /** Replaces the entire factory default scope when supplied. */\n scope?: RedisAgentMemoryScope;\n}\n\n/** A tool map with non-enumerable helpers for scoping and application session recording. */\nexport type RedisAgentMemoryTools = ToolSet & {\n readonly withContext: (scope: RedisAgentMemoryScope) => RedisAgentMemoryTools;\n /** Record USER text in onStart or ASSISTANT text in onEnd. Requires fixed userId/sessionId. */\n readonly createSessionEventHook: <Role extends SessionEventHookOptions['role']>(options: SessionEventHookOptions<Role>) => SessionEventHook<Role>;\n};\n\nfunction fail(message: string): never { throw new RedisAgentMemoryToolError('INVALID_SCOPE', message); }\n\nfunction buildTools(\n client: AgentMemory,\n scope: Readonly<RedisAgentMemoryScope>,\n options: Readonly<RedisAgentMemoryToolOptions>,\n): RedisAgentMemoryTools {\n const deletes = options.allowDeletes ?? false;\n const scoped = createScopedMemory(client, scope);\n const {\n place, resolveSession, resolveOwner, checkPlacement, hasResourceScope,\n } = scoped;\n const assertSession = (sessionId: string, signal?: AbortSignal) => scoped.assertSession(sessionId, { signal });\n const assertMemory = (id: string, signal?: AbortSignal) => scoped.assertMemory(id, { signal });\n const assertPlacementOwner = (value: { namespaceId?: string }, signal?: AbortSignal) => (\n scoped.assertPlacementOwner(value, { signal })\n );\n const append = (input: z.infer<typeof s.event>, signal?: AbortSignal, start = false) => (\n scoped.appendSessionEvent(input, { signal, start })\n );\n const sessionInput = z.object({ sessionId: s.sessionId.optional() });\n const eventInput = sessionInput.extend({ eventId: s.id });\n const tools: ToolSet = {\n get_memory_context: tool({\n description: 'Get fixed memory scope and identity rules before using memory. Contains no credentials.',\n inputSchema: z.object({}), execute: async () => ({ ...scope, allowDeletes: deletes,\n userIdentityRule: 'Use userId as ownerId for the user’s memories and actorId for USER events. ASSISTANT events use the agent’s actorId.',\n sessionOwnerRule: 'The first event actor becomes the immutable session owner. Start with the user.',\n longTermRecall: 'Search spans sessions unless an explicit session filter is supplied.',\n }),\n }),\n start_session: tool({\n description: 'Start a conversation with the user’s first event. Redis Agent Memory generates and returns a session ID when none is provided. Retain the returned ID.',\n inputSchema: z.object({ sessionId: s.sessionId.optional(), actorId: s.id, text: s.text, ...s.placement }),\n execute: (input, { abortSignal }) => append({ ...input, role: 'USER', content: [{ text: input.text }] }, abortSignal, true),\n }),\n add_session_event: tool({\n description: 'Append a USER, ASSISTANT, or SYSTEM event. Reuse the conversation’s sessionId. actorId is the author. Do not duplicate application logging or blindly retry an uncertain append.',\n inputSchema: s.event, execute: (input, { abortSignal }) => append(input, abortSignal),\n }),\n get_session_event: tool({\n description: 'Get one event by sessionId and eventId.', inputSchema: eventInput,\n execute: async (input, { abortSignal }) => {\n const sessionId = resolveSession(input.sessionId);\n if (hasResourceScope) await assertSession(sessionId, abortSignal);\n return client.getSessionEvent(sessionId, input.eventId, { signal: abortSignal });\n },\n }),\n get_session_memory: tool({\n description: 'Get conversation events and its latest summary. Include summarized events only when full older history is needed.',\n inputSchema: sessionInput.extend({ includeSummarisedEvents: z.boolean().optional() }),\n execute: async (input, { abortSignal }) => {\n const result = await client.getSessionMemory(resolveSession(input.sessionId), input.includeSummarisedEvents, { signal: abortSignal });\n if (scope.userId && result.ownerId !== scope.userId) fail('Session is outside the configured user scope.');\n checkPlacement(result); return result;\n },\n }),\n list_sessions: tool({\n description: 'List sessions for an owner, with pagination, within any fixed namespace scope. Unscoped callers must explicitly request includeAll to list the whole store.',\n inputSchema: z.object({ ownerId: s.ownerId.optional(), includeAll: z.boolean().optional(), ...s.page,\n limit: z.number().int().min(1).max(1000).optional() }),\n execute: async (input, { abortSignal }) => {\n if (scope.sessionId) {\n if (input.ownerId && scope.userId && input.ownerId !== scope.userId) fail('Cannot override user scope.');\n const session = await assertSession(scope.sessionId, abortSignal);\n return { items: [{ sessionId: session.sessionId, ownerId: session.ownerId, namespaceId: session.namespaceId }] };\n }\n if (input.includeAll && (scope.userId || scope.namespaceId || input.ownerId)) {\n fail('includeAll cannot be combined with a user or namespace scope, or ownerId.');\n }\n const owner = input.ownerId || scope.userId;\n if (!owner && !scope.namespaceId && !input.includeAll) fail('Supply ownerId or explicitly set includeAll: true.');\n if (owner) resolveOwner(owner);\n // The service rejects includeAll alongside any filter, so a namespace scope stands in for it.\n const filtered = owner || scope.namespaceId;\n const result = await client.listSessions(\n input.limit, input.cursor, owner, filtered ? undefined : true, { signal: abortSignal }, scope.namespaceId,\n );\n for (const item of result.items) checkPlacement(item);\n return result;\n },\n }),\n create_memories: tool({\n description: 'Create up to 100 durable memories in one batch. UUIDs are generated automatically; do not supply IDs. Use the user ID as ownerId; fixed scope.userId supplies it automatically. Returned memoryIds match input order; created and errors report outcomes. New calls generate new IDs, so reconcile uncertain writes before retrying.',\n inputSchema: z.object({ memories: z.array(s.memory).min(1).max(100) }),\n execute: async ({ memories }, { abortSignal }) => {\n const records = memories.map(memory => {\n const sessionId = memory.sessionId ?? scope.sessionId;\n if (scope.sessionId && sessionId !== scope.sessionId) fail('Cannot override session association.');\n return { ...place(memory), memoryId: globalThis.crypto.randomUUID(), ownerId: resolveOwner(memory.ownerId), sessionId };\n });\n const checkedNamespaces = new Set<string>();\n for (const record of records) {\n const namespaceId = record.namespaceId;\n if (namespaceId && !checkedNamespaces.has(namespaceId)) {\n await assertPlacementOwner(record, abortSignal);\n checkedNamespaces.add(namespaceId);\n }\n }\n const result = await client.bulkCreateLongTermMemories({ memories: records }, { signal: abortSignal });\n return { ...result, memoryIds: records.map(record => record.memoryId) };\n },\n }),\n get_memory: tool({\n description: 'Get a long-term memory by ID within the configured scope.', inputSchema: z.object({ memoryId: s.id }),\n execute: ({ memoryId }, { abortSignal }) => assertMemory(memoryId, abortSignal),\n }),\n search_memories: tool({\n description: 'Search durable memories semantically or list with filters. Results are items plus optional nextCursor. Recall spans conversations. Scoped searches require filter.op ALL.',\n inputSchema: s.search,\n execute: async (input, { abortSignal }) => {\n const filter: LongTermMemoryFilter = { ...input.filter, createdAt: input.filter?.createdAt\n ? Object.fromEntries(Object.entries(input.filter.createdAt).filter(([,v]) => v !== undefined).map(([k,v]) => [k, new Date(v!)])) : undefined };\n return scoped.searchLongTermMemory({ ...input, filter }, { signal: abortSignal });\n },\n }),\n update_memory: tool({\n description: 'Correct a memory’s text or organization. Supply at least one change. Custom attributes are supplied at creation; custom extraction-worker updates are outside this toolset.',\n inputSchema: z.object({ memoryId: s.id, changes: s.memoryUpdate }),\n execute: async ({ memoryId, changes }, { abortSignal }) => {\n if (!Object.values(changes).some(v => v !== undefined)) fail('Supply at least one change.');\n if (hasResourceScope) await assertMemory(memoryId, abortSignal);\n if (changes.ownerId !== undefined) resolveOwner(changes.ownerId);\n if (scope.sessionId && changes.sessionId !== undefined && changes.sessionId !== scope.sessionId) fail('Cannot override session association.');\n const placed = place(changes);\n await assertPlacementOwner(placed, abortSignal);\n return client.updateLongTermMemory(memoryId, placed, { signal: abortSignal });\n },\n }),\n };\n if (deletes) Object.assign(tools, {\n delete_memories: tool({\n description: 'Delete 1–100 long-term memories by ID. Use for explicit forget requests. Inspect deleted and per-record errors.',\n inputSchema: z.object({ memoryIds: z.array(s.id).min(1).max(100) }),\n execute: async ({ memoryIds }, { abortSignal }) => {\n if (hasResourceScope) for (const id of memoryIds) await assertMemory(id, abortSignal);\n return client.bulkDeleteLongTermMemories({ memoryIds }, { signal: abortSignal });\n },\n }),\n delete_session_event: tool({\n description: 'Delete one event. Previously promoted long-term memories remain and must be deleted separately.', inputSchema: eventInput,\n execute: async (input, { abortSignal }) => {\n const sessionId = resolveSession(input.sessionId);\n if (hasResourceScope) await assertSession(sessionId, abortSignal);\n await client.deleteSessionEvent(sessionId, input.eventId, { signal: abortSignal });\n return { deleted: true, sessionId, eventId: input.eventId };\n },\n }),\n delete_session_memory: tool({\n description: 'Delete a conversation’s session memory. This does not delete promoted long-term memories.', inputSchema: sessionInput,\n execute: async (input, { abortSignal }) => {\n const sessionId = resolveSession(input.sessionId);\n if (hasResourceScope) await assertSession(sessionId, abortSignal);\n await client.deleteSessionMemory(sessionId, { signal: abortSignal });\n return { deleted: true, sessionId };\n },\n }),\n });\n if (options.namespaceTools) Object.assign(tools, createNamespaceTools(client, {\n ownerId: scope.userId, namespaceId: scope.namespaceId, allowDeletes: deletes, assertMemory,\n }));\n // Errors from the generated SDK may contain response bodies and headers. Never expose these to the model.\n for (const entry of Object.values(tools)) {\n const execute = entry.execute!;\n entry.execute = async (input, execution) => {\n try { return await execute(input, execution); }\n catch (error) {\n if (execution.abortSignal?.aborted) throw new DOMException('Memory operation aborted.', 'AbortError');\n throw sanitizeMemoryError(error);\n }\n };\n }\n // Keep application helpers out of AI SDK tool enumeration and object spreads.\n Object.defineProperties(tools, {\n withContext: {\n value: (context: RedisAgentMemoryScope) => buildTools(\n client,\n copyMemoryScope(extendMemoryScope(scope, context), options),\n options,\n ),\n },\n createSessionEventHook: {\n value: (hookOptions: SessionEventHookOptions) => createSessionEventHook(scope, append, hookOptions),\n },\n });\n return tools as RedisAgentMemoryTools;\n}\n\ntype ModelCallWithDefault = (options?: RedisAgentMemoryModelOptions) => RedisAgentMemoryModel;\ntype ModelCallWithoutDefault = (\n options: RedisAgentMemoryModelOptions & { model: ConfiguredLanguageModel },\n) => RedisAgentMemoryModel;\n\nexport type RedisAgentMemory<DefaultModel extends ConfiguredLanguageModel | undefined = undefined> = Readonly<{\n tools: (options?: RedisAgentMemoryToolsOptions) => RedisAgentMemoryTools;\n model: undefined extends DefaultModel ? ModelCallWithoutDefault : ModelCallWithDefault;\n}>;\n\n/**\n * Create one immutable Redis Agent Memory factory and share its Iris client across tools and request models.\n * Each `model()` call returns fresh request-local state and must be reused only within one application request.\n */\nexport function createRedisAgentMemory<DefaultModel extends ConfiguredLanguageModel | undefined = undefined>(\n input: RedisAgentMemoryOptions<DefaultModel>,\n): RedisAgentMemory<DefaultModel> {\n const options = Object.freeze({ ...input });\n if (options.model !== undefined) assertConfiguredLanguageModel(options.model);\n const defaultScope = copyMemoryScope(options.scope ?? {}, options);\n const toolOptions: Readonly<RedisAgentMemoryToolOptions> = Object.freeze({\n allowDeletes: options.allowDeletes,\n namespaceTools: options.namespaceTools,\n timeoutMs: options.timeoutMs,\n });\n let client: ReturnType<typeof resolveAgentMemoryClient>;\n try {\n client = resolveAgentMemoryClient(\n options.serverUrl,\n options.storeId,\n options.apiKey,\n options.timeoutMs ?? 30_000,\n );\n } catch (error) {\n throw new RedisAgentMemoryToolError(\n 'INVALID_CONFIGURATION',\n error instanceof Error ? error.message : 'Redis Agent Memory connection configuration is invalid.',\n );\n }\n const defaultModel = options.model;\n const memory = {\n tools(callOptions: RedisAgentMemoryToolsOptions = {}) {\n const scope = callOptions.scope === undefined\n ? defaultScope\n : copyMemoryScope(callOptions.scope, toolOptions);\n return buildTools(client, scope, toolOptions);\n },\n model(callOptions: RedisAgentMemoryModelOptions = {}) {\n const selectedModel = callOptions.model === undefined ? defaultModel : callOptions.model;\n assertConfiguredLanguageModel(selectedModel);\n const scope = callOptions.scope === undefined\n ? defaultScope\n : copyMemoryScope(callOptions.scope);\n const { model: _model, ...requestOptions } = callOptions;\n return createRedisAgentMemoryModel(client, selectedModel, { ...requestOptions, scope });\n },\n };\n return Object.freeze(memory) as RedisAgentMemory<DefaultModel>;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAgB,MAAM,IAAI,CAAC;AACxC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAuD,MAAM,yBAAyB,CAAC;AACtH,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,GAEzB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,6BAA6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CAAC,KAAK,CAAC;YACzF,6BAA6B,CAAC,aAAa,CAAC,CAAC;YAC7C,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,KAAK,SAAS;gBAC3C,CAAC,CAAC,YAAY;gBACd,CAAC,CAAC,eAAe,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YACvC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,cAAc,EAAE,GAAG,WAAW,CAAC;YACzD,OAAO,2BAA2B,CAAC,MAAM,EAAE,aAAa,EAAE,EAAE,GAAG,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1F,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAmC,CAAC;AACjE,CAAC","sourcesContent":["import type { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter } from '@redis-iris/agent-memory/models';\nimport { tool, type ToolSet } from 'ai';\nimport { z } from 'zod';\nimport * as s from './schemas.js';\nimport { createNamespaceTools } from './namespaces.js';\nimport { createIngestionTools } from './ingestion.js';\nimport { createSummaryViewTools } from './summary-views.js';\nimport { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';\nimport { createSessionEventHook, type SessionEventHook, type SessionEventHookOptions } from './session-event-hook.js';\nimport {\n copyMemoryScope,\n createScopedMemory,\n extendMemoryScope,\n memoryErrorStatus,\n resolveAgentMemoryClient,\n type RedisAgentMemoryScope,\n} from './scoped-memory.js';\nimport {\n assertConfiguredLanguageModel,\n createRedisAgentMemoryModel,\n type ConfiguredLanguageModel,\n type RedisAgentMemoryModel,\n type RedisAgentMemoryModelOptions,\n} from './provider.js';\nexport { instructions } from './instructions.js';\nexport { RedisAgentMemoryToolError } from './errors.js';\nexport type {\n ConfiguredLanguageModel,\n RedisAgentMemoryDiagnostic, RedisAgentMemoryDiagnosticError,\n RedisAgentMemoryLimits, RedisAgentMemoryModel, RedisAgentMemoryModelOptions,\n RedisAgentMemoryProvenance, RedisAgentMemoryProvenanceEntry,\n} from './provider.js';\nexport type {\n SessionEventHook, SessionEventHookInput, SessionEventHookOptions,\n SessionHookEvent, SessionEventHookErrorContext,\n} from './session-event-hook.js';\nexport type { RedisAgentMemoryScope } from './scoped-memory.js';\ninterface RedisAgentMemoryToolOptions {\n /** Expose deletion tools. Defaults to false. */\n allowDeletes?: boolean;\n /** Expose namespace administration and store-wide routing tools. Defaults to false. */\n namespaceTools?: boolean;\n /** With namespaceTools, also expose put_namespace_routing, which replaces the store-wide routing policy. Defaults to false. */\n routingPolicyWrites?: boolean;\n /** Expose document ingestion and ingestion hook status tools. Defaults to false. */\n ingestionTools?: boolean;\n /** Expose Summary View tools. Defaults to false. */\n summaryViewTools?: boolean;\n /** HTTP request timeout in milliseconds. Defaults to 30,000. Must be positive and finite. */\n timeoutMs?: number;\n}\n\ninterface RedisAgentMemoryBaseOptions extends RedisAgentMemoryToolOptions {\n serverUrl?: string;\n storeId?: string;\n apiKey?: string;\n /** Overridable default. Derive scopes and overrides from trusted, authenticated application state. */\n scope?: RedisAgentMemoryScope;\n}\n\nexport type RedisAgentMemoryOptions<DefaultModel extends ConfiguredLanguageModel | undefined = undefined> =\n RedisAgentMemoryBaseOptions & (undefined extends DefaultModel\n ? { /** Optional configured AI SDK model default. Model-name strings are not accepted. */ model?: DefaultModel }\n : { /** Configured AI SDK model default. Model-name strings are not accepted. */ model: DefaultModel });\n\nexport interface RedisAgentMemoryToolsOptions {\n /** Replaces the entire factory default scope when supplied. */\n scope?: RedisAgentMemoryScope;\n}\n\n/** A tool map with non-enumerable helpers for scoping and application session recording. */\nexport type RedisAgentMemoryTools = ToolSet & {\n readonly withContext: (scope: RedisAgentMemoryScope) => RedisAgentMemoryTools;\n /** Record USER text in onStart or ASSISTANT text in onEnd. Requires fixed userId/sessionId. */\n readonly createSessionEventHook: <Role extends SessionEventHookOptions['role']>(options: SessionEventHookOptions<Role>) => SessionEventHook<Role>;\n};\n\nfunction fail(message: string): never { throw new RedisAgentMemoryToolError('INVALID_SCOPE', message); }\n\n/**\n * A replayed idempotent batch must carry the same memory IDs, or the server rejects it as a different request.\n * Deriving them from the scoped request key keeps their uniqueness scope equal to the key's.\n */\nasync function retryStableMemoryId(scopedKey: string, index: number): Promise<string> {\n const input = new TextEncoder().encode(JSON.stringify([scopedKey, index]));\n const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));\n return Array.from(digest.subarray(0, 16), byte => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction buildTools(\n client: AgentMemory,\n scope: Readonly<RedisAgentMemoryScope>,\n options: Readonly<RedisAgentMemoryToolOptions>,\n): RedisAgentMemoryTools {\n const deletes = options.allowDeletes ?? false;\n const scoped = createScopedMemory(client, scope);\n const {\n place, resolveSession, resolveOwner, checkPlacement, hasResourceScope,\n } = scoped;\n const assertSession = (sessionId: string, signal?: AbortSignal) => scoped.assertSession(sessionId, { signal });\n const assertMemory = (id: string, signal?: AbortSignal) => scoped.assertMemory(id, { signal });\n const assertPlacementOwner = (value: { namespaceId?: string }, signal?: AbortSignal) => (\n scoped.assertPlacementOwner(value, { signal })\n );\n const append = (input: z.infer<typeof s.event>, signal?: AbortSignal, start = false) => (\n scoped.appendSessionEvent(input, { signal, start })\n );\n const sessionInput = z.object({ sessionId: s.sessionId.optional() });\n const eventInput = sessionInput.extend({ eventId: s.id });\n const tools: ToolSet = {\n get_memory_context: tool({\n description: 'Get fixed memory scope and identity rules before using memory. Contains no credentials.',\n inputSchema: z.object({}), execute: async () => ({ ...scope, allowDeletes: deletes,\n userIdentityRule: 'Use userId as ownerId for the user’s memories and actorId for USER events. ASSISTANT events use the agent’s actorId.',\n sessionOwnerRule: 'The first event actor becomes the immutable session owner. Start with the user.',\n longTermRecall: 'Search spans sessions unless an explicit session filter is supplied.',\n }),\n }),\n start_session: tool({\n description: 'Start a conversation with the user’s first event. Redis Agent Memory generates and returns a session ID when none is provided. Retain the returned ID. Fails when the named session already exists. With idempotencyKey, supply sessionId and createdAt too; a retry whose actorId, text, and createdAt match the session’s first event returns that event instead.',\n inputSchema: z.object({\n sessionId: s.sessionId.optional(), actorId: s.actorId, text: s.text,\n createdAt: s.timestamp.optional().describe('ISO 8601 timestamp; defaults to the current time. Required with idempotencyKey, so a retry sends the identical request.'),\n idempotencyKey: s.sessionIdempotencyKey.optional(), ...s.placement,\n }),\n execute: (input, { abortSignal }) => append({ ...input, role: 'USER', content: [{ text: input.text }] }, abortSignal, true),\n }),\n add_session_event: tool({\n description: 'Append a USER, ASSISTANT, or SYSTEM event. Reuse the conversation’s sessionId. actorId is the author. Do not duplicate application logging. The store may not deduplicate appends by idempotencyKey, so after an uncertain append read get_session_memory before retrying.',\n inputSchema: s.event, execute: (input, { abortSignal }) => append(input, abortSignal),\n }),\n get_session_event: tool({\n description: 'Get one event by sessionId and eventId.', inputSchema: eventInput,\n execute: async (input, { abortSignal }) => {\n const sessionId = resolveSession(input.sessionId);\n if (hasResourceScope) await assertSession(sessionId, abortSignal);\n return client.getSessionEvent(sessionId, input.eventId, { signal: abortSignal });\n },\n }),\n get_session_memory: tool({\n description: 'Get conversation events and its latest summary. Include summarized events only when full older history is needed.',\n inputSchema: sessionInput.extend({ includeSummarisedEvents: z.boolean().optional() }),\n execute: async (input, { abortSignal }) => {\n const result = await client.getSessionMemory(resolveSession(input.sessionId), input.includeSummarisedEvents, { signal: abortSignal });\n if (scope.userId && result.ownerId !== scope.userId) fail('Session is outside the configured user scope.');\n checkPlacement(result); return result;\n },\n }),\n list_sessions: tool({\n description: 'List sessions for an owner or a namespace, with pagination, within any fixed scope. Unscoped callers must explicitly request includeAll to list the whole store. Sort by sessionId, createdAt, or updatedAt.',\n inputSchema: z.object({\n ownerId: s.ownerId.optional(), namespaceId: s.id.optional().describe('Only sessions placed in this namespace.'),\n includeAll: z.boolean().optional(), ...s.page, limit: z.number().int().min(1).max(1000).optional(),\n sortBy: z.enum(['sessionId', 'createdAt', 'updatedAt']).optional(), sortOrder: s.sortOrder.optional(),\n }),\n execute: async (input, { abortSignal }) => {\n const { namespaceId } = place({ namespaceId: input.namespaceId });\n if (scope.sessionId) {\n if (input.ownerId && scope.userId && input.ownerId !== scope.userId) fail('Cannot override user scope.');\n const session = await assertSession(scope.sessionId, abortSignal);\n if (input.ownerId && session.ownerId !== input.ownerId) return { items: [] };\n if (namespaceId && session.namespaceId !== namespaceId) return { items: [] };\n return { items: [{ sessionId: session.sessionId, ownerId: session.ownerId, namespaceId: session.namespaceId }] };\n }\n if (input.includeAll && (scope.userId || namespaceId || input.ownerId)) {\n fail('includeAll cannot be combined with a user or namespace scope, ownerId, or namespaceId.');\n }\n const owner = input.ownerId || scope.userId;\n if (!owner && !namespaceId && !input.includeAll) fail('Supply ownerId or namespaceId, or explicitly set includeAll: true.');\n if (owner) resolveOwner(owner);\n // The service rejects includeAll alongside any filter, so a namespace filter stands in for it.\n const filtered = owner || namespaceId;\n const result = await client.listSessions(\n input.limit, input.cursor, owner, filtered ? undefined : true, { signal: abortSignal }, namespaceId,\n input.sortBy, input.sortOrder,\n );\n for (const item of result.items) checkPlacement(item);\n return result;\n },\n }),\n create_memories: tool({\n description: 'Create up to 100 durable memories in one batch. IDs are generated automatically; do not supply them. Use the user ID as ownerId; fixed scope.userId supplies it automatically. created and errors report per-record outcomes. Without idempotencyKey each call generates new IDs and memoryIds lists them all in input order, so reconcile uncertain writes before retrying. With idempotencyKey, a retry of the identical request replays the saved result with the same IDs, and memoryIds stays aligned with the input, holding null for a record the service rejected; that record also appears in errors.',\n inputSchema: z.object({ memories: z.array(s.memory).min(1).max(100), idempotencyKey: s.idempotencyKey.optional() }),\n execute: async ({ memories, idempotencyKey }, { abortSignal }) => {\n const placed = memories.map(memory => {\n const sessionId = memory.sessionId ?? scope.sessionId;\n if (scope.sessionId && sessionId !== scope.sessionId) fail('Cannot override session association.');\n return { ...place(memory), ownerId: resolveOwner(memory.ownerId), sessionId };\n });\n const owners = [...new Set(placed.map(record => record.ownerId))].sort();\n const scopedKey = await scoped.scopeIdempotencyKey(idempotencyKey, ...owners);\n const records = await Promise.all(placed.map(async (record, index) => ({\n ...record,\n memoryId: scopedKey === undefined ? globalThis.crypto.randomUUID() : await retryStableMemoryId(scopedKey, index),\n })));\n const checkedNamespaces = new Set<string>();\n for (const record of records) {\n const namespaceId = record.namespaceId;\n if (namespaceId && !checkedNamespaces.has(namespaceId)) {\n await assertPlacementOwner(record, abortSignal);\n checkedNamespaces.add(namespaceId);\n }\n }\n const result = await client.bulkCreateLongTermMemories({\n memories: records, idempotencyKey: scopedKey,\n }, { signal: abortSignal });\n const all = records.map(record => record.memoryId);\n if (idempotencyKey === undefined) return { ...result, memoryIds: all };\n // Keyed IDs are guessable, so another owner may already hold one; never hand back an ID the service did not create.\n // Nulls keep each position tied to its input record, since an error names only the rejected ID.\n const created = new Set(result.created);\n return { ...result, memoryIds: all.map(id => created.has(id) ? id : null) };\n },\n }),\n get_memory: tool({\n description: 'Get a long-term memory by ID within the configured scope. The record carries its revision, its first source links, and documentManaged when document ingestion produced it.',\n inputSchema: z.object({ memoryId: s.id }),\n execute: ({ memoryId }, { abortSignal }) => assertMemory(memoryId, abortSignal),\n }),\n search_memories: tool({\n description: 'Search durable memories semantically with query, or list them with filters only. Results are items plus optional nextCursor. Recall spans conversations. Scoped searches require filter.op ALL. sortBy and sortOrder order a filter-only listing and cannot be combined with query.',\n inputSchema: s.search,\n execute: async (input, { abortSignal }) => {\n if (input.query !== undefined && (input.sortBy !== undefined || input.sortOrder !== undefined)) {\n throw new RedisAgentMemoryToolError('INVALID_INPUT', 'sortBy and sortOrder apply only to filter-only listing. Omit query to sort.');\n }\n const filter: LongTermMemoryFilter = { ...input.filter, createdAt: input.filter?.createdAt\n ? Object.fromEntries(Object.entries(input.filter.createdAt).filter(([,v]) => v !== undefined).map(([k,v]) => [k, new Date(v!)])) : undefined };\n return scoped.searchLongTermMemory({ ...input, filter }, { signal: abortSignal });\n },\n }),\n update_memory: tool({\n description: 'Partially correct a memory’s text or organization. Supply at least one change; omitted fields stay unchanged. Document-managed memories accept only namespace changes. Use update_memory_fields for custom attributes or upsert_memory for a full replacement.',\n inputSchema: z.object({\n memoryId: s.id, changes: s.memoryUpdate,\n expectedRevision: s.expectedRevision.optional(), idempotencyKey: s.idempotencyKey.optional(),\n }),\n execute: async ({ memoryId, changes, expectedRevision, idempotencyKey }, { abortSignal }) => {\n if (!Object.values(changes).some(v => v !== undefined)) fail('Supply at least one change.');\n if (hasResourceScope) await assertMemory(memoryId, abortSignal);\n if (changes.ownerId !== undefined) resolveOwner(changes.ownerId);\n if (scope.sessionId && changes.sessionId !== undefined && changes.sessionId !== scope.sessionId) fail('Cannot override session association.');\n const placed = place(changes);\n await assertPlacementOwner(placed, abortSignal);\n return client.updateLongTermMemory(memoryId, {\n ...placed, expectedRevision, idempotencyKey: await scoped.scopeIdempotencyKey(idempotencyKey, memoryId),\n }, { signal: abortSignal });\n },\n }),\n upsert_memory: tool({\n description: 'Create or fully replace one manually managed memory by ID, including custom attributes. Omitted optional fields are cleared and memoryType defaults to semantic. Read the memory first and send every field to keep. Pass expectedRevision to guard against concurrent changes. Document-managed memories cannot be replaced.',\n inputSchema: s.memory.extend({\n memoryId: s.memoryId.describe('ID of the memory to replace, or a new ID to create one.'),\n expectedRevision: s.expectedRevision.optional(), idempotencyKey: s.idempotencyKey.optional(),\n }),\n execute: async ({ memoryId, ...input }, { abortSignal }) => {\n if (hasResourceScope) {\n try { await assertMemory(memoryId, abortSignal); }\n catch (error) { if (memoryErrorStatus(error) !== 404) throw error; }\n }\n const sessionId = input.sessionId ?? scope.sessionId;\n if (scope.sessionId && sessionId !== scope.sessionId) fail('Cannot override session association.');\n const placed = { ...place(input), ownerId: resolveOwner(input.ownerId), sessionId };\n await assertPlacementOwner(placed, abortSignal);\n return client.upsertLongTermMemory(memoryId, {\n ...placed, idempotencyKey: await scoped.scopeIdempotencyKey(input.idempotencyKey, memoryId),\n }, { signal: abortSignal });\n },\n }),\n update_memory_fields: tool({\n description: 'Atomically update the text and/or attributes of a custom-typed memory. memoryType must match the stored type. Pass the memory’s current namespaceId; omitting it asserts the memory has no namespace.',\n inputSchema: z.object({\n memoryId: s.id, memoryType: z.string().min(1).describe('The stored custom memory type.'),\n text: s.text.optional(), attributes: s.attributes.optional().describe('Field name to value, matching the custom type’s declared fields.'),\n expectedRevision: s.expectedRevision.optional(), idempotencyKey: s.idempotencyKey.optional(), ...s.placement,\n }),\n execute: async ({ memoryId, ...input }, { abortSignal }) => {\n if (input.text === undefined && input.attributes === undefined) fail('Supply text or attributes.');\n if (hasResourceScope) await assertMemory(memoryId, abortSignal);\n const placed = place(input);\n await assertPlacementOwner(placed, abortSignal);\n await client.updateLongTermMemoryFields(memoryId, {\n ...placed, idempotencyKey: await scoped.scopeIdempotencyKey(input.idempotencyKey, memoryId),\n }, { signal: abortSignal });\n return { updated: true, memoryId };\n },\n }),\n list_memory_sources: tool({\n description: 'List where a memory came from: document revisions or sessions, with their first evidence. Follow nextCursor for more links.',\n inputSchema: z.object({ memoryId: s.id, ...s.page }),\n execute: async ({ memoryId, limit, cursor }, { abortSignal }) => {\n if (hasResourceScope) await assertMemory(memoryId, abortSignal);\n return client.listMemorySourceLinks(memoryId, limit, cursor, { signal: abortSignal });\n },\n }),\n list_memory_source_evidence: tool({\n description: 'Page the extraction evidence for one source of a memory: document chunks or the session event IDs supplied to extraction. Evidence attributes input, not cited facts. Get sourceId from list_memory_sources.',\n inputSchema: z.object({ memoryId: s.id, sourceId: s.id, ...s.page }),\n execute: async ({ memoryId, sourceId, limit, cursor }, { abortSignal }) => {\n if (hasResourceScope) await assertMemory(memoryId, abortSignal);\n return client.listMemorySourceEvidence(memoryId, sourceId, limit, cursor, { signal: abortSignal });\n },\n }),\n list_source_memories: tool({\n description: 'List one owner’s memories derived from a source. Get sourceId from list_memory_sources. Follow nextCursor for more. Memories outside a fixed namespace scope are omitted.',\n inputSchema: z.object({ sourceId: s.id, ownerId: s.ownerId.optional(), ...s.page }),\n execute: async ({ sourceId, ownerId, limit, cursor }, { abortSignal }) => {\n const owner = resolveOwner(ownerId);\n const result = await client.listSourceMemories(sourceId, owner, limit, cursor, { signal: abortSignal });\n if (result.items.some(item => item.ownerId !== owner)) fail('Memory is outside the requested owner.');\n return scope.namespaceId === undefined ? result\n : { ...result, items: result.items.filter(item => item.namespaceId === scope.namespaceId) };\n },\n }),\n };\n if (deletes) Object.assign(tools, {\n delete_memories: tool({\n description: 'Delete 1 to 100 long-term memories by ID. Use for explicit forget requests. Inspect deleted and per-record errors before claiming success.',\n inputSchema: z.object({ memoryIds: z.array(s.id).min(1).max(100) }),\n execute: async ({ memoryIds }, { abortSignal }) => {\n if (hasResourceScope) for (const id of memoryIds) await assertMemory(id, abortSignal);\n return client.bulkDeleteLongTermMemories({ memoryIds }, { signal: abortSignal });\n },\n }),\n delete_session_event: tool({\n description: 'Delete one event. Previously promoted long-term memories remain and must be deleted separately.', inputSchema: eventInput,\n execute: async (input, { abortSignal }) => {\n const sessionId = resolveSession(input.sessionId);\n if (hasResourceScope) await assertSession(sessionId, abortSignal);\n await client.deleteSessionEvent(sessionId, input.eventId, { signal: abortSignal });\n return { deleted: true, sessionId, eventId: input.eventId };\n },\n }),\n delete_session_memory: tool({\n description: 'Delete a conversation’s session memory. This does not delete promoted long-term memories.', inputSchema: sessionInput,\n execute: async (input, { abortSignal }) => {\n const sessionId = resolveSession(input.sessionId);\n if (hasResourceScope) await assertSession(sessionId, abortSignal);\n await client.deleteSessionMemory(sessionId, { signal: abortSignal });\n return { deleted: true, sessionId };\n },\n }),\n });\n if (options.namespaceTools) Object.assign(tools, createNamespaceTools(client, {\n ownerId: scope.userId, namespaceId: scope.namespaceId, allowDeletes: deletes,\n allowRoutingWrites: options.routingPolicyWrites === true, assertMemory,\n }));\n if (options.ingestionTools) Object.assign(tools, createIngestionTools(client, scoped));\n if (options.summaryViewTools) Object.assign(tools, createSummaryViewTools(client, scoped, { allowDeletes: deletes }));\n // Errors from the generated SDK may contain response bodies and headers. Never expose these to the model.\n for (const entry of Object.values(tools)) {\n const execute = entry.execute!;\n entry.execute = async (input, execution) => {\n try { return await execute(input, execution); }\n catch (error) {\n if (execution.abortSignal?.aborted) throw new DOMException('Memory operation aborted.', 'AbortError');\n throw sanitizeMemoryError(error);\n }\n };\n }\n // Keep application helpers out of AI SDK tool enumeration and object spreads.\n Object.defineProperties(tools, {\n withContext: {\n value: (context: RedisAgentMemoryScope) => buildTools(\n client,\n copyMemoryScope(extendMemoryScope(scope, context), options),\n options,\n ),\n },\n createSessionEventHook: {\n value: (hookOptions: SessionEventHookOptions) => createSessionEventHook(scope, append, hookOptions),\n },\n });\n return tools as RedisAgentMemoryTools;\n}\n\ntype ModelCallWithDefault = (options?: RedisAgentMemoryModelOptions) => RedisAgentMemoryModel;\ntype ModelCallWithoutDefault = (\n options: RedisAgentMemoryModelOptions & { model: ConfiguredLanguageModel },\n) => RedisAgentMemoryModel;\n\nexport type RedisAgentMemory<DefaultModel extends ConfiguredLanguageModel | undefined = undefined> = Readonly<{\n tools: (options?: RedisAgentMemoryToolsOptions) => RedisAgentMemoryTools;\n model: undefined extends DefaultModel ? ModelCallWithoutDefault : ModelCallWithDefault;\n}>;\n\n/**\n * Create one immutable Redis Agent Memory factory and share its Iris client across tools and request models.\n * Each `model()` call returns fresh request-local state and must be reused only within one application request.\n */\nexport function createRedisAgentMemory<DefaultModel extends ConfiguredLanguageModel | undefined = undefined>(\n input: RedisAgentMemoryOptions<DefaultModel>,\n): RedisAgentMemory<DefaultModel> {\n const options = Object.freeze({ ...input });\n if (options.model !== undefined) assertConfiguredLanguageModel(options.model);\n const defaultScope = copyMemoryScope(options.scope ?? {}, options);\n const toolOptions: Readonly<RedisAgentMemoryToolOptions> = Object.freeze({\n allowDeletes: options.allowDeletes,\n namespaceTools: options.namespaceTools,\n routingPolicyWrites: options.routingPolicyWrites,\n ingestionTools: options.ingestionTools,\n summaryViewTools: options.summaryViewTools,\n timeoutMs: options.timeoutMs,\n });\n let client: ReturnType<typeof resolveAgentMemoryClient>;\n try {\n client = resolveAgentMemoryClient(\n options.serverUrl,\n options.storeId,\n options.apiKey,\n options.timeoutMs ?? 30_000,\n );\n } catch (error) {\n throw new RedisAgentMemoryToolError(\n 'INVALID_CONFIGURATION',\n error instanceof Error ? error.message : 'Redis Agent Memory connection configuration is invalid.',\n );\n }\n const defaultModel = options.model;\n const memory = {\n tools(callOptions: RedisAgentMemoryToolsOptions = {}) {\n const scope = callOptions.scope === undefined\n ? defaultScope\n : copyMemoryScope(callOptions.scope, toolOptions);\n return buildTools(client, scope, toolOptions);\n },\n model(callOptions: RedisAgentMemoryModelOptions = {}) {\n const selectedModel = callOptions.model === undefined ? defaultModel : callOptions.model;\n assertConfiguredLanguageModel(selectedModel);\n const scope = callOptions.scope === undefined\n ? defaultScope\n : copyMemoryScope(callOptions.scope);\n const { model: _model, ...requestOptions } = callOptions;\n return createRedisAgentMemoryModel(client, selectedModel, { ...requestOptions, scope });\n },\n };\n return Object.freeze(memory) as RedisAgentMemory<DefaultModel>;\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { type ToolSet } from 'ai';
2
+ import type { AgentMemory } from '@redis-iris/agent-memory';
3
+ import { type ScopedMemory } from './scoped-memory.js';
4
+ /** Optional document ingestion and ingestion hook tools. Access checks never trust model-supplied IDs. */
5
+ export declare function createIngestionTools(client: AgentMemory, ctx: ScopedMemory): ToolSet;
6
+ //# sourceMappingURL=ingestion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ingestion.d.ts","sourceRoot":"","sources":["../src/ingestion.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,IAAI,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAI5D,OAAO,EAAqB,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAuB1E,0GAA0G;AAC1G,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,EAAE,YAAY,GAAG,OAAO,CAkIpF"}