korely-memory 0.1.18 → 0.2.1

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