@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
package/src/namespaces.ts CHANGED
@@ -3,11 +3,14 @@ import type { AgentMemory } from "@redis-iris/agent-memory";
3
3
  import type { Namespace } from "@redis-iris/agent-memory/models";
4
4
  import { z } from "zod";
5
5
  import { RedisAgentMemoryToolError } from "./errors.js";
6
+ import * as s from "./schemas.js";
6
7
 
7
8
  export interface NamespaceToolOptions {
8
9
  ownerId?: string;
9
10
  namespaceId?: string;
10
11
  allowDeletes: boolean;
12
+ /** Expose put_namespace_routing, which replaces the store-wide routing policy. */
13
+ allowRoutingWrites?: boolean;
11
14
  assertMemory: (id: string, signal?: AbortSignal) => Promise<unknown>;
12
15
  }
13
16
 
@@ -17,6 +20,30 @@ const namespaceName = z.string().min(1).refine((name) => !name.includes("/"), {
17
20
  message: "A namespace name is one path segment; use path to create a hierarchy.",
18
21
  });
19
22
 
23
+ const routeCondition = z.object({
24
+ kind: z.enum(["LLM_PROMPT", "MATCHER_SPEC"]),
25
+ llmPrompt: z.object({ prompt: z.string().min(1) }).optional().describe("Required for LLM_PROMPT."),
26
+ matcher: z.object({
27
+ kind: z.literal("REGEX"),
28
+ regex: z.object({ pattern: z.string().min(1).describe("RE2 syntax. No lookaround or backreferences.") }),
29
+ }).optional().describe("Required for MATCHER_SPEC."),
30
+ }).refine(
31
+ (condition) => condition.kind === "LLM_PROMPT"
32
+ ? condition.llmPrompt !== undefined && condition.matcher === undefined
33
+ : condition.matcher !== undefined && condition.llmPrompt === undefined,
34
+ { message: "Supply exactly the block that matches kind: llmPrompt for LLM_PROMPT, matcher for MATCHER_SPEC." },
35
+ );
36
+ const routingPolicy = z.object({
37
+ enabled: z.boolean(),
38
+ rules: z.array(z.object({
39
+ id: z.string().min(1).max(64),
40
+ destinationNamespaceId: identifier.describe("A shared namespace ID."),
41
+ enabled: z.boolean(),
42
+ action: z.enum(["ACCEPT", "REJECT"]),
43
+ strategies: z.array(routeCondition).optional(),
44
+ })).optional(),
45
+ });
46
+
20
47
  /** Optional namespace administration tools. Access checks never trust model-supplied IDs. */
21
48
  export function createNamespaceTools(
22
49
  client: AgentMemory,
@@ -43,6 +70,12 @@ export function createNamespaceTools(
43
70
  }
44
71
  }
45
72
 
