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