korely-memory 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -22,12 +22,14 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  APIError: () => APIError,
24
24
  AuthenticationError: () => AuthenticationError,
25
+ ConflictError: () => ConflictError,
25
26
  Korely: () => Korely,
26
27
  KorelyError: () => KorelyError,
27
28
  NamespaceForbiddenError: () => NamespaceForbiddenError,
28
29
  NotFoundError: () => NotFoundError,
29
30
  QuotaExceededError: () => QuotaExceededError,
30
31
  StaleWriteError: () => StaleWriteError,
32
+ TooManyBatchesError: () => TooManyBatchesError,
31
33
  VERSION: () => VERSION
32
34
  });
33
35
  module.exports = __toCommonJS(src_exports);
@@ -46,6 +48,7 @@ var APIError = class extends KorelyError {
46
48
  constructor(message = "", opts = {}) {
47
49
  super(message, opts);
48
50
  this.name = "APIError";
51
+ this.retryAfter = opts.retryAfter;
49
52
  Object.setPrototypeOf(this, new.target.prototype);
50
53
  }
51
54
  };
@@ -70,25 +73,97 @@ var NotFoundError = class _NotFoundError extends APIError {
70
73
  Object.setPrototypeOf(this, _NotFoundError.prototype);
71
74
  }
72
75
  };