73
+ function assertStoreWide(message: string): void {
74
+ if (options.ownerId !== undefined || options.namespaceId !== undefined) {
75
+ throw new RedisAgentMemoryToolError("INVALID_SCOPE", `${message} Unavailable with a fixed user or namespace scope.`);
76
+ }
77
+ }
78
+
46
79
  async function assertNamespace(namespaceId: string, signal?: AbortSignal): Promise<Namespace> {
47
80
  assertNamespaceId(namespaceId);
48
81
  const result = await client.getNamespace(namespaceId, requestOptions(signal));
@@ -53,19 +86,21 @@ export function createNamespaceTools(
53
86
  const tools: ToolSet = {
54
87
  list_namespaces: tool({
55
88
  description:
56
- "List namespace roots or the direct children of a namespace. Reuse nextPageToken to fetch another page. " +
57
- "With a fixed namespace configuration, omit filters and pageToken to retrieve only that namespace.",
89
+ "List namespace roots or the direct children of a namespace. Reuse nextCursor to fetch another page. " +
90
+ "With a fixed namespace configuration, omit filters and cursor to retrieve only that namespace.",
58
91
  inputSchema: z.object({
59
92
  parentId: identifier.optional().describe("List direct children; omit to list roots."),
60
93
  scope: scopeSchema.optional().describe("Root scope. Cannot be combined with parentId."),
61
- ownerId: identifier.optional().describe("Owner of PERSONAL roots. Cannot be combined with parentId."),
94
+ ownerId: s.ownerId.optional().describe("Owner of PERSONAL roots. Cannot be combined with parentId."),
62
95
  limit: z.number().int().min(1).max(1000).optional(),
63
- pageToken: z.string().min(1).optional(),
96
+ cursor: z.string().min(1).optional(),
97
+ sortBy: z.enum(["id", "name", "createdAt", "updatedAt"]).optional().describe("Defaults to id."),
98
+ sortOrder: z.enum(["ASC", "DESC"]).optional().describe("Defaults to ASC."),
64
99
  }),
65
100
  execute: async (input, { abortSignal }) => {
66
101
  if (options.namespaceId !== undefined) {
67
- if (input.parentId !== undefined || input.scope !== undefined || input.ownerId !== undefined || input.pageToken !== undefined) {
68
- throw new RedisAgentMemoryToolError("INVALID_SCOPE", "Omit filters and pageToken when listing a fixed namespace.");
102
+ if (input.parentId !== undefined || input.scope !== undefined || input.ownerId !== undefined || input.cursor !== undefined) {
103
+ throw new RedisAgentMemoryToolError("INVALID_SCOPE", "Omit filters and cursor when listing a fixed namespace.");
69
104
  }
70
105
  return { items: [await assertNamespace(options.namespaceId, abortSignal)] };
71
106
  }
@@ -96,8 +131,10 @@ export function createNamespaceTools(
96
131
  scope,
97
132
  ownerId,
98
133
  input.limit,
99
- input.pageToken,
134
+ input.cursor,
100
135
  requestOptions(abortSignal),
136
+ input.sortBy,
137
+ input.sortOrder,
101
138
  );
102
139
  for (const namespace of result.items) await assertOwner(namespace, abortSignal);
103
140
  return result;
@@ -122,7 +159,7 @@ export function createNamespaceTools(
122
159
  path: z.string().min(1).optional(),
123
160
  scope: scopeSchema.optional(),
124
161
  parentId: identifier.optional(),
125
- ownerId: identifier.optional(),
162
+ ownerId: s.ownerId.optional(),
126
163
  }),
127
164
  execute: async (input, { abortSignal }) => {
128
165
  if (options.namespaceId !== undefined) {
@@ -181,24 +218,54 @@ export function createNamespaceTools(
181
218
 
182
219
  move_memories: tool({
183
220
  description:
184
- "Move existing long-term memories to an existing, active namespace. Supply known memory IDs and the " +
185
- "destination namespace ID. Partial failures are returned in errors; inspect them before claiming success.",
221
+ "Move existing long-term memories to an active namespace, or omit namespaceId to re-route them by the " +
222
+ "store's routing policy. Automatic routing only applies to memories already in a shared namespace. " +
223
+ "Personal and unnamespaced memories keep their placement and get a per-item error. An explicit destination " +
224
+ "must pass admission and is never rerouted. Partial failures are returned in errors; inspect them before claiming success.",
186
225
  inputSchema: z.object({
187
226
  memoryIds: z.array(identifier).min(1).max(100),
188
- namespaceId: identifier.describe("Destination namespace ID."),
227
+ namespaceId: identifier.optional().describe("Destination namespace ID. Omit for automatic routing."),
189
228
  }),
190
229
  execute: async ({ memoryIds, namespaceId }, { abortSignal }) => {
191
- const namespace = await assertNamespace(namespaceId, abortSignal);
192
- if (namespace.state !== "ACTIVE") throw new RedisAgentMemoryToolError("INVALID_SCOPE", "Cannot move memories into an archived namespace.");
230
+ if (namespaceId === undefined) {
231
+ assertStoreWide("Automatic routing can move memories outside the configured scope.");
232
+ } else {
233
+ const namespace = await assertNamespace(namespaceId, abortSignal);
234
+ if (namespace.state !== "ACTIVE") throw new RedisAgentMemoryToolError("INVALID_SCOPE", "Cannot move memories into an archived namespace.");
235
+ }
193
236
  for (const memoryId of memoryIds) await options.assertMemory(memoryId, abortSignal);
194
237
  return client.moveLongTermMemories(
195
- { memoryIds, namespaceRef: { namespaceId } },
238
+ { memoryIds, namespaceId },
196
239
  requestOptions(abortSignal),
197
240
  );
198
241
  },
199
242
  }),
243
+
244
+ get_namespace_routing: tool({
245
+ description:
246
+ "Get the store-wide namespace routing policy. A store without a saved policy returns an empty disabled policy.",
247
+ inputSchema: z.object({}),
248
+ execute: async (_input, { abortSignal }) => {
249
+ assertStoreWide("Namespace routing is a store-wide policy.");
250
+ return client.getNamespaceRouting({}, requestOptions(abortSignal));
251
+ },
252
+ }),
200
253
  };
201
254
 
255
+ if (options.allowRoutingWrites) {
256
+ tools.put_namespace_routing = tool({
257
+ description:
258
+ "Replace the whole store-wide namespace routing policy. Read it with get_namespace_routing first and send " +
259
+ "every rule to keep. Rules only target shared namespaces. ACCEPT selects a destination; REJECT blocks one, " +
260
+ "even when a caller names it. Change routing only on an explicit administrator request.",
261
+ inputSchema: z.object({ policy: routingPolicy }),
262
+ execute: async ({ policy }, { abortSignal }) => {
263
+ assertStoreWide("Namespace routing is a store-wide policy.");
264
+ return client.putNamespaceRouting({ policy }, requestOptions(abortSignal));
265
+ },
266
+ });
267
+ }
268
+
202
269
  if (options.allowDeletes) {
203
270
  tools.delete_namespace = tool({
204
271
  description:
package/src/provider.ts CHANGED
@@ -397,7 +397,7 @@ export function createRedisAgentMemoryModel(
397
397
  let assistantId: string | undefined;
398
398
  if (recording) {
399
399
  if (!scope.sessionId) throw providerError('INVALID_CONFIGURATION', 'Recording requires scope.sessionId.');
400
- try { assistantId = s.id.parse(options.assistantId); }
400
+ try { assistantId = s.actorId.parse(options.assistantId); }
401
401
  catch { throw providerError('INVALID_CONFIGURATION', 'Recording requires a valid assistantId.'); }
402
402
  }
403
403
  const scoped = createScopedMemory(client, scope);
@@ -601,7 +601,7 @@ export function createRedisAgentMemoryModel(
601
601
  return providerMetadata;
602
602
  }
603
603
  const memories = (context?.includedMemories ?? []).map(memory => {
604
- const entry: Record<string, string> = { id: memory.id };
604
+ const entry: Record<string, string> = { id: memory.memoryId };
605
605
  if (memory.memoryType !== undefined) entry.memoryType = memory.memoryType;
606
606
  const createdAt = isoTimestamp(memory.createdAt);
607
607
  const updatedAt = isoTimestamp(memory.updatedAt);
package/src/schemas.ts CHANGED
@@ -1,21 +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
- export const namespaceRef = z.object({ namespaceId: id });
10
- export const placement = { namespace: z.string().max(255).optional(), namespaceRef: namespaceRef.optional() };
11
- export const page = { limit: z.number().int().min(1).max(100).optional(), pageToken: z.string().optional() };
13
+ export const placement = { namespaceId: id.optional() };
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());
12
25
  export const event = z.object({
13
26
  sessionId: sessionId.optional().describe('Reuse the current session ID. Omit only to create a new session.'),
14
- actorId: id.describe('Author of this event: user ID for USER, agent ID for ASSISTANT.'),
27
+ actorId,
15
28
  role: z.enum(['USER', 'ASSISTANT', 'SYSTEM']),
16
29
  content: z.array(z.object({ text })).min(1),
17
30
  createdAt: timestamp.optional().describe('ISO 8601 timestamp; defaults to the current time.'),
18
31
  metadata: z.unknown().optional().describe('Optional JSON metadata attached to the event.'),
32
+ idempotencyKey: sessionIdempotencyKey.optional(),
19
33
  ...placement,
20
34
  });
21
35
  export const memory = z.object({
@@ -24,7 +38,7 @@ export const memory = z.object({
24
38
  sessionId: sessionId.optional(),
25
39
  memoryType: z.string().min(1).optional().describe('Built-in or registered custom memory type.'),
26
40
  topics: topics.optional(),
27
- attributes: z.record(z.string(), z.unknown()).optional(),
41
+ attributes: attributes.optional(),
28
42
  ...placement,
29
43
  });
30
44
  export const memoryUpdate = z.object({
@@ -37,12 +51,15 @@ const comparison = z.object({
37
51
  }).refine(value => Object.values(value).filter(v => v !== undefined).length === 1,
38
52
  'Supply exactly one of eq, ne, in, all.');
39
53
  export const search = z.object({
40
- text: text.optional(), similarityThreshold: z.number().min(0).max(1).optional(), ...page,
41
- filterOp: z.enum(['all', 'any']).optional(),
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.'),
42
58
  filter: z.object({
43
- sessionId: comparison.optional(), ownerId: comparison.optional(), namespace: comparison.optional(),
59
+ op: z.enum(['ALL', 'ANY']).optional(),
60
+ sessionId: comparison.optional(), ownerId: comparison.optional(),
44
61
  topics: comparison.optional(), memoryType: comparison.optional(),
45
- namespaceRef: z.object({ eq: id.optional(), in: z.array(id).min(1).optional() })
62
+ namespaceId: z.object({ eq: id.optional(), in: z.array(id).min(1).optional() })
46
63
  .refine(v => (v.eq === undefined) !== (v.in === undefined), 'Supply exactly one of eq or in.').optional(),
47
64
  unnamespaced: z.boolean().optional(),
48
65
  createdAt: z.object({ gt: timestamp.optional(), gte: timestamp.optional(), lt: timestamp.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';
@@ -9,8 +9,6 @@ export interface RedisAgentMemoryScope {
9
9
  userId?: string;
10
10
  /** Locks session operations and associates new memories; recall still spans this user's sessions. */
11
11
  sessionId?: string;
12
- /** Deprecated label; prefer namespaceId for resource-backed namespaces. */
13
- namespace?: string;
14
12
  namespaceId?: string;
15
13
  }
16
14
 
@@ -21,10 +19,10 @@ export interface ScopeValidationOptions {
21
19
  export type ScopedMemoryRequestOptions = NonNullable<Parameters<AgentMemory['getSessionMemory']>[2]>;
22
20
  type SessionEventInput = z.infer<typeof s.event>;
23
21
  type SearchInput = NonNullable<Parameters<AgentMemory['searchLongTermMemory']>[0]>;
24
- type Placement = { namespace?: string; namespaceRef?: { namespaceId: string } };
22
+ type Placement = { namespaceId?: string };
25
23
 
26
24
  export interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {
27
- /** 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. */
28
26
  start?: boolean;
29
27
  /** Re-read a session created by this append to verify its immutable owner and placement. */
30
28
  postflightNewSession?: boolean;
@@ -59,7 +57,8 @@ export function resolveAgentMemoryClient(
59
57
  const resolvedStoreId = storeId ?? env.AGENT_MEMORY_STORE_ID;
60
58
  if (!key?.trim()) throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');
61
59
  if (!resolvedStoreId?.trim()) throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');
62
- const serverURL = serverUrl ?? env.AGENT_MEMORY_URL ?? 'https://gcp-us-east4.memory.redis.io';
60
+ const serverURL = serverUrl ?? env.AGENT_MEMORY_URL;
61
+ if (!serverURL?.trim()) throw new Error('Set AGENT_MEMORY_URL or pass serverUrl; each store has its own endpoint URL.');
63
62
  const url = new URL(serverURL);
64
63
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
65
64
  throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');
@@ -68,17 +67,27 @@ export function resolveAgentMemoryClient(
68
67
  return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });
69
68
  }
70
69
 
70
+ const SCOPE_KEYS: ReadonlySet<string> = new Set(['userId', 'sessionId', 'namespaceId']);
71
+
72
+ /** Unknown keys would be ignored, silently dropping a boundary the caller meant to enforce. */
73
+ function assertKnownScopeKeys(scope: object, label: string): void {
74
+ for (const key of Object.keys(scope)) {
75
+ if (SCOPE_KEYS.has(key)) continue;
76
+ throw new Error(key === 'namespace'
77
+ ? `${label}.namespace was removed; use ${label}.namespaceId.`
78
+ : `Unknown ${label} field: ${key}.`);
79
+ }
80
+ }
81
+
71
82
  export function copyMemoryScope(
72
83
  scope: RedisAgentMemoryScope,
73
- options: ScopeValidationOptions = {},
84
+ _options: ScopeValidationOptions = {},
74
85
  ): Readonly<RedisAgentMemoryScope> {
86
+ assertKnownScopeKeys(scope, 'scope');
75
87
  const copied = Object.freeze({ ...scope });
76
88
  if (copied.userId !== undefined) s.ownerId.parse(copied.userId);
77
89
  if (copied.sessionId !== undefined) s.sessionId.parse(copied.sessionId);
78
90
  if (copied.namespaceId !== undefined) s.id.parse(copied.namespaceId);
79
- if (copied.namespace !== undefined && !copied.namespace.trim()) throw new Error('scope.namespace must not be empty.');
80
- if (copied.namespace !== undefined && copied.namespaceId !== undefined) throw new Error('Choose scope.namespace or scope.namespaceId.');
81
- if (options.namespaceTools && copied.namespace !== undefined) throw new Error('Namespace resource tools cannot use a legacy namespace scope.');
82
91
  return copied;
83
92
  }
84
93
 
@@ -86,8 +95,9 @@ export function extendMemoryScope(
86
95
  scope: RedisAgentMemoryScope,
87
96
  context: RedisAgentMemoryScope,
88
97
  ): RedisAgentMemoryScope {
98
+ assertKnownScopeKeys(context, 'context scope');
89
99
  const extended = { ...scope };
90
- for (const name of ['userId', 'sessionId', 'namespace', 'namespaceId'] as const) {
100
+ for (const name of ['userId', 'sessionId', 'namespaceId'] as const) {
91
101
  const value = context[name];
92
102
  if (value === undefined) continue;
93
103
  if (scope[name] !== undefined && scope[name] !== value) fail(`Cannot override ${name} scope.`);
@@ -102,28 +112,18 @@ export function extendMemoryScope(
102
112
  */
103
113
  export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMemoryScope) {
104
114
  const scope = copyMemoryScope(inputScope);
105
- const hasResourceScope = Boolean(scope.userId || scope.namespace !== undefined || scope.namespaceId);
115
+ const hasResourceScope = Boolean(scope.userId || scope.namespaceId);
106
116
 
107
117
  const checkPlacement = (value: Placement) => {
108
- if (value.namespace !== undefined && value.namespaceRef !== undefined) fail('Supply namespace or namespaceRef, never both.');
109
- if (scope.namespace !== undefined && value.namespace !== scope.namespace) fail('Resource is outside the configured namespace.');
110
- if (scope.namespaceId !== undefined && value.namespaceRef?.namespaceId !== scope.namespaceId) {
118
+ if (scope.namespaceId !== undefined && value.namespaceId !== scope.namespaceId) {
111
119
  fail('Resource is outside the configured namespace resource.');
112
120
  }
113
121
  };
114
122
 
115
123
  const place = <T extends Placement>(input: T): T => {
116
- const value = { ...input };
117
- if (value.namespace !== undefined && value.namespaceRef !== undefined) fail('Supply namespace or namespaceRef, never both.');
118
- if (scope.namespace !== undefined) {
119
- if (value.namespaceRef || (value.namespace !== undefined && value.namespace !== scope.namespace)) fail('Cannot override namespace scope.');
120
- value.namespace = scope.namespace;
121
- }
122
- if (scope.namespaceId !== undefined) {
123
- if (value.namespace !== undefined || (value.namespaceRef && value.namespaceRef.namespaceId !== scope.namespaceId)) fail('Cannot override namespace scope.');
124
- value.namespaceRef = { namespaceId: scope.namespaceId };
125
- }
126
- return value;
124
+ if (scope.namespaceId === undefined) return { ...input };
125
+ if (input.namespaceId !== undefined && input.namespaceId !== scope.namespaceId) fail('Cannot override namespace scope.');
126
+ return { ...input, namespaceId: scope.namespaceId };
127
127
  };
128
128
 
129
129
  const resolveSession = (value?: string) => {
@@ -164,10 +164,10 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
164
164
  };
165
165
 
166
166
  const assertPlacementOwner = async (value: Placement, options?: ScopedMemoryRequestOptions) => {
167
- if (!scope.userId || !value.namespaceRef) return;
167
+ if (!scope.userId || !value.namespaceId) return;
168
168
  const signal = options?.signal ?? undefined;
169
169
  throwIfAborted(signal);
170
- const { namespace } = await client.getNamespace(value.namespaceRef.namespaceId, options);
170
+ const { namespace } = await client.getNamespace(value.namespaceId, options);
171
171
  throwIfAborted(signal);
172
172
  const root = namespace.rootId === namespace.namespaceId ? namespace
173
173
  : (await client.getNamespace(namespace.rootId, options)).namespace;
@@ -179,12 +179,11 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
179
179
 
180
180
  const scopeSearch = (input: SearchInput): SearchInput => {
181
181
  const filter: LongTermMemoryFilter = { ...input.filter };
182
- if (filter.namespace && filter.namespaceRef) fail('Supply namespace or namespaceRef, never both.');
183
- if (filter.unnamespaced !== undefined && (filter.namespace || filter.namespaceRef)) {
182
+ if (filter.unnamespaced !== undefined && filter.namespaceId) {
184
183
  fail('unnamespaced cannot be combined with namespace selectors.');
185
184
  }
186
- if (hasResourceScope && input.filterOp === 'any') fail('Scoped searches require filterOp all to preserve isolation.');
187
- const fixed = (name: 'ownerId' | 'namespace' | 'namespaceRef', value: string) => {
185
+ if (hasResourceScope && filter.op?.toUpperCase() === 'ANY') fail('Scoped searches require filter.op ALL to preserve isolation.');
186
+ const fixed = (name: 'ownerId' | 'namespaceId', value: string) => {
188
187
  const existing = filter[name];
189
188
  if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {
190
189
  fail(`Cannot override ${name} scope.`);
@@ -192,17 +191,11 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
192
191
  filter[name] = { eq: value };
193
192
  };
194
193
  if (scope.userId) fixed('ownerId', scope.userId);
195
- if (scope.namespace !== undefined || scope.namespaceId) {
194
+ if (scope.namespaceId) {
196
195
  if (filter.unnamespaced !== undefined) fail('Cannot search unnamespaced records within a namespace scope.');
197
- if (scope.namespace !== undefined) {
198
- if (filter.namespaceRef) fail('Cannot override namespace scope.');
199
- fixed('namespace', scope.namespace);
200
- } else {
201
- if (filter.namespace) fail('Cannot override namespace scope.');
202
- fixed('namespaceRef', scope.namespaceId!);
203
- }
196
+ fixed('namespaceId', scope.namespaceId);
204
197
  }
205
- return { ...input, filter, filterOp: hasResourceScope ? 'all' : input.filterOp };
198
+ return { ...input, filter: hasResourceScope ? { ...filter, op: 'ALL' } : filter };
206
199
  };
207
200
 
208
201
  const searchLongTermMemory = (
@@ -215,7 +208,7 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
215
208
  limit: number,
216
209
  options?: ScopedMemoryRequestOptions,
217
210
  ) => {
218
- const result = await searchLongTermMemory({ text, limit }, options);
211
+ const result = await searchLongTermMemory({ query: text, limit }, options);
219
212
  for (const memory of result.items) {
220
213
  if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');
221
214
  checkPlacement(memory);
@@ -223,6 +216,40 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
223
216
  return result;
224
217
  };
225
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
+
226
253
  const appendSessionEvent = async (
227
254
  input: SessionEventInput,
228
255
  options: AppendSessionEventOptions = {},
@@ -233,6 +260,10 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
233
260
  const requestSignal = requestOptions.signal ?? undefined;
234
261
  const placed = place(input);
235
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
+ }
236
267
  let newSession = false;
237
268
  if (sessionId) {
238
269
  resolveSession(sessionId);
@@ -241,7 +272,13 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
241
272
  try {
242
273
  await assertSession(sessionId, requestOptions, validateResponse);
243
274
  throwIfAborted(requestSignal);
244
- 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
+ }
245
282
  } catch (error) {
246
283
  if (memoryErrorStatus(error) !== 404) throw error;
247
284
  newSession = true;
@@ -257,11 +294,13 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
257
294
  await assertPlacementOwner(placed, requestOptions);
258
295
  throwIfAborted(requestSignal);
259
296
  onPostStatus?.('started');
260
- const result = await client.addSessionEvent({
261
- ...placed,
262
- sessionId,
263
- createdAt: input.createdAt ? new Date(input.createdAt) : new Date(),
264
- }, requestOptions);
297
+ const { sessionId: _sessionId, ...eventFields } = placed;
298
+ const idempotencyKey = await scopeIdempotencyKey(input.idempotencyKey, sessionId ?? '');
299
+ const body = { ...eventFields, idempotencyKey, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };
300
+ // createSession refuses an existing ID with 409; addSessionEvent appends and creates a missing session.
301
+ const result = sessionId && !start
302
+ ? await client.addSessionEvent(sessionId, body, requestOptions)
303
+ : await client.createSession({ ...body, sessionId }, requestOptions);
265
304
  onPostStatus?.('acknowledged');
266
305
  if (validateResponse && (
267
306
  result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role
@@ -291,6 +330,7 @@ export function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMe
291
330
  scopeSearch,
292
331
  searchLongTermMemory,
293
332
  searchPersonalMemories,
333
+ scopeIdempotencyKey,
294
334
  appendSessionEvent,
295
335
  });
296
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
  }