korely-memory 0.1.18 → 0.2.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/README.md +14 -7
- package/dist/chunk-VT7GXOPS.js +1131 -0
- package/dist/index.cjs +147 -27
- package/dist/index.d.cts +72 -20
- package/dist/index.d.ts +72 -20
- package/dist/index.js +13 -992
- package/dist/index.node.cjs +1185 -0
- package/dist/index.node.js +34 -0
- package/package.json +10 -2
|
@@ -0,0 +1,1131 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__require,
|
|
3
|
+
keysOf,
|
|
4
|
+
unknownOption
|
|
5
|
+
} from "./chunk-6SD5RRK3.js";
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
var KorelyError = class extends Error {
|
|
9
|
+
constructor(message = "", opts = {}) {
|
|
10
|
+
super(message || opts.code || "Korely error");
|
|
11
|
+
this.name = "KorelyError";
|
|
12
|
+
this.status = opts.status;
|
|
13
|
+
this.code = opts.code;
|
|
14
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var APIError = class extends KorelyError {
|
|
18
|
+
constructor(message = "", opts = {}) {
|
|
19
|
+
super(message, opts);
|
|
20
|
+
this.name = "APIError";
|
|
21
|
+
this.retryAfter = opts.retryAfter;
|
|
22
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var AuthenticationError = class _AuthenticationError extends APIError {
|
|
26
|
+
constructor(message = "", opts = {}) {
|
|
27
|
+
super(message, opts);
|
|
28
|
+
this.name = "AuthenticationError";
|
|
29
|
+
Object.setPrototypeOf(this, _AuthenticationError.prototype);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var NamespaceForbiddenError = class _NamespaceForbiddenError extends APIError {
|
|
33
|
+
constructor(message = "", opts = {}) {
|
|
34
|
+
super(message, opts);
|
|
35
|
+
this.name = "NamespaceForbiddenError";
|
|
36
|
+
Object.setPrototypeOf(this, _NamespaceForbiddenError.prototype);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
var NotFoundError = class _NotFoundError extends APIError {
|
|
40
|
+
constructor(message = "", opts = {}) {
|
|
41
|
+
super(message, opts);
|
|
42
|
+
this.name = "NotFoundError";
|
|
43
|
+
Object.setPrototypeOf(this, _NotFoundError.prototype);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var ConflictError = class extends APIError {
|
|
47
|
+
constructor(message = "", opts = {}) {
|
|
48
|
+
super(message, opts);
|
|
49
|
+
this.name = "ConflictError";
|
|
50
|
+
this.currentFactId = opts.currentFactId;
|
|
51
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var StaleWriteError = class _StaleWriteError extends ConflictError {
|
|
55
|
+
constructor(message = "", opts = {}) {
|
|
56
|
+
super(message, opts);
|
|
57
|
+
this.name = "StaleWriteError";
|
|
58
|
+
Object.setPrototypeOf(this, _StaleWriteError.prototype);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var QuotaExceededError = class extends APIError {
|
|
62
|
+
constructor(message = "", opts = {}) {
|
|
63
|
+
super(message, opts);
|
|
64
|
+
this.name = "QuotaExceededError";
|
|
65
|
+
this.limit = opts.limit;
|
|
66
|
+
this.used = opts.used;
|
|
67
|
+
this.resetsAt = opts.resetsAt;
|
|
68
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError {
|
|
72
|
+
constructor(message = "", opts = {}) {
|
|
73
|
+
super(message, opts);
|
|
74
|
+
this.name = "TooManyBatchesError";
|
|
75
|
+
Object.setPrototypeOf(this, _TooManyBatchesError.prototype);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// src/client.ts
|
|
80
|
+
var VERSION = "0.2.0";
|
|
81
|
+
var REGIONS = { eu: "https://api.korely.ai" };
|
|
82
|
+
var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch", "client");
|
|
83
|
+
var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
|
|
84
|
+
var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp", "kind");
|
|
85
|
+
var SEARCH_KEYS = keysOf()(
|
|
86
|
+
"user_id",
|
|
87
|
+
"agent_id",
|
|
88
|
+
"run_id",
|
|
89
|
+
"metadata",
|
|
90
|
+
"limit",
|
|
91
|
+
"min_score",
|
|
92
|
+
"exclude_sessions"
|
|
93
|
+
);
|
|
94
|
+
var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset", "exclude_sessions");
|
|
95
|
+
var NAME_KEYS = keysOf()("user_id", "agent_id");
|
|
96
|
+
var UPDATE_KEYS = keysOf()("content", "expected_updated_at");
|
|
97
|
+
var USERS_KEYS = keysOf()("agent_id", "limit", "offset");
|
|
98
|
+
var AGENTS_KEYS = keysOf()("limit", "offset");
|
|
99
|
+
var EVENTS_KEYS = keysOf()("user_id", "status", "limit");
|
|
100
|
+
var AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "limit", "offset");
|
|
101
|
+
var ITER_AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "offset", "page_size");
|
|
102
|
+
var FACTS_KEYS = keysOf()(
|
|
103
|
+
"subject",
|
|
104
|
+
"entity",
|
|
105
|
+
"predicate",
|
|
106
|
+
"predicate_family",
|
|
107
|
+
"include_invalidated",
|
|
108
|
+
"as_of",
|
|
109
|
+
"known_as_of",
|
|
110
|
+
"user_id",
|
|
111
|
+
"agent_id",
|
|
112
|
+
"limit",
|
|
113
|
+
"offset",
|
|
114
|
+
"exclude_sessions"
|
|
115
|
+
);
|
|
116
|
+
var TRIPLE_KEYS = keysOf()(
|
|
117
|
+
"user_id",
|
|
118
|
+
"agent_id",
|
|
119
|
+
"run_id",
|
|
120
|
+
"subject_type",
|
|
121
|
+
"object_is_literal",
|
|
122
|
+
"confidence",
|
|
123
|
+
"valid_from",
|
|
124
|
+
"tense"
|
|
125
|
+
);
|
|
126
|
+
var PROFILE_KEYS = keysOf()(
|
|
127
|
+
"user_id",
|
|
128
|
+
"agent_id",
|
|
129
|
+
"as_of",
|
|
130
|
+
"known_as_of",
|
|
131
|
+
"exclude_sessions"
|
|
132
|
+
);
|
|
133
|
+
var CONTEXT_KEYS = keysOf()(
|
|
134
|
+
"query",
|
|
135
|
+
"user_id",
|
|
136
|
+
"agent_id",
|
|
137
|
+
"token_budget",
|
|
138
|
+
"known_as_of",
|
|
139
|
+
"exclude_sessions"
|
|
140
|
+
);
|
|
141
|
+
var CONTEXT_EXTRA_KEYS = keysOf()(
|
|
142
|
+
"user_id",
|
|
143
|
+
"agent_id",
|
|
144
|
+
"token_budget",
|
|
145
|
+
"known_as_of",
|
|
146
|
+
"exclude_sessions"
|
|
147
|
+
);
|
|
148
|
+
function checkOptions(method, opts, known) {
|
|
149
|
+
const problem = unknownOption(method, opts, known);
|
|
150
|
+
if (problem) throw new KorelyError(problem);
|
|
151
|
+
}
|
|
152
|
+
var ACCOUNT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
153
|
+
function accountId(value) {
|
|
154
|
+
if (typeof value !== "string") return void 0;
|
|
155
|
+
const text2 = value.trim();
|
|
156
|
+
return ACCOUNT_ID.test(text2) ? text2 : void 0;
|
|
157
|
+
}
|
|
158
|
+
function coerceContent(content) {
|
|
159
|
+
if (typeof content === "string") return content;
|
|
160
|
+
if (Array.isArray(content)) {
|
|
161
|
+
const parts = [];
|
|
162
|
+
for (const m of content) {
|
|
163
|
+
if (m && typeof m === "object") {
|
|
164
|
+
const role = String(m.role ?? "").trim();
|
|
165
|
+
const raw = m.content;
|
|
166
|
+
const body = raw == null ? "" : String(raw).trim();
|
|
167
|
+
if (role && body) parts.push(`${role}: ${body}`);
|
|
168
|
+
else if (body) parts.push(body);
|
|
169
|
+
} else {
|
|
170
|
+
const s = String(m).trim();
|
|
171
|
+
if (s) parts.push(s);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return parts.join("\n");
|
|
175
|
+
}
|
|
176
|
+
return String(content);
|
|
177
|
+
}
|
|
178
|
+
function seg(value, what) {
|
|
179
|
+
if (value != null && typeof value !== "string" && !(typeof value === "number" && Number.isInteger(value))) {
|
|
180
|
+
throw new KorelyError(`${what} must be a string id, not ${Array.isArray(value) ? "an array" : `a ${typeof value}`}.`);
|
|
181
|
+
}
|
|
182
|
+
const s = value == null ? "" : String(value);
|
|
183
|
+
if (!s) throw new KorelyError(`${what} is empty.`);
|
|
184
|
+
return encodeURIComponent(s);
|
|
185
|
+
}
|
|
186
|
+
function moment(value, what) {
|
|
187
|
+
if (value == null) return void 0;
|
|
188
|
+
if (typeof value === "string") return value;
|
|
189
|
+
if (value instanceof Date) {
|
|
190
|
+
if (Number.isNaN(value.getTime())) throw new KorelyError(`${what} is an invalid Date.`);
|
|
191
|
+
return value.toISOString();
|
|
192
|
+
}
|
|
193
|
+
throw new KorelyError(`${what} must be an ISO 8601 string or a Date, not a ${typeof value}.`);
|
|
194
|
+
}
|
|
195
|
+
function auditFilters(opts) {
|
|
196
|
+
for (const name of ["user_id", "action"]) {
|
|
197
|
+
if (opts[name] === "") {
|
|
198
|
+
throw new KorelyError(
|
|
199
|
+
`${name} is empty: the server reads an empty filter as no filter. Leave it out to mean every ${name.split("_")[0]}.`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
user_id: opts.user_id,
|
|
205
|
+
action: opts.action,
|
|
206
|
+
since: moment(opts.since, "since"),
|
|
207
|
+
until: moment(opts.until, "until")
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function detailLine(detail) {
|
|
211
|
+
if (typeof detail === "string") return detail.trim() ? detail : void 0;
|
|
212
|
+
if (Array.isArray(detail) && detail.length) {
|
|
213
|
+
const parts = detail.slice(0, 3).map((e) => {
|
|
214
|
+
if (!e || typeof e !== "object") return String(e);
|
|
215
|
+
const loc = Array.isArray(e.loc) ? e.loc : [];
|
|
216
|
+
const where = loc.filter((x) => x !== "body").map(String).join(".");
|
|
217
|
+
const msg = String(e.msg ?? "invalid");
|
|
218
|
+
return where ? `${where}: ${msg}` : msg;
|
|
219
|
+
});
|
|
220
|
+
const more = detail.length - 3;
|
|
221
|
+
return parts.join("; ") + (more > 0 ? ` (and ${more} more)` : "");
|
|
222
|
+
}
|
|
223
|
+
return void 0;
|
|
224
|
+
}
|
|
225
|
+
function errorFields(status, body) {
|
|
226
|
+
const text2 = (v) => typeof v === "string" && v.trim() ? v : void 0;
|
|
227
|
+
const b = body && typeof body === "object" ? body : {};
|
|
228
|
+
const pair = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
|
|
229
|
+
const code = text2(b.code) ?? text2(pair.code);
|
|
230
|
+
const message = text2(b.message) ?? text2(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
|
|
231
|
+
return { code, message };
|
|
232
|
+
}
|
|
233
|
+
function quotaFields(body) {
|
|
234
|
+
const b = body && typeof body === "object" ? body : {};
|
|
235
|
+
const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
|
|
236
|
+
const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
237
|
+
const str = (v) => typeof v === "string" && v ? v : void 0;
|
|
238
|
+
return {
|
|
239
|
+
limit: num(b.limit ?? d.limit),
|
|
240
|
+
used: num(b.used ?? d.used),
|
|
241
|
+
resetsAt: str(b.resets_at ?? d.resets_at)
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function conflictFields(body) {
|
|
245
|
+
const b = body && typeof body === "object" ? body : {};
|
|
246
|
+
const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
|
|
247
|
+
const v = b.current_fact_id ?? d.current_fact_id;
|
|
248
|
+
return { currentFactId: typeof v === "string" && v ? v : void 0 };
|
|
249
|
+
}
|
|
250
|
+
function retryAfterSeconds(raw) {
|
|
251
|
+
if (raw == null) return void 0;
|
|
252
|
+
const n = Math.ceil(Number(raw));
|
|
253
|
+
return Number.isFinite(n) && n >= 0 ? n : void 0;
|
|
254
|
+
}
|
|
255
|
+
function fillPair(obj, current, deprecated) {
|
|
256
|
+
if (obj[current] == null && obj[deprecated] != null) obj[current] = obj[deprecated];
|
|
257
|
+
if (obj[deprecated] == null && obj[current] != null) obj[deprecated] = obj[current];
|
|
258
|
+
}
|
|
259
|
+
function iterableOver(page, key) {
|
|
260
|
+
const out = page;
|
|
261
|
+
Object.defineProperty(out, Symbol.iterator, {
|
|
262
|
+
value: () => (page[key] ?? [])[Symbol.iterator](),
|
|
263
|
+
enumerable: false
|
|
264
|
+
});
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
var OUR_HOSTS = ["korely.ai"];
|
|
268
|
+
function isOurs(baseUrl) {
|
|
269
|
+
let host = "";
|
|
270
|
+
try {
|
|
271
|
+
host = new URL(baseUrl).hostname.toLowerCase();
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
return OUR_HOSTS.some((h) => host === h || host.endsWith("." + h));
|
|
276
|
+
}
|
|
277
|
+
function refuseAMismatchedPair(apiKey, baseUrl) {
|
|
278
|
+
const ours = isOurs(baseUrl);
|
|
279
|
+
if (apiKey.startsWith("kor_self_") && ours) {
|
|
280
|
+
throw new KorelyError(
|
|
281
|
+
`This key was issued by an install you run yourself (kor_self_), and ${baseUrl} is the hosted Korely service. It would be refused there, but the memory would arrive first. Point baseUrl at your own server, or set KORELY_BASE_URL.`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
if (apiKey.startsWith("kor_live_") && !ours) {
|
|
285
|
+
throw new KorelyError(
|
|
286
|
+
`This key was issued by the hosted Korely service (kor_live_), and ${baseUrl} is not it. Sending it there hands a credential we issued to a machine that is not ours. Use a key minted by that install (kor_self_), or drop baseUrl to reach the hosted service.`
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
async function exchange(t, method, path, opts = {}) {
|
|
291
|
+
let url = t.baseUrl + path;
|
|
292
|
+
if (opts.params) {
|
|
293
|
+
const qs = new URLSearchParams();
|
|
294
|
+
for (const [k, v] of Object.entries(opts.params)) {
|
|
295
|
+
if (v !== void 0 && v !== null) qs.append(k, String(v));
|
|
296
|
+
}
|
|
297
|
+
const s = qs.toString();
|
|
298
|
+
if (s) url += "?" + s;
|
|
299
|
+
}
|
|
300
|
+
const headers = {
|
|
301
|
+
Accept: "application/json",
|
|
302
|
+
"X-Korely-Client": t.client || `korely-js/${VERSION}`
|
|
303
|
+
};
|
|
304
|
+
if (t.apiKey) headers.Authorization = `Bearer ${t.apiKey}`;
|
|
305
|
+
let body;
|
|
306
|
+
if (opts.body !== void 0) {
|
|
307
|
+
body = JSON.stringify(opts.body);
|
|
308
|
+
headers["Content-Type"] = "application/json";
|
|
309
|
+
}
|
|
310
|
+
const controller = new AbortController();
|
|
311
|
+
let timedOut = false;
|
|
312
|
+
const timer = setTimeout(() => {
|
|
313
|
+
timedOut = true;
|
|
314
|
+
controller.abort();
|
|
315
|
+
}, t.timeoutMs);
|
|
316
|
+
const failed = (e) => new KorelyError(
|
|
317
|
+
timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
|
|
318
|
+
);
|
|
319
|
+
let resp;
|
|
320
|
+
let text2;
|
|
321
|
+
try {
|
|
322
|
+
try {
|
|
323
|
+
resp = await t.fetchImpl(url, {
|
|
324
|
+
method,
|
|
325
|
+
headers,
|
|
326
|
+
body,
|
|
327
|
+
signal: controller.signal,
|
|
328
|
+
// Only a GET follows a redirect. `fetch` follows a POST answered 301,
|
|
329
|
+
// 302 or 303 as a GET with no body, and that GET's answer came back
|
|
330
|
+
// as the POST's; any other call takes the 3xx as its answer (Node
|
|
331
|
+
// gives it whole, a browser as an "opaqueredirect" of status 0).
|
|
332
|
+
redirect: method === "GET" ? "follow" : "manual"
|
|
333
|
+
});
|
|
334
|
+
} catch (e) {
|
|
335
|
+
throw failed(e);
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
text2 = await resp.text();
|
|
339
|
+
} catch (e) {
|
|
340
|
+
throw failed(e);
|
|
341
|
+
}
|
|
342
|
+
} finally {
|
|
343
|
+
clearTimeout(timer);
|
|
344
|
+
}
|
|
345
|
+
let parsed = {};
|
|
346
|
+
if (text2) {
|
|
347
|
+
try {
|
|
348
|
+
parsed = JSON.parse(text2);
|
|
349
|
+
} catch {
|
|
350
|
+
if (resp.ok) {
|
|
351
|
+
throw new KorelyError(
|
|
352
|
+
`The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text2.slice(0, 200))}`,
|
|
353
|
+
{ status: resp.status }
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
parsed = { message: text2 };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (!resp.ok) {
|
|
360
|
+
raiseFor(resp.status, parsed, resp.headers.get("retry-after"), redirectOf(resp, url), method);
|
|
361
|
+
}
|
|
362
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
363
|
+
}
|
|
364
|
+
function originOf(address, base) {
|
|
365
|
+
try {
|
|
366
|
+
return new URL(address, base).origin;
|
|
367
|
+
} catch {
|
|
368
|
+
return void 0;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function redirectOf(resp, url) {
|
|
372
|
+
const location = resp.headers.get("location");
|
|
373
|
+
if (resp.status >= 300 && resp.status < 400 && location) return originOf(location, url);
|
|
374
|
+
if (resp.redirected && resp.url) {
|
|
375
|
+
const at = originOf(resp.url);
|
|
376
|
+
if (at && at !== originOf(url)) return at;
|
|
377
|
+
}
|
|
378
|
+
return void 0;
|
|
379
|
+
}
|
|
380
|
+
function raiseFor(status, body, retryAfter, redirect, method) {
|
|
381
|
+
let { code, message: msg } = errorFields(status, body);
|
|
382
|
+
if (status === 401 && redirect) {
|
|
383
|
+
msg += ` The call was redirected to ${redirect}, and fetch does not send the key to another origin: if that is the server, use that address as baseUrl.`;
|
|
384
|
+
}
|
|
385
|
+
if (status >= 300 && status < 400 || status === 0) {
|
|
386
|
+
const answered = status ? `The server answered ${status} to a ${method ?? "call"}, a redirect` : `The server answered a ${method ?? "call"} with a redirect`;
|
|
387
|
+
const to = redirect ? ` to ${redirect}` : "";
|
|
388
|
+
msg = method === "GET" ? `${answered}${to} that fetch did not follow: that is not the answer to the call.` : `${answered}${to} this client does not follow: a call that is not a GET is never redirected, so that is not its answer, and nothing says it was done.`;
|
|
389
|
+
}
|
|
390
|
+
const opts = {
|
|
391
|
+
status,
|
|
392
|
+
code,
|
|
393
|
+
retryAfter: retryAfterSeconds(retryAfter ?? body?.retry_after ?? body?._retry_after)
|
|
394
|
+
};
|
|
395
|
+
if (status === 401) throw new AuthenticationError(msg, opts);
|
|
396
|
+
if (status === 403) throw new NamespaceForbiddenError(msg, opts);
|
|
397
|
+
if (status === 404) throw new NotFoundError(msg, opts);
|
|
398
|
+
if (status === 409) {
|
|
399
|
+
if (code === "stale_write") throw new StaleWriteError(msg, opts);
|
|
400
|
+
throw new ConflictError(msg, { ...opts, ...conflictFields(body) });
|
|
401
|
+
}
|
|
402
|
+
if (status === 429) {
|
|
403
|
+
const quota = { ...opts, ...quotaFields(body) };
|
|
404
|
+
if (code === "too_many_batches") throw new TooManyBatchesError(msg, quota);
|
|
405
|
+
throw new QuotaExceededError(msg, quota);
|
|
406
|
+
}
|
|
407
|
+
throw new APIError(msg, opts);
|
|
408
|
+
}
|
|
409
|
+
var nodeFiles;
|
|
410
|
+
function useNodeFiles(files) {
|
|
411
|
+
nodeFiles = files;
|
|
412
|
+
}
|
|
413
|
+
function savedConfig() {
|
|
414
|
+
try {
|
|
415
|
+
const proc = typeof process !== "undefined" ? process : void 0;
|
|
416
|
+
if (!proc?.versions?.node) return {};
|
|
417
|
+
const files = nodeFiles ?? lookedUp(proc);
|
|
418
|
+
if (!files) return {};
|
|
419
|
+
const home = proc.env?.KORELY_CONFIG_HOME || files.join(files.homedir(), ".korely");
|
|
420
|
+
const data = JSON.parse(files.readFileSync(files.join(home, "config.json"), "utf8"));
|
|
421
|
+
return data && typeof data === "object" ? data : {};
|
|
422
|
+
} catch {
|
|
423
|
+
return {};
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
function lookedUp(proc) {
|
|
427
|
+
const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof __require === "function" ? __require(id) : void 0;
|
|
428
|
+
const fs = builtin("node:fs");
|
|
429
|
+
const os = builtin("node:os");
|
|
430
|
+
const path = builtin("node:path");
|
|
431
|
+
if (!fs || !os || !path) return void 0;
|
|
432
|
+
return { readFileSync: fs.readFileSync, homedir: os.homedir, join: path.join };
|
|
433
|
+
}
|
|
434
|
+
function text(v) {
|
|
435
|
+
return typeof v === "string" && v ? v : void 0;
|
|
436
|
+
}
|
|
437
|
+
var Korely = class {
|
|
438
|
+
constructor(opts = {}) {
|
|
439
|
+
checkOptions("Korely", opts, CLIENT_KEYS);
|
|
440
|
+
const envKey = typeof process !== "undefined" ? process.env?.KORELY_API_KEY : void 0;
|
|
441
|
+
const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
|
|
442
|
+
const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
|
|
443
|
+
const key = opts.apiKey ?? envKey ?? text(saved.api_key);
|
|
444
|
+
if (!key) {
|
|
445
|
+
throw new KorelyError(
|
|
446
|
+
"No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
this.apiKey = key;
|
|
450
|
+
const envClient = typeof process !== "undefined" ? process.env?.KORELY_CLIENT : void 0;
|
|
451
|
+
this.client = (opts.client ?? envClient ?? "").trim() || void 0;
|
|
452
|
+
this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
|
|
453
|
+
refuseAMismatchedPair(this.apiKey, this.baseUrl);
|
|
454
|
+
this.timeoutMs = opts.timeoutMs ?? 3e4;
|
|
455
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
456
|
+
if (!f) {
|
|
457
|
+
throw new KorelyError(
|
|
458
|
+
"No fetch available. On Node < 18 pass a fetch implementation via { fetch }."
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
this.fetchImpl = f;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* POST /v1/agents/init, with no key: sign up for a free hobby key.
|
|
465
|
+
*
|
|
466
|
+
* The one call that runs without a key, because it is how one is obtained,
|
|
467
|
+
* so it is static: `await Korely.initAgent("my-app")`, then
|
|
468
|
+
* `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
|
|
469
|
+
* label of who signed up, kept for your reference. The answer carries the
|
|
470
|
+
* key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
|
|
471
|
+
* The account it creates has no login: the key is the account, and
|
|
472
|
+
* `deleteAccount({ confirm: "<the account's id>" })` closes it.
|
|
473
|
+
*
|
|
474
|
+
* Cloud only. The server is `baseUrl`, else KORELY_BASE_URL, else the
|
|
475
|
+
* region's. Refusals: 403 `signup_disabled` (NamespaceForbiddenError) when
|
|
476
|
+
* self-signup is closed; 429 `signup_rate_limited` (QuotaExceededError, with
|
|
477
|
+
* `retryAfter`) past the new accounts a network may open in a day. The
|
|
478
|
+
* Self-hosted has no such route and answers 404, or 405 where it serves its
|
|
479
|
+
* dashboard: its keys come from its own dashboard.
|
|
480
|
+
*/
|
|
481
|
+
static async initAgent(agentCaller, opts = {}) {
|
|
482
|
+
checkOptions("initAgent", opts, INIT_KEYS);
|
|
483
|
+
const where = opts.processingRegion;
|
|
484
|
+
if (where !== void 0 && where !== "eu" && where !== "global") {
|
|
485
|
+
throw new KorelyError(`processingRegion is "eu" or "global", not ${JSON.stringify(where)}.`);
|
|
486
|
+
}
|
|
487
|
+
if (agentCaller != null && typeof agentCaller !== "string") {
|
|
488
|
+
throw new KorelyError(
|
|
489
|
+
`agentCaller is a label, a string, not ${Array.isArray(agentCaller) ? "an array" : `a ${typeof agentCaller}`}: Korely.initAgent('my-app', { baseUrl }).`
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
|
|
493
|
+
const baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
|
|
494
|
+
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
495
|
+
if (!fetchImpl) {
|
|
496
|
+
throw new KorelyError(
|
|
497
|
+
"No fetch available. On Node < 18 pass a fetch implementation via { fetch }."
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
return exchange(
|
|
501
|
+
{ baseUrl, timeoutMs: opts.timeoutMs ?? 3e4, fetchImpl },
|
|
502
|
+
"POST",
|
|
503
|
+
"/v1/agents/init",
|
|
504
|
+
{
|
|
505
|
+
body: { agent_caller: agentCaller ?? void 0, processing_region: opts.processingRegion }
|
|
506
|
+
}
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
// ── transport ─────────────────────────────────────────────────────────────
|
|
510
|
+
request(method, path, opts = {}) {
|
|
511
|
+
return exchange(
|
|
512
|
+
{
|
|
513
|
+
baseUrl: this.baseUrl,
|
|
514
|
+
timeoutMs: this.timeoutMs,
|
|
515
|
+
fetchImpl: this.fetchImpl,
|
|
516
|
+
apiKey: this.apiKey,
|
|
517
|
+
client: this.client
|
|
518
|
+
},
|
|
519
|
+
method,
|
|
520
|
+
path,
|
|
521
|
+
opts
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
// ── the key and its account ───────────────────────────────────────────────
|
|
525
|
+
/**
|
|
526
|
+
* GET /v1/ping: does this key work, and what may it do? Both products answer
|
|
527
|
+
* it, with the same shape.
|
|
528
|
+
*
|
|
529
|
+
* The cheapest authenticated call there is: no scope, no rate limit, no
|
|
530
|
+
* quota, so it is how to check a key that was just minted or rotated without
|
|
531
|
+
* spending anything. `users()` was the usual stand-in, and it needs
|
|
532
|
+
* `memories:read` and counts as a query.
|
|
533
|
+
*/
|
|
534
|
+
async ping() {
|
|
535
|
+
return this.request("GET", "/v1/ping");
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* DELETE /v1/account?confirm=<the account's id>: delete the account of this
|
|
539
|
+
* key for good, with every key, project, memory, fact and webhook of it; the
|
|
540
|
+
* key stops working. Cloud only, for an account made by `Korely.initAgent()`
|
|
541
|
+
* or `korely init --agent`, which nobody signs in to: the key is the
|
|
542
|
+
* account, and this is how it is closed (GDPR Art. 17).
|
|
543
|
+
*
|
|
544
|
+
* `confirm` is the account's id, typed by whoever means it, as the
|
|
545
|
+
* dashboard has the email typed: `tenant_id` of GET /admin/whoami, which the
|
|
546
|
+
* error below gives. So a key that leaked, or a script pointed at the wrong
|
|
547
|
+
* key, is not enough with a flag (Korely 1.0.23 asks the same of the
|
|
548
|
+
* server's route). Nothing is deleted, and the DELETE is not sent, unless
|
|
549
|
+
* `confirm` is a UUID equal, spaces trimmed, to the `tenant_id` that GET
|
|
550
|
+
* /admin/whoami gives this key: a missing, `true`, `"true"` or wrong
|
|
551
|
+
* `confirm` rejects with a KorelyError whose `code` is
|
|
552
|
+
* `confirmation_required` (the server's code for the same refusal) and
|
|
553
|
+
* whose message names the id to type when the key may read it. A key that
|
|
554
|
+
* may not read GET /admin/whoami (403, a key without the `admin` scope)
|
|
555
|
+
* deletes nothing: with no id typed it rejects with that same
|
|
556
|
+
* `confirmation_required`, whose message says whoami could not be read;
|
|
557
|
+
* with the id typed, with the server's refusal of the whoami,
|
|
558
|
+
* NamespaceForbiddenError (an APIError, `status` 403, `code` `forbidden`).
|
|
559
|
+
*
|
|
560
|
+
* The account is deleted only on the server's answer that says so
|
|
561
|
+
* (`deleted: true`); any other answer, a redirect (never followed: the
|
|
562
|
+
* DELETE is not a GET) or a 2xx without it, rejects, and the account may
|
|
563
|
+
* still be there. A server older
|
|
564
|
+
* than 1.0.23 takes only `?confirm=true` and refuses the id (422): that
|
|
565
|
+
* rejects with an APIError whose `code` is `server_too_old`, nothing is
|
|
566
|
+
* deleted, and the client does not fall back to the flag. Upgrade the
|
|
567
|
+
* server, or use korely-memory 0.1.18.
|
|
568
|
+
*
|
|
569
|
+
* An account with a Korely login rejects with 409 `account_has_login`
|
|
570
|
+
* (ConflictError): a key that ended up in a log must not be able to delete
|
|
571
|
+
* it, so it is closed from the app (Settings, Account). The Self-hosted has
|
|
572
|
+
* no such route and answers 404 (NotFoundError), or 405 where it serves its
|
|
573
|
+
* dashboard. No audit event survives: the trail is part of what goes.
|
|
574
|
+
*/
|
|
575
|
+
async deleteAccount(opts = {}) {
|
|
576
|
+
checkOptions("deleteAccount", opts, ["confirm"]);
|
|
577
|
+
const typed = accountId(opts?.confirm);
|
|
578
|
+
if (typed === void 0) {
|
|
579
|
+
throw await this.notConfirmed(
|
|
580
|
+
"This deletes the account of this key for good, every key, project, memory and fact of it, and its id, typed, is the confirmation: a flag is not enough."
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
const account = await this.accountOfThisKey();
|
|
584
|
+
if (typed !== account) {
|
|
585
|
+
throw new KorelyError(
|
|
586
|
+
`The account of this key is ${account}, and the confirmation names ${typed}: nothing was deleted. To delete account ${account}, pass { confirm: "${account}" }.`,
|
|
587
|
+
{ code: "confirmation_required" }
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
let body;
|
|
591
|
+
try {
|
|
592
|
+
body = await this.request("DELETE", "/v1/account", { params: { confirm: account } });
|
|
593
|
+
} catch (e) {
|
|
594
|
+
if (e instanceof APIError && e.status === 422) {
|
|
595
|
+
throw new APIError(
|
|
596
|
+
"This server is older than Korely 1.0.23: it deletes an account with ?confirm=true, and this client confirms with the account's id and does not fall back to the flag. Nothing was deleted. Upgrade the server to 1.0.23 or later, or delete the account with korely-memory 0.1.18 (npm install korely-memory@0.1.18).",
|
|
597
|
+
{ status: 422, code: "server_too_old" }
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
throw e;
|
|
601
|
+
}
|
|
602
|
+
if (body?.deleted !== true) {
|
|
603
|
+
throw new KorelyError(
|
|
604
|
+
"DELETE /v1/account answered without `deleted: true`, the answer that says the account is gone: it is not counted as deleted, and it may still be there (GET /admin/whoami answers with this key while it is)."
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
return body;
|
|
608
|
+
}
|
|
609
|
+
/** The id of this key's account: `tenant_id` of GET /admin/whoami, checked
|
|
610
|
+
* as an account id (`accountId`). The errors of the call reject as they
|
|
611
|
+
* come. */
|
|
612
|
+
async accountOfThisKey() {
|
|
613
|
+
const who = await this.request("GET", "/admin/whoami");
|
|
614
|
+
const account = accountId(who?.tenant_id);
|
|
615
|
+
if (account === void 0) {
|
|
616
|
+
throw new KorelyError(
|
|
617
|
+
"GET /admin/whoami gave no account id (a UUID) for this key: nothing was deleted.",
|
|
618
|
+
{ code: "confirmation_required" }
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
return account;
|
|
622
|
+
}
|
|
623
|
+
/** The refusal of a deletion not confirmed, naming the id to type when this
|
|
624
|
+
* key may read it. */
|
|
625
|
+
async notConfirmed(why) {
|
|
626
|
+
let account;
|
|
627
|
+
try {
|
|
628
|
+
account = await this.accountOfThisKey();
|
|
629
|
+
} catch (e) {
|
|
630
|
+
return new KorelyError(
|
|
631
|
+
`${why} Nothing was deleted. The id is tenant_id in GET /admin/whoami, which this key could not read: ${e?.message ?? String(e)}`,
|
|
632
|
+
{ code: "confirmation_required" }
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
return new KorelyError(
|
|
636
|
+
`${why} Nothing was deleted. To delete account ${account}, pass { confirm: "${account}" }.`,
|
|
637
|
+
{ code: "confirmation_required" }
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
// ── audit ─────────────────────────────────────────────────────────────────
|
|
641
|
+
/**
|
|
642
|
+
* GET /v1/audit: what this key's project did, and what its agents read,
|
|
643
|
+
* newest first (`ts` descending, then the event's id, so paging with
|
|
644
|
+
* `offset` is stable). Both products; the key needs `memories:read`.
|
|
645
|
+
*
|
|
646
|
+
* `user_id` keeps the events that touched one end user, the shape of an
|
|
647
|
+
* access or erasure request; `action` one kind ("read", "write", "erase"...;
|
|
648
|
+
* an unknown one answers an empty page); `since` and `until` bound `ts`,
|
|
649
|
+
* both inclusive, as ISO 8601 text or a Date. `limit` is 1 to 1000. To read
|
|
650
|
+
* everything, use `iterAudit()`. The page is iterable.
|
|
651
|
+
*
|
|
652
|
+
* Reading the trail counts against no quota and is not itself written to
|
|
653
|
+
* it; it does count against the rate limit. Scoped to the key's account and
|
|
654
|
+
* project, like every read.
|
|
655
|
+
*/
|
|
656
|
+
async audit(opts = {}) {
|
|
657
|
+
checkOptions("audit", opts, AUDIT_KEYS);
|
|
658
|
+
const page = await this.request(
|
|
659
|
+
"GET",
|
|
660
|
+
"/v1/audit",
|
|
661
|
+
{
|
|
662
|
+
params: { ...auditFilters(opts), limit: opts.limit ?? 100, offset: opts.offset ?? 0 }
|
|
663
|
+
}
|
|
664
|
+
);
|
|
665
|
+
return iterableOver(page, "events");
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Every event `audit()` would page through, for an export:
|
|
669
|
+
* `for await (const e of korely.iterAudit({ user_id }))`. The same filters,
|
|
670
|
+
* `page_size` events per request (1000, the most the API gives),
|
|
671
|
+
* `offset += page.length` until `total`.
|
|
672
|
+
*
|
|
673
|
+
* Without `until` the walk pins it to the newest event of its first page.
|
|
674
|
+
* The trail grows while it is read, newest first, and every new event pushed
|
|
675
|
+
* the rest one place down: the next page began with events already returned.
|
|
676
|
+
* The pin makes the export the trail as it stood when it started.
|
|
677
|
+
*
|
|
678
|
+
* A rate limit rejects mid-way, as any call does, and the SDK does not
|
|
679
|
+
* retry. To resume, call again with the same `until` (pin it yourself:
|
|
680
|
+
* `until: new Date()`) and `offset` the number of events already read.
|
|
681
|
+
*/
|
|
682
|
+
async *iterAudit(opts = {}) {
|
|
683
|
+
checkOptions("iterAudit", opts, ITER_AUDIT_KEYS);
|
|
684
|
+
const filters = auditFilters(opts);
|
|
685
|
+
let offset = opts.offset ?? 0;
|
|
686
|
+
let pin = filters.until === void 0 && offset === 0;
|
|
687
|
+
for (; ; ) {
|
|
688
|
+
const page = await this.audit({
|
|
689
|
+
user_id: opts.user_id,
|
|
690
|
+
action: opts.action,
|
|
691
|
+
since: filters.since,
|
|
692
|
+
until: filters.until,
|
|
693
|
+
limit: opts.page_size ?? 1e3,
|
|
694
|
+
offset
|
|
695
|
+
});
|
|
696
|
+
if (!page.events.length) return;
|
|
697
|
+
yield* page.events;
|
|
698
|
+
if (pin && page.events[0].ts) {
|
|
699
|
+
filters.until = page.events[0].ts;
|
|
700
|
+
pin = false;
|
|
701
|
+
}
|
|
702
|
+
offset += page.events.length;
|
|
703
|
+
if (offset >= page.total) return;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
// ── memories ────────────────────────────────────────────────────────────
|
|
707
|
+
/**
|
|
708
|
+
* POST /v1/memories: store a memory; resolves to it with extracted facts.
|
|
709
|
+
* `content` is a string, or a list of chat messages (role/content), joined
|
|
710
|
+
* into one block before sending. Pass `timestamp` (ISO date/datetime) for
|
|
711
|
+
* backfill: facts extracted inherit it as `valid_from`.
|
|
712
|
+
*
|
|
713
|
+
* Say whose memory it is with `user_id` or `agent_id` (or both): Korely
|
|
714
|
+
* 1.0.19 and later refuse a write with neither, a 422 APIError with
|
|
715
|
+
* `code === "identity_required"`. This client sends the ids each call names
|
|
716
|
+
* and no others.
|
|
717
|
+
*/
|
|
718
|
+
async add(content, opts = {}) {
|
|
719
|
+
checkOptions("add", opts, ADD_KEYS);
|
|
720
|
+
const text2 = coerceContent(content);
|
|
721
|
+
if (!text2.trim()) {
|
|
722
|
+
throw new KorelyError(
|
|
723
|
+
"content is empty: pass a non-blank string or messages with content."
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
return this.request("POST", "/v1/memories", {
|
|
727
|
+
body: {
|
|
728
|
+
content: text2,
|
|
729
|
+
agent_id: opts.agent_id,
|
|
730
|
+
user_id: opts.user_id,
|
|
731
|
+
run_id: opts.run_id,
|
|
732
|
+
metadata: opts.metadata,
|
|
733
|
+
timestamp: opts.timestamp,
|
|
734
|
+
kind: opts.kind
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* POST /v1/memories/search: semantic search over raw memories, ranked by
|
|
740
|
+
* score (vector similarity to the query). `run_id` scopes to one session,
|
|
741
|
+
* `metadata` filters on what you stored at write time. `limit` defaults to
|
|
742
|
+
* the server default (15), max 50.
|
|
743
|
+
*/
|
|
744
|
+
async search(query, opts = {}) {
|
|
745
|
+
checkOptions("search", opts, SEARCH_KEYS);
|
|
746
|
+
const body = await this.request("POST", "/v1/memories/search", {
|
|
747
|
+
body: {
|
|
748
|
+
query,
|
|
749
|
+
user_id: opts.user_id,
|
|
750
|
+
agent_id: opts.agent_id,
|
|
751
|
+
run_id: opts.run_id,
|
|
752
|
+
metadata: opts.metadata,
|
|
753
|
+
limit: opts.limit,
|
|
754
|
+
min_score: opts.min_score,
|
|
755
|
+
// Sent only when true: an older server does not know the field.
|
|
756
|
+
exclude_sessions: opts.exclude_sessions ? true : void 0
|
|
757
|
+
}
|
|
758
|
+
});
|
|
759
|
+
return body.results ?? [];
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* GET /v1/memories: list a scope, newest first. The page is iterable.
|
|
763
|
+
* `limit` goes up to 200 (the server capped it at 100 before 2026-09-28);
|
|
764
|
+
* `total` and `offset` walk the rest.
|
|
765
|
+
*/
|
|
766
|
+
async getAll(opts = {}) {
|
|
767
|
+
checkOptions("getAll", opts, LIST_KEYS);
|
|
768
|
+
const page = await this.request(
|
|
769
|
+
"GET",
|
|
770
|
+
"/v1/memories",
|
|
771
|
+
{
|
|
772
|
+
params: {
|
|
773
|
+
user_id: opts.user_id,
|
|
774
|
+
agent_id: opts.agent_id,
|
|
775
|
+
run_id: opts.run_id,
|
|
776
|
+
limit: opts.limit ?? 50,
|
|
777
|
+
offset: opts.offset ?? 0,
|
|
778
|
+
exclude_sessions: opts.exclude_sessions ? "true" : void 0
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
);
|
|
782
|
+
return iterableOver(page, "memories");
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* POST /v1/users/:user_id/names: declare that this end user is also called
|
|
786
|
+
* `name` (`declareName("Maria Rossi", { user_id: "maria" })`), Korely Agent
|
|
787
|
+
* 0.1.42. The store never merges two names of a person by itself, since two
|
|
788
|
+
* people can share one; after this the facts about `name` in the end user's
|
|
789
|
+
* memory read as the end user's, those already written included. In the
|
|
790
|
+
* key's project. Declaring the same name again answers the same; a name
|
|
791
|
+
* already declared for somebody else in that memory rejects with a
|
|
792
|
+
* ConflictError. Call it once per name the person is called by.
|
|
793
|
+
*/
|
|
794
|
+
async declareName(name, opts) {
|
|
795
|
+
checkOptions("declareName", opts, NAME_KEYS);
|
|
796
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
797
|
+
throw new KorelyError("declareName needs a name.");
|
|
798
|
+
}
|
|
799
|
+
return this.request("POST", `/v1/users/${seg(opts.user_id, "user_id")}/names`, {
|
|
800
|
+
body: { name, agent_id: opts.agent_id }
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
/** GET /v1/memories/:id: full content, metadata, extracted facts. */
|
|
804
|
+
async get(memoryId) {
|
|
805
|
+
return this.request("GET", `/v1/memories/${seg(memoryId, "memoryId")}`);
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* PATCH /v1/memories/:id: re-runs extraction. Pass `expected_updated_at`
|
|
809
|
+
* for optimistic concurrency (throws StaleWriteError instead of clobbering).
|
|
810
|
+
*/
|
|
811
|
+
async update(memoryId, opts) {
|
|
812
|
+
checkOptions("update", opts, UPDATE_KEYS);
|
|
813
|
+
return this.request("PATCH", `/v1/memories/${seg(memoryId, "memoryId")}`, {
|
|
814
|
+
body: {
|
|
815
|
+
content: opts.content,
|
|
816
|
+
expected_updated_at: opts.expected_updated_at
|
|
817
|
+
}
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* DELETE /v1/memories/:id: forget one memory. It drops out of every default
|
|
822
|
+
* read, and the facts only it asserted are invalidated (kept as history,
|
|
823
|
+
* audited). The facts its facts had closed are true again: the receipt
|
|
824
|
+
* counts them in `facts_reopened`. For erasure use `deleteAll`.
|
|
825
|
+
*/
|
|
826
|
+
async delete(memoryId) {
|
|
827
|
+
return this.request("DELETE", `/v1/memories/${seg(memoryId, "memoryId")}`);
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* DELETE /v1/users/:user_id/memories: ERASE every memory and fact of one end
|
|
831
|
+
* user (GDPR Art. 17). Physical deletion, not a flag: nothing is readable
|
|
832
|
+
* afterwards. The audit row (counts, never content) survives.
|
|
833
|
+
*
|
|
834
|
+
* The receipt counts the rows in `memories_deleted` and `facts_deleted`.
|
|
835
|
+
* `memories_forgotten` and `facts_invalidated` are deprecated aliases with
|
|
836
|
+
* the same numbers; whichever pair the server sends fills both.
|
|
837
|
+
*/
|
|
838
|
+
async deleteAll(opts) {
|
|
839
|
+
checkOptions("deleteAll", opts, ["user_id"]);
|
|
840
|
+
const r = await this.request(
|
|
841
|
+
"DELETE",
|
|
842
|
+
`/v1/users/${seg(opts.user_id, "user_id")}/memories`
|
|
843
|
+
);
|
|
844
|
+
const fields = r;
|
|
845
|
+
fillPair(fields, "memories_deleted", "memories_forgotten");
|
|
846
|
+
fillPair(fields, "facts_deleted", "facts_invalidated");
|
|
847
|
+
return r;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* GET /v1/memories/:id/history: the lifecycle timeline of a memory,
|
|
851
|
+
* created / updated / deleted, plus every typed fact it produced.
|
|
852
|
+
*/
|
|
853
|
+
async history(memoryId) {
|
|
854
|
+
return this.request("GET", `/v1/memories/${seg(memoryId, "memoryId")}/history`);
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* GET /v1/users: the end users you've stored data for (distinct user_id
|
|
858
|
+
* namespaces), each with active memory + fact counts and last-active time.
|
|
859
|
+
*/
|
|
860
|
+
async users(opts = {}) {
|
|
861
|
+
checkOptions("users", opts, USERS_KEYS);
|
|
862
|
+
const page = await this.request(
|
|
863
|
+
"GET",
|
|
864
|
+
"/v1/users",
|
|
865
|
+
{
|
|
866
|
+
params: {
|
|
867
|
+
agent_id: opts.agent_id,
|
|
868
|
+
limit: opts.limit ?? 50,
|
|
869
|
+
offset: opts.offset ?? 0
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
);
|
|
873
|
+
return iterableOver(page, "users");
|
|
874
|
+
}
|
|
875
|
+
// ── agents ────────────────────────────────────────────────────────────────
|
|
876
|
+
/**
|
|
877
|
+
* GET /v1/agents: the agent namespaces written under in this key's project
|
|
878
|
+
* (the distinct non-null agent_id values), each with active memory + fact
|
|
879
|
+
* counts and last-active time. The antidote to the agent-cap trap: when a
|
|
880
|
+
* write is rejected with `agent_cap_exceeded`, call this to see which
|
|
881
|
+
* namespaces already exist and reuse one instead of minting a new id.
|
|
882
|
+
*
|
|
883
|
+
* `total` counts this project's namespaces (exactly the ones this key can
|
|
884
|
+
* delete); `used` counts the cap slots taken across the whole account, by
|
|
885
|
+
* name, which is what the 403 compares with `cap`. `used` is above `total`
|
|
886
|
+
* when other projects use names this one does not. A self-hosted install
|
|
887
|
+
* sets no cap and answers `cap: 0`.
|
|
888
|
+
*/
|
|
889
|
+
async listAgents(opts = {}) {
|
|
890
|
+
checkOptions("listAgents", opts, AGENTS_KEYS);
|
|
891
|
+
const page = await this.request("GET", "/v1/agents", {
|
|
892
|
+
params: {
|
|
893
|
+
limit: opts.limit ?? 50,
|
|
894
|
+
offset: opts.offset ?? 0
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
return iterableOver(page, "agents");
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* DELETE /v1/agents/:agent_id: hard-delete an agent namespace, purging every
|
|
901
|
+
* memory + fact written under this agent_id in this key's project
|
|
902
|
+
* (soft-forgetting its data does NOT free its cap slot; this does). Resolves
|
|
903
|
+
* to the purge counts and an audit id. Its `slot_freed` is always
|
|
904
|
+
* undefined: no Korely server sends it, and none ever has. To see whether a
|
|
905
|
+
* cap slot is free, read `cap` and `used` from `listAgents()`.
|
|
906
|
+
*
|
|
907
|
+
* The namespace must be one `listAgents()` shows for this key: anything else
|
|
908
|
+
* rejects with NotFoundError, including a name only another project of the
|
|
909
|
+
* account uses (the server answered 200 with zero counts for it before
|
|
910
|
+
* 2026-09-28, and freed nothing). The cap counts a name across the account,
|
|
911
|
+
* so while another project still uses the same agent_id its rows stay and
|
|
912
|
+
* the slot stays taken.
|
|
913
|
+
*/
|
|
914
|
+
async deleteAgent(agentId) {
|
|
915
|
+
return this.request("DELETE", `/v1/agents/${seg(agentId, "agentId")}`);
|
|
916
|
+
}
|
|
917
|
+
// ── facts ─────────────────────────────────────────────────────────────────
|
|
918
|
+
/**
|
|
919
|
+
* GET /v1/facts: typed (subject, predicate, object) triples with bi-temporal
|
|
920
|
+
* validity. Pass `as_of` (ISO date) for a point-in-time query, and
|
|
921
|
+
* `known_as_of` (ISO date) for what the store knew on that date (Korely
|
|
922
|
+
* Agent 0.1.26; older servers ignore it). Resolves to an array that also
|
|
923
|
+
* carries `total`, the matches across all pages.
|
|
924
|
+
*/
|
|
925
|
+
async getFacts(opts = {}) {
|
|
926
|
+
checkOptions("getFacts", opts, FACTS_KEYS);
|
|
927
|
+
const params = {
|
|
928
|
+
subject: opts.subject,
|
|
929
|
+
entity: opts.entity,
|
|
930
|
+
predicate: opts.predicate,
|
|
931
|
+
predicate_family: opts.predicate_family,
|
|
932
|
+
as_of: opts.as_of,
|
|
933
|
+
known_as_of: opts.known_as_of,
|
|
934
|
+
user_id: opts.user_id,
|
|
935
|
+
agent_id: opts.agent_id,
|
|
936
|
+
limit: opts.limit ?? 50,
|
|
937
|
+
offset: opts.offset ?? 0
|
|
938
|
+
};
|
|
939
|
+
if (opts.include_invalidated) params.include_invalidated = "true";
|
|
940
|
+
if (opts.exclude_sessions) params.exclude_sessions = "true";
|
|
941
|
+
const body = await this.request("GET", "/v1/facts", { params });
|
|
942
|
+
const facts = [...body.facts ?? []];
|
|
943
|
+
Object.defineProperty(facts, "total", {
|
|
944
|
+
value: typeof body.total === "number" ? body.total : facts.length,
|
|
945
|
+
enumerable: false
|
|
946
|
+
});
|
|
947
|
+
return facts;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* POST /v1/facts: write a typed (subject, predicate, object) triple directly,
|
|
951
|
+
* skipping extraction. The server runs the contradiction check; the fact is
|
|
952
|
+
* bi-temporal (pass `valid_from` for a historical fact, `tense: "past"` for
|
|
953
|
+
* one that is over). Resolves to the written Fact, with `invalidated`
|
|
954
|
+
* listing any fact ids it superseded. `user_id` or `agent_id` says whose
|
|
955
|
+
* fact it is, as on `add()` (Korely 1.0.19 and later refuse neither).
|
|
956
|
+
*/
|
|
957
|
+
async addFactTriple(subject, predicate, object, opts = {}) {
|
|
958
|
+
checkOptions("addFactTriple", opts, TRIPLE_KEYS);
|
|
959
|
+
const fact = await this.request("POST", "/v1/facts", {
|
|
960
|
+
body: {
|
|
961
|
+
subject,
|
|
962
|
+
predicate,
|
|
963
|
+
object,
|
|
964
|
+
user_id: opts.user_id,
|
|
965
|
+
agent_id: opts.agent_id,
|
|
966
|
+
run_id: opts.run_id,
|
|
967
|
+
subject_type: opts.subject_type ?? "unknown",
|
|
968
|
+
object_is_literal: opts.object_is_literal ?? false,
|
|
969
|
+
confidence: opts.confidence ?? 0.9,
|
|
970
|
+
valid_from: opts.valid_from,
|
|
971
|
+
tense: opts.tense
|
|
972
|
+
}
|
|
973
|
+
});
|
|
974
|
+
return {
|
|
975
|
+
...fact,
|
|
976
|
+
user_id: fact.user_id !== void 0 ? fact.user_id : opts.user_id,
|
|
977
|
+
agent_id: fact.agent_id !== void 0 ? fact.agent_id : opts.agent_id
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* POST /v1/facts/:id/forget: close a fact; it stops being current and stays
|
|
982
|
+
* in history.
|
|
983
|
+
*
|
|
984
|
+
* `at` is the date it STOPPED being true, not the date you noticed. Reading
|
|
985
|
+
* `as_of` a date before it still returns the fact, which is the reason
|
|
986
|
+
* history is kept rather than rows deleted.
|
|
987
|
+
*
|
|
988
|
+
* Idempotent: closing an already-closed fact changes nothing and comes back
|
|
989
|
+
* with `status === "already_forgotten"`.
|
|
990
|
+
*
|
|
991
|
+
* This is the half that makes a no-model write path possible: an agent that
|
|
992
|
+
* knows a fact is finished says so, and nothing has to infer it.
|
|
993
|
+
*/
|
|
994
|
+
async forgetFact(factId, opts = {}) {
|
|
995
|
+
checkOptions("forgetFact", opts, ["at"]);
|
|
996
|
+
return this.request("POST", `/v1/facts/${seg(factId, "factId")}/forget`, {
|
|
997
|
+
body: { at: opts.at }
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* PATCH /v1/facts/:id: supersede a fact with a corrected one.
|
|
1002
|
+
*
|
|
1003
|
+
* Not an edit: the old row keeps its dates and gains a pointer to the new
|
|
1004
|
+
* one, so `as_of` before the correction still returns what you believed then.
|
|
1005
|
+
* At least one of the three fields is required.
|
|
1006
|
+
*
|
|
1007
|
+
* Resolves to the new Fact in the write shape. Its `invalidated` lists every
|
|
1008
|
+
* fact the correction superseded: the corrected one first, then any other
|
|
1009
|
+
* that the contradiction check on the new fact closed. It is not always one
|
|
1010
|
+
* id. A correction that names the fact as it already stands (same subject,
|
|
1011
|
+
* predicate and object, still open) supersedes nothing: the server
|
|
1012
|
+
* reconfirms the fact and returns it, same `id`, with `invalidated: []`.
|
|
1013
|
+
*/
|
|
1014
|
+
async correctFact(factId, changes) {
|
|
1015
|
+
return this.request("PATCH", `/v1/facts/${seg(factId, "factId")}`, {
|
|
1016
|
+
body: changes
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* GET /v1/profile: the assembled profile of one end user, the active typed
|
|
1021
|
+
* facts known about them, the end user's own facts first, grouped by family.
|
|
1022
|
+
* Pass `as_of` (ISO date) for the point-in-time profile, `known_as_of` for
|
|
1023
|
+
* the profile as the store knew it then.
|
|
1024
|
+
*/
|
|
1025
|
+
async getProfile(opts) {
|
|
1026
|
+
checkOptions("getProfile", opts, PROFILE_KEYS);
|
|
1027
|
+
return this.request("GET", "/v1/profile", {
|
|
1028
|
+
params: {
|
|
1029
|
+
user_id: opts.user_id,
|
|
1030
|
+
agent_id: opts.agent_id,
|
|
1031
|
+
as_of: opts.as_of,
|
|
1032
|
+
known_as_of: opts.known_as_of,
|
|
1033
|
+
exclude_sessions: opts.exclude_sessions ? "true" : void 0
|
|
1034
|
+
}
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
// ── context ─────────────────────────────────────────────────────────────
|
|
1038
|
+
/**
|
|
1039
|
+
* GET /v1/context: one call that assembles a prompt-ready context block
|
|
1040
|
+
* (profile + relevant facts + memories) within a token budget. With
|
|
1041
|
+
* `known_as_of` (ISO date), the block as the store could have built it then.
|
|
1042
|
+
*/
|
|
1043
|
+
async getContext(opts, extra = {}) {
|
|
1044
|
+
if (typeof opts === "string") checkOptions("getContext", extra, CONTEXT_EXTRA_KEYS);
|
|
1045
|
+
else checkOptions("getContext", opts, CONTEXT_KEYS);
|
|
1046
|
+
const o = typeof opts === "string" ? { ...extra, query: opts } : opts;
|
|
1047
|
+
if (!o || typeof o.query !== "string" || !o.query.trim()) {
|
|
1048
|
+
throw new KorelyError("getContext needs a query.");
|
|
1049
|
+
}
|
|
1050
|
+
return this.request("GET", "/v1/context", {
|
|
1051
|
+
params: {
|
|
1052
|
+
query: o.query,
|
|
1053
|
+
user_id: o.user_id,
|
|
1054
|
+
agent_id: o.agent_id,
|
|
1055
|
+
token_budget: o.token_budget ?? 800,
|
|
1056
|
+
known_as_of: o.known_as_of,
|
|
1057
|
+
exclude_sessions: o.exclude_sessions ? "true" : void 0
|
|
1058
|
+
}
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
// ── processing state ───────────────────────────────────────────────────────
|
|
1062
|
+
/**
|
|
1063
|
+
* GET /v1/events: which writes have finished being processed.
|
|
1064
|
+
*
|
|
1065
|
+
* `add()` resolves as soon as the memory is stored; fact extraction runs
|
|
1066
|
+
* behind it. Each event carries a memory's `status` ("processing", "ready"
|
|
1067
|
+
* or "error"), newest first. `status` filters before `limit` (up to 200) is
|
|
1068
|
+
* applied, so `{ status: "error" }` returns the latest errors however many
|
|
1069
|
+
* ready writes came after them. `processing` counts every write of this
|
|
1070
|
+
* key's project still in flight (of `user_id`, when given), whatever
|
|
1071
|
+
* `status` and `limit` say. No webhook fires when extraction finishes, so
|
|
1072
|
+
* this is how to know.
|
|
1073
|
+
*/
|
|
1074
|
+
async events(opts = {}) {
|
|
1075
|
+
checkOptions("events", opts, EVENTS_KEYS);
|
|
1076
|
+
return this.request("GET", "/v1/events", {
|
|
1077
|
+
params: {
|
|
1078
|
+
user_id: opts.user_id,
|
|
1079
|
+
status: opts.status,
|
|
1080
|
+
limit: opts.limit ?? 50
|
|
1081
|
+
}
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
// ── batch ─────────────────────────────────────────────────────────────────
|
|
1085
|
+
/**
|
|
1086
|
+
* POST /v1/batch: bulk import, up to 500 memory objects, processed
|
|
1087
|
+
* asynchronously. Each object is the body of one `add()` (see
|
|
1088
|
+
* `BatchMemory`): `content` and optionally `user_id`, `agent_id`, `run_id`,
|
|
1089
|
+
* `metadata` and `timestamp`. On Korely 1.0.19 and later each object needs
|
|
1090
|
+
* `user_id` or `agent_id`: one with neither refuses the whole batch before
|
|
1091
|
+
* anything is queued, a 422 (`code === "identity_required"`) whose message
|
|
1092
|
+
* names it, `memories[3].user_id or memories[3].agent_id is required`.
|
|
1093
|
+
*
|
|
1094
|
+
* `timestamp` means what it means on `add()`: when the events happened.
|
|
1095
|
+
* The facts extracted from the item inherit it as `valid_from`, so a
|
|
1096
|
+
* migration keeps its real dates; without it an item is dated when it is
|
|
1097
|
+
* imported. A value that is not an ISO 8601 date or datetime refuses the
|
|
1098
|
+
* whole batch before anything is queued: a 422 (APIError,
|
|
1099
|
+
* `code === "invalid_request"`) whose message names the item, e.g.
|
|
1100
|
+
* `memories[3].timestamp`. Any key not listed above is refused the same
|
|
1101
|
+
* way. Servers older than 2026-09-28 refuse `timestamp` itself.
|
|
1102
|
+
*
|
|
1103
|
+
* On the Cloud a batch is also refused, before anything is stored, with a
|
|
1104
|
+
* 429: `quota_exceeded` (QuotaExceededError) when its memories do not fit in
|
|
1105
|
+
* what is left of the month, batches already queued included, and
|
|
1106
|
+
* `too_many_batches` (TooManyBatchesError) while three batches are still
|
|
1107
|
+
* being imported. The Self-hosted meters nothing and refuses neither.
|
|
1108
|
+
*/
|
|
1109
|
+
async batch(memories) {
|
|
1110
|
+
return this.request("POST", "/v1/batch", { body: { memories } });
|
|
1111
|
+
}
|
|
1112
|
+
/** GET /v1/batch/:id: poll an import job. */
|
|
1113
|
+
async batchStatus(jobId) {
|
|
1114
|
+
return this.request("GET", `/v1/batch/${seg(jobId, "jobId")}`);
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
|
|
1118
|
+
export {
|
|
1119
|
+
KorelyError,
|
|
1120
|
+
APIError,
|
|
1121
|
+
AuthenticationError,
|
|
1122
|
+
NamespaceForbiddenError,
|
|
1123
|
+
NotFoundError,
|
|
1124
|
+
ConflictError,
|
|
1125
|
+
StaleWriteError,
|
|
1126
|
+
QuotaExceededError,
|
|
1127
|
+
TooManyBatchesError,
|
|
1128
|
+
VERSION,
|
|
1129
|
+
useNodeFiles,
|
|
1130
|
+
Korely
|
|
1131
|
+
};
|