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