@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.
Files changed (49) hide show
  1. package/CHANGELOG.md +47 -36
  2. package/README.md +13 -8
  3. package/TOOLS.md +264 -31
  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 +167 -33
  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 +8 -4
  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 +70 -15
  22. package/dist/namespaces.js.map +1 -1
  23. package/dist/provider.js +2 -2
  24. package/dist/provider.js.map +1 -1
  25. package/dist/schemas.d.ts +32 -33
  26. package/dist/schemas.d.ts.map +1 -1
  27. package/dist/schemas.js +24 -11
  28. package/dist/schemas.js.map +1 -1
  29. package/dist/scoped-memory.d.ts +11 -9
  30. package/dist/scoped-memory.d.ts.map +1 -1
  31. package/dist/scoped-memory.js +80 -56
  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 +2 -2
  40. package/src/errors.ts +6 -1
  41. package/src/index.ts +162 -33
  42. package/src/ingestion.ts +160 -0
  43. package/src/instructions.ts +8 -4
  44. package/src/namespaces.ts +81 -14
  45. package/src/provider.ts +2 -2
  46. package/src/schemas.ts +28 -11
  47. package/src/scoped-memory.ts +88 -48
  48. package/src/session-event-hook.ts +1 -1
  49. package/src/summary-views.ts +300 -0
