@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/src/schemas.ts CHANGED
@@ -1,20 +1,35 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  export const id = z.string().min(1).max(255);
4
- export const sessionId = z.string().min(1).max(64).regex(/^[A-Za-z0-9-]+$/);
5
- export const ownerId = sessionId.describe('Stable application user identifier. Reuse it across conversations.');
4
+ export const sessionId = z.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
5
+ export const memoryId = z.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
6
+ const principalId = z.string().min(1).max(64).regex(/^(?!\.\.?$)[A-Za-z0-9_+=.@-]+$/);
7
+ export const ownerId = principalId.describe('Stable application user identifier. Reuse it across conversations.');
8
+ export const actorId = principalId.describe(
9
+ 'Author of this event: user ID for USER, agent ID for ASSISTANT. 1 to 64 letters, digits, or _+=.@-, and not . or ..');
6
10
  export const timestamp = z.iso.datetime({ offset: true });
7
11
  export const text = z.string().min(1).max(50_000);
8
12
  export const topics = z.array(z.string().min(1).max(100)).max(50);
9
13
  export const placement = { namespaceId: id.optional() };
10
14
  export const page = { limit: z.number().int().min(1).max(100).optional(), cursor: z.string().optional() };
15
+ export const idempotencyKey = z.string().min(1).max(255).describe(
16
+ 'Retry key. Reuse it only with the identical request to replay the saved result for up to 24 hours. ' +
17
+ 'Required when the store selects an input hook.');
18
+ export const sessionIdempotencyKey = z.string().min(1).max(255).describe(
19
+ 'Required when the store selects an input hook. The store may not deduplicate session events by this key, ' +
20
+ 'so after an uncertain append read get_session_memory before retrying.');
21
+ export const expectedRevision = z.string().min(1).describe(
22
+ 'Apply the write only if the memory still has this revision. Read it from get_memory. A stale revision fails with HTTP 412.');
23
+ export const sortOrder = z.enum(['ASC', 'DESC']);
24
+ export const attributes = z.record(z.string(), z.unknown());
11
25
  export const event = z.object({
12
26
  sessionId: sessionId.optional().describe('Reuse the current session ID. Omit only to create a new session.'),
13
- actorId: id.describe('Author of this event: user ID for USER, agent ID for ASSISTANT.'),
27
+ actorId,
14
28
  role: z.enum(['USER', 'ASSISTANT', 'SYSTEM']),
15
29
  content: z.array(z.object({ text })).min(1),
16
30
  createdAt: timestamp.optional().describe('ISO 8601 timestamp; defaults to the current time.'),
17
31
  metadata: z.unknown().optional().describe('Optional JSON metadata attached to the event.'),
32
+ idempotencyKey: sessionIdempotencyKey.optional(),
18
33
  ...placement,
19
34
  });