73
- var StaleWriteError = class _StaleWriteError extends APIError {
76
+ var ConflictError = class extends APIError {
77
+ constructor(message = "", opts = {}) {
78
+ super(message, opts);
79
+ this.name = "ConflictError";
80
+ Object.setPrototypeOf(this, new.target.prototype);
81
+ }
82
+ };
83
+ var StaleWriteError = class _StaleWriteError extends ConflictError {
74
84
  constructor(message = "", opts = {}) {
75
85
  super(message, opts);
76
86
  this.name = "StaleWriteError";
77
87
  Object.setPrototypeOf(this, _StaleWriteError.prototype);
78
88
  }
79
89
  };
80
- var QuotaExceededError = class _QuotaExceededError extends APIError {
90
+ var QuotaExceededError = class extends APIError {
81
91
  constructor(message = "", opts = {}) {
82
92
  super(message, opts);
83
93
  this.name = "QuotaExceededError";
84
- this.retryAfter = opts.retryAfter;
85
- Object.setPrototypeOf(this, _QuotaExceededError.prototype);
94
+ Object.setPrototypeOf(this, new.target.prototype);
95
+ }
96
+ };
97
+ var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError {
98
+ constructor(message = "", opts = {}) {
99
+ super(message, opts);
100
+ this.name = "TooManyBatchesError";
101
+ Object.setPrototypeOf(this, _TooManyBatchesError.prototype);
86
102
  }
87
103
  };
88
104
 
105
+ // src/options.ts
106
+ function keysOf() {
107
+ return (...keys) => keys;
108
+ }
109
+ function unknownOption(method, opts, known) {
110
+ if (opts === void 0 || opts === null) return void 0;
111
+ if (typeof opts !== "object" || Array.isArray(opts)) {
112
+ return `${method}: the options must be an object, got ${Array.isArray(opts) ? "an array" : typeof opts}.`;
113
+ }
114
+ for (const key of Object.keys(opts)) {
115
+ if (known.includes(key)) continue;
116
+ const snake = key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
117
+ const camel = key.replace(/_([a-z])/g, (_m, c) => c.toUpperCase());
118
+ const meant = known.includes(snake) ? snake : known.includes(camel) ? camel : void 0;
119
+ return `${method}: unknown option ${key}.` + (meant ? ` Did you mean ${meant}?` : "") + ` It takes: ${known.join(", ")}.`;
120
+ }
121
+ return void 0;
122
+ }
123
+
89
124
  // src/client.ts
90
- var VERSION = "0.1.9";
125
+ var VERSION = "0.1.11";
91
126
  var REGIONS = { eu: "https://api.korely.ai" };
127
+ var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch");
128
+ var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
129
+ var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp");
130
+ var SEARCH_KEYS = keysOf()("user_id", "agent_id", "run_id", "metadata", "limit");
131
+ var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset");
132
+ var UPDATE_KEYS = keysOf()("content", "expected_updated_at");
133
+ var USERS_KEYS = keysOf()("agent_id", "limit", "offset");
134
+ var AGENTS_KEYS = keysOf()("limit", "offset");
135
+ var EVENTS_KEYS = keysOf()("user_id", "status", "limit");
136
+ var AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "limit", "offset");
137
+ var ITER_AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "offset", "page_size");
138
+ var FACTS_KEYS = keysOf()(
139
+ "subject",
140
+ "entity",
141
+ "predicate",
142
+ "predicate_family",
143
+ "include_invalidated",
144
+ "as_of",
145
+ "user_id",
146
+ "agent_id",
147
+ "limit",
148
+ "offset"
149
+ );
150
+ var TRIPLE_KEYS = keysOf()(
151
+ "user_id",
152
+ "agent_id",
153
+ "run_id",
154
+ "subject_type",
155
+ "object_is_literal",
156
+ "confidence",
157
+ "valid_from",
158
+ "tense"
159
+ );
160
+ var PROFILE_KEYS = keysOf()("user_id", "agent_id", "as_of");
161
+ var CONTEXT_KEYS = keysOf()("query", "user_id", "agent_id", "token_budget");
162
+ var CONTEXT_EXTRA_KEYS = keysOf()("user_id", "agent_id", "token_budget");
163
+ function checkOptions(method, opts, known) {
164
+ const problem = unknownOption(method, opts, known);
165
+ if (problem) throw new KorelyError(problem);
166
+ }
92
167
  function coerceContent(content) {
93
168
  if (typeof content === "string") return content;
94
169
  if (Array.isArray(content)) {
@@ -117,6 +192,30 @@ function seg(value, what) {
117
192
  if (!s) throw new KorelyError(`${what} is empty.`);
118
193
  return encodeURIComponent(s);
119
194
  }
195
+ function moment(value, what) {
196
+ if (value == null) return void 0;
197
+ if (typeof value === "string") return value;
198
+ if (value instanceof Date) {
199
+ if (Number.isNaN(value.getTime())) throw new KorelyError(`${what} is an invalid Date.`);
200
+ return value.toISOString();
201
+ }
202
+ throw new KorelyError(`${what} must be an ISO 8601 string or a Date, not a ${typeof value}.`);
203
+ }
204
+ function auditFilters(opts) {
205
+ for (const name of ["user_id", "action"]) {
206
+ if (opts[name] === "") {
207
+ throw new KorelyError(
208
+ `${name} is empty: the server reads an empty filter as no filter. Leave it out to mean every ${name.split("_")[0]}.`
209
+ );
210
+ }
211
+ }
212
+ return {
213
+ user_id: opts.user_id,
214
+ action: opts.action,
215
+ since: moment(opts.since, "since"),
216
+ until: moment(opts.until, "until")
217
+ };
218
+ }
120
219
  function detailLine(detail) {
121
220
  if (typeof detail === "string") return detail.trim() ? detail : void 0;
122
221
  if (Array.isArray(detail) && detail.length) {
@@ -133,13 +232,18 @@ function detailLine(detail) {
133
232
  return void 0;
134
233
  }
135
234
  function errorFields(status, body) {
136
- const text = (v) => typeof v === "string" && v.trim() ? v : void 0;
235
+ const text2 = (v) => typeof v === "string" && v.trim() ? v : void 0;
137
236
  const b = body && typeof body === "object" ? body : {};
138
237
  const pair = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
139
- const code = text(b.code) ?? text(pair.code);
140
- const message = text(b.message) ?? text(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
238
+ const code = text2(b.code) ?? text2(pair.code);
239
+ const message = text2(b.message) ?? text2(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
141
240
  return { code, message };
142
241
  }
242
+ function retryAfterSeconds(raw) {
243
+ if (raw == null) return void 0;
244
+ const n = Math.ceil(Number(raw));
245
+ return Number.isFinite(n) && n >= 0 ? n : void 0;
246
+ }
143
247
  function fillPair(obj, current, deprecated) {
144
248
  if (obj[current] == null && obj[deprecated] != null) obj[current] = obj[deprecated];
145
249
  if (obj[deprecated] == null && obj[current] != null) obj[deprecated] = obj[current];
@@ -175,23 +279,128 @@ function refuseAMismatchedPair(apiKey, baseUrl) {
175
279
  );
176
280
  }
177
281
  }
282
+ async function exchange(t, method, path, opts = {}) {
283
+ let url = t.baseUrl + path;
284
+ if (opts.params) {
285
+ const qs = new URLSearchParams();
286
+ for (const [k, v] of Object.entries(opts.params)) {
287
+ if (v !== void 0 && v !== null) qs.append(k, String(v));
288
+ }
289
+ const s = qs.toString();
290
+ if (s) url += "?" + s;
291
+ }
292
+ const headers = {
293
+ Accept: "application/json",
294
+ "X-Korely-Client": `korely-js/${VERSION}`
295
+ };
296
+ if (t.apiKey) headers.Authorization = `Bearer ${t.apiKey}`;
297
+ let body;
298
+ if (opts.body !== void 0) {
299
+ body = JSON.stringify(opts.body);
300
+ headers["Content-Type"] = "application/json";
301
+ }
302
+ const controller = new AbortController();
303
+ let timedOut = false;
304
+ const timer = setTimeout(() => {
305
+ timedOut = true;
306
+ controller.abort();
307
+ }, t.timeoutMs);
308
+ const failed = (e) => new KorelyError(
309
+ timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
310
+ );
311
+ let resp;
312
+ let text2;
313
+ try {
314
+ try {
315
+ resp = await t.fetchImpl(url, {
316
+ method,
317
+ headers,
318
+ body,
319
+ signal: controller.signal
320
+ });
321
+ } catch (e) {
322
+ throw failed(e);
323
+ }
324
+ try {
325
+ text2 = await resp.text();
326
+ } catch (e) {
327
+ throw failed(e);
328
+ }
329
+ } finally {
330
+ clearTimeout(timer);
331
+ }
332
+ let parsed = {};
333
+ if (text2) {
334
+ try {
335
+ parsed = JSON.parse(text2);
336
+ } catch {
337
+ if (resp.ok) {
338
+ throw new KorelyError(
339
+ `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text2.slice(0, 200))}`,
340
+ { status: resp.status }
341
+ );
342
+ }
343
+ parsed = { message: text2 };
344
+ }
345
+ }
346
+ if (!resp.ok) {
347
+ raiseFor(resp.status, parsed, resp.headers.get("retry-after"));
348
+ }
349
+ return parsed && typeof parsed === "object" ? parsed : {};
350
+ }
351
+ function raiseFor(status, body, retryAfter) {
352
+ const { code, message: msg } = errorFields(status, body);
353
+ const opts = {
354
+ status,
355
+ code,
356
+ retryAfter: retryAfterSeconds(retryAfter ?? body?.retry_after ?? body?._retry_after)
357
+ };
358
+ if (status === 401) throw new AuthenticationError(msg, opts);
359
+ if (status === 403) throw new NamespaceForbiddenError(msg, opts);
360
+ if (status === 404) throw new NotFoundError(msg, opts);
361
+ if (status === 409) {
362
+ if (code === "stale_write") throw new StaleWriteError(msg, opts);
363
+ throw new ConflictError(msg, opts);
364
+ }
365
+ if (status === 429) {
366
+ if (code === "too_many_batches") throw new TooManyBatchesError(msg, opts);
367
+ throw new QuotaExceededError(msg, opts);
368
+ }
369
+ throw new APIError(msg, opts);
370
+ }
371
+ function savedConfig() {
372
+ try {
373
+ const proc = typeof process !== "undefined" ? process : void 0;
374
+ if (!proc?.versions?.node) return {};
375
+ const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof require === "function" ? require(id) : void 0;
376
+ const fs = builtin("node:fs");
377
+ const os = builtin("node:os");
378
+ const path = builtin("node:path");
379
+ if (!fs || !os || !path) return {};
380
+ const home = proc.env?.KORELY_CONFIG_HOME || path.join(os.homedir(), ".korely");
381
+ const data = JSON.parse(fs.readFileSync(path.join(home, "config.json"), "utf8"));
382
+ return data && typeof data === "object" ? data : {};
383
+ } catch {
384
+ return {};
385
+ }
386
+ }
387
+ function text(v) {
388
+ return typeof v === "string" && v ? v : void 0;
389
+ }
178
390
  var Korely = class {
179
391
  constructor(opts = {}) {
180
- if (opts && Object.prototype.hasOwnProperty.call(opts, "base_url")) {
181
- throw new KorelyError(
182
- "Unknown option base_url: the JavaScript SDK takes baseUrl (new Korely({ baseUrl: 'https://...' })) or the KORELY_BASE_URL env var."
183
- );
184
- }
392
+ checkOptions("Korely", opts, CLIENT_KEYS);
185
393
  const envKey = typeof process !== "undefined" ? process.env?.KORELY_API_KEY : void 0;
186
- const key = opts.apiKey ?? envKey;
394
+ const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
395
+ const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
396
+ const key = opts.apiKey ?? envKey ?? text(saved.api_key);
187
397
  if (!key) {
188
398
  throw new KorelyError(
189
- "No API key. Pass { apiKey: 'kor_live_...' } or set KORELY_API_KEY."
399
+ "No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
190
400
  );
191
401
  }
192
402
  this.apiKey = key;
193
- const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
194
- this.baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
403
+ this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
195
404
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
196
405
  this.timeoutMs = opts.timeoutMs ?? 3e4;
197
406
  const f = opts.fetch ?? globalThis.fetch;
@@ -202,92 +411,166 @@ var Korely = class {
202
411
  }
203
412
  this.fetchImpl = f;
204
413
  }
205
- // ── transport ─────────────────────────────────────────────────────────────
206
- async request(method, path, opts = {}) {
207
- let url = this.baseUrl + path;
208
- if (opts.params) {
209
- const qs = new URLSearchParams();
210
- for (const [k, v] of Object.entries(opts.params)) {
211
- if (v !== void 0 && v !== null) qs.append(k, String(v));
212
- }
213
- const s = qs.toString();
214
- if (s) url += "?" + s;
414
+ /**
415
+ * POST /v1/agents/init, with no key: sign up for a free hobby key.
416
+ *
417
+ * The one call that runs without a key, because it is how one is obtained,
418
+ * so it is static: `await Korely.initAgent("my-app")`, then
419
+ * `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
420
+ * label of who signed up, kept for your reference. The answer carries the
421
+ * key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
422
+ * The account it creates has no login: the key is the account, and
423
+ * `deleteAccount({ confirm: true })` closes it.
424
+ *
425
+ * Cloud only. The server is `baseUrl`, else KORELY_BASE_URL, else the
426
+ * region's. Refusals: 403 `signup_disabled` (NamespaceForbiddenError) when
427
+ * self-signup is closed; 429 `signup_rate_limited` (QuotaExceededError, with
428
+ * `retryAfter`) past the new accounts a network may open in a day. The
429
+ * Self-hosted has no such route and answers 404, or 405 where it serves its
430
+ * dashboard: its keys come from its own dashboard.
431
+ */
432
+ static async initAgent(agentCaller, opts = {}) {
433
+ checkOptions("initAgent", opts, INIT_KEYS);
434
+ const where = opts.processingRegion;
435
+ if (where !== void 0 && where !== "eu" && where !== "global") {
436
+ throw new KorelyError(`processingRegion is "eu" or "global", not ${JSON.stringify(where)}.`);
215
437
  }
216
- const headers = {
217
- Authorization: `Bearer ${this.apiKey}`,
218
- Accept: "application/json",
219
- "X-Korely-Client": `korely-js/${VERSION}`
220
- };
221
- let body;
222
- if (opts.body !== void 0) {
223
- body = JSON.stringify(opts.body);
224
- headers["Content-Type"] = "application/json";
438
+ if (agentCaller != null && typeof agentCaller !== "string") {
439
+ throw new KorelyError(
440
+ `agentCaller is a label, a string, not ${Array.isArray(agentCaller) ? "an array" : `a ${typeof agentCaller}`}: Korely.initAgent('my-app', { baseUrl }).`
441
+ );
225
442
  }
226
- const controller = new AbortController();
227
- let timedOut = false;
228
- const timer = setTimeout(() => {
229
- timedOut = true;
230
- controller.abort();
231
- }, this.timeoutMs);
232
- const failed = (e) => new KorelyError(
233
- timedOut ? `Request timed out after ${this.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
234
- );
235
- let resp;
236
- let text;
237
- try {
238
- try {
239
- resp = await this.fetchImpl(url, {
240
- method,
241
- headers,
242
- body,
243
- signal: controller.signal
244
- });
245
- } catch (e) {
246
- throw failed(e);
247
- }
248
- try {
249
- text = await resp.text();
250
- } catch (e) {
251
- throw failed(e);
252
- }
253
- } finally {
254
- clearTimeout(timer);
443
+ const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
444
+ const baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
445
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
446
+ if (!fetchImpl) {
447
+ throw new KorelyError(
448
+ "No fetch available. On Node < 18 pass a fetch implementation via { fetch }."
449
+ );
255
450
  }
256
- let parsed = {};
257
- if (text) {
258
- try {
259
- parsed = JSON.parse(text);
260
- } catch {
261
- if (resp.ok) {
262
- throw new KorelyError(
263
- `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text.slice(0, 200))}`,
264
- { status: resp.status }
265
- );
266
- }
267
- parsed = { message: text };
451
+ return exchange(
452
+ { baseUrl, timeoutMs: opts.timeoutMs ?? 3e4, fetchImpl },
453
+ "POST",
454
+ "/v1/agents/init",
455
+ {
456
+ body: { agent_caller: agentCaller ?? void 0, processing_region: opts.processingRegion }
268
457
  }
458
+ );
459
+ }
460
+ // ── transport ─────────────────────────────────────────────────────────────
461
+ request(method, path, opts = {}) {
462
+ return exchange(
463
+ { baseUrl: this.baseUrl, timeoutMs: this.timeoutMs, fetchImpl: this.fetchImpl, apiKey: this.apiKey },
464
+ method,
465
+ path,
466
+ opts
467
+ );
468
+ }
469
+ // ── the key and its account ───────────────────────────────────────────────
470
+ /**
471
+ * GET /v1/ping: does this key work, and what may it do? Both products answer
472
+ * it, with the same shape.
473
+ *
474
+ * The cheapest authenticated call there is: no scope, no rate limit, no
475
+ * quota, so it is how to check a key that was just minted or rotated without
476
+ * spending anything. `users()` was the usual stand-in, and it needs
477
+ * `memories:read` and counts as a query.
478
+ */
479
+ async ping() {
480
+ return this.request("GET", "/v1/ping");
481
+ }
482
+ /**
483
+ * DELETE /v1/account?confirm=true: delete the account of this key for good,
484
+ * with every key, project, memory, fact and webhook of it; the key stops
485
+ * working. Cloud only, for an account made by `Korely.initAgent()` or
486
+ * `korely init --agent`, which nobody signs in to: the key is the account,
487
+ * and this is how it is closed (GDPR Art. 17).
488
+ *
489
+ * `{ confirm: true }` is required, and checked here, before anything is
490
+ * sent: without it, a KorelyError whose `code` is `confirmation_required`,
491
+ * the code the server gives the same refusal.
492
+ *
493
+ * An account with a Korely login rejects with 409 `account_has_login`
494
+ * (ConflictError): a key that ended up in a log must not be able to delete
495
+ * it, so it is closed from the app (Settings, Account). The Self-hosted has
496
+ * no such route and answers 404 (NotFoundError), or 405 where it serves its
497
+ * dashboard. No audit event survives: the trail is part of what goes.
498
+ */
499
+ async deleteAccount(opts = {}) {
500
+ checkOptions("deleteAccount", opts, ["confirm"]);
501
+ if (opts?.confirm !== true) {
502
+ throw new KorelyError(
503
+ "deleteAccount() deletes this key's account, every key, memory and fact of it, for good. Pass { confirm: true } to mean it.",
504
+ { code: "confirmation_required" }
505
+ );
269
506
  }
270
- if (!resp.ok) {
271
- this.raise(resp.status, parsed, resp.headers.get("retry-after"));
272
- }
273
- return parsed && typeof parsed === "object" ? parsed : {};
274
- }
275
- raise(status, body, retryAfter) {
276
- const { code, message: msg } = errorFields(status, body);
277
- if (status === 401) throw new AuthenticationError(msg, { status, code });
278
- if (status === 403) throw new NamespaceForbiddenError(msg, { status, code });
279
- if (status === 404) throw new NotFoundError(msg, { status, code });
280
- if (status === 409) throw new StaleWriteError(msg, { status, code });
281
- if (status === 429) {
282
- const raw = retryAfter ?? body?.retry_after ?? body?._retry_after;
283
- let ra;
284
- if (raw != null) {
285
- const n = Math.ceil(Number(raw));
286
- ra = Number.isFinite(n) && n >= 0 ? n : void 0;
507
+ return this.request("DELETE", "/v1/account", { params: { confirm: "true" } });
508
+ }
509
+ // ── audit ─────────────────────────────────────────────────────────────────
510
+ /**
511
+ * GET /v1/audit: what this key's project did, and what its agents read,
512
+ * newest first (`ts` descending, then the event's id, so paging with
513
+ * `offset` is stable). Both products; the key needs `memories:read`.
514
+ *
515
+ * `user_id` keeps the events that touched one end user, the shape of an
516
+ * access or erasure request; `action` one kind ("read", "write", "erase"...;
517
+ * an unknown one answers an empty page); `since` and `until` bound `ts`,
518
+ * both inclusive, as ISO 8601 text or a Date. `limit` is 1 to 1000. To read
519
+ * everything, use `iterAudit()`. The page is iterable.
520
+ *
521
+ * Reading the trail counts against no quota and is not itself written to
522
+ * it; it does count against the rate limit. Scoped to the key's account and
523
+ * project, like every read.
524
+ */
525
+ async audit(opts = {}) {
526
+ checkOptions("audit", opts, AUDIT_KEYS);
527
+ const page = await this.request(
528
+ "GET",
529
+ "/v1/audit",
530
+ {
531
+ params: { ...auditFilters(opts), limit: opts.limit ?? 100, offset: opts.offset ?? 0 }
532
+ }
533
+ );
534
+ return iterableOver(page, "events");
535
+ }
536
+ /**
537
+ * Every event `audit()` would page through, for an export:
538
+ * `for await (const e of korely.iterAudit({ user_id }))`. The same filters,
539
+ * `page_size` events per request (1000, the most the API gives),
540
+ * `offset += page.length` until `total`.
541
+ *
542
+ * Without `until` the walk pins it to the newest event of its first page.
543
+ * The trail grows while it is read, newest first, and every new event pushed
544
+ * the rest one place down: the next page began with events already returned.
545
+ * The pin makes the export the trail as it stood when it started.
546
+ *
547
+ * A rate limit rejects mid-way, as any call does, and the SDK does not
548
+ * retry. To resume, call again with the same `until` (pin it yourself:
549
+ * `until: new Date()`) and `offset` the number of events already read.
550
+ */
551
+ async *iterAudit(opts = {}) {
552
+ checkOptions("iterAudit", opts, ITER_AUDIT_KEYS);
553
+ const filters = auditFilters(opts);
554
+ let offset = opts.offset ?? 0;
555
+ let pin = filters.until === void 0 && offset === 0;
556
+ for (; ; ) {
557
+ const page = await this.audit({
558
+ user_id: opts.user_id,
559
+ action: opts.action,
560
+ since: filters.since,
561
+ until: filters.until,
562
+ limit: opts.page_size ?? 1e3,
563
+ offset
564
+ });
565
+ if (!page.events.length) return;
566
+ yield* page.events;
567
+ if (pin && page.events[0].ts) {
568
+ filters.until = page.events[0].ts;
569
+ pin = false;
287
570
  }
288
- throw new QuotaExceededError(msg, { status, code, retryAfter: ra });
571
+ offset += page.events.length;
572
+ if (offset >= page.total) return;
289
573
  }
290
- throw new APIError(msg, { status, code });
291
574
  }
292
575
  // ── memories ────────────────────────────────────────────────────────────
293
576
  /**
@@ -297,15 +580,16 @@ var Korely = class {
297
580
  * backfill: facts extracted inherit it as `valid_from`.
298
581
  */
299
582
  async add(content, opts = {}) {
300
- const text = coerceContent(content);
301
- if (!text.trim()) {
583
+ checkOptions("add", opts, ADD_KEYS);
584
+ const text2 = coerceContent(content);
585
+ if (!text2.trim()) {
302
586
  throw new KorelyError(
303
587
  "content is empty: pass a non-blank string or messages with content."
304
588
  );
305
589
  }
306
590
  return this.request("POST", "/v1/memories", {
307
591
  body: {
308
- content: text,
592
+ content: text2,
309
593
  agent_id: opts.agent_id,
310
594
  user_id: opts.user_id,
311
595
  run_id: opts.run_id,
@@ -321,6 +605,7 @@ var Korely = class {
321
605
  * the server default (15), max 50.
322
606
  */
323
607
  async search(query, opts = {}) {
608
+ checkOptions("search", opts, SEARCH_KEYS);
324
609
  const body = await this.request("POST", "/v1/memories/search", {
325
610
  body: {
326
611
  query,
@@ -339,6 +624,7 @@ var Korely = class {
339
624
  * `total` and `offset` walk the rest.
340
625
  */
341
626
  async getAll(opts = {}) {
627
+ checkOptions("getAll", opts, LIST_KEYS);
342
628
  const page = await this.request(
343
629
  "GET",
344
630
  "/v1/memories",
@@ -363,6 +649,7 @@ var Korely = class {
363
649
  * for optimistic concurrency (throws StaleWriteError instead of clobbering).
364
650
  */
365
651
  async update(memoryId, opts) {
652
+ checkOptions("update", opts, UPDATE_KEYS);
366
653
  return this.request("PATCH", `/v1/memories/${seg(memoryId, "memoryId")}`, {
367
654
  body: {
368
655
  content: opts.content,
@@ -388,6 +675,7 @@ var Korely = class {
388
675
  * the same numbers; whichever pair the server sends fills both.
389
676
  */
390
677
  async deleteAll(opts) {
678
+ checkOptions("deleteAll", opts, ["user_id"]);
391
679
  const r = await this.request(
392
680
  "DELETE",
393
681
  `/v1/users/${seg(opts.user_id, "user_id")}/memories`
@@ -409,6 +697,7 @@ var Korely = class {
409
697
  * namespaces), each with active memory + fact counts and last-active time.
410
698
  */
411
699
  async users(opts = {}) {
700
+ checkOptions("users", opts, USERS_KEYS);
412
701
  const page = await this.request(
413
702
  "GET",
414
703
  "/v1/users",
@@ -437,6 +726,7 @@ var Korely = class {
437
726
  * sets no cap and answers `cap: 0`.
438
727
  */
439
728
  async listAgents(opts = {}) {
729
+ checkOptions("listAgents", opts, AGENTS_KEYS);
440
730
  const page = await this.request("GET", "/v1/agents", {
441
731
  params: {
442
732
  limit: opts.limit ?? 50,
@@ -468,6 +758,7 @@ var Korely = class {
468
758
  * array that also carries `total`, the matches across all pages.
469
759
  */
470
760
  async getFacts(opts = {}) {
761
+ checkOptions("getFacts", opts, FACTS_KEYS);
471
762
  const params = {
472
763
  subject: opts.subject,
473
764
  entity: opts.entity,
@@ -496,7 +787,8 @@ var Korely = class {
496
787
  * listing any fact ids it superseded.
497
788
  */
498
789
  async addFactTriple(subject, predicate, object, opts = {}) {
499
- return this.request("POST", "/v1/facts", {
790
+ checkOptions("addFactTriple", opts, TRIPLE_KEYS);
791
+ const fact = await this.request("POST", "/v1/facts", {
500
792
  body: {
501
793
  subject,
502
794
  predicate,
@@ -511,6 +803,11 @@ var Korely = class {
511
803
  tense: opts.tense
512
804
  }
513
805
  });
806
+ return {
807
+ ...fact,
808
+ user_id: fact.user_id !== void 0 ? fact.user_id : opts.user_id,
809
+ agent_id: fact.agent_id !== void 0 ? fact.agent_id : opts.agent_id
810
+ };
514
811
  }
515
812
  /**
516
813
  * POST /v1/facts/:id/forget: close a fact; it stops being current and stays
@@ -527,6 +824,7 @@ var Korely = class {
527
824
  * knows a fact is finished says so, and nothing has to infer it.
528
825
  */
529
826
  async forgetFact(factId, opts = {}) {
827
+ checkOptions("forgetFact", opts, ["at"]);
530
828
  return this.request("POST", `/v1/facts/${seg(factId, "factId")}/forget`, {
531
829
  body: { at: opts.at }
532
830
  });
@@ -556,6 +854,7 @@ var Korely = class {
556
854
  * Pass `as_of` (ISO date) for the point-in-time profile.
557
855
  */
558
856
  async getProfile(opts) {
857
+ checkOptions("getProfile", opts, PROFILE_KEYS);
559
858
  return this.request("GET", "/v1/profile", {
560
859
  params: {
561
860
  user_id: opts.user_id,
@@ -570,6 +869,8 @@ var Korely = class {
570
869
  * (profile + relevant facts + memories) within a token budget.
571
870
  */
572
871
  async getContext(opts, extra = {}) {
872
+ if (typeof opts === "string") checkOptions("getContext", extra, CONTEXT_EXTRA_KEYS);
873
+ else checkOptions("getContext", opts, CONTEXT_KEYS);
573
874
  const o = typeof opts === "string" ? { ...extra, query: opts } : opts;
574
875
  if (!o || typeof o.query !== "string" || !o.query.trim()) {
575
876
  throw new KorelyError("getContext needs a query.");
@@ -597,6 +898,7 @@ var Korely = class {
597
898
  * this is how to know.
598
899
  */
599
900
  async events(opts = {}) {
901
+ checkOptions("events", opts, EVENTS_KEYS);
600
902
  return this.request("GET", "/v1/events", {
601
903
  params: {
602
904
  user_id: opts.user_id,
@@ -620,6 +922,12 @@ var Korely = class {
620
922
  * `code === "invalid_request"`) whose message names the item, e.g.
621
923
  * `memories[3].timestamp`. Any key not listed above is refused the same
622
924
  * way. Servers older than 2026-09-28 refuse `timestamp` itself.
925
+ *
926
+ * On the Cloud a batch is also refused, before anything is stored, with a
927
+ * 429: `quota_exceeded` (QuotaExceededError) when its memories do not fit in
928
+ * what is left of the month, batches already queued included, and
929
+ * `too_many_batches` (TooManyBatchesError) while three batches are still
930
+ * being imported. The Self-hosted meters nothing and refuses neither.
623
931
  */
624
932
  async batch(memories) {
625
933
  return this.request("POST", "/v1/batch", { body: { memories } });
@@ -633,11 +941,13 @@ var Korely = class {
633
941
  0 && (module.exports = {
634
942
  APIError,
635
943
  AuthenticationError,
944
+ ConflictError,
636
945
  Korely,
637
946
  KorelyError,
638
947
  NamespaceForbiddenError,
639
948
  NotFoundError,
640
949
  QuotaExceededError,
641
950
  StaleWriteError,
951
+ TooManyBatchesError,
642
952
  VERSION
643
953
  });