@@ -0,0 +1,276 @@
1
+ import { tool } from 'ai';
2
+ import { z } from 'zod';
3
+ import { RedisAgentMemoryToolError } from './errors.js';
4
+ import * as s from './schemas.js';
5
+ /**
6
+ * view covers the definition and result reads; read adds partition refreshes;
7
+ * manage adds edits, full refreshes, and deletes. Levels are listed weakest first.
8
+ */
9
+ const LEVELS = ['none', 'view', 'read', 'manage'];
10
+ function fail(message) {
11
+ throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);
12
+ }
13
+ const groupBy = z.array(z.enum(['ownerId', 'sessionId', 'namespaceId', 'memoryType']))
14
+ .max(4)
15
+ .refine(fields => new Set(fields).size === fields.length, 'List each groupBy field once.')
16
+ .describe('One partition per distinct value of these fields. An empty list keeps a single summary.');
17
+ const output = z.object({
18
+ format: z.enum(['TEXT', 'STRUCTURED']),
19
+ instructions: z.string().min(1).optional().describe('What the summary should cover.'),
20
+ schema: z.object({
21
+ fields: z.array(z.object({
22
+ name: z.string().min(1),
23
+ description: z.string(),
24
+ type: z.enum(['STRING', 'INTEGER', 'FLOAT', 'BOOLEAN', 'STRING_LIST', 'FLOAT_LIST', 'OBJECT']),
25
+ })).min(1),
26
+ }).optional().describe('Flat field list for STRUCTURED output. Nested schemas and required fields are not supported.'),
27
+ }).refine(value => (value.format === 'STRUCTURED') === (value.schema !== undefined), 'Supply schema exactly when format is STRUCTURED.');
28
+ const refreshPolicy = z.object({
29
+ mode: z.enum(['MANUAL', 'CONTINUOUS']),
30
+ debounceSeconds: z.number().int().nonnegative().optional(),
31
+ reconcileIntervalSeconds: z.number().int().positive().optional(),
32
+ }).refine(value => value.mode === 'CONTINUOUS'
33
+ ? value.reconcileIntervalSeconds !== undefined
34
+ : value.debounceSeconds === undefined && value.reconcileIntervalSeconds === undefined, 'CONTINUOUS requires reconcileIntervalSeconds. MANUAL omits both interval fields.');
35
+ const evictionPolicy = z.object({ maxPartitions: z.number().int().positive() })
36
+ .describe('Keep at most this many partitions.');
37
+ const timeWindowSeconds = z.number().int().positive().describe('Only summarize memories from this rolling window.');
38
+ const filter = s.search.shape.filter.describe('Long-term memory filter that selects the source memories.');
39
+ const partition = z.object({
40
+ ownerId: s.ownerId.optional(), sessionId: s.sessionId.optional(), namespaceId: s.id.optional(), memoryType: s.id.optional(),
41
+ }).describe('One value for each groupBy field of the view. Omit for a view without groupBy.');
42
+ const viewId = s.id.describe('Summary View ID, such as sv_ followed by 32 hex characters.');
43
+ function toFilter(input) {
44
+ const { createdAt, ...rest } = input;
45
+ if (createdAt === undefined)
46
+ return rest;
47
+ return {
48
+ ...rest,
49
+ createdAt: Object.fromEntries(Object.entries(createdAt)
50
+ .filter(([, value]) => value !== undefined)
51
+ .map(([key, value]) => [key, new Date(value)])),
52
+ };
53
+ }
54
+ /** Optional Summary View tools. Scoped toolsets only reach views whose partitions they can prove are theirs. */
55
+ export function createSummaryViewTools(client, ctx, options) {
56
+ const fixed = ['ownerId', 'namespaceId']
57
+ .map(field => [field, field === 'ownerId' ? ctx.scope.userId : ctx.scope.namespaceId])
58
+ .filter((entry) => entry[1] !== undefined);
59
+ // The view ownerId is the API caller, not the application user, so access is proven from filter and groupBy.
60
+ function access(view) {
61
+ if (!ctx.hasResourceScope)
62
+ return 'manage';
63
+ if (view.visibility !== 'PRIVATE' && view.visibility !== 'SHARED')
64
+ return 'none';
65
+ const viewFilter = view.filter ?? {};
66
+ const conditions = Object.entries(viewFilter).filter(([key, value]) => key !== 'op' && value !== undefined).length;
67
+ // The service default for op is not documented, so an implicit op only counts when nothing else could be ORed in.
68
+ const conjunctive = viewFilter.op?.toUpperCase() === 'ALL' || (viewFilter.op === undefined && conditions === 1);
69
+ let level = 'manage';
70
+ for (const [field, value] of fixed) {
71
+ const condition = viewFilter[field];
72
+ // A filter naming another user or namespace is that scope's view, even when it also groups by the field.
73
+ if (condition?.eq !== undefined && condition.eq !== value)
74
+ return 'none';
75
+ if (condition?.in !== undefined && !condition.in.includes(value))
76
+ return 'none';
77
+ const pinned = conjunctive && condition?.eq === value
78
+ && Object.values(condition).filter(item => item !== undefined).length === 1;
79
+ if (pinned)
80
+ continue;
81
+ if (!view.groupBy.includes(field))
82
+ return 'none';
83
+ level = 'read';
84
+ }
85
+ // Every store-authorized caller sees a SHARED view, so a scoped toolset reads its own partition but never changes the view.
86
+ return view.visibility === 'SHARED' ? 'view' : level;
87
+ }
88
+ /** A definition that spans several users or namespaces names the others, so a scoped caller sees only its own value. */
89
+ function redact(view) {
90
+ if (!ctx.hasResourceScope || view.filter === undefined)
91
+ return view;
92
+ const filter = { ...view.filter };
93
+ for (const [field, value] of fixed) {
94
+ const condition = filter[field];
95
+ if (condition === undefined)
96
+ continue;
97
+ if (condition.eq !== undefined)
98
+ filter[field] = { eq: condition.eq };
99
+ else if (condition.in !== undefined)
100
+ filter[field] = { in: [value] };
101
+ else
102
+ delete filter[field];
103
+ }
104
+ return { ...view, filter };
105
+ }
106
+ async function assertView(id, needed, signal) {
107
+ const view = await client.getSummaryView(id, { signal });
108
+ const level = access(view);
109
+ if (level === 'none')
110
+ fail('Summary View is outside the configured user or namespace scope.');
111
+ if (LEVELS.indexOf(level) >= LEVELS.indexOf(needed))
112
+ return view;
113
+ if (view.visibility === 'SHARED') {
114
+ fail('A SHARED Summary View is read-only with a fixed user or namespace. Its definition and your partition can be read.');
115
+ }
116
+ fail('This Summary View is shared across users or namespaces. Only views whose filter is pinned to the configured scope can be changed.');
117
+ }
118
+ function scopeFilter(input) {
119
+ const converted = input && toFilter(input);
120
+ return ctx.hasResourceScope ? ctx.scopeSearch({ filter: converted }).filter : converted;
121
+ }
122
+ function resolvePartition(view, input = {}) {
123
+ const resolved = { ...input };
124
+ if (view) {
125
+ for (const [field, value] of fixed) {
126
+ if (resolved[field] !== undefined && resolved[field] !== value)
127
+ fail(`Cannot reach another ${field} partition.`);
128
+ if (view.groupBy.includes(field))
129
+ resolved[field] = value;
130
+ }
131
+ }
132
+ return Object.values(resolved).some(value => value !== undefined) ? resolved : undefined;
133
+ }
134
+ const tools = {
135
+ list_summary_views: tool({
136
+ description: 'List Summary View definitions and their state. Summary text is not included; use get_summary_view_result for it. ' +
137
+ 'Reuse nextCursor to fetch another page. With a fixed user or namespace, only views whose filter pins or whose ' +
138
+ 'groupBy splits by that user and namespace are listed, so a page can hold fewer items than limit. ' +
139
+ 'SHARED views among them are read-only.',
140
+ inputSchema: z.object({ ...s.page }),
141
+ execute: async ({ limit, cursor }, { abortSignal }) => {
142
+ const result = await client.listSummaryViews(limit, cursor, { signal: abortSignal });
143
+ return { ...result, items: result.items.filter(view => access(view) !== 'none').map(redact) };
144
+ },
145
+ }),
146
+ get_summary_view: tool({
147
+ description: 'Get one Summary View definition with its filter, groupBy, output, refresh policy, state, and definitionVersion. ' +
148
+ 'With a fixed user or namespace, views outside that user or namespace are refused, and other users and namespaces are left out of the filter. A SHARED view inside them can be read.',
149
+ inputSchema: z.object({ viewId }),
150
+ execute: async ({ viewId: id }, { abortSignal }) => redact(await assertView(id, 'view', abortSignal)),
151
+ }),
152
+ create_summary_view: tool({
153
+ description: 'Create a Summary View that keeps a generated summary of matching long-term memories. ' +
154
+ 'groupBy splits it into one partition per value of each listed field. TEXT output writes prose. ' +
155
+ 'STRUCTURED output fills the fields in output.schema. MANUAL views refresh only through refresh_summary_view. ' +
156
+ 'CONTINUOUS views refresh on their own and reconcile every reconcileIntervalSeconds. ' +
157
+ 'The first refresh runs asynchronously. PRIVATE (the default) keeps the view to this API caller. ' +
158
+ 'SHARED publishes a view of shared memories to every store-authorized caller. ' +
159
+ 'With a fixed user or namespace, the view is always PRIVATE, SHARED is refused, and the filter is pinned to that ' +
160
+ 'user and namespace, so groupBy cannot reach other memories.',
161
+ inputSchema: z.object({
162
+ name: z.string().min(1),
163
+ description: z.string().optional(),
164
+ visibility: z.enum(['PRIVATE', 'SHARED']).optional().describe('Immutable after creation.'),
165
+ filter,
166
+ groupBy,
167
+ evictionPolicy: evictionPolicy.optional(),
168
+ timeWindowSeconds: timeWindowSeconds.optional(),
169
+ output,
170
+ refreshPolicy,
171
+ }),
172
+ execute: async ({ visibility, filter: input, ...request }, { abortSignal }) => {
173
+ if (ctx.hasResourceScope && visibility === 'SHARED') {
174
+ fail('A toolset with a fixed user or namespace can only create PRIVATE Summary Views.');
175
+ }
176
+ return client.createSummaryView({
177
+ ...request,
178
+ source: 'LONG_TERM',
179
+ visibility: ctx.hasResourceScope ? 'PRIVATE' : visibility,
180
+ filter: scopeFilter(input),
181
+ }, { signal: abortSignal });
182
+ },
183
+ }),
184
+ update_summary_view: tool({
185
+ description: 'Change a Summary View. Source and visibility cannot change. Changes to filter, groupBy, time window, eviction, ' +
186
+ 'output, or refresh policy increment definitionVersion and refresh the view. Name and description changes do not. ' +
187
+ 'state switches the view between ACTIVE and DISABLED. filter and clearFilter cannot be combined, nor can ' +
188
+ 'timeWindowSeconds and clearTimeWindow. With a fixed user or namespace, only PRIVATE views whose filter is pinned to ' +
189
+ 'that user and namespace can change, a new filter is pinned the same way, and clearFilter is refused.',
190
+ inputSchema: z.object({
191
+ viewId,
192
+ name: z.string().min(1).optional(),
193
+ description: z.string().optional().describe('Send an empty string to clear it.'),
194
+ filter: filter.describe('Replaces the saved filter.'),
195
+ clearFilter: z.boolean().optional(),
196
+ groupBy: groupBy.optional(),
197
+ evictionPolicy: evictionPolicy.optional(),
198
+ timeWindowSeconds: timeWindowSeconds.optional(),
199
+ clearTimeWindow: z.boolean().optional(),
200
+ output: output.optional(),
201
+ refreshPolicy: refreshPolicy.optional(),
202
+ state: z.enum(['ACTIVE', 'DISABLED']).optional(),
203
+ }),
204
+ execute: async ({ viewId: id, filter: input, ...changes }, { abortSignal }) => {
205
+ if (input === undefined && !Object.values(changes).some(value => value !== undefined))
206
+ fail('Supply at least one change.');
207
+ if (ctx.hasResourceScope) {
208
+ if (changes.clearFilter)
209
+ fail('Cannot clear the filter that keeps this view inside the configured scope.');
210
+ await assertView(id, 'manage', abortSignal);
211
+ }
212
+ return client.updateSummaryView(id, {
213
+ ...changes,
214
+ filter: input === undefined ? undefined : scopeFilter(input),
215
+ }, { signal: abortSignal });
216
+ },
217
+ }),
218
+ refresh_summary_view: tool({
219
+ description: 'Queue a Summary View refresh. It runs asynchronously, so read the result later and check its status. ' +
220
+ 'PARTITION refreshes one exact partition. FULL reconciles every partition and takes no partition. ' +
221
+ 'With a fixed user or namespace, the partition is filled in with that user and namespace, other values are refused, ' +
222
+ 'FULL is allowed only on views whose filter is pinned to that user and namespace, and SHARED views are refused.',
223
+ inputSchema: z.object({ viewId, target: z.enum(['PARTITION', 'FULL']), partition: partition.optional() }),
224
+ execute: async ({ viewId: id, target, partition: input }, { abortSignal }) => {
225
+ if (target === 'FULL' && input !== undefined)
226
+ fail('A FULL refresh takes no partition.');
227
+ const view = ctx.hasResourceScope
228
+ ? await assertView(id, target === 'FULL' ? 'manage' : 'read', abortSignal)
229
+ : undefined;
230
+ return client.refreshSummaryView(id, {
231
+ target,
232
+ scope: target === 'PARTITION' ? resolvePartition(view, input) : undefined,
233
+ }, { signal: abortSignal });
234
+ },
235
+ }),
236
+ get_summary_view_result: tool({
237
+ description: 'Read the generated summary for one exact partition of a Summary View. Check status before using value. ' +
238
+ 'COLD, PENDING, and EMPTY have no value. READY and REFRESHING carry a value. FAILED keeps the last good value ' +
239
+ 'when one exists and reports errorCode. stale means the value lags its sources. truncated means some memories ' +
240
+ 'or content were left out. Invalid output is withheld while the service repairs it. ' +
241
+ 'With a fixed user or namespace, the partition is filled in with that user and namespace and other values are refused. ' +
242
+ 'This also applies to SHARED views.',
243
+ inputSchema: z.object({
244
+ viewId,
245
+ partition: partition.optional(),
246
+ includeSourceMemoryIds: z.boolean().optional().describe('Also return the IDs of the summarized memories.'),
247
+ }),
248
+ execute: async ({ viewId: id, partition: input, includeSourceMemoryIds }, { abortSignal }) => {
249
+ const view = ctx.hasResourceScope ? await assertView(id, 'view', abortSignal) : undefined;
250
+ const resolved = resolvePartition(view, input) ?? {};
251
+ return client.getSummaryViewResult(id, resolved.ownerId, resolved.sessionId, resolved.namespaceId, resolved.memoryType, includeSourceMemoryIds, { signal: abortSignal });
252
+ },
253
+ }),
254
+ };
255
+ if (options.allowDeletes) {
256
+ tools.delete_summary_view = tool({
257
+ description: 'Delete a Summary View on the user\'s explicit request. Deletion is asynchronous and safe to repeat. ' +
258
+ 'The view enters DELETING and its schedule and materialized summaries are removed. ' +
259
+ 'With a fixed user or namespace, only PRIVATE views whose filter is pinned to that user and namespace can be deleted.',
260
+ inputSchema: z.object({ viewId }),
261
+ execute: async ({ viewId: id }, { abortSignal }) => {
262
+ if (ctx.hasResourceScope)
263
+ await assertView(id, 'manage', abortSignal);
264
+ return client.deleteSummaryView(id, { signal: abortSignal });
265
+ },
266
+ });
267
+ }
268
+ // Summary Views are store-wide and a session binds no user or namespace, so a sessionId-only toolset has no boundary to stay inside.
269
+ if (ctx.scope.sessionId !== undefined && !ctx.hasResourceScope) {
270
+ for (const entry of Object.values(tools)) {
271
+ entry.execute = async () => fail('Summary View tools are unavailable when the toolset is scoped only by sessionId; fix a userId or namespaceId.');
272
+ }
273
+ }
274
+ return tools;
275
+ }
276
+ //# sourceMappingURL=summary-views.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"summary-views.js","sourceRoot":"","sources":["../src/summary-views.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAgB,MAAM,IAAI,CAAC;AAGxC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAOlC;;;GAGG;AACH,MAAM,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAU,CAAC;AAK3D,SAAS,IAAI,CAAC,OAAe;IAC3B,MA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CAAC,gBAAgB;oBAAE,MAAM,UAAU,CAAC,EAAE,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;gBACtE,OAAO,MAAM,CAAC,iBAAiB,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;YAC/D,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IAED,qIAAqI;IACrI,IAAI,GAAG,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;QAC/D,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YACzC,KAAK,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,+GAA+G,CAAC,CAAC;QACpJ,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { tool, type ToolSet } from 'ai';\nimport type { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter, SummaryView, SummaryViewScope } from '@redis-iris/agent-memory/models';\nimport { z } from 'zod';\nimport { RedisAgentMemoryToolError } from './errors.js';\nimport * as s from './schemas.js';\nimport type { ScopedMemory } from './scoped-memory.js';\n\nexport interface SummaryViewToolOptions {\n allowDeletes: boolean;\n}\n\n/**\n * view covers the definition and result reads; read adds partition refreshes;\n * manage adds edits, full refreshes, and deletes. Levels are listed weakest first.\n */\nconst LEVELS = ['none', 'view', 'read', 'manage'] as const;\ntype Access = typeof LEVELS[number];\ntype ScopedField = 'ownerId' | 'namespaceId';\ntype FilterInput = NonNullable<z.infer<typeof s.search>['filter']>;\n\nfunction fail(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);\n}\n\nconst groupBy = z.array(z.enum(['ownerId', 'sessionId', 'namespaceId', 'memoryType']))\n .max(4)\n .refine(fields => new Set(fields).size === fields.length, 'List each groupBy field once.')\n .describe('One partition per distinct value of these fields. An empty list keeps a single summary.');\nconst output = z.object({\n format: z.enum(['TEXT', 'STRUCTURED']),\n instructions: z.string().min(1).optional().describe('What the summary should cover.'),\n schema: z.object({\n fields: z.array(z.object({\n name: z.string().min(1),\n description: z.string(),\n type: z.enum(['STRING', 'INTEGER', 'FLOAT', 'BOOLEAN', 'STRING_LIST', 'FLOAT_LIST', 'OBJECT']),\n })).min(1),\n }).optional().describe('Flat field list for STRUCTURED output. Nested schemas and required fields are not supported.'),\n}).refine(value => (value.format === 'STRUCTURED') === (value.schema !== undefined),\n 'Supply schema exactly when format is STRUCTURED.');\nconst refreshPolicy = z.object({\n mode: z.enum(['MANUAL', 'CONTINUOUS']),\n debounceSeconds: z.number().int().nonnegative().optional(),\n reconcileIntervalSeconds: z.number().int().positive().optional(),\n}).refine(value => value.mode === 'CONTINUOUS'\n ? value.reconcileIntervalSeconds !== undefined\n : value.debounceSeconds === undefined && value.reconcileIntervalSeconds === undefined,\n'CONTINUOUS requires reconcileIntervalSeconds. MANUAL omits both interval fields.');\nconst evictionPolicy = z.object({ maxPartitions: z.number().int().positive() })\n .describe('Keep at most this many partitions.');\nconst timeWindowSeconds = z.number().int().positive().describe('Only summarize memories from this rolling window.');\nconst filter = s.search.shape.filter.describe('Long-term memory filter that selects the source memories.');\nconst partition = z.object({\n ownerId: s.ownerId.optional(), sessionId: s.sessionId.optional(), namespaceId: s.id.optional(), memoryType: s.id.optional(),\n}).describe('One value for each groupBy field of the view. Omit for a view without groupBy.');\nconst viewId = s.id.describe('Summary View ID, such as sv_ followed by 32 hex characters.');\n\nfunction toFilter(input: FilterInput): LongTermMemoryFilter {\n const { createdAt, ...rest } = input;\n if (createdAt === undefined) return rest;\n return {\n ...rest,\n createdAt: Object.fromEntries(Object.entries(createdAt)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, new Date(value!)])),\n };\n}\n\n/** Optional Summary View tools. Scoped toolsets only reach views whose partitions they can prove are theirs. */\nexport function createSummaryViewTools(\n client: AgentMemory,\n ctx: ScopedMemory,\n options: SummaryViewToolOptions,\n): ToolSet {\n const fixed = (['ownerId', 'namespaceId'] as const)\n .map(field => [field, field === 'ownerId' ? ctx.scope.userId : ctx.scope.namespaceId] as const)\n .filter((entry): entry is readonly [ScopedField, string] => entry[1] !== undefined);\n\n // The view ownerId is the API caller, not the application user, so access is proven from filter and groupBy.\n function access(view: SummaryView): Access {\n if (!ctx.hasResourceScope) return 'manage';\n if (view.visibility !== 'PRIVATE' && view.visibility !== 'SHARED') return 'none';\n const viewFilter: LongTermMemoryFilter = view.filter ?? {};\n const conditions = Object.entries(viewFilter).filter(([key, value]) => key !== 'op' && value !== undefined).length;\n // The service default for op is not documented, so an implicit op only counts when nothing else could be ORed in.\n const conjunctive = viewFilter.op?.toUpperCase() === 'ALL' || (viewFilter.op === undefined && conditions === 1);\n let level: Access = 'manage';\n for (const [field, value] of fixed) {\n const condition = viewFilter[field];\n // A filter naming another user or namespace is that scope's view, even when it also groups by the field.\n if (condition?.eq !== undefined && condition.eq !== value) return 'none';\n if (condition?.in !== undefined && !condition.in.includes(value)) return 'none';\n const pinned = conjunctive && condition?.eq === value\n && Object.values(condition).filter(item => item !== undefined).length === 1;\n if (pinned) continue;\n if (!view.groupBy.includes(field)) return 'none';\n level = 'read';\n }\n // Every store-authorized caller sees a SHARED view, so a scoped toolset reads its own partition but never changes the view.\n return view.visibility === 'SHARED' ? 'view' : level;\n }\n\n /** A definition that spans several users or namespaces names the others, so a scoped caller sees only its own value. */\n function redact(view: SummaryView): SummaryView {\n if (!ctx.hasResourceScope || view.filter === undefined) return view;\n const filter: LongTermMemoryFilter = { ...view.filter };\n for (const [field, value] of fixed) {\n const condition = filter[field];\n if (condition === undefined) continue;\n if (condition.eq !== undefined) filter[field] = { eq: condition.eq };\n else if (condition.in !== undefined) filter[field] = { in: [value] };\n else delete filter[field];\n }\n return { ...view, filter };\n }\n\n async function assertView(id: string, needed: Exclude<Access, 'none'>, signal?: AbortSignal): Promise<SummaryView> {\n const view = await client.getSummaryView(id, { signal });\n const level = access(view);\n if (level === 'none') fail('Summary View is outside the configured user or namespace scope.');\n if (LEVELS.indexOf(level) >= LEVELS.indexOf(needed)) return view;\n if (view.visibility === 'SHARED') {\n fail('A SHARED Summary View is read-only with a fixed user or namespace. Its definition and your partition can be read.');\n }\n fail('This Summary View is shared across users or namespaces. Only views whose filter is pinned to the configured scope can be changed.');\n }\n\n function scopeFilter(input?: FilterInput): LongTermMemoryFilter | undefined {\n const converted = input && toFilter(input);\n return ctx.hasResourceScope ? ctx.scopeSearch({ filter: converted }).filter : converted;\n }\n\n function resolvePartition(view: SummaryView | undefined, input: SummaryViewScope = {}): SummaryViewScope | undefined {\n const resolved = { ...input };\n if (view) {\n for (const [field, value] of fixed) {\n if (resolved[field] !== undefined && resolved[field] !== value) fail(`Cannot reach another ${field} partition.`);\n if (view.groupBy.includes(field)) resolved[field] = value;\n }\n }\n return Object.values(resolved).some(value => value !== undefined) ? resolved : undefined;\n }\n\n const tools: ToolSet = {\n list_summary_views: tool({\n description:\n 'List Summary View definitions and their state. Summary text is not included; use get_summary_view_result for it. ' +\n 'Reuse nextCursor to fetch another page. With a fixed user or namespace, only views whose filter pins or whose ' +\n 'groupBy splits by that user and namespace are listed, so a page can hold fewer items than limit. ' +\n 'SHARED views among them are read-only.',\n inputSchema: z.object({ ...s.page }),\n execute: async ({ limit, cursor }, { abortSignal }) => {\n const result = await client.listSummaryViews(limit, cursor, { signal: abortSignal });\n return { ...result, items: result.items.filter(view => access(view) !== 'none').map(redact) };\n },\n }),\n\n get_summary_view: tool({\n description:\n 'Get one Summary View definition with its filter, groupBy, output, refresh policy, state, and definitionVersion. ' +\n 'With a fixed user or namespace, views outside that user or namespace are refused, and other users and namespaces are left out of the filter. A SHARED view inside them can be read.',\n inputSchema: z.object({ viewId }),\n execute: async ({ viewId: id }, { abortSignal }) => redact(await assertView(id, 'view', abortSignal)),\n }),\n\n create_summary_view: tool({\n description:\n 'Create a Summary View that keeps a generated summary of matching long-term memories. ' +\n 'groupBy splits it into one partition per value of each listed field. TEXT output writes prose. ' +\n 'STRUCTURED output fills the fields in output.schema. MANUAL views refresh only through refresh_summary_view. ' +\n 'CONTINUOUS views refresh on their own and reconcile every reconcileIntervalSeconds. ' +\n 'The first refresh runs asynchronously. PRIVATE (the default) keeps the view to this API caller. ' +\n 'SHARED publishes a view of shared memories to every store-authorized caller. ' +\n 'With a fixed user or namespace, the view is always PRIVATE, SHARED is refused, and the filter is pinned to that ' +\n 'user and namespace, so groupBy cannot reach other memories.',\n inputSchema: z.object({\n name: z.string().min(1),\n description: z.string().optional(),\n visibility: z.enum(['PRIVATE', 'SHARED']).optional().describe('Immutable after creation.'),\n filter,\n groupBy,\n evictionPolicy: evictionPolicy.optional(),\n timeWindowSeconds: timeWindowSeconds.optional(),\n output,\n refreshPolicy,\n }),\n execute: async ({ visibility, filter: input, ...request }, { abortSignal }) => {\n if (ctx.hasResourceScope && visibility === 'SHARED') {\n fail('A toolset with a fixed user or namespace can only create PRIVATE Summary Views.');\n }\n return client.createSummaryView({\n ...request,\n source: 'LONG_TERM',\n visibility: ctx.hasResourceScope ? 'PRIVATE' : visibility,\n filter: scopeFilter(input),\n }, { signal: abortSignal });\n },\n }),\n\n update_summary_view: tool({\n description:\n 'Change a Summary View. Source and visibility cannot change. Changes to filter, groupBy, time window, eviction, ' +\n 'output, or refresh policy increment definitionVersion and refresh the view. Name and description changes do not. ' +\n 'state switches the view between ACTIVE and DISABLED. filter and clearFilter cannot be combined, nor can ' +\n 'timeWindowSeconds and clearTimeWindow. With a fixed user or namespace, only PRIVATE views whose filter is pinned to ' +\n 'that user and namespace can change, a new filter is pinned the same way, and clearFilter is refused.',\n inputSchema: z.object({\n viewId,\n name: z.string().min(1).optional(),\n description: z.string().optional().describe('Send an empty string to clear it.'),\n filter: filter.describe('Replaces the saved filter.'),\n clearFilter: z.boolean().optional(),\n groupBy: groupBy.optional(),\n evictionPolicy: evictionPolicy.optional(),\n timeWindowSeconds: timeWindowSeconds.optional(),\n clearTimeWindow: z.boolean().optional(),\n output: output.optional(),\n refreshPolicy: refreshPolicy.optional(),\n state: z.enum(['ACTIVE', 'DISABLED']).optional(),\n }),\n execute: async ({ viewId: id, filter: input, ...changes }, { abortSignal }) => {\n if (input === undefined && !Object.values(changes).some(value => value !== undefined)) fail('Supply at least one change.');\n if (ctx.hasResourceScope) {\n if (changes.clearFilter) fail('Cannot clear the filter that keeps this view inside the configured scope.');\n await assertView(id, 'manage', abortSignal);\n }\n return client.updateSummaryView(id, {\n ...changes,\n filter: input === undefined ? undefined : scopeFilter(input),\n }, { signal: abortSignal });\n },\n }),\n\n refresh_summary_view: tool({\n description:\n 'Queue a Summary View refresh. It runs asynchronously, so read the result later and check its status. ' +\n 'PARTITION refreshes one exact partition. FULL reconciles every partition and takes no partition. ' +\n 'With a fixed user or namespace, the partition is filled in with that user and namespace, other values are refused, ' +\n 'FULL is allowed only on views whose filter is pinned to that user and namespace, and SHARED views are refused.',\n inputSchema: z.object({ viewId, target: z.enum(['PARTITION', 'FULL']), partition: partition.optional() }),\n execute: async ({ viewId: id, target, partition: input }, { abortSignal }) => {\n if (target === 'FULL' && input !== undefined) fail('A FULL refresh takes no partition.');\n const view = ctx.hasResourceScope\n ? await assertView(id, target === 'FULL' ? 'manage' : 'read', abortSignal)\n : undefined;\n return client.refreshSummaryView(id, {\n target,\n scope: target === 'PARTITION' ? resolvePartition(view, input) : undefined,\n }, { signal: abortSignal });\n },\n }),\n\n get_summary_view_result: tool({\n description:\n 'Read the generated summary for one exact partition of a Summary View. Check status before using value. ' +\n 'COLD, PENDING, and EMPTY have no value. READY and REFRESHING carry a value. FAILED keeps the last good value ' +\n 'when one exists and reports errorCode. stale means the value lags its sources. truncated means some memories ' +\n 'or content were left out. Invalid output is withheld while the service repairs it. ' +\n 'With a fixed user or namespace, the partition is filled in with that user and namespace and other values are refused. ' +\n 'This also applies to SHARED views.',\n inputSchema: z.object({\n viewId,\n partition: partition.optional(),\n includeSourceMemoryIds: z.boolean().optional().describe('Also return the IDs of the summarized memories.'),\n }),\n execute: async ({ viewId: id, partition: input, includeSourceMemoryIds }, { abortSignal }) => {\n const view = ctx.hasResourceScope ? await assertView(id, 'view', abortSignal) : undefined;\n const resolved = resolvePartition(view, input) ?? {};\n return client.getSummaryViewResult(\n id, resolved.ownerId, resolved.sessionId, resolved.namespaceId, resolved.memoryType,\n includeSourceMemoryIds, { signal: abortSignal },\n );\n },\n }),\n };\n\n if (options.allowDeletes) {\n tools.delete_summary_view = tool({\n description:\n 'Delete a Summary View on the user\\'s explicit request. Deletion is asynchronous and safe to repeat. ' +\n 'The view enters DELETING and its schedule and materialized summaries are removed. ' +\n 'With a fixed user or namespace, only PRIVATE views whose filter is pinned to that user and namespace can be deleted.',\n inputSchema: z.object({ viewId }),\n execute: async ({ viewId: id }, { abortSignal }) => {\n if (ctx.hasResourceScope) await assertView(id, 'manage', abortSignal);\n return client.deleteSummaryView(id, { signal: abortSignal });\n },\n });\n }\n\n // Summary Views are store-wide and a session binds no user or namespace, so a sessionId-only toolset has no boundary to stay inside.\n if (ctx.scope.sessionId !== undefined && !ctx.hasResourceScope) {\n for (const entry of Object.values(tools)) {\n entry.execute = async () => fail('Summary View tools are unavailable when the toolset is scoped only by sessionId; fix a userId or namespaceId.');\n }\n }\n\n return tools;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redis/vercel-ai-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "AI SDK tools for Redis Agent Memory: session history, persistent memories, and semantic search",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -59,7 +59,7 @@
59
59
  "prepublishOnly": "npm run check"
