@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
@@ -1 +1 @@
1
- {"version":3,"file":"scoped-memory.js","sourceRoot":"","sources":["../src/scoped-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AA8BlC,SAAS,cAAc,CAAC,MAAoB;IAC1C,IAAI,MAAM,EAAE,OAAO;QAAE,MAAM,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAAY,CAAC,CAAC;AAC1G,CAAC;AAED,SAAS,IAAI,CAAC,OAAe;IAC3B,MAAM,IAAI,yBAAyB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,YAAY,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ;QACjH,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC;AAED,yGAAyG;AACzG,MAAM,UAAU,wBAAwB,CACtC,SAAkB,EAClB,OAAgB,EAChB,MAAe,EACf,SAAS,GAAG,MAAM,EAClB,MAAoD,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG;IAErG,MAAM,GAAG,GAAG,MAAM,IAAI,GAAG,CAAC,oBAAoB,CAAC;IAC/C,MAAM,eAAe,GAAG,OAAO,IAAI,GAAG,CAAC,qBAAqB,CAAC;IAC7D,IAAI,CAAC,GAAG,EAAE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,CAAC,CAAC;QACvE,YAAY,EAAE,CAAC,cAAc,CAAC,CAAC;QAC/B,IAAI,gBAAgB,IAAI,CACtB,MAAM,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CACnH,EAAE,CAAC;YACF,IAAI,CAAC,+DAA+D,CAAC,CAAC;QACxE,CAAC;QACD,cAAc,CAAC,aAAa,CAAC,CAAC;QAC9B,IAAI,oBAAoB,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;YACpD,MAAM,aAAa,CAAC,SAAS,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;YACjE,cAAc,CAAC,aAAa,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,KAAK;QACL,gBAAgB;QAChB,cAAc;QACd,KAAK;QACL,cAAc;QACd,YAAY;QACZ,aAAa;QACb,cAAc;QACd,oBAAoB;QACpB,YAAY;QACZ,oBAAoB;QACpB,WAAW;QACX,oBAAoB;QACpB,sBAAsB;QACtB,kBAAkB;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter } from '@redis-iris/agent-memory/models';\nimport type { z } from 'zod';\nimport { RedisAgentMemoryToolError } from './errors.js';\nimport * as s from './schemas.js';\n\nexport interface RedisAgentMemoryScope {\n /** Stable application user ID. Used as the memory owner and as the actor for USER events. */\n userId?: string;\n /** Locks session operations and associates new memories; recall still spans this user's sessions. */\n sessionId?: string;\n namespaceId?: string;\n}\n\nexport interface ScopeValidationOptions {\n namespaceTools?: boolean;\n}\n\nexport type ScopedMemoryRequestOptions = NonNullable<Parameters<AgentMemory['getSessionMemory']>[2]>;\ntype SessionEventInput = z.infer<typeof s.event>;\ntype SearchInput = NonNullable<Parameters<AgentMemory['searchLongTermMemory']>[0]>;\ntype Placement = { namespaceId?: string };\n\nexport interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {\n /** Reject when the named session already exists. Used by the legacy start_session tool. */\n start?: boolean;\n /** Re-read a session created by this append to verify its immutable owner and placement. */\n postflightNewSession?: boolean;\n /** @internal Reports whether the append POST started or was acknowledged. */\n onPostStatus?: (status: 'started' | 'acknowledged') => void;\n /** @internal Validates the echoed event identity for wrapper writes. */\n validateResponse?: boolean;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new DOMException('Memory operation aborted.', 'AbortError');\n}\n\nfunction fail(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);\n}\n\nexport function memoryErrorStatus(error: unknown): number | undefined {\n return typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'\n ? error.statusCode : undefined;\n}\n\n/** Resolve and validate connection configuration without exposing credentials outside the SDK client. */\nexport function resolveAgentMemoryClient(\n serverUrl?: string,\n storeId?: string,\n apiKey?: string,\n timeoutMs = 30_000,\n env: Readonly<Record<string, string | undefined>> = typeof process === 'undefined' ? {} : process.env,\n): AgentMemory {\n const key = apiKey ?? env.AGENT_MEMORY_API_KEY;\n const resolvedStoreId = storeId ?? env.AGENT_MEMORY_STORE_ID;\n if (!key?.trim()) throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');\n if (!resolvedStoreId?.trim()) throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');\n const serverURL = serverUrl ?? env.AGENT_MEMORY_URL;\n if (!serverURL?.trim()) throw new Error('Set AGENT_MEMORY_URL or pass serverUrl; each store has its own endpoint URL.');\n const url = new URL(serverURL);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {\n throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('timeoutMs must be positive.');\n return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });\n}\n\nconst SCOPE_KEYS: ReadonlySet<string> = new Set(['userId', 'sessionId', 'namespaceId']);\n\n/** Unknown keys would be ignored, silently dropping a boundary the caller meant to enforce. */\nfunction assertKnownScopeKeys(scope: object, label: string): void {\n for (const key of Object.keys(scope)) {\n if (SCOPE_KEYS.has(key)) continue;\n throw new Error(key === 'namespace'\n ? `${label}.namespace was removed; use ${label}.namespaceId.`\n : `Unknown ${label} field: ${key}.`);\n }\n}\n\nexport function copyMemoryScope(\n scope: RedisAgentMemoryScope,\n _options: ScopeValidationOptions = {},\n): Readonly<RedisAgentMemoryScope> {\n assertKnownScopeKeys(scope, 'scope');\n const copied = Object.freeze({ ...scope });\n if (copied.userId !== undefined) s.ownerId.parse(copied.userId);\n if (copied.sessionId !== undefined) s.sessionId.parse(copied.sessionId);\n if (copied.namespaceId !== undefined) s.id.parse(copied.namespaceId);\n return copied;\n}\n\nexport function extendMemoryScope(\n scope: RedisAgentMemoryScope,\n context: RedisAgentMemoryScope,\n): RedisAgentMemoryScope {\n assertKnownScopeKeys(context, 'context scope');\n const extended = { ...scope };\n for (const name of ['userId', 'sessionId', 'namespaceId'] as const) {\n const value = context[name];\n if (value === undefined) continue;\n if (scope[name] !== undefined && scope[name] !== value) fail(`Cannot override ${name} scope.`);\n extended[name] = value;\n }\n return extended;\n}\n\n/**\n * Security boundary shared by tools, hooks, and the provider wrapper.\n * The client and validated scope are captured once and never exposed as enumerable state.\n */\nexport function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMemoryScope) {\n const scope = copyMemoryScope(inputScope);\n const hasResourceScope = Boolean(scope.userId || scope.namespaceId);\n\n const checkPlacement = (value: Placement) => {\n if (scope.namespaceId !== undefined && value.namespaceId !== scope.namespaceId) {\n fail('Resource is outside the configured namespace resource.');\n }\n };\n\n const place = <T extends Placement>(input: T): T => {\n if (scope.namespaceId === undefined) return { ...input };\n if (input.namespaceId !== undefined && input.namespaceId !== scope.namespaceId) fail('Cannot override namespace scope.');\n return { ...input, namespaceId: scope.namespaceId };\n };\n\n const resolveSession = (value?: string) => {\n if (scope.sessionId && value && value !== scope.sessionId) fail('Cannot override session scope.');\n const resolved = value ?? scope.sessionId;\n if (!resolved) fail('Supply sessionId or configure scope.sessionId.');\n return resolved;\n };\n\n const resolveOwner = (value?: string) => {\n if (scope.userId && value && value !== scope.userId) fail('Cannot override user scope.');\n const resolved = value ?? scope.userId;\n if (!resolved) fail('Supply ownerId or configure scope.userId.');\n return resolved;\n };\n\n const assertSession = async (\n sessionId: string,\n options?: ScopedMemoryRequestOptions,\n validateSessionId = false,\n ) => {\n resolveSession(sessionId);\n const session = await client.getSessionMemory(sessionId, false, options);\n if (validateSessionId && session.sessionId !== sessionId) fail('Session response does not match the configured session scope.');\n if (scope.userId && session.ownerId !== scope.userId) fail('Session is outside the configured user scope.');\n checkPlacement(session);\n return session;\n };\n\n const restoreSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options);\n const restoreScopedSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options, true);\n\n const assertMemory = async (id: string, options?: ScopedMemoryRequestOptions) => {\n const memory = await client.getLongTermMemory(id, options);\n if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');\n checkPlacement(memory);\n return memory;\n };\n\n const assertPlacementOwner = async (value: Placement, options?: ScopedMemoryRequestOptions) => {\n if (!scope.userId || !value.namespaceId) return;\n const signal = options?.signal ?? undefined;\n throwIfAborted(signal);\n const { namespace } = await client.getNamespace(value.namespaceId, options);\n throwIfAborted(signal);\n const root = namespace.rootId === namespace.namespaceId ? namespace\n : (await client.getNamespace(namespace.rootId, options)).namespace;\n throwIfAborted(signal);\n if (root.scope !== 'PERSONAL' || root.ownerId !== scope.userId) {\n fail('Namespace placement is outside the configured user’s personal namespaces.');\n }\n };\n\n const scopeSearch = (input: SearchInput): SearchInput => {\n const filter: LongTermMemoryFilter = { ...input.filter };\n if (filter.unnamespaced !== undefined && filter.namespaceId) {\n fail('unnamespaced cannot be combined with namespace selectors.');\n }\n if (hasResourceScope && filter.op?.toUpperCase() === 'ANY') fail('Scoped searches require filter.op ALL to preserve isolation.');\n const fixed = (name: 'ownerId' | 'namespaceId', value: string) => {\n const existing = filter[name];\n if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {\n fail(`Cannot override ${name} scope.`);\n }\n filter[name] = { eq: value };\n };\n if (scope.userId) fixed('ownerId', scope.userId);\n if (scope.namespaceId) {\n if (filter.unnamespaced !== undefined) fail('Cannot search unnamespaced records within a namespace scope.');\n fixed('namespaceId', scope.namespaceId);\n }\n return { ...input, filter: hasResourceScope ? { ...filter, op: 'ALL' } : filter };\n };\n\n const searchLongTermMemory = (\n input: SearchInput,\n options?: ScopedMemoryRequestOptions,\n ) => client.searchLongTermMemory(scopeSearch(input), options);\n\n const searchPersonalMemories = async (\n text: string,\n limit: number,\n options?: ScopedMemoryRequestOptions,\n ) => {\n const result = await searchLongTermMemory({ query: text, limit }, options);\n for (const memory of result.items) {\n if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');\n checkPlacement(memory);\n }\n return result;\n };\n\n const appendSessionEvent = async (\n input: SessionEventInput,\n options: AppendSessionEventOptions = {},\n ) => {\n const {\n start = false, postflightNewSession = false, onPostStatus, validateResponse = false, ...requestOptions\n } = options;\n const requestSignal = requestOptions.signal ?? undefined;\n const placed = place(input);\n const sessionId = input.sessionId ?? scope.sessionId;\n let newSession = false;\n if (sessionId) {\n resolveSession(sessionId);\n if (hasResourceScope || start) {\n throwIfAborted(requestSignal);\n try {\n await assertSession(sessionId, requestOptions, validateResponse);\n throwIfAborted(requestSignal);\n if (start) fail('This session already exists; use add_session_event.');\n } catch (error) {\n if (memoryErrorStatus(error) !== 404) throw error;\n newSession = true;\n if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {\n fail('A new session must start with a USER event whose actorId is the configured userId.');\n }\n }\n }\n } else if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {\n fail('A new session must start with a USER event whose actorId is the configured userId.');\n }\n throwIfAborted(requestSignal);\n await assertPlacementOwner(placed, requestOptions);\n throwIfAborted(requestSignal);\n onPostStatus?.('started');\n const { sessionId: _sessionId, ...eventFields } = placed;\n const body = { ...eventFields, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };\n // createSession refuses an existing ID with 409; addSessionEvent appends and creates a missing session.\n const result = sessionId && !start\n ? await client.addSessionEvent(sessionId, body, requestOptions)\n : await client.createSession({ ...body, sessionId }, requestOptions);\n onPostStatus?.('acknowledged');\n if (validateResponse && (\n result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role\n )) {\n fail('Saved event is outside the configured session or actor scope.');\n }\n throwIfAborted(requestSignal);\n if (postflightNewSession && newSession && sessionId) {\n await assertSession(sessionId, requestOptions, validateResponse);\n throwIfAborted(requestSignal);\n }\n return result;\n };\n\n return Object.freeze({\n scope,\n hasResourceScope,\n checkPlacement,\n place,\n resolveSession,\n resolveOwner,\n assertSession,\n restoreSession,\n restoreScopedSession,\n assertMemory,\n assertPlacementOwner,\n scopeSearch,\n searchLongTermMemory,\n searchPersonalMemories,\n appendSessionEvent,\n });\n}\n\nexport type ScopedMemory = ReturnType<typeof createScopedMemory>;\n"]}
1
+ {"version":3,"file":"scoped-memory.js","sourceRoot":"","sources":["../src/scoped-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AA8BlC,SAAS,cAAc,CAAC,MAAoB;IAC1C,IAAI,MAAM,EAAE,OAAO;QAAE,MAAM,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAA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,aAAa,CAAC,SAAS,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;YACjE,cAAc,CAAC,aAAa,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,KAAK;QACL,gBAAgB;QAChB,cAAc;QACd,KAAK;QACL,cAAc;QACd,YAAY;QACZ,aAAa;QACb,cAAc;QACd,oBAAoB;QACpB,YAAY;QACZ,oBAAoB;QACpB,WAAW;QACX,oBAAoB;QACpB,sBAAsB;QACtB,mBAAmB;QACnB,kBAAkB;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { AgentMemory } from '@redis-iris/agent-memory';\nimport type { LongTermMemoryFilter, SessionEvent } from '@redis-iris/agent-memory/models';\nimport type { z } from 'zod';\nimport { RedisAgentMemoryToolError } from './errors.js';\nimport * as s from './schemas.js';\n\nexport interface RedisAgentMemoryScope {\n /** Stable application user ID. Used as the memory owner and as the actor for USER events. */\n userId?: string;\n /** Locks session operations and associates new memories; recall still spans this user's sessions. */\n sessionId?: string;\n namespaceId?: string;\n}\n\nexport interface ScopeValidationOptions {\n namespaceTools?: boolean;\n}\n\nexport type ScopedMemoryRequestOptions = NonNullable<Parameters<AgentMemory['getSessionMemory']>[2]>;\ntype SessionEventInput = z.infer<typeof s.event>;\ntype SearchInput = NonNullable<Parameters<AgentMemory['searchLongTermMemory']>[0]>;\ntype Placement = { namespaceId?: string };\n\nexport interface AppendSessionEventOptions extends ScopedMemoryRequestOptions {\n /** Create the session. An existing one is refused unless the request is keyed and matches its first event. */\n start?: boolean;\n /** Re-read a session created by this append to verify its immutable owner and placement. */\n postflightNewSession?: boolean;\n /** @internal Reports whether the append POST started or was acknowledged. */\n onPostStatus?: (status: 'started' | 'acknowledged') => void;\n /** @internal Validates the echoed event identity for wrapper writes. */\n validateResponse?: boolean;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new DOMException('Memory operation aborted.', 'AbortError');\n}\n\nfunction fail(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', message);\n}\n\nexport function memoryErrorStatus(error: unknown): number | undefined {\n return typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'\n ? error.statusCode : undefined;\n}\n\n/** Resolve and validate connection configuration without exposing credentials outside the SDK client. */\nexport function resolveAgentMemoryClient(\n serverUrl?: string,\n storeId?: string,\n apiKey?: string,\n timeoutMs = 30_000,\n env: Readonly<Record<string, string | undefined>> = typeof process === 'undefined' ? {} : process.env,\n): AgentMemory {\n const key = apiKey ?? env.AGENT_MEMORY_API_KEY;\n const resolvedStoreId = storeId ?? env.AGENT_MEMORY_STORE_ID;\n if (!key?.trim()) throw new Error('Set AGENT_MEMORY_API_KEY or pass an Iris API key.');\n if (!resolvedStoreId?.trim()) throw new Error('Set AGENT_MEMORY_STORE_ID or pass storeId.');\n const serverURL = serverUrl ?? env.AGENT_MEMORY_URL;\n if (!serverURL?.trim()) throw new Error('Set AGENT_MEMORY_URL or pass serverUrl; each store has its own endpoint URL.');\n const url = new URL(serverURL);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {\n throw new Error('serverUrl must be an HTTP(S) URL without credentials, query, or fragment.');\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('timeoutMs must be positive.');\n return new AgentMemory({ apiKey: key, storeId: resolvedStoreId, serverURL, timeoutMs });\n}\n\nconst SCOPE_KEYS: ReadonlySet<string> = new Set(['userId', 'sessionId', 'namespaceId']);\n\n/** Unknown keys would be ignored, silently dropping a boundary the caller meant to enforce. */\nfunction assertKnownScopeKeys(scope: object, label: string): void {\n for (const key of Object.keys(scope)) {\n if (SCOPE_KEYS.has(key)) continue;\n throw new Error(key === 'namespace'\n ? `${label}.namespace was removed; use ${label}.namespaceId.`\n : `Unknown ${label} field: ${key}.`);\n }\n}\n\nexport function copyMemoryScope(\n scope: RedisAgentMemoryScope,\n _options: ScopeValidationOptions = {},\n): Readonly<RedisAgentMemoryScope> {\n assertKnownScopeKeys(scope, 'scope');\n const copied = Object.freeze({ ...scope });\n if (copied.userId !== undefined) s.ownerId.parse(copied.userId);\n if (copied.sessionId !== undefined) s.sessionId.parse(copied.sessionId);\n if (copied.namespaceId !== undefined) s.id.parse(copied.namespaceId);\n return copied;\n}\n\nexport function extendMemoryScope(\n scope: RedisAgentMemoryScope,\n context: RedisAgentMemoryScope,\n): RedisAgentMemoryScope {\n assertKnownScopeKeys(context, 'context scope');\n const extended = { ...scope };\n for (const name of ['userId', 'sessionId', 'namespaceId'] as const) {\n const value = context[name];\n if (value === undefined) continue;\n if (scope[name] !== undefined && scope[name] !== value) fail(`Cannot override ${name} scope.`);\n extended[name] = value;\n }\n return extended;\n}\n\n/**\n * Security boundary shared by tools, hooks, and the provider wrapper.\n * The client and validated scope are captured once and never exposed as enumerable state.\n */\nexport function createScopedMemory(client: AgentMemory, inputScope: RedisAgentMemoryScope) {\n const scope = copyMemoryScope(inputScope);\n const hasResourceScope = Boolean(scope.userId || scope.namespaceId);\n\n const checkPlacement = (value: Placement) => {\n if (scope.namespaceId !== undefined && value.namespaceId !== scope.namespaceId) {\n fail('Resource is outside the configured namespace resource.');\n }\n };\n\n const place = <T extends Placement>(input: T): T => {\n if (scope.namespaceId === undefined) return { ...input };\n if (input.namespaceId !== undefined && input.namespaceId !== scope.namespaceId) fail('Cannot override namespace scope.');\n return { ...input, namespaceId: scope.namespaceId };\n };\n\n const resolveSession = (value?: string) => {\n if (scope.sessionId && value && value !== scope.sessionId) fail('Cannot override session scope.');\n const resolved = value ?? scope.sessionId;\n if (!resolved) fail('Supply sessionId or configure scope.sessionId.');\n return resolved;\n };\n\n const resolveOwner = (value?: string) => {\n if (scope.userId && value && value !== scope.userId) fail('Cannot override user scope.');\n const resolved = value ?? scope.userId;\n if (!resolved) fail('Supply ownerId or configure scope.userId.');\n return resolved;\n };\n\n const assertSession = async (\n sessionId: string,\n options?: ScopedMemoryRequestOptions,\n validateSessionId = false,\n ) => {\n resolveSession(sessionId);\n const session = await client.getSessionMemory(sessionId, false, options);\n if (validateSessionId && session.sessionId !== sessionId) fail('Session response does not match the configured session scope.');\n if (scope.userId && session.ownerId !== scope.userId) fail('Session is outside the configured user scope.');\n checkPlacement(session);\n return session;\n };\n\n const restoreSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options);\n const restoreScopedSession = (options?: ScopedMemoryRequestOptions) => assertSession(resolveSession(), options, true);\n\n const assertMemory = async (id: string, options?: ScopedMemoryRequestOptions) => {\n const memory = await client.getLongTermMemory(id, options);\n if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');\n checkPlacement(memory);\n return memory;\n };\n\n const assertPlacementOwner = async (value: Placement, options?: ScopedMemoryRequestOptions) => {\n if (!scope.userId || !value.namespaceId) return;\n const signal = options?.signal ?? undefined;\n throwIfAborted(signal);\n const { namespace } = await client.getNamespace(value.namespaceId, options);\n throwIfAborted(signal);\n const root = namespace.rootId === namespace.namespaceId ? namespace\n : (await client.getNamespace(namespace.rootId, options)).namespace;\n throwIfAborted(signal);\n if (root.scope !== 'PERSONAL' || root.ownerId !== scope.userId) {\n fail('Namespace placement is outside the configured user’s personal namespaces.');\n }\n };\n\n const scopeSearch = (input: SearchInput): SearchInput => {\n const filter: LongTermMemoryFilter = { ...input.filter };\n if (filter.unnamespaced !== undefined && filter.namespaceId) {\n fail('unnamespaced cannot be combined with namespace selectors.');\n }\n if (hasResourceScope && filter.op?.toUpperCase() === 'ANY') fail('Scoped searches require filter.op ALL to preserve isolation.');\n const fixed = (name: 'ownerId' | 'namespaceId', value: string) => {\n const existing = filter[name];\n if (existing && (existing.eq !== value || Object.values(existing).filter(item => item !== undefined).length !== 1)) {\n fail(`Cannot override ${name} scope.`);\n }\n filter[name] = { eq: value };\n };\n if (scope.userId) fixed('ownerId', scope.userId);\n if (scope.namespaceId) {\n if (filter.unnamespaced !== undefined) fail('Cannot search unnamespaced records within a namespace scope.');\n fixed('namespaceId', scope.namespaceId);\n }\n return { ...input, filter: hasResourceScope ? { ...filter, op: 'ALL' } : filter };\n };\n\n const searchLongTermMemory = (\n input: SearchInput,\n options?: ScopedMemoryRequestOptions,\n ) => client.searchLongTermMemory(scopeSearch(input), options);\n\n const searchPersonalMemories = async (\n text: string,\n limit: number,\n options?: ScopedMemoryRequestOptions,\n ) => {\n const result = await searchLongTermMemory({ query: text, limit }, options);\n for (const memory of result.items) {\n if (scope.userId && memory.ownerId !== scope.userId) fail('Memory is outside the configured user scope.');\n checkPlacement(memory);\n }\n return result;\n };\n\n /**\n * The store treats an idempotency key as store-wide, so two users whose models both pick a generic key would collide.\n * Hashing the fixed scope and the request target into the key keeps retries identical and isolates everyone else.\n */\n function scopeIdempotencyKey(key: string, ...target: string[]): Promise<string>;\n function scopeIdempotencyKey(key: string | undefined, ...target: string[]): Promise<string | undefined>;\n async function scopeIdempotencyKey(key: string | undefined, ...target: string[]) {\n if (key === undefined) return undefined;\n const input = new TextEncoder().encode(JSON.stringify([\n key, scope.userId ?? null, scope.sessionId ?? null, scope.namespaceId ?? null, target,\n ]));\n const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));\n return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');\n }\n\n const findStartEvent = async (\n sessionId: string,\n input: SessionEventInput,\n options: ScopedMemoryRequestOptions,\n ) => {\n const { events, namespaceId } = await client.getSessionMemory(sessionId, true, options);\n if (input.namespaceId !== undefined && namespaceId !== input.namespaceId) {\n fail('This session already exists in a different namespace than requested; use add_session_event.');\n }\n // createdAt is caller-supplied and a later append may be backdated; systemTimestamp is the store's own clock.\n // The store gives events no creation marker, so every event tied for the earliest clock reading is a candidate.\n const earliest = Math.min(...events.map(event => event.systemTimestamp.getTime()));\n const sameText = (event: SessionEvent) => event.content.length === input.content.length\n && event.content.every((part, index) => part.text === input.content[index]!.text);\n return events.find(event => event.systemTimestamp.getTime() === earliest\n && event.actorId === input.actorId && event.role === input.role && sameText(event)\n && (input.createdAt === undefined || event.createdAt.getTime() === Date.parse(input.createdAt)));\n };\n\n const appendSessionEvent = async (\n input: SessionEventInput,\n options: AppendSessionEventOptions = {},\n ) => {\n const {\n start = false, postflightNewSession = false, onPostStatus, validateResponse = false, ...requestOptions\n } = options;\n const requestSignal = requestOptions.signal ?? undefined;\n const placed = place(input);\n const sessionId = input.sessionId ?? scope.sessionId;\n if (start && input.idempotencyKey !== undefined) {\n if (!sessionId) fail('A keyed start_session needs a sessionId, so a retry can find the session it created.');\n if (input.createdAt === undefined) fail('A keyed start_session needs createdAt, so a retry sends the identical request.');\n }\n let newSession = false;\n if (sessionId) {\n resolveSession(sessionId);\n if (hasResourceScope || start) {\n throwIfAborted(requestSignal);\n try {\n await assertSession(sessionId, requestOptions, validateResponse);\n throwIfAborted(requestSignal);\n if (start) {\n if (!input.idempotencyKey) fail('This session already exists; use add_session_event.');\n // The store answers a repeated createSession with 409 even for the same key, so the replay happens here.\n const first = await findStartEvent(sessionId, input, requestOptions);\n if (!first) fail('This session already exists and its first event differs from this request; use add_session_event.');\n return { event: first };\n }\n } catch (error) {\n if (memoryErrorStatus(error) !== 404) throw error;\n newSession = true;\n if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {\n fail('A new session must start with a USER event whose actorId is the configured userId.');\n }\n }\n }\n } else if (scope.userId && (input.actorId !== scope.userId || input.role !== 'USER')) {\n fail('A new session must start with a USER event whose actorId is the configured userId.');\n }\n throwIfAborted(requestSignal);\n await assertPlacementOwner(placed, requestOptions);\n throwIfAborted(requestSignal);\n onPostStatus?.('started');\n const { sessionId: _sessionId, ...eventFields } = placed;\n const idempotencyKey = await scopeIdempotencyKey(input.idempotencyKey, sessionId ?? '');\n const body = { ...eventFields, idempotencyKey, createdAt: input.createdAt ? new Date(input.createdAt) : new Date() };\n // createSession refuses an existing ID with 409; addSessionEvent appends and creates a missing session.\n const result = sessionId && !start\n ? await client.addSessionEvent(sessionId, body, requestOptions)\n : await client.createSession({ ...body, sessionId }, requestOptions);\n onPostStatus?.('acknowledged');\n if (validateResponse && (\n result.event.sessionId !== sessionId || result.event.actorId !== input.actorId || result.event.role !== input.role\n )) {\n fail('Saved event is outside the configured session or actor scope.');\n }\n throwIfAborted(requestSignal);\n if (postflightNewSession && newSession && sessionId) {\n await assertSession(sessionId, requestOptions, validateResponse);\n throwIfAborted(requestSignal);\n }\n return result;\n };\n\n return Object.freeze({\n scope,\n hasResourceScope,\n checkPlacement,\n place,\n resolveSession,\n resolveOwner,\n assertSession,\n restoreSession,\n restoreScopedSession,\n assertMemory,\n assertPlacementOwner,\n scopeSearch,\n searchLongTermMemory,\n searchPersonalMemories,\n scopeIdempotencyKey,\n appendSessionEvent,\n });\n}\n\nexport type ScopedMemory = ReturnType<typeof createScopedMemory>;\n"]}
@@ -40,7 +40,7 @@ export function createSessionEventHook(scope, write, options) {
40
40
  const { role, onError, onEventStart, onEventSaved } = options;
41
41
  if (role !== 'USER' && role !== 'ASSISTANT')
42
42
  throw new Error('createSessionEventHook requires role USER or ASSISTANT.');
43
- const actorId = s.id.parse(options.actorId);
43
+ const actorId = s.actorId.parse(options.actorId);
44
44
  if (role === 'USER' && actorId !== scope.userId) {
45
45
  throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');
46
46
  }
@@ -1 +1 @@
1
- {"version":3,"file":"session-event-hook.js","sourceRoot":"","sources":["../src/session-event-hook.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAyClC,SAAS,YAAY,CAAC,OAAe;IACnC,MAAM,IAAI,yBAAyB,CAAC,6BAA6B,EAAE,OAAO,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,YAAY,CACnB,KAA4B,EAC5B,IAAiB,EACjB,OAAe;IAEf,IAAI,IAAI,KAAK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AAC,CAAC,CAAC;YAC7G,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ModelMessage } from 'ai';\nimport type { z } from 'zod';\nimport { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';\nimport * as s from './schemas.js';\n\ntype SessionRole = 'USER' | 'ASSISTANT';\ntype ObserverResult = void | PromiseLike<void>;\ntype SessionEventInput = z.infer<typeof s.event>;\n\ninterface SessionEventHookInputs {\n USER: { readonly messages: ReadonlyArray<ModelMessage> };\n ASSISTANT: { readonly finalStep: { readonly text: string } };\n}\n\n/** USER hooks consume onStart messages; ASSISTANT hooks consume onEnd final text. */\nexport type SessionEventHookInput<Role extends SessionRole = SessionRole> = SessionEventHookInputs[Role];\n\nexport type SessionEventHook<Role extends SessionRole = SessionRole> = (event: SessionEventHookInput<Role>) => Promise<void>;\n\n/** Identity of an event about to be written or confirmed saved. Contains no message text. */\nexport interface SessionHookEvent {\n readonly sessionId: string;\n readonly role: SessionRole;\n readonly actorId: string;\n}\n\nexport interface SessionEventHookErrorContext extends SessionHookEvent {\n readonly userId: string;\n /** A failed write may have committed; verify before retrying. */\n readonly phase: 'validation' | 'write';\n}\n\nexport interface SessionEventHookOptions<Role extends SessionRole = SessionRole> {\n /** Record one USER event in onStart or one ASSISTANT event in onEnd. */\n role: Role;\n /** Event author. For USER events, this must match the scoped userId. */\n actorId: string;\n /** Required because the AI SDK ignores exceptions thrown by lifecycle callbacks. */\n onError: (error: RedisAgentMemoryToolError, context: SessionEventHookErrorContext) => ObserverResult;\n /** Optional observers are awaited; observer errors never change which events are written. */\n onEventStart?: (event: SessionHookEvent) => ObserverResult;\n onEventSaved?: (event: SessionHookEvent) => ObserverResult;\n}\n\nfunction invalidInput(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', message);\n}\n\nfunction extractEvent(\n event: SessionEventHookInput,\n role: SessionRole,\n actorId: string,\n): SessionEventInput | undefined {\n if (role === 'USER') {\n if (!('messages' in event) || !Array.isArray(event.messages)) {\n invalidInput('USER session recording requires messages from an onStart event.');\n }\n const messages: ReadonlyArray<ModelMessage> = event.messages;\n const user = messages.at(-1);\n if (user?.role !== 'user') invalidInput('Session recording requires the current final input message to have role user.');\n const content = typeof user.content === 'string'\n ? [{ text: user.content }]\n : user.content.flatMap(part => part.type === 'text' && part.text.length > 0 ? [{ text: part.text }] : []);\n return s.event.parse({ actorId, role, content });\n }\n if (!('finalStep' in event) || typeof event.finalStep?.text !== 'string') {\n invalidInput('ASSISTANT session recording requires finalStep.text from an onEnd event.');\n }\n if (event.finalStep.text.length === 0) return undefined;\n return s.event.parse({ actorId, role, content: [{ text: event.finalStep.text }] });\n}\n\nasync function observe(callback: () => ObserverResult): Promise<void> {\n try { await callback(); } catch { /* Observers must not interrupt recording or cause a write to be retried. */ }\n}\n\n/** Internal adapter. The writer retains the toolset's immutable scope and shared SDK client. */\nexport function createSessionEventHook<Role extends SessionRole>(\n scope: { readonly userId?: string; readonly sessionId?: string },\n write: (event: SessionEventInput) => Promise<unknown>,\n options: SessionEventHookOptions<Role>,\n): SessionEventHook<Role> {\n if (!scope.userId || !scope.sessionId) {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'createSessionEventHook requires scope.userId and scope.sessionId.');\n }\n if (typeof options?.onError !== 'function') throw new Error('createSessionEventHook requires an onError callback.');\n const { role, onError, onEventStart, onEventSaved } = options;\n if (role !== 'USER' && role !== 'ASSISTANT') throw new Error('createSessionEventHook requires role USER or ASSISTANT.');\n const actorId = s.id.parse(options.actorId);\n if (role === 'USER' && actorId !== scope.userId) {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');\n }\n for (const [name, observer] of [['onEventStart', onEventStart], ['onEventSaved', onEventSaved]] as const) {\n if (observer !== undefined && typeof observer !== 'function') throw new Error(`${name} must be a function.`);\n }\n const userId = scope.userId;\n const info: SessionHookEvent = Object.freeze({ sessionId: scope.sessionId, role, actorId });\n\n return async event => {\n let input: SessionEventInput | undefined;\n try {\n input = extractEvent(event, role, actorId);\n } catch (error) {\n const safeError = error instanceof RedisAgentMemoryToolError ? error\n : new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', `Session recording requires valid ${role} text. Each text part must be non-empty and at most 50,000 characters.`);\n await observe(() => onError(safeError, Object.freeze({ ...info, userId, phase: 'validation' })));\n return;\n }\n if (!input) return;\n\n await observe(() => onEventStart?.(info));\n try {\n await write(input);\n } catch (error) {\n await observe(() => onError(sanitizeMemoryError(error), Object.freeze({ ...info, userId, phase: 'write' })));\n return;\n }\n await observe(() => onEventSaved?.(info));\n };\n}\n"]}
1
+ {"version":3,"file":"session-event-hook.js","sourceRoot":"","sources":["../src/session-event-hook.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAyClC,SAAS,YAAY,CAAC,OAAe;IACnC,MAAM,IAAI,yBAAyB,CAAC,6BAA6B,EAAE,OAAO,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,YAAY,CACnB,KAA4B,EAC5B,IAAiB,EACjB,OAAe;IAEf,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC;QACpB,IAAI,CAAC,CAAC,UAAU,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7D,YAAY,CAAC,iEAAiE,CAAC,CAAC;QAClF,CAAC;QACD,MAAM,QAAQ,GAAgC,KAAK,CAAC,QAAQ,CAAC;QAC7D,MAAM,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,IAAI,EAAE,IAAI,KAAK,MAAM;YAAE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H,KAAK,GAAG,YAAY,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAC7C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,SAAS,GAAG,KAAK,YAAY,yBAAyB,CAAC,CAAC,CAAC,KAAK;gBAClE,CAAC,CAAC,IAAI,yBAAyB,CAAC,6BAA6B,EAAE,oCAAoC,IAAI,wEAAwE,CAAC,CAAC;YACnL,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC;YACjG,OAAO;QACT,CAAC;QACD,IAAI,CAAC,KAAK;YAAE,OAAO;QAEnB,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1C,IAAI,CAAC;YACH,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ModelMessage } from 'ai';\nimport type { z } from 'zod';\nimport { RedisAgentMemoryToolError, sanitizeMemoryError } from './errors.js';\nimport * as s from './schemas.js';\n\ntype SessionRole = 'USER' | 'ASSISTANT';\ntype ObserverResult = void | PromiseLike<void>;\ntype SessionEventInput = z.infer<typeof s.event>;\n\ninterface SessionEventHookInputs {\n USER: { readonly messages: ReadonlyArray<ModelMessage> };\n ASSISTANT: { readonly finalStep: { readonly text: string } };\n}\n\n/** USER hooks consume onStart messages; ASSISTANT hooks consume onEnd final text. */\nexport type SessionEventHookInput<Role extends SessionRole = SessionRole> = SessionEventHookInputs[Role];\n\nexport type SessionEventHook<Role extends SessionRole = SessionRole> = (event: SessionEventHookInput<Role>) => Promise<void>;\n\n/** Identity of an event about to be written or confirmed saved. Contains no message text. */\nexport interface SessionHookEvent {\n readonly sessionId: string;\n readonly role: SessionRole;\n readonly actorId: string;\n}\n\nexport interface SessionEventHookErrorContext extends SessionHookEvent {\n readonly userId: string;\n /** A failed write may have committed; verify before retrying. */\n readonly phase: 'validation' | 'write';\n}\n\nexport interface SessionEventHookOptions<Role extends SessionRole = SessionRole> {\n /** Record one USER event in onStart or one ASSISTANT event in onEnd. */\n role: Role;\n /** Event author. For USER events, this must match the scoped userId. */\n actorId: string;\n /** Required because the AI SDK ignores exceptions thrown by lifecycle callbacks. */\n onError: (error: RedisAgentMemoryToolError, context: SessionEventHookErrorContext) => ObserverResult;\n /** Optional observers are awaited; observer errors never change which events are written. */\n onEventStart?: (event: SessionHookEvent) => ObserverResult;\n onEventSaved?: (event: SessionHookEvent) => ObserverResult;\n}\n\nfunction invalidInput(message: string): never {\n throw new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', message);\n}\n\nfunction extractEvent(\n event: SessionEventHookInput,\n role: SessionRole,\n actorId: string,\n): SessionEventInput | undefined {\n if (role === 'USER') {\n if (!('messages' in event) || !Array.isArray(event.messages)) {\n invalidInput('USER session recording requires messages from an onStart event.');\n }\n const messages: ReadonlyArray<ModelMessage> = event.messages;\n const user = messages.at(-1);\n if (user?.role !== 'user') invalidInput('Session recording requires the current final input message to have role user.');\n const content = typeof user.content === 'string'\n ? [{ text: user.content }]\n : user.content.flatMap(part => part.type === 'text' && part.text.length > 0 ? [{ text: part.text }] : []);\n return s.event.parse({ actorId, role, content });\n }\n if (!('finalStep' in event) || typeof event.finalStep?.text !== 'string') {\n invalidInput('ASSISTANT session recording requires finalStep.text from an onEnd event.');\n }\n if (event.finalStep.text.length === 0) return undefined;\n return s.event.parse({ actorId, role, content: [{ text: event.finalStep.text }] });\n}\n\nasync function observe(callback: () => ObserverResult): Promise<void> {\n try { await callback(); } catch { /* Observers must not interrupt recording or cause a write to be retried. */ }\n}\n\n/** Internal adapter. The writer retains the toolset's immutable scope and shared SDK client. */\nexport function createSessionEventHook<Role extends SessionRole>(\n scope: { readonly userId?: string; readonly sessionId?: string },\n write: (event: SessionEventInput) => Promise<unknown>,\n options: SessionEventHookOptions<Role>,\n): SessionEventHook<Role> {\n if (!scope.userId || !scope.sessionId) {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'createSessionEventHook requires scope.userId and scope.sessionId.');\n }\n if (typeof options?.onError !== 'function') throw new Error('createSessionEventHook requires an onError callback.');\n const { role, onError, onEventStart, onEventSaved } = options;\n if (role !== 'USER' && role !== 'ASSISTANT') throw new Error('createSessionEventHook requires role USER or ASSISTANT.');\n const actorId = s.actorId.parse(options.actorId);\n if (role === 'USER' && actorId !== scope.userId) {\n throw new RedisAgentMemoryToolError('INVALID_SCOPE', 'USER session event actorId must match scope.userId.');\n }\n for (const [name, observer] of [['onEventStart', onEventStart], ['onEventSaved', onEventSaved]] as const) {\n if (observer !== undefined && typeof observer !== 'function') throw new Error(`${name} must be a function.`);\n }\n const userId = scope.userId;\n const info: SessionHookEvent = Object.freeze({ sessionId: scope.sessionId, role, actorId });\n\n return async event => {\n let input: SessionEventInput | undefined;\n try {\n input = extractEvent(event, role, actorId);\n } catch (error) {\n const safeError = error instanceof RedisAgentMemoryToolError ? error\n : new RedisAgentMemoryToolError('INVALID_SESSION_EVENT_INPUT', `Session recording requires valid ${role} text. Each text part must be non-empty and at most 50,000 characters.`);\n await observe(() => onError(safeError, Object.freeze({ ...info, userId, phase: 'validation' })));\n return;\n }\n if (!input) return;\n\n await observe(() => onEventStart?.(info));\n try {\n await write(input);\n } catch (error) {\n await observe(() => onError(sanitizeMemoryError(error), Object.freeze({ ...info, userId, phase: 'write' })));\n return;\n }\n await observe(() => onEventSaved?.(info));\n };\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import { type ToolSet } from 'ai';
2
+ import type { AgentMemory } from '@redis-iris/agent-memory';
3
+ import type { ScopedMemory } from './scoped-memory.js';
4
+ export interface SummaryViewToolOptions {
5
+ allowDeletes: boolean;
6
+ }
7
+ /** Optional Summary View tools. Scoped toolsets only reach views whose partitions they can prove are theirs. */
8
+ export declare function createSummaryViewTools(client: AgentMemory, ctx: ScopedMemory, options: SummaryViewToolOptions): ToolSet;
9
+ //# sourceMappingURL=summary-views.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"summary-views.d.ts","sourceRoot":"","sources":["../src/summary-views.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,IAAI,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAK5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,OAAO,CAAC;CACvB;AA2DD,gHAAgH;AAChH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,WAAW,EACnB,GAAG,EAAE,YAAY,EACjB,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAiOT"}
@@ -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,MAAM,IAAI,yBAAyB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC,CAAC;KACnF,GAAG,CAAC,CAAC,CAAC;KACN,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,MAAM,EAAE,+BAA+B,CAAC;KACzF,QAAQ,CAAC,yFAAyF,CAAC,CAAC;AACvG,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;IACtB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AE,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.2.0",
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",
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
  }