korely-memory 0.1.6 → 0.1.8
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/README.md +115 -27
- package/dist/ai-sdk.cjs +361 -0
- package/dist/ai-sdk.d.cts +156 -0
- package/dist/ai-sdk.d.ts +156 -0
- package/dist/ai-sdk.js +334 -0
- package/dist/index.cjs +240 -90
- package/dist/index.d.cts +302 -68
- package/dist/index.d.ts +302 -68
- package/dist/index.js +237 -87
- package/package.json +26 -3
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# korely-memory
|
|
2
2
|
|
|
3
|
-
The JavaScript / TypeScript SDK for [Korely Agents](https://korely.ai/agents)
|
|
4
|
-
memory for AI agents, with
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
The JavaScript / TypeScript SDK for [Korely Agents](https://korely.ai/agents):
|
|
4
|
+
memory for AI agents, with typed bi-temporal facts behind every write. A thin,
|
|
5
|
+
**zero-dependency** client over the Korely REST API (uses the native `fetch`).
|
|
6
|
+
Same package name as the Python twin on
|
|
7
7
|
[PyPI](https://pypi.org/project/korely-memory/).
|
|
8
8
|
|
|
9
9
|
```bash
|
|
@@ -22,7 +22,7 @@ await korely.add("Maria prefers email over Slack, and her renewal is in October.
|
|
|
22
22
|
user_id: "customer-4812",
|
|
23
23
|
});
|
|
24
24
|
|
|
25
|
-
// Later
|
|
25
|
+
// Later, even in a new session, pull a prompt-ready block back
|
|
26
26
|
const ctx = await korely.getContext({
|
|
27
27
|
query: "how does Maria like to be contacted?",
|
|
28
28
|
user_id: "customer-4812",
|
|
@@ -31,8 +31,62 @@ console.log(ctx.context); // drop straight into your system prompt
|
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
That's the whole loop: `add` to remember, `getContext` (or `search`) to recall.
|
|
34
|
-
Behind `add`, Korely extracts typed, bi-temporal facts
|
|
35
|
-
|
|
34
|
+
Behind `add`, Korely extracts typed, bi-temporal facts; you just hand it text.
|
|
35
|
+
|
|
36
|
+
## Vercel AI SDK
|
|
37
|
+
|
|
38
|
+
`korely-memory/ai-sdk` gives any [AI SDK](https://ai-sdk.dev) model (AI SDK 5,
|
|
39
|
+
6 or 7) a memory of each of your users. Install `ai` next to this package; the
|
|
40
|
+
core client never loads it.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// app/api/chat/route.ts
|
|
44
|
+
import {
|
|
45
|
+
convertToModelMessages,
|
|
46
|
+
createUIMessageStreamResponse,
|
|
47
|
+
streamText,
|
|
48
|
+
toUIMessageStream,
|
|
49
|
+
type UIMessage,
|
|
50
|
+
} from "ai";
|
|
51
|
+
import { waitUntil } from "@vercel/functions";
|
|
52
|
+
import { withKorelyMemory } from "korely-memory/ai-sdk";
|
|
53
|
+
|
|
54
|
+
export async function POST(req: Request) {
|
|
55
|
+
const { messages }: { messages: UIMessage[] } = await req.json();
|
|
56
|
+
const userId = await currentUserId(req); // from your auth, never from the request body
|
|
57
|
+
|
|
58
|
+
const result = streamText({
|
|
59
|
+
model: withKorelyMemory("anthropic/claude-sonnet-5.5", { userId, waitUntil }),
|
|
60
|
+
instructions: "You are the support assistant of Acme.",
|
|
61
|
+
messages: await convertToModelMessages(messages),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) });
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Before each call, the wrapper reads `getContext` for the latest user message
|
|
69
|
+
and adds what Korely knows as system messages after your own: first the part
|
|
70
|
+
that is the same on every call, so the provider's prompt cache keeps it, then
|
|
71
|
+
`Current date: YYYY-MM-DD` and the facts and memories this question brought.
|
|
72
|
+
After a reply that ends the turn, it stores the user message and the reply as
|
|
73
|
+
one memory, without waiting for the write (`waitUntil` keeps a serverless
|
|
74
|
+
function alive until it lands). If Korely cannot be reached, or takes longer
|
|
75
|
+
than `contextTimeoutMs` (5 s) to answer, the call goes on without memory,
|
|
76
|
+
`onError` is told, and an answer that arrives later is dropped.
|
|
77
|
+
|
|
78
|
+
Options: `userId` (required), `agentId`, `runId`, `client` (a configured
|
|
79
|
+
`Korely`, default `new Korely()`), `tokenBudget` (800), `contextTimeoutMs`
|
|
80
|
+
(5000; 0 waits for the client's own 30 s), `includeDate` (true), `timeZone`
|
|
81
|
+
("UTC"), `remember` (true), `waitUntil`, `onError`.
|
|
82
|
+
|
|
83
|
+
To let the model decide when to look something up or save it, give it the
|
|
84
|
+
tools instead: `tools: korelyTools({ userId })` adds `searchMemory` and
|
|
85
|
+
`addMemory`, and takes the same options except `remember` and `waitUntil`.
|
|
86
|
+
`searchMemory` also waits at most `contextTimeoutMs`, then tells the model the
|
|
87
|
+
memory is unavailable right now (`onError` hears of it, phase `"search"`).
|
|
88
|
+
Either way the user comes from your code: the model has no field to name
|
|
89
|
+
another one.
|
|
36
90
|
|
|
37
91
|
## Methods
|
|
38
92
|
|
|
@@ -40,22 +94,25 @@ Every method maps to one REST endpoint.
|
|
|
40
94
|
|
|
41
95
|
| Method | Endpoint | |
|
|
42
96
|
|---|---|---|
|
|
43
|
-
| `add(content, opts?)` | `POST /v1/memories` | Write. `content` is a string or a list of chat messages. `opts.timestamp` (ISO) backfills the past
|
|
44
|
-
| `search(query, opts?)` | `POST /v1/memories/search` |
|
|
45
|
-
| `getAll(opts?)` | `GET /v1/memories` | List a scope, newest first. |
|
|
97
|
+
| `add(content, opts?)` | `POST /v1/memories` | Write. `content` is a string or a list of chat messages. `opts.timestamp` (ISO) backfills the past: facts inherit it as `valid_from`. |
|
|
98
|
+
| `search(query, opts?)` | `POST /v1/memories/search` | Semantic search over memories; filter by `user_id`, `agent_id`, `run_id`, `metadata`. |
|
|
99
|
+
| `getAll(opts?)` | `GET /v1/memories` | List a scope, newest first. The page is iterable; `limit` up to 200. |
|
|
46
100
|
| `get(id)` | `GET /v1/memories/:id` | One memory, with its facts. |
|
|
47
101
|
| `update(id, { content })` | `PATCH /v1/memories/:id` | Re-runs extraction. |
|
|
48
102
|
| `delete(id)` | `DELETE /v1/memories/:id` | Forget one (audited). |
|
|
49
|
-
| `deleteAll({ user_id })` | `DELETE /v1/users/:user_id/memories` |
|
|
103
|
+
| `deleteAll({ user_id })` | `DELETE /v1/users/:user_id/memories` | Erase everything for a user (GDPR). The receipt counts `memories_deleted` and `facts_deleted`; `memories_forgotten` and `facts_invalidated` are deprecated aliases. |
|
|
50
104
|
| `history(id)` | `GET /v1/memories/:id/history` | A memory's timeline + the facts it produced. |
|
|
51
105
|
| `users(opts?)` | `GET /v1/users` | Your end users, with counts. |
|
|
52
|
-
| `listAgents(opts?)` | `GET /v1/agents` |
|
|
53
|
-
| `deleteAgent(agentId)` | `DELETE /v1/agents/:agent_id` | Purge an agent namespace
|
|
54
|
-
| `getFacts(opts?)` | `GET /v1/facts` | Typed facts; `as_of` for point-in-time. |
|
|
55
|
-
| `addFactTriple(s, p, o, opts?)` | `POST /v1/facts` | Write a fact directly (bi-temporal). |
|
|
106
|
+
| `listAgents(opts?)` | `GET /v1/agents` | This project's agent namespaces, with counts. `total` counts this project's names, `used` the cap slots taken across the account. Call after `agent_cap_exceeded` to reuse an id. |
|
|
107
|
+
| `deleteAgent(agentId)` | `DELETE /v1/agents/:agent_id` | Purge an agent namespace of this project. `NotFoundError` for a name the project does not use; `slot_freed` says whether the cap slot is free now. |
|
|
108
|
+
| `getFacts(opts?)` | `GET /v1/facts` | Typed facts; `as_of` for point-in-time. The array also carries `total`. |
|
|
109
|
+
| `addFactTriple(s, p, o, opts?)` | `POST /v1/facts` | Write a fact directly (bi-temporal; `tense: "past"` for one that is over). |
|
|
110
|
+
| `correctFact(id, changes)` | `PATCH /v1/facts/:id` | Supersede a fact with a corrected one; `invalidated` lists what it closed. Restating the fact as it stands reconfirms it (`invalidated: []`). |
|
|
111
|
+
| `forgetFact(id, { at? })` | `POST /v1/facts/:id/forget` | Close a fact; it stays in history. |
|
|
56
112
|
| `getProfile({ user_id, as_of? })` | `GET /v1/profile` | The assembled profile of one end user. |
|
|
57
|
-
| `getContext({ query, user_id? })` | `GET /v1/context` | One call
|
|
58
|
-
| `
|
|
113
|
+
| `getContext({ query, user_id? })` | `GET /v1/context` | One call, a prompt-ready context block. |
|
|
114
|
+
| `events(opts?)` | `GET /v1/events` | Which writes are still being extracted; `limit` up to 200. |
|
|
115
|
+
| `batch(memories)` | `POST /v1/batch` | Bulk import, for migrations. Each item takes `timestamp`, as `add()` does. |
|
|
59
116
|
| `batchStatus(jobId)` | `GET /v1/batch/:id` | Poll an import job. |
|
|
60
117
|
|
|
61
118
|
## Bi-temporal facts (the moat)
|
|
@@ -76,17 +133,22 @@ await korely.addFactTriple("Marco", "works_at", "Acme GmbH", {
|
|
|
76
133
|
|
|
77
134
|
## Errors
|
|
78
135
|
|
|
79
|
-
Every error
|
|
136
|
+
Every error the server answers with is an `APIError` carrying the stable `code`
|
|
137
|
+
and the `message` of the REST error envelope (`{code, message}`; a self-hosted
|
|
138
|
+
install that answers FastAPI's `detail` is read the same way). The common
|
|
139
|
+
statuses also have their own subclass.
|
|
140
|
+
Everything subclasses `KorelyError`, which is also what a client-side problem
|
|
141
|
+
throws (no key, a connection error, a timeout).
|
|
80
142
|
|
|
81
143
|
```ts
|
|
82
|
-
import { Korely,
|
|
144
|
+
import { Korely, APIError, QuotaExceededError } from "korely-memory";
|
|
83
145
|
|
|
84
146
|
try {
|
|
85
147
|
await korely.add("...", { user_id: "u" });
|
|
86
148
|
} catch (e) {
|
|
87
|
-
if (e instanceof QuotaExceededError) {
|
|
88
|
-
console.log(`Rate limited
|
|
89
|
-
} else if (e instanceof
|
|
149
|
+
if (e instanceof QuotaExceededError && e.retryAfter !== undefined) {
|
|
150
|
+
console.log(`Rate limited, retry after ${e.retryAfter}s`);
|
|
151
|
+
} else if (e instanceof APIError && e.code === "invalid_key") {
|
|
90
152
|
console.log("Bad or missing API key");
|
|
91
153
|
} else {
|
|
92
154
|
throw e;
|
|
@@ -94,20 +156,46 @@ try {
|
|
|
94
156
|
}
|
|
95
157
|
```
|
|
96
158
|
|
|
97
|
-
`AuthenticationError` (401) · `NamespaceForbiddenError` (403
|
|
98
|
-
|
|
99
|
-
`
|
|
159
|
+
`AuthenticationError` (401) · `NamespaceForbiddenError` (403, e.g.
|
|
160
|
+
`agent_cap_exceeded`) · `NotFoundError` (404) · `StaleWriteError` (409) ·
|
|
161
|
+
`QuotaExceededError` (429: `retryAfter` is set for `rate_limit_exceeded`,
|
|
162
|
+
undefined for the monthly `quota_exceeded`) · `APIError` (the base of all of
|
|
163
|
+
these, and everything else: 422, 503). The SDK does not retry on its own.
|
|
100
164
|
|
|
101
165
|
## Configuration
|
|
102
166
|
|
|
103
167
|
```ts
|
|
104
168
|
new Korely({
|
|
105
169
|
apiKey: "kor_live_...", // or the KORELY_API_KEY env var
|
|
106
|
-
region: "eu", // EU only
|
|
107
|
-
timeoutMs: 30000,
|
|
170
|
+
region: "eu", // EU only: data stored and processed in the EU
|
|
171
|
+
timeoutMs: 30000, // covers the whole request, response body included
|
|
108
172
|
});
|
|
109
173
|
```
|
|
110
174
|
|
|
175
|
+
### Your own server (korely-agent)
|
|
176
|
+
|
|
177
|
+
Point the client at your install with `baseUrl`, or with the `KORELY_BASE_URL`
|
|
178
|
+
env var, and use the key your install issued (`kor_self_...`):
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
const korely = new Korely({
|
|
182
|
+
apiKey: "kor_self_...", // or KORELY_API_KEY
|
|
183
|
+
baseUrl: "https://memory.example.com", // or KORELY_BASE_URL
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The option is `baseUrl`, in camelCase. `base_url` is the Python spelling and
|
|
188
|
+
this SDK refuses it, rather than ignore it and send your memories to the hosted
|
|
189
|
+
service. A `kor_self_` key is never sent to the hosted service, and a
|
|
190
|
+
`kor_live_` key is never sent anywhere else.
|
|
191
|
+
|
|
192
|
+
For a server whose certificate a private CA signed (Caddy's local CA on a
|
|
193
|
+
laptop install), Node reads the CA from `NODE_EXTRA_CA_CERTS`:
|
|
194
|
+
|
|
195
|
+
```sh
|
|
196
|
+
NODE_EXTRA_CA_CERTS=/path/to/root.crt node agent.js
|
|
197
|
+
```
|
|
198
|
+
|
|
111
199
|
Requires Node 18+ (native `fetch`), or any runtime with a global `fetch`. On
|
|
112
200
|
older runtimes, pass one via `{ fetch }`.
|
|
113
201
|
|
package/dist/ai-sdk.cjs
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/ai-sdk.ts
|
|
21
|
+
var ai_sdk_exports = {};
|
|
22
|
+
__export(ai_sdk_exports, {
|
|
23
|
+
korelyMemoryMiddleware: () => korelyMemoryMiddleware,
|
|
24
|
+
korelyTools: () => korelyTools,
|
|
25
|
+
withKorelyMemory: () => withKorelyMemory
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(ai_sdk_exports);
|
|
28
|
+
var import_ai = require("ai");
|
|
29
|
+
var import_korely_memory = require("korely-memory");
|
|
30
|
+
var QUERY_MAX = 2e3;
|
|
31
|
+
var CONTENT_MAX = 16e3;
|
|
32
|
+
var USER_MAX = 6e3;
|
|
33
|
+
var TURN_OVERHEAD = 18;
|
|
34
|
+
var DEFAULT_TOKEN_BUDGET = 800;
|
|
35
|
+
var CONTEXT_REUSE_MS = 5 * 6e4;
|
|
36
|
+
var FAILURE_REUSE_MS = 3e4;
|
|
37
|
+
var DEFAULT_CONTEXT_TIMEOUT_MS = 5e3;
|
|
38
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
39
|
+
function scopeOf(options, caller) {
|
|
40
|
+
const o = options ?? {};
|
|
41
|
+
if (typeof o.userId !== "string" || !o.userId.trim()) {
|
|
42
|
+
throw new import_korely_memory.KorelyError(
|
|
43
|
+
`${caller} needs a userId: the id of your end user, from your own auth. Without it a read would span every end user of the project.`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
client: o.client ?? new import_korely_memory.Korely(),
|
|
48
|
+
userId: o.userId,
|
|
49
|
+
agentId: o.agentId,
|
|
50
|
+
runId: o.runId,
|
|
51
|
+
tokenBudget: o.tokenBudget ?? DEFAULT_TOKEN_BUDGET,
|
|
52
|
+
today: o.includeDate === false ? void 0 : dateLine(o.timeZone),
|
|
53
|
+
limit: contextLimit(o.contextTimeoutMs),
|
|
54
|
+
report: reporter(o.onError)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function dateLine(timeZone) {
|
|
58
|
+
if (!timeZone) return () => `Current date: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
|
|
59
|
+
let format;
|
|
60
|
+
try {
|
|
61
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
62
|
+
timeZone,
|
|
63
|
+
year: "numeric",
|
|
64
|
+
month: "2-digit",
|
|
65
|
+
day: "2-digit"
|
|
66
|
+
});
|
|
67
|
+
} catch {
|
|
68
|
+
throw new import_korely_memory.KorelyError(`timeZone ${JSON.stringify(timeZone)} is not an IANA time zone, e.g. "Europe/Rome".`);
|
|
69
|
+
}
|
|
70
|
+
return () => {
|
|
71
|
+
const part = {};
|
|
72
|
+
for (const { type, value } of format.formatToParts(/* @__PURE__ */ new Date())) part[type] = value;
|
|
73
|
+
return `Current date: ${part.year}-${part.month}-${part.day}`;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function clip(text, max) {
|
|
77
|
+
if (text.length <= max) return text;
|
|
78
|
+
const mark = " \u2026 ";
|
|
79
|
+
const headLength = Math.floor((max - mark.length) / 2);
|
|
80
|
+
let head = text.slice(0, headLength);
|
|
81
|
+
let tail = text.slice(text.length - (max - mark.length - headLength));
|
|
82
|
+
if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
|
|
83
|
+
if (/^[\uDC00-\uDFFF]/.test(tail)) tail = tail.slice(1);
|
|
84
|
+
return head + mark + tail;
|
|
85
|
+
}
|
|
86
|
+
function isText(part) {
|
|
87
|
+
return part.type === "text" && typeof part.text === "string";
|
|
88
|
+
}
|
|
89
|
+
function latestUserText(prompt) {
|
|
90
|
+
for (let i = prompt.length - 1; i >= 0; i--) {
|
|
91
|
+
const message = prompt[i];
|
|
92
|
+
if (message.role !== "user") continue;
|
|
93
|
+
const content = message.content;
|
|
94
|
+
if (typeof content === "string") return content.trim();
|
|
95
|
+
if (!Array.isArray(content)) return "";
|
|
96
|
+
return content.filter(isText).map((part) => part.text).join("\n").trim();
|
|
97
|
+
}
|
|
98
|
+
return "";
|
|
99
|
+
}
|
|
100
|
+
function userMessageCount(prompt) {
|
|
101
|
+
return prompt.filter((message) => message.role === "user").length;
|
|
102
|
+
}
|
|
103
|
+
function partsOf(ctx) {
|
|
104
|
+
const stable = typeof ctx?.stable === "string" ? ctx.stable : "";
|
|
105
|
+
const volatile = typeof ctx?.volatile === "string" ? ctx.volatile : "";
|
|
106
|
+
if (stable.trim() || volatile.trim()) return { stable, volatile };
|
|
107
|
+
return { stable: "", volatile: typeof ctx?.context === "string" ? ctx.context : "" };
|
|
108
|
+
}
|
|
109
|
+
function memoryMessages(parts, date) {
|
|
110
|
+
const messages = [];
|
|
111
|
+
if (parts?.stable.trim()) messages.push({ role: "system", content: parts.stable });
|
|
112
|
+
const turn = [date, parts?.volatile.trim() ? parts.volatile : void 0].filter(Boolean).join("\n\n");
|
|
113
|
+
if (turn) messages.push({ role: "system", content: turn });
|
|
114
|
+
return messages;
|
|
115
|
+
}
|
|
116
|
+
function withMemory(prompt, messages) {
|
|
117
|
+
let head = 0;
|
|
118
|
+
while (head < prompt.length && prompt[head].role === "system") head++;
|
|
119
|
+
return [...prompt.slice(0, head), ...messages, ...prompt.slice(head)];
|
|
120
|
+
}
|
|
121
|
+
function endsTurn(finishReason, content) {
|
|
122
|
+
const reason = typeof finishReason === "string" ? finishReason : finishReason?.unified;
|
|
123
|
+
if (reason === "tool-calls" || reason === "error") return false;
|
|
124
|
+
return !content.some(
|
|
125
|
+
(part) => part.type === "tool-call" && !part.providerExecuted
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
function contextLimit(value) {
|
|
129
|
+
const ms = value ?? DEFAULT_CONTEXT_TIMEOUT_MS;
|
|
130
|
+
if (typeof ms !== "number" || Number.isNaN(ms) || ms < 0) {
|
|
131
|
+
throw new import_korely_memory.KorelyError(
|
|
132
|
+
`contextTimeoutMs must be a number of milliseconds, 0 or more, got ${JSON.stringify(value)}. 0 or Infinity waits for the client's own timeout.`
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
return ms === 0 || ms >= MAX_TIMER_MS ? void 0 : ms;
|
|
136
|
+
}
|
|
137
|
+
var DEFAULT_WARNING = {
|
|
138
|
+
context: "korely-memory/ai-sdk: could not read the memory; this call went on without it.",
|
|
139
|
+
remember: "korely-memory/ai-sdk: could not store the turn.",
|
|
140
|
+
search: "korely-memory/ai-sdk: searchMemory could not read the memory."
|
|
141
|
+
};
|
|
142
|
+
function reporter(onError) {
|
|
143
|
+
return (error, phase) => {
|
|
144
|
+
try {
|
|
145
|
+
if (onError) onError(error, { phase });
|
|
146
|
+
else console.warn(DEFAULT_WARNING[phase], error);
|
|
147
|
+
} catch {
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function readWithin(read, limit) {
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
let timer;
|
|
154
|
+
const finish = (outcome) => {
|
|
155
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
156
|
+
resolve(outcome);
|
|
157
|
+
};
|
|
158
|
+
if (limit !== void 0) {
|
|
159
|
+
timer = setTimeout(() => {
|
|
160
|
+
const error = new import_korely_memory.KorelyError(`GET /v1/context took longer than ${limit} ms (contextTimeoutMs).`);
|
|
161
|
+
finish({ ok: false, error, timedOut: true });
|
|
162
|
+
}, limit);
|
|
163
|
+
}
|
|
164
|
+
Promise.resolve().then(read).then(
|
|
165
|
+
(ctx) => finish({ ok: true, ctx }),
|
|
166
|
+
(error) => finish({ ok: false, error, timedOut: false })
|
|
167
|
+
);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
function korelyMemoryMiddleware(options) {
|
|
171
|
+
const scope = scopeOf(options, "korelyMemoryMiddleware");
|
|
172
|
+
const remember = options.remember ?? true;
|
|
173
|
+
const report = scope.report;
|
|
174
|
+
const waitUntil = options.waitUntil;
|
|
175
|
+
let lastTurn;
|
|
176
|
+
function contextFor(query, turn) {
|
|
177
|
+
const key = `${turn}\0${query}`;
|
|
178
|
+
if (lastTurn && lastTurn.key === key && Date.now() < lastTurn.until) return lastTurn.parts;
|
|
179
|
+
const entry = { key, until: Date.now() + CONTEXT_REUSE_MS, parts: Promise.resolve(void 0) };
|
|
180
|
+
entry.parts = readWithin(
|
|
181
|
+
() => scope.client.getContext({
|
|
182
|
+
query: clip(query, QUERY_MAX),
|
|
183
|
+
user_id: scope.userId,
|
|
184
|
+
agent_id: scope.agentId,
|
|
185
|
+
token_budget: scope.tokenBudget
|
|
186
|
+
}),
|
|
187
|
+
scope.limit
|
|
188
|
+
).then((outcome) => {
|
|
189
|
+
if (outcome.ok) return partsOf(outcome.ctx);
|
|
190
|
+
entry.until = Date.now() + FAILURE_REUSE_MS;
|
|
191
|
+
report(outcome.error, "context");
|
|
192
|
+
return void 0;
|
|
193
|
+
}).catch(() => void 0);
|
|
194
|
+
lastTurn = entry;
|
|
195
|
+
return entry.parts;
|
|
196
|
+
}
|
|
197
|
+
function rememberTurn(prompt, reply) {
|
|
198
|
+
const user = latestUserText(prompt);
|
|
199
|
+
if (!user || !reply.trim()) return;
|
|
200
|
+
const userPart = clip(user, USER_MAX);
|
|
201
|
+
const replyPart = clip(reply, CONTENT_MAX - TURN_OVERHEAD - userPart.length);
|
|
202
|
+
const write = Promise.resolve().then(
|
|
203
|
+
() => scope.client.add(
|
|
204
|
+
[
|
|
205
|
+
{ role: "user", content: userPart },
|
|
206
|
+
{ role: "assistant", content: replyPart }
|
|
207
|
+
],
|
|
208
|
+
{ user_id: scope.userId, agent_id: scope.agentId, run_id: scope.runId }
|
|
209
|
+
)
|
|
210
|
+
).then(
|
|
211
|
+
() => void 0,
|
|
212
|
+
(error) => report(error, "remember")
|
|
213
|
+
);
|
|
214
|
+
if (!waitUntil) return;
|
|
215
|
+
try {
|
|
216
|
+
waitUntil(write);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
report(error, "remember");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return {
|
|
222
|
+
specificationVersion: "v4",
|
|
223
|
+
transformParams: async ({ params }) => {
|
|
224
|
+
const query = latestUserText(params.prompt);
|
|
225
|
+
const parts = query ? await contextFor(query, userMessageCount(params.prompt)) : void 0;
|
|
226
|
+
const added = memoryMessages(parts, scope.today?.());
|
|
227
|
+
return added.length ? { ...params, prompt: withMemory(params.prompt, added) } : params;
|
|
228
|
+
},
|
|
229
|
+
wrapGenerate: async ({ doGenerate, params }) => {
|
|
230
|
+
const result = await doGenerate();
|
|
231
|
+
if (remember) {
|
|
232
|
+
try {
|
|
233
|
+
if (endsTurn(result.finishReason, result.content)) {
|
|
234
|
+
rememberTurn(params.prompt, result.content.filter(isText).map((part) => part.text).join(""));
|
|
235
|
+
}
|
|
236
|
+
} catch (error) {
|
|
237
|
+
report(error, "remember");
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return result;
|
|
241
|
+
},
|
|
242
|
+
wrapStream: async ({ doStream, params }) => {
|
|
243
|
+
const result = await doStream();
|
|
244
|
+
if (!remember) return result;
|
|
245
|
+
let reply = "";
|
|
246
|
+
let toolCall = false;
|
|
247
|
+
let failed = false;
|
|
248
|
+
let finished = false;
|
|
249
|
+
const watch = new TransformStream({
|
|
250
|
+
transform(part, controller) {
|
|
251
|
+
controller.enqueue(part);
|
|
252
|
+
if (finished) return;
|
|
253
|
+
try {
|
|
254
|
+
if (part.type === "text-delta") reply += part.delta;
|
|
255
|
+
else if (part.type === "tool-call") toolCall ||= !part.providerExecuted;
|
|
256
|
+
else if (part.type === "error") failed = true;
|
|
257
|
+
else if (part.type === "finish") {
|
|
258
|
+
finished = true;
|
|
259
|
+
if (!failed && !toolCall && endsTurn(part.finishReason, [])) rememberTurn(params.prompt, reply);
|
|
260
|
+
}
|
|
261
|
+
} catch (error) {
|
|
262
|
+
report(error, "remember");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
return { ...result, stream: result.stream.pipeThrough(watch) };
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
function resolveModel(model) {
|
|
271
|
+
if (typeof model !== "string") return model;
|
|
272
|
+
const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? import_ai.gateway;
|
|
273
|
+
return provider.languageModel(model);
|
|
274
|
+
}
|
|
275
|
+
function withKorelyMemory(model, options) {
|
|
276
|
+
const middleware = korelyMemoryMiddleware(options);
|
|
277
|
+
return (0, import_ai.wrapLanguageModel)({ model: resolveModel(model), middleware });
|
|
278
|
+
}
|
|
279
|
+
var NOTHING_IN_MEMORY = "Nothing in memory bears on this.";
|
|
280
|
+
var MEMORY_UNAVAILABLE = "Memory is unavailable right now: earlier conversations cannot be checked. Answer from this conversation alone.";
|
|
281
|
+
function oneText(value, key, max) {
|
|
282
|
+
const raw = value && typeof value === "object" ? value[key] : void 0;
|
|
283
|
+
if (typeof raw !== "string" || !raw.trim()) {
|
|
284
|
+
return { success: false, error: new Error(`${key} must be a non-empty string.`) };
|
|
285
|
+
}
|
|
286
|
+
return { success: true, value: { [key]: clip(raw.trim(), max) } };
|
|
287
|
+
}
|
|
288
|
+
function korelyTools(options) {
|
|
289
|
+
const scope = scopeOf(options, "korelyTools");
|
|
290
|
+
const withDate = (text) => scope.today ? `${scope.today()}
|
|
291
|
+
|
|
292
|
+
${text}` : text;
|
|
293
|
+
return {
|
|
294
|
+
searchMemory: (0, import_ai.tool)({
|
|
295
|
+
description: "Look up what you know about the user from earlier conversations: facts about their life and work, preferences, decisions, plans, and what they said before. Use it when the answer may depend on something the user told you in the past.",
|
|
296
|
+
inputSchema: (0, import_ai.jsonSchema)(
|
|
297
|
+
{
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: {
|
|
300
|
+
query: {
|
|
301
|
+
type: "string",
|
|
302
|
+
description: 'What to look up, as a short question or a few words, e.g. "preferred contact channel".'
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
required: ["query"],
|
|
306
|
+
additionalProperties: false
|
|
307
|
+
},
|
|
308
|
+
{ validate: (value) => oneText(value, "query", QUERY_MAX) }
|
|
309
|
+
),
|
|
310
|
+
execute: async ({ query }) => {
|
|
311
|
+
const outcome = await readWithin(
|
|
312
|
+
() => scope.client.getContext({
|
|
313
|
+
query,
|
|
314
|
+
user_id: scope.userId,
|
|
315
|
+
agent_id: scope.agentId,
|
|
316
|
+
token_budget: scope.tokenBudget
|
|
317
|
+
}),
|
|
318
|
+
scope.limit
|
|
319
|
+
);
|
|
320
|
+
if (!outcome.ok) {
|
|
321
|
+
scope.report(outcome.error, "search");
|
|
322
|
+
if (!outcome.timedOut) throw outcome.error;
|
|
323
|
+
return withDate(MEMORY_UNAVAILABLE);
|
|
324
|
+
}
|
|
325
|
+
const ctx = outcome.ctx;
|
|
326
|
+
return withDate(typeof ctx?.context === "string" && ctx.context.trim() ? ctx.context : NOTHING_IN_MEMORY);
|
|
327
|
+
}
|
|
328
|
+
}),
|
|
329
|
+
addMemory: (0, import_ai.tool)({
|
|
330
|
+
description: "Save something worth remembering about the user for future conversations: a fact about their life or work, a preference, a decision, a plan. One self-contained statement per call. Never save passwords, card numbers or other secrets.",
|
|
331
|
+
inputSchema: (0, import_ai.jsonSchema)(
|
|
332
|
+
{
|
|
333
|
+
type: "object",
|
|
334
|
+
properties: {
|
|
335
|
+
memory: {
|
|
336
|
+
type: "string",
|
|
337
|
+
description: 'The statement to remember, e.g. "Maria prefers email over Slack."'
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
required: ["memory"],
|
|
341
|
+
additionalProperties: false
|
|
342
|
+
},
|
|
343
|
+
{ validate: (value) => oneText(value, "memory", CONTENT_MAX) }
|
|
344
|
+
),
|
|
345
|
+
execute: async ({ memory }) => {
|
|
346
|
+
const saved = await scope.client.add(memory, {
|
|
347
|
+
user_id: scope.userId,
|
|
348
|
+
agent_id: scope.agentId,
|
|
349
|
+
run_id: scope.runId
|
|
350
|
+
});
|
|
351
|
+
return saved?.id ? { saved: true, id: saved.id } : { saved: true };
|
|
352
|
+
}
|
|
353
|
+
})
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
357
|
+
0 && (module.exports = {
|
|
358
|
+
korelyMemoryMiddleware,
|
|
359
|
+
korelyTools,
|
|
360
|
+
withKorelyMemory
|
|
361
|
+
});
|