60
60
  },
61
61
  "dependencies": {
62
- "@redis-iris/agent-memory": "~0.3.1",
62
+ "@redis-iris/agent-memory": "^1.0.0",
63
63
  "@types/json-schema": "^7.0.15"
64
64
  },
65
65
  "peerDependencies": {
package/src/errors.ts CHANGED
@@ -5,12 +5,17 @@ export class RedisAgentMemoryToolError extends Error {
5
5
  }
6
6
  }
7
7
 
8
+ const statusGuidance: Record<number, string> = {
9
+ 409: 'The request conflicts with the current state: the target already exists, changed concurrently, is archived or still has children, or the idempotencyKey was already used for a different request. Read the current state before retrying. Reuse an idempotencyKey only for the identical request.',
10
+ 412: 'The memory changed after expectedRevision was read, so nothing was written. Call get_memory for the current revision, reapply the change to it, and send that revision as expectedRevision.',
11
+ };
12
+
8
13
  /** Share safe SDK error handling between model tools and application hooks. */
9
14
  export function sanitizeMemoryError(error: unknown): RedisAgentMemoryToolError {
10
15
  if (error instanceof RedisAgentMemoryToolError) return error;
11
16
  const code = typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'
12
17
  ? error.statusCode : undefined;
13
18
  return new RedisAgentMemoryToolError(code ? `IRIS_HTTP_${code}` : 'IRIS_REQUEST_FAILED',
14
- code ? `Iris request failed (HTTP ${code}). Check service configuration and request scope. Writes may have partially succeeded; verify before retrying.`
19
+ code ? `Iris request failed (HTTP ${code}). ${statusGuidance[code] ?? 'Check service configuration and request scope. Writes may have partially succeeded; verify before retrying.'}`
15
20
  : 'Iris request failed. Check connectivity and service configuration. Verify writes before retrying.', code);
16
21
  }