20
35
  export const memory = z.object({
@@ -23,7 +38,7 @@ export const memory = z.object({
23
38
  sessionId: sessionId.optional(),
24
39
  memoryType: z.string().min(1).optional().describe('Built-in or registered custom memory type.'),
25
40
  topics: topics.optional(),
26
- attributes: z.record(z.string(), z.unknown()).optional(),
41
+ attributes: attributes.optional(),
27
42
  ...placement,
28
43
  });
29
44
  export const memoryUpdate = z.object({
@@ -37,6 +52,9 @@ const comparison = z.object({
37
52
  'Supply exactly one of eq, ne, in, all.');
38
53
  export const search = z.object({
39
54
  query: text.optional(), minScore: z.number().min(0).max(1).optional(), ...page,
55
+ sortBy: z.enum(['createdAt', 'updatedAt']).optional().describe('Order a filter-only listing. Omit query when sorting.'),
56
+ sortOrder: sortOrder.optional().describe('Order a filter-only listing. Omit query when sorting.'),
57
+ excludeDocumentManaged: z.boolean().optional().describe('Omit memories produced by document ingestion.'),
40
58
  filter: z.object({
41
59
  op: z.enum(['ALL', 'ANY']).optional(),
42
60
  sessionId: comparison.optional(), ownerId: comparison.optional(),
@@ -1,5 +1,5 @@
1
1
  import { AgentMemory } from '@redis-iris/agent-memory';
2
- import type { LongTermMemoryFilter } from '@redis-iris/agent-memory/models';
2
+ import type { LongTermMemoryFilter, SessionEvent } from '@redis-iris/agent-memory/models';
3
3
  import type { z } from 'zod';
4
4
  import { RedisAgentMemoryToolError } from './errors.js';
5
5
  import * as s from './schemas.js';
@@ -22,7 +22,7 @@ type SearchInput = NonNullable<Parameters<AgentMemory['searchLongTermMemory']>[0
22
22
  type Placement = { namespaceId?: string };
23
23
 
24
24
  export interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {
25
- /** Reject when the named session already exists. Used by the legacy start_session tool. */
25
+ /** Create the session. An existing one is refused unless the request is keyed and matches its first event. */
26
26
  start?: boolean;
27
27
  /** Re-read a session created by this append to verify its immutable owner and placement. */
28
28
  postflightNewSession?: boolean;
@@ -216,6 +216,40 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
216
216
  return result;
217
217
  };
218
218
 
219
+ /**
220
+ * The store treats an idempotency key as store-wide, so two users whose models both pick a generic key would collide.
221
+ * Hashing the fixed scope and the request target into the key keeps retries identical and isolates everyone else.
222
+ */
223
+ function scopeIdempotencyKey(key: string, ...target: string[]): Promise<string>;
224
+ function scopeIdempotencyKey(key: string | undefined, ...target: string[]): Promise<string | undefined>;
225
+ async function scopeIdempotencyKey(key: string | undefined, ...target: string[]) {
226
+ if (key === undefined) return undefined;
227
+ const input = new TextEncoder().encode(JSON.stringify([
228
+ key, scope.userId ?? null, scope.sessionId ?? null, scope.namespaceId ?? null, target,
229
+ ]));
230
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));
231
+ return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');
232
+ }
233
+
234
+ const findStartEvent = async (
235
+ sessionId: string,
236
+ input: SessionEventInput,
237
+ options: ScopedMemoryRequestOptions,
238
+ ) => {
239
+ const { events, namespaceId } = await client.getSessionMemory(sessionId, true, options);
240
+ if (input.namespaceId !== undefined && namespaceId !== input.namespaceId) {
241
+ fail('This session already exists in a different namespace than requested; use add_session_event.');
242
+ }
243
+ // createdAt is caller-supplied and a later append may be backdated; systemTimestamp is the store's own clock.
244
+ // The store gives events no creation marker, so every event tied for the earliest clock reading is a candidate.
245
+ const earliest = Math.min(...events.map(event => event.systemTimestamp.getTime()));
246
+ const sameText = (event: SessionEvent) => event.content.length === input.content.length
247
+ && event.content.every((part, index) => part.text === input.content[index]!.text);
248
+ return events.find(event => event.systemTimestamp.getTime() === earliest
249
+ && event.actorId === input.actorId && event.role === input.role && sameText(event)
250
+ && (input.createdAt === undefined || event.createdAt.getTime() === Date.parse(input.createdAt)));
251
+ };
252
+
219
253
  const appendSessionEvent = async (
220
254
  input: SessionEventInput,
221
255
  options: AppendSessionEventOptions = {},
@@ -226,6 +260,10 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
226
260
  const requestSignal = requestOptions.signal ?? undefined;
227
261
  const placed = place(input);
228
262
  const sessionId = input.sessionId ?? scope.sessionId;
263
+ if (start && input.idempotencyKey !== undefined) {
264
+ if (!sessionId) fail('A keyed start_session needs a sessionId, so a retry can find the session it created.');
265
+ if (input.createdAt === undefined) fail('A keyed start_session needs createdAt, so a retry sends the identical request.');
266
+ }
229
267
  let newSession = false;
230
268
  if (sessionId) {
231
269
  resolveSession(sessionId);
@@ -234,7 +272,13 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
234
272
  try {
235
273
  await assertSession(sessionId, requestOptions, validateResponse);
236
274
  throwIfAborted(requestSignal);
237
- if (start) fail('This session already exists; use add_session_event.');
275
+ if (start) {
276
+ if (!input.idempotencyKey) fail('This session already exists; use add_session_event.');
277
+ // The store answers a repeated createSession with 409 even for the same key, so the replay happens here.
278
+ const first = await findStartEvent(sessionId, input, requestOptions);
279
+ if (!first) fail('This session already exists and its first event differs from this request; use add_session_event.');
280
+ return { event: first };
281
+ }
238
282
  } catch (error) {
239
283
  if (memoryErrorStatus(error) !== 404) throw error;
240
284
  newSession = true;
@@ -251,7 +295,8 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
251
295
  throwIfAborted(requestSignal);
252
296
  onPostStatus?.('started');
253
297
  const { sessionId: _sessionId, ...eventFields } = placed;
254
- const body = { ...eventFields, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };
298
+ const idempotencyKey = await scopeIdempotencyKey(input.idempotencyKey, sessionId ?? '');
299
+ const body = { ...eventFields, idempotencyKey, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };
255
300
  // createSession refuses an existing ID with 409; addSessionEvent appends and creates a missing session.
256
301
  const result = sessionId && !start
257
302
  ? await client.addSessionEvent(sessionId, body, requestOptions)
@@ -285,6 +330,7 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
285
330
  scopeSearch,
286
331
  searchLongTermMemory,
287
332
  searchPersonalMemories,
333
+ scopeIdempotencyKey,
288
334
  appendSessionEvent,
289
335
  });
290
336
  }
@@ -86,7 +86,7 @@ export function createSessionEventHook<Role extends SessionRole>(
86
86
  if (typeof options?.onError !== 'function') throw new Error('createSessionEventHook requires an onError callback.');
87
87
  const { role, onError, onEventStart, onEventSaved } = options;
88
88
  if (role !== 'USER' && role !== 'ASSISTANT') throw new Error('createSessionEventHook requires role USER or ASSISTANT.');
89
- const actorId = s.id.parse(options.actorId);
89
+ const actorId = s.actorId.parse(options.actorId);
90
90
  if (role === 'USER' && actorId !== scope.userId) {
91
91
  throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');
92
92
  }
@@ -0,0 +1,300 @@
1
+ import { tool, type ToolSet } from 'ai';
2
+ import type { AgentMemory } from '@redis-iris/agent-memory';
3
+ import type { LongTermMemoryFilter, SummaryView, SummaryViewScope } from '@redis-iris/agent-memory/models';
4
+ import { z } from 'zod';
5
+ import { RedisAgentMemoryToolError } from './errors.js';
6
+ import * as s from './schemas.js';
7
+ import type { ScopedMemory } from './scoped-memory.js';
8
+
9
+ export interface SummaryViewToolOptions {
10
+ allowDeletes: boolean;
11
+ }
12
+
13
+ /**
14
+ * view covers the definition and result reads; read adds partition refreshes;
15
+ * manage adds edits, full refreshes, and deletes. Levels are listed weakest first.
16
+ */
17
+ const LEVELS = ['none', 'view', 'read', 'manage'] as const;
18
+ type Access = typeof LEVELS[number];
19
+ type ScopedField = 'ownerId' | 'namespaceId';
20
+ type FilterInput = NonNullable<z.infer<typeof s.search>['filter']>;
21
+
22
+ function fail(message: string): never {
23
+ throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);
24
+ }
25
+
26
+ const groupBy = z.array(z.enum(['ownerId', 'sessionId', 'namespaceId', 'memoryType']))
27
+ .max(4)
28
+ .refine(fields => new Set(fields).size === fields.length, 'List each groupBy field once.')
29
+ .describe('One partition per distinct value of these fields. An empty list keeps a single summary.');
30
+ const output = z.object({
31
+ format: z.enum(['TEXT', 'STRUCTURED']),
32
+ instructions: z.string().min(1).optional().describe('What the summary should cover.'),
33
+ schema: z.object({
34
+ fields: z.array(z.object({
35
+ name: z.string().min(1),
36
+ description: z.string(),
37
+ type: z.enum(['STRING', 'INTEGER', 'FLOAT', 'BOOLEAN', 'STRING_LIST', 'FLOAT_LIST', 'OBJECT']),
38
+ })).min(1),
39
+ }).optional().describe('Flat field list for STRUCTURED output. Nested schemas and required fields are not supported.'),
40
+ }).refine(value => (value.format === 'STRUCTURED') === (value.schema !== undefined),
41
+ 'Supply schema exactly when format is STRUCTURED.');
42
+ const refreshPolicy = z.object({
43
+ mode: z.enum(['MANUAL', 'CONTINUOUS']),
44
+ debounceSeconds: z.number().int().nonnegative().optional(),
45
+ reconcileIntervalSeconds: z.number().int().positive().optional(),
46
+ }).refine(value => value.mode === 'CONTINUOUS'
47
+ ? value.reconcileIntervalSeconds !== undefined
48
+ : value.debounceSeconds === undefined && value.reconcileIntervalSeconds === undefined,
49
+ 'CONTINUOUS requires reconcileIntervalSeconds. MANUAL omits both interval fields.');
50
+ const evictionPolicy = z.object({ maxPartitions: z.number().int().positive() })
51
+ .describe('Keep at most this many partitions.');
52
+ const timeWindowSeconds = z.number().int().positive().describe('Only summarize memories from this rolling window.');
53
+ const filter = s.search.shape.filter.describe('Long-term memory filter that selects the source memories.');
54
+ const partition = z.object({
55
+ ownerId: s.ownerId.optional(), sessionId: s.sessionId.optional(), namespaceId: s.id.optional(), memoryType: s.id.optional(),
56
+ }).describe('One value for each groupBy field of the view. Omit for a view without groupBy.');
57
+ const viewId = s.id.describe('Summary View ID, such as sv_ followed by 32 hex characters.');
58
+
59
+ function toFilter(input: FilterInput): LongTermMemoryFilter {
60
+ const { createdAt, ...rest } = input;
61
+ if (createdAt === undefined) return rest;
62
+ return {
63
+ ...rest,
64
+ createdAt: Object.fromEntries(Object.entries(createdAt)
65
+ .filter(([, value]) => value !== undefined)
66
+ .map(([key, value]) => [key, new Date(value!)])),
67
+ };
68
+ }
69
+
70
+ /** Optional Summary View tools. Scoped toolsets only reach views whose partitions they can prove are theirs. */
71
+ export function createSummaryViewTools(
72
+ client: AgentMemory,
73
+ ctx: ScopedMemory,
74
+ options: SummaryViewToolOptions,
75
+ ): ToolSet {
76
+ const fixed = (['ownerId', 'namespaceId'] as const)
77
+ .map(field => [field, field === 'ownerId' ? ctx.scope.userId : ctx.scope.namespaceId] as const)
78
+ .filter((entry): entry is readonly [ScopedField, string] => entry[1] !== undefined);
79
+
80
+ // The view ownerId is the API caller, not the application user, so access is proven from filter and groupBy.
81
+ function access(view: SummaryView): Access {
82
+ if (!ctx.hasResourceScope) return 'manage';
83
+ if (view.visibility !== 'PRIVATE' && view.visibility !== 'SHARED') return 'none';
84
+ const viewFilter: LongTermMemoryFilter = view.filter ?? {};
85
+ const conditions = Object.entries(viewFilter).filter(([key, value]) => key !== 'op' && value !== undefined).length;
86
+ // The service default for op is not documented, so an implicit op only counts when nothing else could be ORed in.
87
+ const conjunctive = viewFilter.op?.toUpperCase() === 'ALL' || (viewFilter.op === undefined && conditions === 1);
88
+ let level: Access = 'manage';
89
+ for (const [field, value] of fixed) {
90
+ const condition = viewFilter[field];
91
+ // A filter naming another user or namespace is that scope's view, even when it also groups by the field.
92
+ if (condition?.eq !== undefined && condition.eq !== value) return 'none';
93
+ if (condition?.in !== undefined && !condition.in.includes(value)) return 'none';
94
+ const pinned = conjunctive && condition?.eq === value
95
+ && Object.values(condition).filter(item => item !== undefined).length === 1;
96
+ if (pinned) continue;
97
+ if (!view.groupBy.includes(field)) return 'none';
98
+ level = 'read';
99
+ }
100
+ // Every store-authorized caller sees a SHARED view, so a scoped toolset reads its own partition but never changes the view.
101
+ return view.visibility === 'SHARED' ? 'view' : level;
102
+ }
103
+
104
+ /** A definition that spans several users or namespaces names the others, so a scoped caller sees only its own value. */
105
+ function redact(view: SummaryView): SummaryView {
106
+ if (!ctx.hasResourceScope || view.filter === undefined) return view;
107
+ const filter: LongTermMemoryFilter = { ...view.filter };
108
+ for (const [field, value] of fixed) {
109
+ const condition = filter[field];
110
+ if (condition === undefined) continue;
111
+ if (condition.eq !== undefined) filter[field] = { eq: condition.eq };
112
+ else if (condition.in !== undefined) filter[field] = { in: [value] };
113
+ else delete filter[field];
114
+ }
115
+ return { ...view, filter };
116
+ }
117
+
118
+ async function assertView(id: string, needed: Exclude<Access, 'none'>, signal?: AbortSignal): Promise<SummaryView> {
119
+ const view = await client.getSummaryView(id, { signal });
120
+ const level = access(view);
121
+ if (level === 'none') fail('Summary View is outside the configured user or namespace scope.');
122
+ if (LEVELS.indexOf(level) >= LEVELS.indexOf(needed)) return view;
123
+ if (view.visibility === 'SHARED') {
124
+ fail('A SHARED Summary View is read-only with a fixed user or namespace. Its definition and your partition can be read.');
125
+ }
126
+ fail('This Summary View is shared across users or namespaces. Only views whose filter is pinned to the configured scope can be changed.');
127
+ }
128
+
129
+ function scopeFilter(input?: FilterInput): LongTermMemoryFilter | undefined {
130
+ const converted = input && toFilter(input);
131
+ return ctx.hasResourceScope ? ctx.scopeSearch({ filter: converted }).filter : converted;
132
+ }
133
+
134
+ function resolvePartition(view: SummaryView | undefined, input: SummaryViewScope = {}): SummaryViewScope | undefined {
135
+ const resolved = { ...input };
136
+ if (view) {
137
+ for (const [field, value] of fixed) {
138
+ if (resolved[field] !== undefined && resolved[field] !== value) fail(`Cannot reach another ${field} partition.`);
139
+ if (view.groupBy.includes(field)) resolved[field] = value;
140
+ }
141
+ }
142
+ return Object.values(resolved).some(value => value !== undefined) ? resolved : undefined;
143
+ }
144
+
145
+ const tools: ToolSet = {
146
+ list_summary_views: tool({
147
+ description:
148
+ 'List Summary View definitions and their state. Summary text is not included; use get_summary_view_result for it. ' +
149
+ 'Reuse nextCursor to fetch another page. With a fixed user or namespace, only views whose filter pins or whose ' +
150
+ 'groupBy splits by that user and namespace are listed, so a page can hold fewer items than limit. ' +
151
+ 'SHARED views among them are read-only.',
152
+ inputSchema: z.object({ ...s.page }),
153
+ execute: async ({ limit, cursor }, { abortSignal }) => {
154
+ const result = await client.listSummaryViews(limit, cursor, { signal: abortSignal });
155
+ return { ...result, items: result.items.filter(view => access(view) !== 'none').map(redact) };
156
+ },
157
+ }),
158
+
159
+ get_summary_view: tool({
160
+ description:
161
+ 'Get one Summary View definition with its filter, groupBy, output, refresh policy, state, and definitionVersion. ' +
162
+ '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.',
163
+ inputSchema: z.object({ viewId }),
164
+ execute: async ({ viewId: id }, { abortSignal }) => redact(await assertView(id, 'view', abortSignal)),
165
+ }),
166
+
167
+ create_summary_view: tool({
168
+ description:
169
+ 'Create a Summary View that keeps a generated summary of matching long-term memories. ' +
170
+ 'groupBy splits it into one partition per value of each listed field. TEXT output writes prose. ' +
171
+ 'STRUCTURED output fills the fields in output.schema. MANUAL views refresh only through refresh_summary_view. ' +
172
+ 'CONTINUOUS views refresh on their own and reconcile every reconcileIntervalSeconds. ' +
173
+ 'The first refresh runs asynchronously. PRIVATE (the default) keeps the view to this API caller. ' +
174
+ 'SHARED publishes a view of shared memories to every store-authorized caller. ' +
175
+ 'With a fixed user or namespace, the view is always PRIVATE, SHARED is refused, and the filter is pinned to that ' +
176
+ 'user and namespace, so groupBy cannot reach other memories.',
177
+ inputSchema: z.object({
178
+ name: z.string().min(1),
179
+ description: z.string().optional(),
180
+ visibility: z.enum(['PRIVATE', 'SHARED']).optional().describe('Immutable after creation.'),
181
+ filter,
182
+ groupBy,
183
+ evictionPolicy: evictionPolicy.optional(),
184
+ timeWindowSeconds: timeWindowSeconds.optional(),
185
+ output,
186
+ refreshPolicy,
187
+ }),
188
+ execute: async ({ visibility, filter: input, ...request }, { abortSignal }) => {
189
+ if (ctx.hasResourceScope && visibility === 'SHARED') {
190
+ fail('A toolset with a fixed user or namespace can only create PRIVATE Summary Views.');
191
+ }
192
+ return client.createSummaryView({
193
+ ...request,
194
+ source: 'LONG_TERM',
195
+ visibility: ctx.hasResourceScope ? 'PRIVATE' : visibility,
196
+ filter: scopeFilter(input),
197
+ }, { signal: abortSignal });
198
+ },
199
+ }),
200
+
201
+ update_summary_view: tool({
202
+ description:
203
+ 'Change a Summary View. Source and visibility cannot change. Changes to filter, groupBy, time window, eviction, ' +
204
+ 'output, or refresh policy increment definitionVersion and refresh the view. Name and description changes do not. ' +
205
+ 'state switches the view between ACTIVE and DISABLED. filter and clearFilter cannot be combined, nor can ' +
206
+ 'timeWindowSeconds and clearTimeWindow. With a fixed user or namespace, only PRIVATE views whose filter is pinned to ' +
207
+ 'that user and namespace can change, a new filter is pinned the same way, and clearFilter is refused.',
208
+ inputSchema: z.object({
209
+ viewId,
210
+ name: z.string().min(1).optional(),
211
+ description: z.string().optional().describe('Send an empty string to clear it.'),
212
+ filter: filter.describe('Replaces the saved filter.'),
213
+ clearFilter: z.boolean().optional(),
214
+ groupBy: groupBy.optional(),
215
+ evictionPolicy: evictionPolicy.optional(),
216
+ timeWindowSeconds: timeWindowSeconds.optional(),
217
+ clearTimeWindow: z.boolean().optional(),
218
+ output: output.optional(),
219
+ refreshPolicy: refreshPolicy.optional(),
220
+ state: z.enum(['ACTIVE', 'DISABLED']).optional(),
221
+ }),
222
+ execute: async ({ viewId: id, filter: input, ...changes }, { abortSignal }) => {
223
+ if (input === undefined && !Object.values(changes).some(value => value !== undefined)) fail('Supply at least one change.');
224
+ if (ctx.hasResourceScope) {
225
+ if (changes.clearFilter) fail('Cannot clear the filter that keeps this view inside the configured scope.');
226
+ await assertView(id, 'manage', abortSignal);
227
+ }
228
+ return client.updateSummaryView(id, {
229
+ ...changes,
230
+ filter: input === undefined ? undefined : scopeFilter(input),
231
+ }, { signal: abortSignal });
232
+ },
233
+ }),
234
+
235
+ refresh_summary_view: tool({
236
+ description:
237
+ 'Queue a Summary View refresh. It runs asynchronously, so read the result later and check its status. ' +
238
+ 'PARTITION refreshes one exact partition. FULL reconciles every partition and takes no partition. ' +
239
+ 'With a fixed user or namespace, the partition is filled in with that user and namespace, other values are refused, ' +
240
+ 'FULL is allowed only on views whose filter is pinned to that user and namespace, and SHARED views are refused.',
241
+ inputSchema: z.object({ viewId, target: z.enum(['PARTITION', 'FULL']), partition: partition.optional() }),
242
+ execute: async ({ viewId: id, target, partition: input }, { abortSignal }) => {
243
+ if (target === 'FULL' && input !== undefined) fail('A FULL refresh takes no partition.');
244
+ const view = ctx.hasResourceScope
245
+ ? await assertView(id, target === 'FULL' ? 'manage' : 'read', abortSignal)
246
+ : undefined;
247
+ return client.refreshSummaryView(id, {
248
+ target,
249
+ scope: target === 'PARTITION' ? resolvePartition(view, input) : undefined,
250
+ }, { signal: abortSignal });
251
+ },
252
+ }),
253
+
254
+ get_summary_view_result: tool({
255
+ description:
256
+ 'Read the generated summary for one exact partition of a Summary View. Check status before using value. ' +
257
+ 'COLD, PENDING, and EMPTY have no value. READY and REFRESHING carry a value. FAILED keeps the last good value ' +
258
+ 'when one exists and reports errorCode. stale means the value lags its sources. truncated means some memories ' +
259
+ 'or content were left out. Invalid output is withheld while the service repairs it. ' +
260
+ 'With a fixed user or namespace, the partition is filled in with that user and namespace and other values are refused. ' +
261
+ 'This also applies to SHARED views.',
262
+ inputSchema: z.object({
263
+ viewId,
264
+ partition: partition.optional(),
265
+ includeSourceMemoryIds: z.boolean().optional().describe('Also return the IDs of the summarized memories.'),
266
+ }),
267
+ execute: async ({ viewId: id, partition: input, includeSourceMemoryIds }, { abortSignal }) => {
268
+ const view = ctx.hasResourceScope ? await assertView(id, 'view', abortSignal) : undefined;
269
+ const resolved = resolvePartition(view, input) ?? {};
270
+ return client.getSummaryViewResult(
271
+ id, resolved.ownerId, resolved.sessionId, resolved.namespaceId, resolved.memoryType,
272
+ includeSourceMemoryIds, { signal: abortSignal },
273
+ );
274
+ },
275
+ }),
276
+ };
277
+
278
+ if (options.allowDeletes) {
279
+ tools.delete_summary_view = tool({
280
+ description:
281
+ 'Delete a Summary View on the user\'s explicit request. Deletion is asynchronous and safe to repeat. ' +
282
+ 'The view enters DELETING and its schedule and materialized summaries are removed. ' +
283
+ 'With a fixed user or namespace, only PRIVATE views whose filter is pinned to that user and namespace can be deleted.',
284
+ inputSchema: z.object({ viewId }),
285
+ execute: async ({ viewId: id }, { abortSignal }) => {
286
+ if (ctx.hasResourceScope) await assertView(id, 'manage', abortSignal);
287
+ return client.deleteSummaryView(id, { signal: abortSignal });
288
+ },
289
+ });
290
+ }
291
+
292
+ // Summary Views are store-wide and a session binds no user or namespace, so a sessionId-only toolset has no boundary to stay inside.
293
+ if (ctx.scope.sessionId !== undefined && !ctx.hasResourceScope) {
294
+ for (const entry of Object.values(tools)) {
295
+ entry.execute = async () => fail('Summary View tools are unavailable when the toolset is scoped only by sessionId; fix a userId or namespaceId.');
296
+ }
297
+ }
298
+
299
+ return tools;
300
+ }