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.
package/dist/index.cjs CHANGED
@@ -126,11 +126,28 @@ function unknownOption(method, opts, known) {
126
126
  }
127
127
 
128
128
  // src/client.ts
129
- var VERSION = "0.1.18";
129
+ var VERSION = "0.2.1";
130
130
  var REGIONS = { eu: "https://api.korely.ai" };
131
131
  var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch", "client");
132
132
  var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
133
- var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp", "kind");
133
+ var ADD_KEYS = keysOf()(
134
+ "agent_id",
135
+ "user_id",
136
+ "run_id",
137
+ "metadata",
138
+ "timestamp",
139
+ "kind",
140
+ "idempotency_key"
141
+ );
142
+ function idempotencyHeader(key) {
143
+ if (key === void 0) return void 0;
144
+ if (typeof key !== "string" || !/^[\x20-\x7e]{1,255}$/.test(key)) {
145
+ throw new KorelyError(
146
+ "idempotency_key must be 1 to 255 printable ASCII characters (space to ~), one per write: a UUID will do."
147
+ );
148
+ }
149
+ return { "Idempotency-Key": `"${key.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` };
150
+ }
134
151
  var SEARCH_KEYS = keysOf()(
135
152
  "user_id",
136
153
  "agent_id",
@@ -138,7 +155,9 @@ var SEARCH_KEYS = keysOf()(
138
155
  "metadata",
139
156
  "limit",
140
157
  "min_score",
141
- "exclude_sessions"
158
+ "exclude_sessions",
159
+ "types",
160
+ "full_text"
142
161
  );
143
162
  var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset", "exclude_sessions");
144
163
  var NAME_KEYS = keysOf()("user_id", "agent_id");
@@ -198,6 +217,12 @@ function checkOptions(method, opts, known) {
198
217
  const problem = unknownOption(method, opts, known);
199
218
  if (problem) throw new KorelyError(problem);
200
219
  }
220
+ var ACCOUNT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
221
+ function accountId(value) {
222
+ if (typeof value !== "string") return void 0;
223
+ const text2 = value.trim();
224
+ return ACCOUNT_ID.test(text2) ? text2 : void 0;
225
+ }
201
226
  function coerceContent(content) {
202
227
  if (typeof content === "string") return content;
203
228
  if (Array.isArray(content)) {
@@ -350,6 +375,7 @@ async function exchange(t, method, path, opts = {}) {
350
375
  body = JSON.stringify(opts.body);
351
376
  headers["Content-Type"] = "application/json";
352
377
  }
378
+ Object.assign(headers, opts.headers);
353
379
  const controller = new AbortController();
354
380
  let timedOut = false;
355
381
  const timer = setTimeout(() => {
@@ -367,7 +393,12 @@ async function exchange(t, method, path, opts = {}) {
367
393
  method,
368
394
  headers,
369
395
  body,
370
- signal: controller.signal
396
+ signal: controller.signal,
397
+ // Only a GET follows a redirect. `fetch` follows a POST answered 301,
398
+ // 302 or 303 as a GET with no body, and that GET's answer came back
399
+ // as the POST's; any other call takes the 3xx as its answer (Node
400
+ // gives it whole, a browser as an "opaqueredirect" of status 0).
401
+ redirect: method === "GET" ? "follow" : "manual"
371
402
  });
372
403
  } catch (e) {
373
404
  throw failed(e);
@@ -395,12 +426,36 @@ async function exchange(t, method, path, opts = {}) {
395
426
  }
396
427
  }
397
428
  if (!resp.ok) {
398
- raiseFor(resp.status, parsed, resp.headers.get("retry-after"));
429
+ raiseFor(resp.status, parsed, resp.headers.get("retry-after"), redirectOf(resp, url), method);
399
430
  }
400
431
  return parsed && typeof parsed === "object" ? parsed : {};
401
432
  }
402
- function raiseFor(status, body, retryAfter) {
403
- const { code, message: msg } = errorFields(status, body);
433
+ function originOf(address, base) {
434
+ try {
435
+ return new URL(address, base).origin;
436
+ } catch {
437
+ return void 0;
438
+ }
439
+ }
440
+ function redirectOf(resp, url) {
441
+ const location = resp.headers.get("location");
442
+ if (resp.status >= 300 && resp.status < 400 && location) return originOf(location, url);
443
+ if (resp.redirected && resp.url) {
444
+ const at = originOf(resp.url);
445
+ if (at && at !== originOf(url)) return at;
446
+ }
447
+ return void 0;
448
+ }
449
+ function raiseFor(status, body, retryAfter, redirect, method) {
450
+ let { code, message: msg } = errorFields(status, body);
451
+ if (status === 401 && redirect) {
452
+ 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.`;
453
+ }
454
+ if (status >= 300 && status < 400 || status === 0) {
455
+ const answered = status ? `The server answered ${status} to a ${method ?? "call"}, a redirect` : `The server answered a ${method ?? "call"} with a redirect`;
456
+ const to = redirect ? ` to ${redirect}` : "";
457
+ 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.`;
458
+ }
404
459
  const opts = {
405
460
  status,
406
461
  code,
@@ -420,22 +475,44 @@ function raiseFor(status, body, retryAfter) {
420
475
  }
421
476
  throw new APIError(msg, opts);
422
477
  }
478
+ var nodeFiles;
423
479
  function savedConfig() {
424
480
  try {
425
- const proc = typeof process !== "undefined" ? process : void 0;
426
- if (!proc?.versions?.node) return {};
427
- const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof require === "function" ? require(id) : void 0;
428
- const fs = builtin("node:fs");
429
- const os = builtin("node:os");
430
- const path = builtin("node:path");
431
- if (!fs || !os || !path) return {};
432
- const home = proc.env?.KORELY_CONFIG_HOME || path.join(os.homedir(), ".korely");
433
- const data = JSON.parse(fs.readFileSync(path.join(home, "config.json"), "utf8"));
481
+ const at = configFile();
482
+ if (!at) return {};
483
+ const data = JSON.parse(at.files.readFileSync(at.path, "utf8"));
434
484
  return data && typeof data === "object" ? data : {};
435
485
  } catch {
436
486
  return {};
437
487
  }
438
488
  }
489
+ function configFile() {
490
+ const proc = typeof process !== "undefined" ? process : void 0;
491
+ if (!proc?.versions?.node) return void 0;
492
+ const files = nodeFiles ?? lookedUp(proc);
493
+ if (!files) return void 0;
494
+ const home = proc.env?.KORELY_CONFIG_HOME || files.join(files.homedir(), ".korely");
495
+ return { files, path: files.join(home, "config.json") };
496
+ }
497
+ function noKey() {
498
+ let file;
499
+ try {
500
+ file = configFile()?.path;
501
+ } catch {
502
+ file = void 0;
503
+ }
504
+ return new KorelyError(
505
+ `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}.` : "")
506
+ );
507
+ }
508
+ function lookedUp(proc) {
509
+ const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof require === "function" ? require(id) : void 0;
510
+ const fs = builtin("node:fs");
511
+ const os = builtin("node:os");
512
+ const path = builtin("node:path");
513
+ if (!fs || !os || !path) return void 0;
514
+ return { readFileSync: fs.readFileSync, homedir: os.homedir, join: path.join };
515
+ }
439
516
  function text(v) {
440
517
  return typeof v === "string" && v ? v : void 0;
441
518
  }
@@ -447,9 +524,7 @@ var Korely = class {
447
524
  const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
448
525
  const key = opts.apiKey ?? envKey ?? text(saved.api_key);
449
526
  if (!key) {
450
- throw new KorelyError(
451
- "No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
452
- );
527
+ throw noKey();
453
528
  }
454
529
  this.apiKey = key;
455
530
  const envClient = typeof process !== "undefined" ? process.env?.KORELY_CLIENT : void 0;
@@ -466,15 +541,18 @@ var Korely = class {
466
541
  this.fetchImpl = f;
467
542
  }
468
543
  /**
469
- * POST /v1/agents/init, with no key: sign up for a free hobby key.
544
+ * POST /v1/agents/init, with no key: sign up for a key that costs nothing.
470
545
  *
471
546
  * The one call that runs without a key, because it is how one is obtained,
472
547
  * so it is static: `await Korely.initAgent("my-app")`, then
473
548
  * `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
474
549
  * label of who signed up, kept for your reference. The answer carries the
475
- * key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
550
+ * key, shown once (save it), when it stops working (`expires_at`), the
551
+ * trial in words (`note`: its limits until the account is adopted, and how
552
+ * to adopt it), its `tier`, `region`, `scopes` and `quotas` (the monthly
553
+ * numbers once adopted).
476
554
  * The account it creates has no login: the key is the account, and
477
- * `deleteAccount({ confirm: true })` closes it.
555
+ * `deleteAccount({ confirm: "<the account's id>" })` closes it.
478
556
  *
479
557
  * Cloud only. The server is `baseUrl`, else KORELY_BASE_URL, else the
480
558
  * region's. Refusals: 403 `signup_disabled` (NamespaceForbiddenError) when
@@ -540,15 +618,36 @@ var Korely = class {
540
618
  return this.request("GET", "/v1/ping");
541
619
  }
542
620
  /**
543
- * DELETE /v1/account?confirm=true: delete the account of this key for good,
544
- * with every key, project, memory, fact and webhook of it; the key stops
545
- * working. Cloud only, for an account made by `Korely.initAgent()` or
546
- * `korely init --agent`, which nobody signs in to: the key is the account,
547
- * and this is how it is closed (GDPR Art. 17).
621
+ * DELETE /v1/account?confirm=<the account's id>: delete the account of this
622
+ * key for good, with every key, project, memory, fact and webhook of it; the
623
+ * key stops working. Cloud only, for an account made by `Korely.initAgent()`
624
+ * or `korely init --agent`, which nobody signs in to: the key is the
625
+ * account, and this is how it is closed (GDPR Art. 17).
626
+ *
627
+ * `confirm` is the account's id, typed by whoever means it, as the
628
+ * dashboard has the email typed: `tenant_id` of GET /admin/whoami, which the
629
+ * error below gives. So a key that leaked, or a script pointed at the wrong
630
+ * key, is not enough with a flag (Korely 1.0.23 asks the same of the
631
+ * server's route). Nothing is deleted, and the DELETE is not sent, unless
632
+ * `confirm` is a UUID equal, spaces trimmed, to the `tenant_id` that GET
633
+ * /admin/whoami gives this key: a missing, `true`, `"true"` or wrong
634
+ * `confirm` rejects with a KorelyError whose `code` is
635
+ * `confirmation_required` (the server's code for the same refusal) and
636
+ * whose message names the id to type when the key may read it. A key that
637
+ * may not read GET /admin/whoami (403, a key without the `admin` scope)
638
+ * deletes nothing: with no id typed it rejects with that same
639
+ * `confirmation_required`, whose message says whoami could not be read;
640
+ * with the id typed, with the server's refusal of the whoami,
641
+ * NamespaceForbiddenError (an APIError, `status` 403, `code` `forbidden`).
548
642
  *
549
- * `{ confirm: true }` is required, and checked here, before anything is
550
- * sent: without it, a KorelyError whose `code` is `confirmation_required`,
551
- * the code the server gives the same refusal.
643
+ * The account is deleted only on the server's answer that says so
644
+ * (`deleted: true`); any other answer, a redirect (never followed: the
645
+ * DELETE is not a GET) or a 2xx without it, rejects, and the account may
646
+ * still be there. A server older
647
+ * than 1.0.23 takes only `?confirm=true` and refuses the id (422): that
648
+ * rejects with an APIError whose `code` is `server_too_old`, nothing is
649
+ * deleted, and the client does not fall back to the flag. Upgrade the
650
+ * server, or use korely-memory 0.1.18.
552
651
  *
553
652
  * An account with a Korely login rejects with 409 `account_has_login`
554
653
  * (ConflictError): a key that ended up in a log must not be able to delete
@@ -558,13 +657,68 @@ var Korely = class {
558
657
  */
559
658
  async deleteAccount(opts = {}) {
560
659
  checkOptions("deleteAccount", opts, ["confirm"]);
561
- if (opts?.confirm !== true) {
660
+ const typed = accountId(opts?.confirm);
661
+ if (typed === void 0) {
662
+ throw await this.notConfirmed(
663
+ "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."
664
+ );
665
+ }
666
+ const account = await this.accountOfThisKey();
667
+ if (typed !== account) {
562
668
  throw new KorelyError(
563
- "deleteAccount() deletes this key's account, every key, memory and fact of it, for good. Pass { confirm: true } to mean it.",
669
+ `The account of this key is ${account}, and the confirmation names ${typed}: nothing was deleted. To delete account ${account}, pass { confirm: "${account}" }.`,
564
670
  { code: "confirmation_required" }
565
671
  );
566
672
  }
567
- return this.request("DELETE", "/v1/account", { params: { confirm: "true" } });
673
+ let body;
674
+ try {
675
+ body = await this.request("DELETE", "/v1/account", { params: { confirm: account } });
676
+ } catch (e) {
677
+ if (e instanceof APIError && e.status === 422) {
678
+ throw new APIError(
679
+ "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).",
680
+ { status: 422, code: "server_too_old" }
681
+ );
682
+ }
683
+ throw e;
684
+ }
685
+ if (body?.deleted !== true) {
686
+ throw new KorelyError(
687
+ "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)."
688
+ );
689
+ }
690
+ return body;
691
+ }
692
+ /** The id of this key's account: `tenant_id` of GET /admin/whoami, checked
693
+ * as an account id (`accountId`). The errors of the call reject as they
694
+ * come. */
695
+ async accountOfThisKey() {
696
+ const who = await this.request("GET", "/admin/whoami");
697
+ const account = accountId(who?.tenant_id);
698
+ if (account === void 0) {
699
+ throw new KorelyError(
700
+ "GET /admin/whoami gave no account id (a UUID) for this key: nothing was deleted.",
701
+ { code: "confirmation_required" }
702
+ );
703
+ }
704
+ return account;
705
+ }
706
+ /** The refusal of a deletion not confirmed, naming the id to type when this
707
+ * key may read it. */
708
+ async notConfirmed(why) {
709
+ let account;
710
+ try {
711
+ account = await this.accountOfThisKey();
712
+ } catch (e) {
713
+ return new KorelyError(
714
+ `${why} Nothing was deleted. The id is tenant_id in GET /admin/whoami, which this key could not read: ${e?.message ?? String(e)}`,
715
+ { code: "confirmation_required" }
716
+ );
717
+ }
718
+ return new KorelyError(
719
+ `${why} Nothing was deleted. To delete account ${account}, pass { confirm: "${account}" }.`,
720
+ { code: "confirmation_required" }
721
+ );
568
722
  }
569
723
  // ── audit ─────────────────────────────────────────────────────────────────
570
724
  /**
@@ -661,14 +815,17 @@ var Korely = class {
661
815
  metadata: opts.metadata,
662
816
  timestamp: opts.timestamp,
663
817
  kind: opts.kind
664
- }
818
+ },
819
+ headers: idempotencyHeader(opts.idempotency_key)
665
820
  });
666
821
  }
667
822
  /**
668
823
  * POST /v1/memories/search: semantic search over raw memories, ranked by
669
- * score (vector similarity to the query). `run_id` scopes to one session,
670
- * `metadata` filters on what you stored at write time. `limit` defaults to
671
- * the server default (15), max 50.
824
+ * score (vector similarity to the query); with `types`, over the facts too,
825
+ * or the facts only. `run_id` scopes to one session, `metadata` filters on
826
+ * what you stored at write time. `limit` defaults to the server default
827
+ * (15), max 50. `full_text: true` adds each result's whole text as
828
+ * `content`.
672
829
  */
673
830
  async search(query, opts = {}) {
674
831
  checkOptions("search", opts, SEARCH_KEYS);
@@ -682,7 +839,10 @@ var Korely = class {
682
839
  limit: opts.limit,
683
840
  min_score: opts.min_score,
684
841
  // Sent only when true: an older server does not know the field.
685
- exclude_sessions: opts.exclude_sessions ? true : void 0
842
+ exclude_sessions: opts.exclude_sessions ? true : void 0,
843
+ // Sent only when given, as `min_score`: Korely 1.0.13 and later.
844
+ types: opts.types,
845
+ full_text: opts.full_text ? true : void 0
686
846
  }
687
847
  });
688
848
  return body.results ?? [];
@@ -749,7 +909,8 @@ var Korely = class {
749
909
  /**
750
910
  * DELETE /v1/memories/:id: forget one memory. It drops out of every default
751
911
  * read, and the facts only it asserted are invalidated (kept as history,
752
- * audited). For erasure use `deleteAll`.
912
+ * audited). The facts its facts had closed are true again: the receipt
913
+ * counts them in `facts_reopened`. For erasure use `deleteAll`.
753
914
  */
754
915
  async delete(memoryId) {
755
916
  return this.request("DELETE", `/v1/memories/${seg(memoryId, "memoryId")}`);
@@ -828,14 +989,16 @@ var Korely = class {
828
989
  * DELETE /v1/agents/:agent_id: hard-delete an agent namespace, purging every
829
990
  * memory + fact written under this agent_id in this key's project
830
991
  * (soft-forgetting its data does NOT free its cap slot; this does). Resolves
831
- * to the purge counts, an audit id and `slot_freed`.
992
+ * to the purge counts and an audit id. Its `slot_freed` is always
993
+ * undefined: no Korely server sends it, and none ever has. To see whether a
994
+ * cap slot is free, read `cap` and `used` from `listAgents()`.
832
995
  *
833
996
  * The namespace must be one `listAgents()` shows for this key: anything else
834
997
  * rejects with NotFoundError, including a name only another project of the
835
998
  * account uses (the server answered 200 with zero counts for it before
836
999
  * 2026-09-28, and freed nothing). The cap counts a name across the account,
837
1000
  * so while another project still uses the same agent_id its rows stay and
838
- * `slot_freed` is false.
1001
+ * the slot stays taken.
839
1002
  */
840
1003
  async deleteAgent(agentId) {
841
1004
  return this.request("DELETE", `/v1/agents/${seg(agentId, "agentId")}`);
@@ -1032,8 +1195,11 @@ var Korely = class {
1032
1195
  * `too_many_batches` (TooManyBatchesError) while three batches are still
1033
1196
  * being imported. The Self-hosted meters nothing and refuses neither.
1034
1197
  */
1035
- async batch(memories) {
1036
- return this.request("POST", "/v1/batch", { body: { memories } });
1198
+ async batch(memories, opts = {}) {
1199
+ return this.request("POST", "/v1/batch", {
1200
+ body: { memories },
1201
+ headers: idempotencyHeader(opts.idempotency_key)
1202
+ });
1037
1203
  }
1038
1204
  /** GET /v1/batch/:id: poll an import job. */
1039
1205
  async batchStatus(jobId) {