@redis/vercel-ai-sdk 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +38 -0
- package/LICENSE +21 -0
- package/README.md +185 -2
- package/TOOLS.md +359 -0
- package/dist/errors.d.ts +9 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +21 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +239 -0
- package/dist/index.js.map +1 -0
- package/dist/instructions.d.ts +3 -0
- package/dist/instructions.d.ts.map +1 -0
- package/dist/instructions.js +16 -0
- package/dist/instructions.js.map +1 -0
- package/dist/namespaces.d.ts +11 -0
- package/dist/namespaces.d.ts.map +1 -0
- package/dist/namespaces.js +182 -0
- package/dist/namespaces.js.map +1 -0
- package/dist/provider.d.ts +54 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +666 -0
- package/dist/provider.js.map +1 -0
- package/dist/schemas.d.ts +125 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +54 -0
- package/dist/schemas.js.map +1 -0
- package/dist/scoped-memory.d.ts +63 -0
- package/dist/scoped-memory.d.ts.map +1 -0
- package/dist/scoped-memory.js +252 -0
- package/dist/scoped-memory.js.map +1 -0
- package/dist/session-event-hook.d.ts +49 -0
- package/dist/session-event-hook.d.ts.map +1 -0
- package/dist/session-event-hook.js +77 -0
- package/dist/session-event-hook.js.map +1 -0
- package/package.json +74 -4
- package/src/errors.ts +16 -0
- package/src/index.ts +310 -0
- package/src/instructions.ts +15 -0
- package/src/namespaces.ts +217 -0
- package/src/provider.ts +741 -0
- package/src/schemas.ts +55 -0
- package/src/scoped-memory.ts +298 -0
- package/src/session-event-hook.ts +120 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- Initial standalone `ai-sdk-redis-agent-memory` library for AI SDK 7.
|
|
6
|
+
- Added the unified root `createRedisAgentMemory({ serverUrl, storeId, apiKey,
|
|
7
|
+
scope?, model?, allowDeletes?, namespaceTools?, timeoutMs? })` factory.
|
|
8
|
+
- Added `memory.tools({ scope? })` for explicit AI SDK memory tools and
|
|
9
|
+
`memory.model({ scope?, model?, ...options })` for fresh request-scoped
|
|
10
|
+
automatic-memory models. Tools do not require a configured model.
|
|
11
|
+
- Factory scope and model are optional defaults. `undefined` call options fall
|
|
12
|
+
back to them; a supplied scope replaces the whole default scope, and a supplied
|
|
13
|
+
configured model replaces the model default without mutating prior results.
|
|
14
|
+
- Retained non-enumerable toolset `withContext(scope)` for further scope narrowing
|
|
15
|
+
and `createSessionEventHook(options)` for USER `onStart` and ASSISTANT `onEnd`
|
|
16
|
+
recording, with explicit actors, sanitized errors, and optional observers.
|
|
17
|
+
- Removed the unreleased `RedisAgentMemory` class,
|
|
18
|
+
`createRedisAgentMemoryTools(...)`, `createRedisAgentMemoryProvider(...)`,
|
|
19
|
+
provider object/`forRequest(...)`, `wrap(...)`, and separate `./provider`
|
|
20
|
+
public entry point. Their supported capabilities now live on the unified factory;
|
|
21
|
+
provider-related public types are exported from the package root.
|
|
22
|
+
- Added automatic session restoration, scoped personal-memory recall, optional
|
|
23
|
+
provenance, and best-effort session recording for automatic-memory models.
|
|
24
|
+
- Session events, session retrieval, long-term memory CRUD, semantic search, and
|
|
25
|
+
optional namespace administration use the official
|
|
26
|
+
`@redis-iris/agent-memory` SDK.
|
|
27
|
+
- Automatically generate UUIDs for new memories and return IDs in input order
|
|
28
|
+
alongside per-record outcomes.
|
|
29
|
+
- Enforce user, session, and namespace scopes, including ownership checks and
|
|
30
|
+
safe search filters. Factory scope is an overridable trusted default, not an
|
|
31
|
+
authentication or authorization ceiling.
|
|
32
|
+
- Disable deletion and namespace administration tools by default; enable them
|
|
33
|
+
with `allowDeletes` and `namespaceTools` on the unified factory.
|
|
34
|
+
- Added configurable `timeoutMs` with a 30-second default, cancellation, and
|
|
35
|
+
sanitized tool errors.
|
|
36
|
+
- Reorganized runnable applications under `demo/tools/` and `demo/provider/`.
|
|
37
|
+
- Require AI SDK 7.0.114 or newer within 7.x and Zod 4.1.8 or newer within 4.x.
|
|
38
|
+
- Ship ESM output, TypeScript declarations, source maps, and MIT license.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ai-sdk-redis-agent-memory contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,186 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Redis Agent Memory for Vercel's AI SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Redis Agent Memory](https://redis.io/agent-memory/), a part of the [Iris suite](https://redis.io/iris/), provides a managed memory layer that gives agents intelligent short-term memory and persistent context across conversations.
|
|
4
|
+
It allows AI agents to combine session history with long-term memories so they can recall user preferences, retain useful facts, and pick up where they left off.
|
|
5
|
+
|
|
6
|
+
This integration supports two complementary ways to add Redis Agent Memory to agents built with Vercel's [AI SDK](https://ai-sdk.dev/): an automatic-memory model wrapper that restores context and records sessions, and ordinary memory tools.
|
|
7
|
+
Both are created by the same server-side `createRedisAgentMemory(...)` factory.
|
|
8
|
+
|
|
9
|
+
## Choose an approach
|
|
10
|
+
|
|
11
|
+
| | Automatic-memory model | Tools |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| Entry point | `ai-sdk-redis-agent-memory` | `ai-sdk-redis-agent-memory` |
|
|
14
|
+
| Setup | `memory.model({ scope?, model?, ...options })` | `memory.tools({ scope? })` |
|
|
15
|
+
| Agent integration | Pass a fresh returned model as the request's `model` | Pass the returned tool map as `tools` alongside your model |
|
|
16
|
+
| Recall and history | Restores the scoped session and injects recalled personal memories before inference by default | The model chooses memory tools; the application manages input history |
|
|
17
|
+
| Session recording | Automatic USER recording and successful text-bearing assistant steps by default in Iris-managed mode | Model-selected session tools, or optional application lifecycle hooks |
|
|
18
|
+
| Choose when | You want automatic context and continuity without model-selected memory tools | You want explicit operations, selective tools, or model-directed memory management |
|
|
19
|
+
| Quick start | [Automatic context and recording](#automatic-memory-model) | [Agent-managed recording](TOOLS.md#agent-managed-session-recording-no-hooks) or [recording hooks](TOOLS.md#automatic-session-recording-with-hooks) |
|
|
20
|
+
|
|
21
|
+
Hooks are an optional recording mode of the tools approach, not a prerequisite for either integration.
|
|
22
|
+
The approaches may coexist, but do not enable automatic model recording and session-write tools or recording hooks for the same interaction: that can duplicate events.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
Requires Node.js 22+, AI SDK 7.0.114+ (7.x), and Zod 4.1.8+ (4.x).
|
|
27
|
+
This is a server-side, ESM-only package with TypeScript declarations.
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npm install @redis/vercel-ai-sdk
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Provision a Redis Agent Memory store in [Redis Cloud](https://cloud.redis.io/#/agent-memory), then set `AGENT_MEMORY_API_KEY` and `AGENT_MEMORY_STORE_ID` in your server environment.
|
|
34
|
+
Set `AGENT_MEMORY_URL` if your store uses a different endpoint.
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
These examples use Anthropic directly; install its provider with `npm install @ai-sdk/anthropic@^4` and set `ANTHROPIC_API_KEY`.
|
|
39
|
+
Other AI SDK 7-compatible configured models work with the same APIs. Model-name strings are not accepted.
|
|
40
|
+
|
|
41
|
+
### Automatic-memory model
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { anthropic } from '@ai-sdk/anthropic';
|
|
45
|
+
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
46
|
+
import { createRedisAgentMemory } from 'ai-sdk-redis-agent-memory';
|
|
47
|
+
|
|
48
|
+
const memory = createRedisAgentMemory({
|
|
49
|
+
serverUrl: process.env.AGENT_MEMORY_URL,
|
|
50
|
+
storeId: process.env.AGENT_MEMORY_STORE_ID,
|
|
51
|
+
apiKey: process.env.AGENT_MEMORY_API_KEY,
|
|
52
|
+
model: anthropic('claude-sonnet-4-5'),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
async function reply(userId: string, sessionId: string, prompt: string) {
|
|
56
|
+
const agent = new ToolLoopAgent({
|
|
57
|
+
model: memory.model({
|
|
58
|
+
scope: { userId, sessionId },
|
|
59
|
+
assistantId: 'assistant',
|
|
60
|
+
}),
|
|
61
|
+
stopWhen: isStepCount(8),
|
|
62
|
+
});
|
|
63
|
+
return agent.generate({ prompt });
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Configure the Redis Agent Memory connection and, optionally, a default model once.
|
|
68
|
+
Create a fresh request-scoped model with `memory.model(...)` inside every application request.
|
|
69
|
+
The wrapper restores the Iris session, recalls personal long-term memories, injects a bounded untrusted context block, and records the current user input plus every successful text-bearing raw assistant step.
|
|
70
|
+
It exposes no memory tools to the model.
|
|
71
|
+
When context is nonempty, the wrapper prepends `IRIS MEMORY CONTEXT MAY BE STALE.\n`; that fixed 34-UTF-16-unit framing sits outside the separate session and long-term-memory character budgets.
|
|
72
|
+
|
|
73
|
+
A default model is optional because `memory.tools()` is independent.
|
|
74
|
+
If the factory has no model, provide one to each `memory.model({ model, ... })` call.
|
|
75
|
+
Missing, string-valued, or otherwise invalid models fail synchronously before network calls.
|
|
76
|
+
|
|
77
|
+
The factory shares its Redis Agent Memory client and configured default model.
|
|
78
|
+
Each `memory.model()` result owns its scope, recall/restoration snapshot, USER-write attempt, recording budget, sequencing, and concurrency/cancellation state.
|
|
79
|
+
Reuse that result for steps and retries **within one application request**, never across independent requests.
|
|
80
|
+
Factory, tool, and model construction make no network calls.
|
|
81
|
+
Overlapping calls on one request model are rejected; independent request models may run concurrently.
|
|
82
|
+
Do not pass `model: memory` to a singleton agent; automatic agent-level lifecycle integration is not supported.
|
|
83
|
+
|
|
84
|
+
The default `historyMode: 'iris'` restores the session and defaults `recording` to `true`.
|
|
85
|
+
The current USER event is written once before inference; every successful raw model step with generated text is written afterward, including intermediate tool-loop steps.
|
|
86
|
+
Only text is restored and recorded; image-only input, reasoning, tool arguments/results, binary data, and system events are omitted.
|
|
87
|
+
Redis Agent Memory may extract long-term memories asynchronously from recorded events.
|
|
88
|
+
Consent, PII handling, retention, and extraction policy remain application and Redis Agent Memory configuration concerns.
|
|
89
|
+
|
|
90
|
+
Application-managed mode does not restore session events and defaults recording off, but still recalls long-term memory:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const model = memory.model({
|
|
94
|
+
scope: { userId, sessionId },
|
|
95
|
+
historyMode: 'application',
|
|
96
|
+
recording: false,
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Set `includeMemoryProvenance: true` to add a sanitized `providerMetadata.redisAgentMemory.memories` list for memories actually included in the prompt.
|
|
101
|
+
Entries contain only `id`, `memoryType`, `createdAt`, and `updatedAt`.
|
|
102
|
+
Provenance is off by default.
|
|
103
|
+
Existing underlying metadata is preserved; if it already owns `redisAgentMemory`, wrapper provenance is omitted.
|
|
104
|
+
|
|
105
|
+
The wrapper is best effort, not exactly once.
|
|
106
|
+
Redis Agent Memory has no conditional session creation or append idempotency key; a timed-out POST may have committed. Use collision-resistant session IDs bound to authenticated state and serialize requests by exact session ID.
|
|
107
|
+
Never combine automatic recording with session hooks or model-callable session-write tools for the same interaction.
|
|
108
|
+
|
|
109
|
+
For streaming, nonterminal parts pass through as produced.
|
|
110
|
+
Recording follows raw provider finish plus normal source close, and the terminal finish is held only for the bounded save.
|
|
111
|
+
Cancellation or transport failure before raw completion prevents the assistant write where possible; an accepted POST cannot be rolled back.
|
|
112
|
+
Memory failures are exposed through the optional content-free `onDiagnostic` callback and do not replace successful model output.
|
|
113
|
+
Scope violations remain hard failures.
|
|
114
|
+
|
|
115
|
+
## Runnable demos
|
|
116
|
+
|
|
117
|
+
- [`demo/provider/`](demo/provider/) demonstrates the automatic-memory model approach.
|
|
118
|
+
- [`demo/tools/`](demo/tools/) demonstrates the explicit tools and recording-hook approach.
|
|
119
|
+
|
|
120
|
+
Each demo has independent installation, test, and startup instructions and is excluded from npm releases.
|
|
121
|
+
|
|
122
|
+
## Configuration
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
const memory = createRedisAgentMemory({
|
|
126
|
+
serverUrl,
|
|
127
|
+
storeId,
|
|
128
|
+
apiKey,
|
|
129
|
+
scope,
|
|
130
|
+
model,
|
|
131
|
+
allowDeletes,
|
|
132
|
+
namespaceTools,
|
|
133
|
+
timeoutMs,
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
| Factory option | Default / behavior |
|
|
138
|
+
| --- | --- |
|
|
139
|
+
| `serverUrl` | `AGENT_MEMORY_URL`, then the production US East endpoint |
|
|
140
|
+
| `storeId` | `AGENT_MEMORY_STORE_ID`; required here or through the environment |
|
|
141
|
+
| `apiKey` | `AGENT_MEMORY_API_KEY`; required here or through the environment |
|
|
142
|
+
| `scope` | Optional default `{ userId?, sessionId?, namespaceId? | namespace? }` |
|
|
143
|
+
| `model` | Optional configured AI SDK model default; never a model-name string |
|
|
144
|
+
| `allowDeletes` | `false`; exposes deletion tools when true |
|
|
145
|
+
| `namespaceTools` | `false`; exposes namespace administration tools when true |
|
|
146
|
+
| `timeoutMs` | `30000` per HTTP request; must be positive and finite |
|
|
147
|
+
|
|
148
|
+
Scope accepts `userId`, `sessionId`, `namespaceId`, and the legacy `namespace` label.
|
|
149
|
+
`namespaceId` and `namespace` are mutually exclusive.
|
|
150
|
+
Configuration is validated and copied at construction; later mutations of caller-owned objects do not alter factory defaults.
|
|
151
|
+
|
|
152
|
+
`memory.model(...)` accepts `scope?`, `model?`, `assistantId?`, `historyMode?`, `recording?`, `query?`, `strictReads?`, `includeMemoryProvenance?`, `limits?`, and `onDiagnostic?`.
|
|
153
|
+
`memory.tools({ scope? })` accepts only a scope override.
|
|
154
|
+
Omitting an override or passing `undefined` uses its factory default.
|
|
155
|
+
A defined scope override replaces the full default scope; a defined model override replaces the model default.
|
|
156
|
+
Inputs, the factory, and previously returned toolsets/models are never mutated.
|
|
157
|
+
|
|
158
|
+
Automatic-memory models require a resolved scope with `userId`; Iris-managed history or recording additionally requires `sessionId`, and recording requires a valid `assistantId`.
|
|
159
|
+
Tools preserve their prior unscoped behavior when no scope is configured. All existing validation and ownership/namespace checks run after default resolution.
|
|
160
|
+
|
|
161
|
+
Model limits default to 5 recalled memories, 8,000 characters of long-term memory context, 24,000 characters of restored session context, one-second shared read and per-write deadlines, and a 100,000-UTF-16-unit cumulative recording budget.
|
|
162
|
+
Override them through `limits`; diagnostics remain opt-in through `onDiagnostic` and never include prompt, memory, or credential text.
|
|
163
|
+
|
|
164
|
+
The factory scope is trusted configuration, not an authorization ceiling.
|
|
165
|
+
Resolve scope and overrides from authenticated application state.
|
|
166
|
+
During tool execution, the AI SDK `abortSignal` is forwarded to Iris.
|
|
167
|
+
Session hooks use the configured HTTP timeout.
|
|
168
|
+
SDK defaults disable automatic retries, avoiding duplicate appends after uncertain outcomes.
|
|
169
|
+
|
|
170
|
+
## Development
|
|
171
|
+
|
|
172
|
+
```sh
|
|
173
|
+
git clone https://github.com/redis/vercel-ai-sdk.git
|
|
174
|
+
cd vercel-ai-sdk
|
|
175
|
+
npm ci
|
|
176
|
+
npm run check
|
|
177
|
+
npm pack
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Install the resulting tarball in your application with `npm install /path/to/vercel-ai-sdk-0.1.0.tgz`. It contains the compiled library, declarations, source maps, source files, and package documentation. No demo application or credentials are included.
|
|
181
|
+
|
|
182
|
+
See [CONTRIBUTING.md](https://github.com/redis/vercel-ai-sdk/blob/main/CONTRIBUTING.md) for the repository layout, commands, and release process. The tests use mocked HTTP and model boundaries and do not require API credentials.
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
[MIT](LICENSE).
|
package/TOOLS.md
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
# Redis Agent Memory Tools for Vercel's AI SDK
|
|
2
|
+
|
|
3
|
+
[Redis Agent Memory](https://redis.io/agent-memory/), a part of the [Iris suite](https://redis.io/iris/), provides a managed memory layer that gives agents intelligent short-term memory and persistent context across conversations.
|
|
4
|
+
It allows AI agents to combine session history with long-term memories so they can recall user preferences, retain useful facts, and pick up where they left off.
|
|
5
|
+
|
|
6
|
+
This integration provides tools that add Redis Agent Memory to agents built with Vercel's [AI SDK](https://ai-sdk.dev/).
|
|
7
|
+
The tools are created by the same server-side `createRedisAgentMemory(...)` factory.
|
|
8
|
+
Use the tools either to delegate memory management entirely to your AI agent, or for implementing a desired custom behavior.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Follow the [steps in the README.md](README.md#installation).
|
|
13
|
+
|
|
14
|
+
## Quick start
|
|
15
|
+
|
|
16
|
+
These examples use Anthropic directly; install its provider with `npm install @ai-sdk/anthropic@^4` and set `ANTHROPIC_API_KEY`.
|
|
17
|
+
Other AI SDK 7-compatible configured models work with the same APIs. Model-name strings are not accepted.
|
|
18
|
+
|
|
19
|
+
### Agent-managed session recording (no hooks)
|
|
20
|
+
|
|
21
|
+
Give the agent the memory tools and let it decide when to record session events or save long-term facts.
|
|
22
|
+
Tools do not require a configured model.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { anthropic } from '@ai-sdk/anthropic';
|
|
26
|
+
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
27
|
+
import { createRedisAgentMemory, instructions } from 'ai-sdk-redis-agent-memory';
|
|
28
|
+
|
|
29
|
+
const userId = 'user-123';
|
|
30
|
+
const sessionId = 'conversation-456';
|
|
31
|
+
const agentId = 'assistant-1';
|
|
32
|
+
|
|
33
|
+
const memory = createRedisAgentMemory({
|
|
34
|
+
serverUrl: process.env.AGENT_MEMORY_URL,
|
|
35
|
+
storeId: process.env.AGENT_MEMORY_STORE_ID,
|
|
36
|
+
apiKey: process.env.AGENT_MEMORY_API_KEY,
|
|
37
|
+
});
|
|
38
|
+
const tools = memory.tools({ scope: { userId, sessionId } });
|
|
39
|
+
|
|
40
|
+
const agent = new ToolLoopAgent({
|
|
41
|
+
model: anthropic('claude-sonnet-4-5'),
|
|
42
|
+
tools,
|
|
43
|
+
instructions: `${instructions}
|
|
44
|
+
Current user and memory owner: ${userId}
|
|
45
|
+
Current session: ${sessionId}
|
|
46
|
+
Current assistant actor: ${agentId}
|
|
47
|
+
The application does not log session events. Decide when to record this conversation
|
|
48
|
+
using start_session or add_session_event. Start a new session with the user's
|
|
49
|
+
message, then use add_session_event for subsequent USER and ASSISTANT events.`,
|
|
50
|
+
stopWhen: isStepCount(8),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const result = await agent.generate({
|
|
54
|
+
prompt: 'Remember that I prefer TypeScript examples.',
|
|
55
|
+
});
|
|
56
|
+
console.log(result.finalStep.text);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Instructions guide the model's tool choices; they do not guarantee that every message or the final reply is stored.
|
|
60
|
+
Saving a long-term fact with `create_memories` is separate from recording conversation events.
|
|
61
|
+
This approach does not automatically load conversation history into model context.
|
|
62
|
+
|
|
63
|
+
### Automatic session recording with hooks
|
|
64
|
+
|
|
65
|
+
Use toolset `onStart` and `onEnd` helpers to record the current user message and the final assistant reply independently of the model's tool choices.
|
|
66
|
+
Keep session-write tools out of `activeTools` to avoid duplicate recording.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { anthropic } from '@ai-sdk/anthropic';
|
|
70
|
+
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
71
|
+
import { createRedisAgentMemory, instructions } from 'ai-sdk-redis-agent-memory';
|
|
72
|
+
|
|
73
|
+
const userId = 'user-123';
|
|
74
|
+
const sessionId = 'conversation-456';
|
|
75
|
+
const agentId = 'assistant-1';
|
|
76
|
+
const memory = createRedisAgentMemory({
|
|
77
|
+
serverUrl: process.env.AGENT_MEMORY_URL,
|
|
78
|
+
storeId: process.env.AGENT_MEMORY_STORE_ID,
|
|
79
|
+
apiKey: process.env.AGENT_MEMORY_API_KEY,
|
|
80
|
+
});
|
|
81
|
+
const tools = memory.tools({ scope: { userId, sessionId } });
|
|
82
|
+
|
|
83
|
+
const agent = new ToolLoopAgent({
|
|
84
|
+
model: anthropic('claude-sonnet-4-5'),
|
|
85
|
+
tools,
|
|
86
|
+
activeTools: [
|
|
87
|
+
'get_memory_context', 'get_session_memory',
|
|
88
|
+
'create_memories', 'search_memories', 'update_memory',
|
|
89
|
+
],
|
|
90
|
+
instructions: `${instructions}
|
|
91
|
+
Current user and memory owner: ${userId}
|
|
92
|
+
Current session: ${sessionId}
|
|
93
|
+
Current assistant actor: ${agentId}
|
|
94
|
+
The application records user input before generation and the final reply afterward.
|
|
95
|
+
Do not write session events. Use get_session_memory to read saved messages.`,
|
|
96
|
+
stopWhen: isStepCount(8),
|
|
97
|
+
onStart: tools.createSessionEventHook({
|
|
98
|
+
role: 'USER',
|
|
99
|
+
actorId: userId,
|
|
100
|
+
onError: error => console.error('USER session save failed:', error.message),
|
|
101
|
+
}),
|
|
102
|
+
onEnd: tools.createSessionEventHook({
|
|
103
|
+
role: 'ASSISTANT',
|
|
104
|
+
actorId: agentId,
|
|
105
|
+
onError: error => console.error('ASSISTANT session save failed:', error.message),
|
|
106
|
+
}),
|
|
107
|
+
});
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The USER write is awaited before the model starts, and the ASSISTANT hook records nonempty final text in `onEnd`.
|
|
111
|
+
See [Recording session events](#recording-session-events) for input requirements, observers, and failure behavior.
|
|
112
|
+
|
|
113
|
+
## Combining tools
|
|
114
|
+
|
|
115
|
+
`memory.tools()` returns an AI SDK `ToolSet`.
|
|
116
|
+
Its enumerable properties are exclusively tools; credentials and the SDK client remain in closures.
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { createRedisAgentMemory } from 'ai-sdk-redis-agent-memory';
|
|
120
|
+
|
|
121
|
+
const memory = createRedisAgentMemory({ serverUrl, storeId, apiKey });
|
|
122
|
+
const memoryTools = memory.tools({ scope: { userId } });
|
|
123
|
+
const tools = {
|
|
124
|
+
search_memories: memoryTools.search_memories!,
|
|
125
|
+
get_memory: memoryTools.get_memory!,
|
|
126
|
+
};
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
This is a server-side package.
|
|
130
|
+
Never put the Redis Agent Memory API keys in a frontend bundle.
|
|
131
|
+
|
|
132
|
+
## Reusing tools across conversations
|
|
133
|
+
|
|
134
|
+
Create a toolset for each trusted request scope.
|
|
135
|
+
Factory-level scope is only an overridable default: it is not an authorization ceiling.
|
|
136
|
+
Supplying a call-level scope replaces the **entire** factory scope rather than merging fields, so a session or namespace from another request cannot be inherited accidentally.
|
|
137
|
+
Omitting `scope`, or passing `scope: undefined`, uses the factory default.
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
const memory = createRedisAgentMemory({
|
|
141
|
+
serverUrl,
|
|
142
|
+
storeId,
|
|
143
|
+
apiKey,
|
|
144
|
+
scope: { userId: 'default-user', sessionId: 'default-session' },
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const first = memory.tools(); // uses the complete factory scope
|
|
148
|
+
const second = memory.tools({
|
|
149
|
+
scope: { userId: 'user-42', sessionId: 'conversation-2' },
|
|
150
|
+
}); // replaces it completely
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Factory defaults and per-call overrides must come from trusted, authenticated application state.
|
|
154
|
+
They do not establish the caller's identity or replace application authorization.
|
|
155
|
+
|
|
156
|
+
A returned toolset retains the non-enumerable `withContext(scope)` helper for **narrowing that toolset's already resolved scope**, plus `createSessionEventHook(options)`.
|
|
157
|
+
`withContext` shares the client, does not mutate either toolset, fills only missing fields, and rejects conflicting fixed values.
|
|
158
|
+
This is intentionally different from the whole-scope replacement used by `memory.tools({ scope })`:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
const userTools = memory.tools({ scope: { userId: 'user-42' } });
|
|
162
|
+
const conversationTools = userTools.withContext({ sessionId: 'conversation-1' });
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Scope remains optional for tools.
|
|
166
|
+
An unscoped toolset retains its existing unscoped behavior.
|
|
167
|
+
Helpers are omitted from enumeration and object spread.
|
|
168
|
+
|
|
169
|
+
## Recording session events
|
|
170
|
+
|
|
171
|
+
Call `createSessionEventHook(options)` on a scoped toolset and pass the returned callback to the matching lifecycle hook: `role: 'USER'` goes on `onStart`, and `role: 'ASSISTANT'` goes on `onEnd`.
|
|
172
|
+
Each callback records one event using the same ownership and namespace checks as the session tools.
|
|
173
|
+
The [hook example above](#automatic-session-recording-with-hooks) shows both callbacks.
|
|
174
|
+
|
|
175
|
+
`userId` and `sessionId` must be fixed in the toolset's resolved scope before creating the hook, through `memory.tools({ scope })` or the returned toolset's `withContext(scope)` narrowing helper.
|
|
176
|
+
The hook captures that scope.
|
|
177
|
+
Supply `actorId` for each hook; the USER actor must equal scoped `userId`, and the ASSISTANT actor identifies your agent.
|
|
178
|
+
Like `withContext`, the helper is non-enumerable, so it is not advertised to the model or copied by object spread.
|
|
179
|
+
|
|
180
|
+
The USER hook reads the `onStart` input messages.
|
|
181
|
+
The final message must have role `user`, with either a content string or text parts.
|
|
182
|
+
Text parts remain separate event content items; images, files, and other non-text parts are ignored.
|
|
183
|
+
A user message without nonempty text fails validation.
|
|
184
|
+
The ASSISTANT hook reads `finalStep.text` and skips an empty reply.
|
|
185
|
+
Each hook validates its event before writing.
|
|
186
|
+
No `include.requestMessages` setting is needed.
|
|
187
|
+
Earlier history, intermediate steps, tool calls, and tool results are not recorded.
|
|
188
|
+
|
|
189
|
+
The USER write is awaited before the model starts, so memory tools can read that message during generation.
|
|
190
|
+
It remains saved if generation later fails.
|
|
191
|
+
The ASSISTANT event is recorded only when AI SDK invokes `onEnd` with nonempty final
|
|
192
|
+
text.
|
|
193
|
+
|
|
194
|
+
Hook options are:
|
|
195
|
+
|
|
196
|
+
| Option | Behavior |
|
|
197
|
+
| --- | --- |
|
|
198
|
+
| `role` | Required: `'USER'` for `onStart`, or `'ASSISTANT'` for `onEnd` |
|
|
199
|
+
| `actorId` | Required author ID; must match scoped `userId` for USER events |
|
|
200
|
+
| `onError(error, context)` | Required handler for validation or write failures; receives a sanitized `RedisAgentMemoryToolError` |
|
|
201
|
+
| `onEventStart(info)` | Optional observer called before each append attempt |
|
|
202
|
+
| `onEventSaved(info)` | Optional observer called after each confirmed append |
|
|
203
|
+
|
|
204
|
+
Observer `info` has type `SessionHookEvent` and contains `sessionId`, `role`, and `actorId`.
|
|
205
|
+
Error `context` contains those fields plus `userId` and `phase` (`'validation'` or `'write'`).
|
|
206
|
+
Callbacks may be asynchronous and are awaited; their exceptions, including exceptions from `onError`, are ignored.
|
|
207
|
+
Observer errors do not interrupt recording.
|
|
208
|
+
Hook writes do not trigger the AI SDK's `onToolExecutionStart` or `onToolExecutionEnd` callbacks; use the event observers for session logging.
|
|
209
|
+
|
|
210
|
+
The two hooks run independently.
|
|
211
|
+
A USER save failure does not stop generation or prevent the ASSISTANT hook from running.
|
|
212
|
+
A failed write may have committed without confirmation, so the assistant event may still be appended afterward.
|
|
213
|
+
Ownership checks still prevent an ASSISTANT event from starting a new user-owned session.
|
|
214
|
+
Writes are not atomic, retried, or deduplicated; verify uncertain outcomes before retrying and register each hook only once per generation.
|
|
215
|
+
AI SDK ignores lifecycle callback exceptions, so report failures through `onError`.
|
|
216
|
+
To require persistence before proceeding with generation or returning a reply, use the official SDK in the application workflow.
|
|
217
|
+
|
|
218
|
+
## Configuration
|
|
219
|
+
|
|
220
|
+
The configuration is documented in the project's [README.md](README.md#configuration).
|
|
221
|
+
|
|
222
|
+
## Tool reference
|
|
223
|
+
|
|
224
|
+
All parameter names are camelCase.
|
|
225
|
+
IDs remain visible to the model; fixed scopes cannot be overridden.
|
|
226
|
+
The three deletion tools below are exposed only when `options.allowDeletes` is `true`.
|
|
227
|
+
|
|
228
|
+
| Tool | Parameters and result |
|
|
229
|
+
| --- | --- |
|
|
230
|
+
| `get_memory_context` | `{}` → configured IDs and identity rules, no secrets |
|
|
231
|
+
| `start_session` | `{actorId, text, sessionId?, namespace?, namespaceRef?}` → `{event}`; omit sessionId to have it generated |
|
|
232
|
+
| `add_session_event` | `{actorId, role, content: [{text}], sessionId?, createdAt?, metadata?, namespace?, namespaceRef?}` → `{event}` |
|
|
233
|
+
| `get_session_event` | `{sessionId?, eventId}` → `{event}` |
|
|
234
|
+
| `get_session_memory` | `{sessionId?, includeSummarisedEvents?}` → session, events, optional summary |
|
|
235
|
+
| `list_sessions` | `{ownerId?, includeAll?, limit?, pageToken?}` → `{items: string[], total, nextPageToken?}` |
|
|
236
|
+
| `create_memories` | `{memories: [...]}` without IDs → `{memoryIds, created, errors?}`; UUIDs are generated automatically |
|
|
237
|
+
| `get_memory` | `{memoryId}` → memory record |
|
|
238
|
+
| `search_memories` | `{text?, filter?, filterOp?, similarityThreshold?, limit?, pageToken?}` → `{items, nextPageToken?}` |
|
|
239
|
+
| `update_memory` | `{memoryId, changes: {...}}` → updated memory record |
|
|
240
|
+
| `delete_memories` | `{memoryIds: [...]}` → `{deleted, errors?}` |
|
|
241
|
+
| `delete_session_event` | `{sessionId?, eventId}` → deletion confirmation |
|
|
242
|
+
| `delete_session_memory` | `{sessionId?}` → deletion confirmation |
|
|
243
|
+
|
|
244
|
+
`sessionId` is required for retrieval/deletion unless fixed in the scope.
|
|
245
|
+
`role` is `USER`, `ASSISTANT`, or `SYSTEM`. `createdAt` accepts an ISO 8601 string with timezone and defaults to the current time.
|
|
246
|
+
Session/owner IDs follow the server's 1–64 alphanumeric-or-hyphen convention; actor IDs accept 1–255 characters.
|
|
247
|
+
|
|
248
|
+
A create record contains:
|
|
249
|
+
|
|
250
|
+
```ts
|
|
251
|
+
{
|
|
252
|
+
text: 'The user prefers TypeScript.',
|
|
253
|
+
ownerId: 'user-123', // Optional when scope.userId is set
|
|
254
|
+
sessionId: 'conversation-456', // Optional; defaults to scoped session
|
|
255
|
+
memoryType: 'semantic', // Optional; registered custom types also work
|
|
256
|
+
topics: ['programming'],
|
|
257
|
+
attributes: { /* fields matching your custom type, if applicable */ },
|
|
258
|
+
namespaceRef: { namespaceId: 'your-namespace-id' },
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
The wrapper generates a UUID v4 for each create record.
|
|
263
|
+
The agent does not supply an `id`.
|
|
264
|
+
The returned `memoryIds` array lists all generated IDs in input order, including any failed records; `created` contains successful IDs and `errors` contains per-ID failures.
|
|
265
|
+
Keep successful IDs for later retrieval, updates, and deletion.
|
|
266
|
+
|
|
267
|
+
Each `create_memories` invocation generates fresh IDs.
|
|
268
|
+
If a request times out or its outcome is uncertain, search for the memories before retrying to avoid duplicates.
|
|
269
|
+
Retry only records confirmed to have failed.
|
|
270
|
+
|
|
271
|
+
Bulk create/delete accepts 1–100 records/IDs and preserves the server's per-record errors.
|
|
272
|
+
Text accepts 1–50,000 characters; topics accept up to 50 tags.
|
|
273
|
+
Updates support `text`, `memoryType`, `topics`, `ownerId`, `sessionId`, and namespace placement.
|
|
274
|
+
An empty `sessionId` or legacy `namespace` clears it when not fixed by scope. Updating custom extraction-worker fields is deliberately outside the agent toolset; use the official SDK's worker endpoint for that workflow.
|
|
275
|
+
|
|
276
|
+
Search filters support `ownerId`, `sessionId`, legacy `namespace`, `topics`, and `memoryType` with exactly one of `{eq}`, `{ne}`, `{in: [...]}`, or `{all: [...]}`.
|
|
277
|
+
`namespaceRef` supports `{eq}` or `{in}`. Use `unnamespaced` without namespace selectors. Date comparisons accept ISO strings:
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
{
|
|
281
|
+
text: 'preferred programming language',
|
|
282
|
+
filter: {
|
|
283
|
+
ownerId: { eq: 'user-123' },
|
|
284
|
+
topics: { in: ['programming'] },
|
|
285
|
+
createdAt: { gte: '2026-01-01T00:00:00Z' },
|
|
286
|
+
attributes: { confirmed: { boolean: true } },
|
|
287
|
+
},
|
|
288
|
+
filterOp: 'all',
|
|
289
|
+
limit: 10,
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Attribute filters accept exactly one of `{string}`, `{number}`, `{boolean}`, or `{list: string[]}` per field.
|
|
294
|
+
Omit `text` to list/filter without a semantic query.
|
|
295
|
+
Pagination uses the returned opaque `nextPageToken` with the same search parameters.
|
|
296
|
+
|
|
297
|
+
## Identity and scope behavior
|
|
298
|
+
|
|
299
|
+
`scope.userId` identifies the application user.
|
|
300
|
+
The tools use that identity in role-specific fields: `ownerId` for the user's memories, sessions, and PERSONAL namespaces, and `actorId` for their USER events.
|
|
301
|
+
Memory creation supplies `ownerId` automatically from `scope.userId`; session tools and `createSessionEventHook` require an explicit `actorId`.
|
|
302
|
+
|
|
303
|
+
Append `instructions` to your agent's instructions and supply current user/agent/session IDs in trusted application context.
|
|
304
|
+
A USER event uses the human user's ID as `actorId`; an ASSISTANT event uses the agent's ID.
|
|
305
|
+
The first event establishes immutable session ownership, so initialize user-owned sessions with the user's message.
|
|
306
|
+
With `scope.userId` set, the wrapper requires a new session to start with a USER event whose `actorId` matches that user ID.
|
|
307
|
+
|
|
308
|
+
The host must retain session IDs between requests.
|
|
309
|
+
An agent generating a session ID does not itself make that ID persistent across future model calls.
|
|
310
|
+
In the tools approach, persist IDs and conversation history in application storage and reuse them on later requests.
|
|
311
|
+
The automatic-memory model can restore available Redis Agent Memory session history when given the same session ID.
|
|
312
|
+
|
|
313
|
+
`scope.sessionId` restricts session operations but **does not filter long-term recall by session**, allowing recall from earlier conversations.
|
|
314
|
+
To limit long-term recall to one conversation, pass an explicit `filter.sessionId`.
|
|
315
|
+
|
|
316
|
+
User/namespace-scoped searches require `filterOp: 'all'`; an OR filter could bypass a fixed owner predicate and is rejected.
|
|
317
|
+
Direct-ID reads, updates, and deletes check existing ownership/placement before returning or mutating a resource.
|
|
318
|
+
User-scoped resource placements require a PERSONAL namespace owned by that user.
|
|
319
|
+
A legacy namespace label is a grouping value and has no resource ownership to inspect.
|
|
320
|
+
|
|
321
|
+
With a fixed session, `list_sessions` returns only that session.
|
|
322
|
+
With a namespace scope and no fixed session it rejects listing, because Redis Agent Memory has no namespace filter for this endpoint; use known IDs.
|
|
323
|
+
Unscoped store-wide listing requires explicit `includeAll: true`.
|
|
324
|
+
|
|
325
|
+
Resolved scopes provide application guardrails and use preflight reads.
|
|
326
|
+
Factory scope is only a replaceable default, not an authorization ceiling.
|
|
327
|
+
Neither is a substitute for authentication, store-level permissions, or protection against concurrent ownership changes made by other clients.
|
|
328
|
+
|
|
329
|
+
## Optional namespace tools
|
|
330
|
+
|
|
331
|
+
Set `namespaceTools: true` on `createRedisAgentMemory(...)` to add:
|
|
332
|
+
|
|
333
|
+
| Tool | Parameters |
|
|
334
|
+
| --- | --- |
|
|
335
|
+
| `list_namespaces` | `{parentId?, scope?, ownerId?, limit?, pageToken?}` |
|
|
336
|
+
| `get_namespace` | `{namespaceId}` |
|
|
337
|
+
| `create_namespace` | `{name?, path?, scope?, parentId?, ownerId?}` |
|
|
338
|
+
| `update_namespace` | `{namespaceId, name?, state?: 'ARCHIVED'}` |
|
|
339
|
+
| `move_memories` | `{memoryIds, namespaceId}` |
|
|
340
|
+
| `delete_namespace` | `{namespaceId}`; omitted when deletes are disabled |
|
|
341
|
+
|
|
342
|
+
Create roots with name/scope, children with name/parentId, or a hierarchy with path/scope.
|
|
343
|
+
Namespace scopes are `PERSONAL` and `SHARED`; PERSONAL roots require an owner.
|
|
344
|
+
User-scoped tools restrict access to that user's personal namespaces, including child namespaces inheriting root ownership.
|
|
345
|
+
A fixed namespace scope prevents creation or moving memories outside that namespace.
|
|
346
|
+
Legacy namespace scopes cannot enable resource administration tools.
|
|
347
|
+
Archive and delete operations follow the server's rules; deletion is for empty leaf namespaces.
|
|
348
|
+
|
|
349
|
+
## Failures and cancellation
|
|
350
|
+
|
|
351
|
+
Tool execution throws `RedisAgentMemoryToolError` with a safe `code`, message, and optional HTTP `statusCode`.
|
|
352
|
+
Upstream headers, bodies, and API keys are not passed into model context.
|
|
353
|
+
Cancellation is surfaced as `AbortError`.
|
|
354
|
+
Bulk results retain partial errors so the agent can identify individual failures.
|
|
355
|
+
An uncertain memory creation or session append can already have committed: reconcile its outcome before retrying.
|
|
356
|
+
|
|
357
|
+
Automatic summary/promotion behavior belongs to the Redis Agent Memory store configuration.
|
|
358
|
+
Deleting session history does not cascade to promoted long-term memories.
|
|
359
|
+
The package has no LLM dependency of its own and does not configure store promotion workers, store administration, or custom extraction workers.
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Safe error details suitable for an AI SDK tool result. Never attach upstream bodies or headers. */
|
|
2
|
+
export declare class RedisAgentMemoryToolError extends Error {
|
|
3
|
+
readonly code: string;
|
|
4
|
+
readonly statusCode?: number | undefined;
|
|
5
|
+
constructor(code: string, message: string, statusCode?: number | undefined);
|
|
6
|
+
}
|
|
7
|
+
/** Share safe SDK error handling between model tools and application hooks. */
|
|
8
|
+
export declare function sanitizeMemoryError(error: unknown): RedisAgentMemoryToolError;
|
|
9
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,qBAAa,yBAA0B,SAAQ,KAAK;aACtB,IAAI,EAAE,MAAM;aAAmC,UAAU,CAAC,EAAE,MAAM;gBAAlE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAkB,UAAU,CAAC,EAAE,MAAM,YAAA;CAG/F;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,yBAAyB,CAO7E"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Safe error details suitable for an AI SDK tool result. Never attach upstream bodies or headers. */
|
|
2
|
+
export class RedisAgentMemoryToolError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
statusCode;
|
|
5
|
+
constructor(code, message, statusCode) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.statusCode = statusCode;
|
|
9
|
+
this.name = 'IrisToolError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Share safe SDK error handling between model tools and application hooks. */
|
|
13
|
+
export function sanitizeMemoryError(error) {
|
|
14
|
+
if (error instanceof RedisAgentMemoryToolError)
|
|
15
|
+
return error;
|
|
16
|
+
const code = typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'
|
|
17
|
+
? error.statusCode : undefined;
|
|
18
|
+
return new RedisAgentMemoryToolError(code ? `IRIS_HTTP_${code}` : 'IRIS_REQUEST_FAILED', code ? `Iris request failed (HTTP ${code}). Check service configuration and request scope. Writes may have partially succeeded; verify before retrying.`
|
|
19
|
+
: 'Iris request failed. Check connectivity and service configuration. Verify writes before retrying.', code);
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IACtB;IAA+C;IAA3E,YAA4B,IAAY,EAAE,OAAe,EAAkB,UAAmB;QAC5F,KAAK,CAAC,OAAO,CAAC,CAAC;QADW,SAAI,GAAJ,IAAI,CAAQ;QAAmC,eAAU,GAAV,UAAU,CAAS;QAC5E,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9C,CAAC;CACF;AAED,+EAA+E;AAC/E,MAAM,UAAU,mBAAmB,CAAC,KAAc;IAChD,IAAI,KAAK,YAAY,yBAAyB;QAAE,OAAO,KAAK,CAAC;IAC7D,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,YAAY,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ;QACvH,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;IACjC,OAAO,IAAI,yBAAyB,CAAC,IAAI,CAAC,CAAC,CAAC,aAAa,IAAI,EAAE,CAAC,CAAC,CAAC,qBAAqB,EACrF,IAAI,CAAC,CAAC,CAAC,6BAA6B,IAAI,gHAAgH;QACtJ,CAAC,CAAC,mGAAmG,EAAE,IAAI,CAAC,CAAC;AACnH,CAAC","sourcesContent":["/** Safe error details suitable for an AI SDK tool result. Never attach upstream bodies or headers. */\nexport class RedisAgentMemoryToolError extends Error {\n constructor(public readonly code: string, message: string, public readonly statusCode?: number) {\n super(message); this.name = 'IrisToolError';\n }\n}\n\n/** Share safe SDK error handling between model tools and application hooks. */\nexport function sanitizeMemoryError(error: unknown): RedisAgentMemoryToolError {\n if (error instanceof RedisAgentMemoryToolError) return error;\n const code = typeof error === 'object' && error !== null && 'statusCode' in error && typeof error.statusCode === 'number'\n ? error.statusCode : undefined;\n return new RedisAgentMemoryToolError(code ? `IRIS_HTTP_${code}` : 'IRIS_REQUEST_FAILED',\n code ? `Iris request failed (HTTP ${code}). Check service configuration and request scope. Writes may have partially succeeded; verify before retrying.`\n : 'Iris request failed. Check connectivity and service configuration. Verify writes before retrying.', code);\n}\n"]}
|