korely-memory 0.2.0 → 0.2.2

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.d.ts CHANGED
@@ -78,13 +78,25 @@ interface Memory {
78
78
  /** "note" or "session" (Korely Agent 0.1.42); absent from an older server. */
79
79
  kind?: "note" | "session";
80
80
  }
81
+ /** What `search()` may search, each once in `types`: the memories, or the
82
+ * facts true now (Korely 1.0.13 and later). */
83
+ type SearchKind = "memories" | "facts";
81
84
  interface SearchHit {
82
85
  id?: string;
83
86
  score?: number;
87
+ /** The first 280 characters of the text. */
84
88
  snippet?: string;
85
89
  user_id?: string;
86
90
  agent_id?: string;
87
91
  metadata?: Record<string, unknown>;
92
+ /** "memory" or "fact": in every result when the search names `types`
93
+ * (Korely 1.0.13 and later), absent otherwise. */
94
+ type?: "memory" | "fact" | string;
95
+ /** The whole text (a memory's as stored, a fact's line): only with
96
+ * `full_text: true` (Korely 1.0.13 and later). */
97
+ content?: string;
98
+ /** A fact's result: the fact as `getFacts()` shows it. Absent for a memory. */
99
+ fact?: Fact;
88
100
  }
89
101
  /** Iterable like the Python SDK's MemoryPage: `for (const m of page)` works,
90
102
  * and `page.memories` / `page.total` still do. */
@@ -318,7 +330,7 @@ interface PingResponse {
318
330
  /** What the key may do, e.g. "memories:read". */
319
331
  scopes: string[];
320
332
  }
321
- /** What `Korely.initAgent()` answers: a new hobby key and what it buys. */
333
+ /** What `Korely.initAgent()` answers: a new key, when it ends, and what the account may do. */
322
334
  interface AgentInitResult {
323
335
  /** The key, shown this once and never again: save it. */
324
336
  api_key: string;
@@ -327,7 +339,16 @@ interface AgentInitResult {
327
339
  /** Where the new project's memories are read by a model. */
328
340
  processing_region?: "eu" | "global";
329
341
  scopes: string[];
330
- /** The hobby allowance: writes_per_month, queries_per_month, agents, the monthly AI budget. */
342
+ /** When the key stops working (ISO 8601, with its time zone). Absent from a
343
+ * server older than Korely Agent 1.0.10. */
344
+ expires_at?: string;
345
+ /** The same in the server's words: how long the key lasts, the trial's
346
+ * limits until the account is adopted, and how to adopt it. Absent from a
347
+ * server older than Korely Agent 1.0.10. */
348
+ note?: string;
349
+ /** The free plan's monthly allowance: writes_per_month, queries_per_month,
350
+ * agents, the monthly AI budget. With a `note`, it applies once the account
351
+ * is adopted; until then the trial's limits do. */
331
352
  quotas: Record<string, unknown>;
332
353
  /** The Terms of Service that creating the account accepts. Absent from a
333
354
  * server older than Korely Agent 0.1.27. */
@@ -418,6 +439,17 @@ interface AddOptions {
418
439
  * field with a 422.
419
440
  */
420
441
  kind?: "note" | "session";
442
+ /**
443
+ * The same write sent again with the same key is made once (Korely Agent
444
+ * 1.0.27 and later; an older server ignores it). Without one the client
445
+ * makes one for this write (0.2.2). A write whose answer never came (a
446
+ * timeout, a connection that failed) may have been made: the client sends
447
+ * it once more with the same key (`retryWrites`), and if that does not
448
+ * succeed either (no answer, a 5xx, a 429) it rejects with KorelyError
449
+ * `write_not_confirmed`, naming the key and the cause. Pass your own key to send the write again later yourself: one
450
+ * new key per write, the same one only to send that write again.
451
+ */
452
+ idempotency_key?: string;
421
453
  }
422
454
  /** What `declareName` declared: in `user_id`'s memory (`agent_id` the
423
455
  * namespace, none for the end user's own) the facts about `name` read as the
@@ -450,6 +482,22 @@ interface SearchOptions {
450
482
  min_score?: number;
451
483
  /** Leave out the work sessions (`kind: "session"`) and what only they stated (Korely Agent 0.1.42). */
452
484
  exclude_sessions?: boolean;
485
+ /**
486
+ * What to search, each kind once: `["memories"]` (what the server searches
487
+ * when it is not sent), `["facts"]`, the facts true now, or both, each kind
488
+ * ranked by its own score and the rankings merged by rank (a fact's score
489
+ * and a memory's are not to be compared). Every result then says its
490
+ * `type`, and a fact's carries `fact`. `run_id`, `metadata` and `min_score`
491
+ * narrow the memories only: with `"facts"` the server answers 422. Sent
492
+ * only when given: Korely 1.0.13 and later; an older server answers 422.
493
+ */
494
+ types?: SearchKind[];
495
+ /**
496
+ * Also return each result's whole text as `content`; `snippet` stays its
497
+ * first 280 characters. A memory can hold 16,000 characters. Sent only
498
+ * when true: Korely 1.0.13 and later; an older server answers 422.
499
+ */
500
+ full_text?: boolean;
453
501
  }
454
502
  interface ListOptions {
455
503
  user_id?: string;
@@ -559,6 +607,7 @@ interface GetContextOptions {
559
607
  query: string;
560
608
  user_id?: string;
561
609
  agent_id?: string;
610
+ /** 50 to 8000 tokens. Default 1500, the API's default since Korely 1.0.35. */
562
611
  token_budget?: number;
563
612
  /**
564
613
  * ISO date: the block as the store could have built it then, the facts it
@@ -580,7 +629,7 @@ interface ForgetReceipt {
580
629
 
581
630
  /** Must equal `version` in package.json (a test checks). It goes out in the
582
631
  * X-Korely-Client header, and said 0.1.1 from 0.1.1 to 0.1.6. */
583
- declare const VERSION = "0.2.0";
632
+ declare const VERSION = "0.2.2";
584
633
  interface KorelyOptions {
585
634
  /** Your `kor_live_...` key. Falls back to the KORELY_API_KEY env var. */
586
635
  apiKey?: string;
@@ -603,6 +652,16 @@ interface KorelyOptions {
603
652
  * label no agent cap counts. Left out, the header names this library.
604
653
  */
605
654
  client?: string;
655
+ /**
656
+ * A write (`add`, `batch`) whose answer never came, a timeout or a
657
+ * connection that failed, is sent once more, after half a second, with the
658
+ * same Idempotency-Key, which Korely 1.0.27 and later make once. Default
659
+ * true; false sends every write once. A retry that does not succeed (no
660
+ * answer again, a 5xx, a 429) leaves it unconfirmed. Either way a write left
661
+ * unconfirmed rejects with a KorelyError `write_not_confirmed` that names
662
+ * the key.
663
+ */
664
+ retryWrites?: boolean;
606
665
  }
607
666
  /** Where and how `Korely.initAgent()` signs up: the client options a call
608
667
  * without a key can use. */
@@ -619,16 +678,21 @@ declare class Korely {
619
678
  readonly baseUrl: string;
620
679
  readonly timeoutMs: number;
621
680
  readonly client?: string;
681
+ /** Whether a write that got no answer is sent once more with its key. */
682
+ readonly retryWrites: boolean;
622
683
  private readonly fetchImpl;
623
684
  constructor(opts?: KorelyOptions);
624
685
  /**
625
- * POST /v1/agents/init, with no key: sign up for a free hobby key.
686
+ * POST /v1/agents/init, with no key: sign up for a key that costs nothing.
626
687
  *
627
688
  * The one call that runs without a key, because it is how one is obtained,
628
689
  * so it is static: `await Korely.initAgent("my-app")`, then
629
690
  * `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
630
691
  * label of who signed up, kept for your reference. The answer carries the
631
- * key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
692
+ * key, shown once (save it), when it stops working (`expires_at`), the
693
+ * trial in words (`note`: its limits until the account is adopted, and how
694
+ * to adopt it), its `tier`, `region`, `scopes` and `quotas` (the monthly
695
+ * numbers once adopted).
632
696
  * The account it creates has no login: the key is the account, and
633
697
  * `deleteAccount({ confirm: "<the account's id>" })` closes it.
634
698
  *
@@ -641,6 +705,20 @@ declare class Korely {
641
705
  */
642
706
  static initAgent(agentCaller?: string, opts?: InitAgentOptions): Promise<AgentInitResult>;
643
707
  private request;
708
+ /**
709
+ * POST a write that creates (`add`, `batch`) with an Idempotency-Key: the
710
+ * caller's, else one made here, the same on both tries. A try with no
711
+ * answer (`connection_error`) may have been made, so it is sent once more
712
+ * after WRITE_RETRY_DELAY_MS, unless `retryWrites` is false. Only a
713
+ * success of the retry tells what became of the first try: anything else it
714
+ * meets (no answer, a 409 `idempotency_key_in_use` for a first try still
715
+ * being made, a 5xx, a 429) leaves the write unconfirmed, as does a first
716
+ * try with no answer and no retry. That rejects with KorelyError
717
+ * `write_not_confirmed`, naming the key and the cause. Never a third try,
718
+ * never a first try the server answered, never a read. `how` is how a
719
+ * caller reads to look for it, for the message.
720
+ */
721
+ private write;
644
722
  /**
645
723
  * GET /v1/ping: does this key work, and what may it do? Both products answer
646
724
  * it, with the same shape.
@@ -745,9 +823,11 @@ declare class Korely {
745
823
  add(content: string | Message[], opts?: AddOptions): Promise<Memory>;
746
824
  /**
747
825
  * POST /v1/memories/search: semantic search over raw memories, ranked by
748
- * score (vector similarity to the query). `run_id` scopes to one session,
749
- * `metadata` filters on what you stored at write time. `limit` defaults to
750
- * the server default (15), max 50.
826
+ * score (vector similarity to the query); with `types`, over the facts too,
827
+ * or the facts only. `run_id` scopes to one session, `metadata` filters on
828
+ * what you stored at write time. `limit` defaults to the server default
829
+ * (15), max 50. `full_text: true` adds each result's whole text as
830
+ * `content`.
751
831
  */
752
832
  search(query: string, opts?: SearchOptions): Promise<SearchHit[]>;
753
833
  /**
@@ -936,7 +1016,9 @@ declare class Korely {
936
1016
  * `too_many_batches` (TooManyBatchesError) while three batches are still
937
1017
  * being imported. The Self-hosted meters nothing and refuses neither.
938
1018
  */
939
- batch(memories: Array<BatchMemory | Record<string, unknown>>): Promise<BatchJob>;
1019
+ batch(memories: Array<BatchMemory | Record<string, unknown>>, opts?: {
1020
+ idempotency_key?: string;
1021
+ }): Promise<BatchJob>;
940
1022
  /** GET /v1/batch/:id: poll an import job. */
941
1023
  batchStatus(jobId: string): Promise<BatchJob>;
942
1024
  }
@@ -954,7 +1036,8 @@ declare class Korely {
954
1036
  *
955
1037
  * A KorelyError that is not an APIError never reached the server, or got no
956
1038
  * usable answer: no API key, a key and address that do not belong together,
957
- * a connection error or a timeout.
1039
+ * a connection error or a timeout (code `connection_error`; a write left
1040
+ * unconfirmed after its retry is `write_not_confirmed`, see `add()`).
958
1041
  */
959
1042
  interface KorelyErrorOptions {
960
1043
  status?: number;
@@ -1085,4 +1168,4 @@ declare class TooManyBatchesError extends QuotaExceededError {
1085
1168
  constructor(message?: string, opts?: QuotaErrorOptions);
1086
1169
  }
1087
1170
 
1088
- export { APIError, type AccountDeleteReceipt, type AddFactTripleOptions, type AddOptions, type AgentDeleteReceipt, type AgentInitResult, type AgentScope, type AgentsPage, type AuditAction, type AuditActor, type AuditEvent, type AuditOptions, type AuditPage, type AuditRead, AuthenticationError, type BatchJob, type BatchMemory, type BulkReceipt, ConflictError, type Context, type DeclareNameOptions, type DeclaredName, type DeleteReceipt, type EventsOptions, type EventsResponse, type Fact, type FactList, type ForgetReceipt, type GetContextOptions, type GetFactsOptions, type GetProfileOptions, type HistoryEvent, type HistoryEventType, type InitAgentOptions, type IterAuditOptions, Korely, KorelyError, type KorelyOptions, type ListAgentsOptions, type ListOptions, type Memory, type MemoryEvent, type MemoryHistory, type MemoryPage, type Message, NamespaceForbiddenError, NotFoundError, type PingResponse, type Profile, QuotaExceededError, type SearchHit, type SearchOptions, StaleWriteError, TooManyBatchesError, type UpdateOptions, type UserScope, type UsersOptions, type UsersPage, VERSION };
1171
+ export { APIError, type AccountDeleteReceipt, type AddFactTripleOptions, type AddOptions, type AgentDeleteReceipt, type AgentInitResult, type AgentScope, type AgentsPage, type AuditAction, type AuditActor, type AuditEvent, type AuditOptions, type AuditPage, type AuditRead, AuthenticationError, type BatchJob, type BatchMemory, type BulkReceipt, ConflictError, type Context, type DeclareNameOptions, type DeclaredName, type DeleteReceipt, type EventsOptions, type EventsResponse, type Fact, type FactList, type ForgetReceipt, type GetContextOptions, type GetFactsOptions, type GetProfileOptions, type HistoryEvent, type HistoryEventType, type InitAgentOptions, type IterAuditOptions, Korely, KorelyError, type KorelyOptions, type ListAgentsOptions, type ListOptions, type Memory, type MemoryEvent, type MemoryHistory, type MemoryPage, type Message, NamespaceForbiddenError, NotFoundError, type PingResponse, type Profile, QuotaExceededError, type SearchHit, type SearchKind, type SearchOptions, StaleWriteError, TooManyBatchesError, type UpdateOptions, type UserScope, type UsersOptions, type UsersPage, VERSION };
package/dist/index.js CHANGED
@@ -10,8 +10,8 @@ import {
10
10
  StaleWriteError,
11
11
  TooManyBatchesError,
12
12
  VERSION
13
- } from "./chunk-VT7GXOPS.js";
14
- import "./chunk-6SD5RRK3.js";
13
+ } from "./chunk-UW36NLA6.js";
14
+ import "./chunk-EQTA322A.js";
15
15
  export {
16
16
  APIError,
17
17
  AuthenticationError,
@@ -127,13 +127,48 @@ function unknownOption(method, opts, known) {
127
127
  }
128
128
  return void 0;
129
129
  }
130
+ var DEFAULT_TOKEN_BUDGET = 1500;
130
131
 
131
132
  // src/client.ts
132
- var VERSION = "0.2.0";
133
+ var VERSION = "0.2.2";
133
134
  var REGIONS = { eu: "https://api.korely.ai" };
134
- var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch", "client");
135
+ var CLIENT_KEYS = keysOf()(
136
+ "apiKey",
137
+ "region",
138
+ "baseUrl",
139
+ "timeoutMs",
140
+ "fetch",
141
+ "client",
142
+ "retryWrites"
143
+ );
135
144
  var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
136
- var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp", "kind");
145
+ var ADD_KEYS = keysOf()(
146
+ "agent_id",
147
+ "user_id",
148
+ "run_id",
149
+ "metadata",
150
+ "timestamp",
151
+ "kind",
152
+ "idempotency_key"
153
+ );
154
+ var WRITE_RETRY_DELAY_MS = 500;
155
+ function newIdempotencyKey() {
156
+ const c = globalThis.crypto;
157
+ if (c?.randomUUID) return c.randomUUID().replace(/-/g, "");
158
+ const bytes = new Uint8Array(16);
159
+ if (c?.getRandomValues) c.getRandomValues(bytes);
160
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
161
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
162
+ }
163
+ function idempotencyHeader(key) {
164
+ if (key === void 0) return void 0;
165
+ if (typeof key !== "string" || !/^[\x20-\x7e]{1,255}$/.test(key)) {
166
+ throw new KorelyError(
167
+ "idempotency_key must be 1 to 255 printable ASCII characters (space to ~), one per write: a UUID will do."
168
+ );
169
+ }
170
+ return { "Idempotency-Key": `"${key.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` };
171
+ }
137
172
  var SEARCH_KEYS = keysOf()(
138
173
  "user_id",
139
174
  "agent_id",
@@ -141,7 +176,9 @@ var SEARCH_KEYS = keysOf()(
141
176
  "metadata",
142
177
  "limit",
143
178
  "min_score",
144
- "exclude_sessions"
179
+ "exclude_sessions",
180
+ "types",
181
+ "full_text"
145
182
  );
146
183
  var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset", "exclude_sessions");
147
184
  var NAME_KEYS = keysOf()("user_id", "agent_id");
@@ -359,6 +396,7 @@ async function exchange(t, method, path, opts = {}) {
359
396
  body = JSON.stringify(opts.body);
360
397
  headers["Content-Type"] = "application/json";
361
398
  }
399
+ Object.assign(headers, opts.headers);
362
400
  const controller = new AbortController();
363
401
  let timedOut = false;
364
402
  const timer = setTimeout(() => {
@@ -366,7 +404,8 @@ async function exchange(t, method, path, opts = {}) {
366
404
  controller.abort();
367
405
  }, t.timeoutMs);
368
406
  const failed = (e) => new KorelyError(
369
- timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
407
+ timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`,
408
+ { code: "connection_error" }
370
409
  );
371
410
  let resp;
372
411
  let text2;
@@ -464,17 +503,33 @@ function useNodeFiles(files) {
464
503
  }
465
504
  function savedConfig() {
466
505
  try {
467
- const proc = typeof process !== "undefined" ? process : void 0;
468
- if (!proc?.versions?.node) return {};
469
- const files = nodeFiles ?? lookedUp(proc);
470
- if (!files) return {};
471
- const home = proc.env?.KORELY_CONFIG_HOME || files.join(files.homedir(), ".korely");
472
- const data = JSON.parse(files.readFileSync(files.join(home, "config.json"), "utf8"));
506
+ const at = configFile();
507
+ if (!at) return {};
508
+ const data = JSON.parse(at.files.readFileSync(at.path, "utf8"));
473
509
  return data && typeof data === "object" ? data : {};
474
510
  } catch {
475
511
  return {};
476
512
  }
477
513
  }
514
+ function configFile() {
515
+ const proc = typeof process !== "undefined" ? process : void 0;
516
+ if (!proc?.versions?.node) return void 0;
517
+ const files = nodeFiles ?? lookedUp(proc);
518
+ if (!files) return void 0;
519
+ const home = proc.env?.KORELY_CONFIG_HOME || files.join(files.homedir(), ".korely");
520
+ return { files, path: files.join(home, "config.json") };
521
+ }
522
+ function noKey() {
523
+ let file;
524
+ try {
525
+ file = configFile()?.path;
526
+ } catch {
527
+ file = void 0;
528
+ }
529
+ return new KorelyError(
530
+ `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}.` : "")
531
+ );
532
+ }
478
533
  function lookedUp(proc) {
479
534
  const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof require === "function" ? require(id) : void 0;
480
535
  const fs = builtin("node:fs");
@@ -494,9 +549,7 @@ var Korely = class {
494
549
  const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
495
550
  const key = opts.apiKey ?? envKey ?? text(saved.api_key);
496
551
  if (!key) {
497
- throw new KorelyError(
498
- "No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
499
- );
552
+ throw noKey();
500
553
  }
501
554
  this.apiKey = key;
502
555
  const envClient = typeof process !== "undefined" ? process.env?.KORELY_CLIENT : void 0;
@@ -504,6 +557,7 @@ var Korely = class {
504
557
  this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
505
558
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
506
559
  this.timeoutMs = opts.timeoutMs ?? 3e4;
560
+ this.retryWrites = opts.retryWrites ?? true;
507
561
  const f = opts.fetch ?? globalThis.fetch;
508
562
  if (!f) {
509
563
  throw new KorelyError(
@@ -513,13 +567,16 @@ var Korely = class {
513
567
  this.fetchImpl = f;
514
568
  }
515
569
  /**
516
- * POST /v1/agents/init, with no key: sign up for a free hobby key.
570
+ * POST /v1/agents/init, with no key: sign up for a key that costs nothing.
517
571
  *
518
572
  * The one call that runs without a key, because it is how one is obtained,
519
573
  * so it is static: `await Korely.initAgent("my-app")`, then
520
574
  * `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
521
575
  * label of who signed up, kept for your reference. The answer carries the
522
- * key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
576
+ * key, shown once (save it), when it stops working (`expires_at`), the
577
+ * trial in words (`note`: its limits until the account is adopted, and how
578
+ * to adopt it), its `tier`, `region`, `scopes` and `quotas` (the monthly
579
+ * numbers once adopted).
523
580
  * The account it creates has no login: the key is the account, and
524
581
  * `deleteAccount({ confirm: "<the account's id>" })` closes it.
525
582
  *
@@ -573,6 +630,40 @@ var Korely = class {
573
630
  opts
574
631
  );
575
632
  }
633
+ /**
634
+ * POST a write that creates (`add`, `batch`) with an Idempotency-Key: the
635
+ * caller's, else one made here, the same on both tries. A try with no
636
+ * answer (`connection_error`) may have been made, so it is sent once more
637
+ * after WRITE_RETRY_DELAY_MS, unless `retryWrites` is false. Only a
638
+ * success of the retry tells what became of the first try: anything else it
639
+ * meets (no answer, a 409 `idempotency_key_in_use` for a first try still
640
+ * being made, a 5xx, a 429) leaves the write unconfirmed, as does a first
641
+ * try with no answer and no retry. That rejects with KorelyError
642
+ * `write_not_confirmed`, naming the key and the cause. Never a third try,
643
+ * never a first try the server answered, never a read. `how` is how a
644
+ * caller reads to look for it, for the message.
645
+ */
646
+ async write(path, body, given, how) {
647
+ const key = given ?? newIdempotencyKey();
648
+ const headers = idempotencyHeader(key);
649
+ const tries = this.retryWrites ? 2 : 1;
650
+ const failed = [];
651
+ for (let attempt = 0; attempt < tries; attempt++) {
652
+ if (attempt) await new Promise((resolve) => setTimeout(resolve, WRITE_RETRY_DELAY_MS));
653
+ try {
654
+ return await this.request("POST", path, { body, headers });
655
+ } catch (e) {
656
+ if (!(e instanceof KorelyError) || attempt === 0 && e.code !== "connection_error") throw e;
657
+ failed.push(e);
658
+ }
659
+ }
660
+ const causes = failed.map((e) => e.status ? `${e.message} (HTTP ${e.status})` : e.message);
661
+ const what = tries > 1 ? causes.join("; the retry with the same key: ") : `${causes[0]} (sent once: retryWrites is false)`;
662
+ throw new KorelyError(
663
+ `POST ${path} was not confirmed: ${what}. The write may have been made. Send it again with the same Idempotency-Key, ${key}: Korely 1.0.27 and later make it at most once within 24 hours. Or look for it first (${how}).`,
664
+ { code: "write_not_confirmed" }
665
+ );
666
+ }
576
667
  // ── the key and its account ───────────────────────────────────────────────
577
668
  /**
578
669
  * GET /v1/ping: does this key work, and what may it do? Both products answer
@@ -775,23 +866,23 @@ var Korely = class {
775
866
  "content is empty: pass a non-blank string or messages with content."
776
867
  );
777
868
  }
778
- return this.request("POST", "/v1/memories", {
779
- body: {
780
- content: text2,
781
- agent_id: opts.agent_id,
782
- user_id: opts.user_id,
783
- run_id: opts.run_id,
784
- metadata: opts.metadata,
785
- timestamp: opts.timestamp,
786
- kind: opts.kind
787
- }
788
- });
869
+ return this.write("/v1/memories", {
870
+ content: text2,
871
+ agent_id: opts.agent_id,
872
+ user_id: opts.user_id,
873
+ run_id: opts.run_id,
874
+ metadata: opts.metadata,
875
+ timestamp: opts.timestamp,
876
+ kind: opts.kind
877
+ }, opts.idempotency_key, "getAll() or search()");
789
878
  }
790
879
  /**
791
880
  * POST /v1/memories/search: semantic search over raw memories, ranked by
792
- * score (vector similarity to the query). `run_id` scopes to one session,
793
- * `metadata` filters on what you stored at write time. `limit` defaults to
794
- * the server default (15), max 50.
881
+ * score (vector similarity to the query); with `types`, over the facts too,
882
+ * or the facts only. `run_id` scopes to one session, `metadata` filters on
883
+ * what you stored at write time. `limit` defaults to the server default
884
+ * (15), max 50. `full_text: true` adds each result's whole text as
885
+ * `content`.
795
886
  */
796
887
  async search(query, opts = {}) {
797
888
  checkOptions("search", opts, SEARCH_KEYS);
@@ -805,7 +896,10 @@ var Korely = class {
805
896
  limit: opts.limit,
806
897
  min_score: opts.min_score,
807
898
  // Sent only when true: an older server does not know the field.
808
- exclude_sessions: opts.exclude_sessions ? true : void 0
899
+ exclude_sessions: opts.exclude_sessions ? true : void 0,
900
+ // Sent only when given, as `min_score`: Korely 1.0.13 and later.
901
+ types: opts.types,
902
+ full_text: opts.full_text ? true : void 0
809
903
  }
810
904
  });
811
905
  return body.results ?? [];
@@ -1104,7 +1198,7 @@ var Korely = class {
1104
1198
  query: o.query,
1105
1199
  user_id: o.user_id,
1106
1200
  agent_id: o.agent_id,
1107
- token_budget: o.token_budget ?? 800,
1201
+ token_budget: o.token_budget ?? DEFAULT_TOKEN_BUDGET,
1108
1202
  known_as_of: o.known_as_of,
1109
1203
  exclude_sessions: o.exclude_sessions ? "true" : void 0
1110
1204
  }
@@ -1158,8 +1252,8 @@ var Korely = class {
1158
1252
  * `too_many_batches` (TooManyBatchesError) while three batches are still
1159
1253
  * being imported. The Self-hosted meters nothing and refuses neither.
1160
1254
  */
1161
- async batch(memories) {
1162
- return this.request("POST", "/v1/batch", { body: { memories } });
1255
+ async batch(memories, opts = {}) {
1256
+ return this.write("/v1/batch", { memories }, opts.idempotency_key, "getAll() once the import has run");
1163
1257
  }
1164
1258
  /** GET /v1/batch/:id: poll an import job. */
1165
1259
  async batchStatus(jobId) {
@@ -11,8 +11,8 @@ import {
11
11
  TooManyBatchesError,
12
12
  VERSION,
13
13
  useNodeFiles
14
- } from "./chunk-VT7GXOPS.js";
15
- import "./chunk-6SD5RRK3.js";
14
+ } from "./chunk-UW36NLA6.js";
15
+ import "./chunk-EQTA322A.js";
16
16
 
17
17
  // src/node.ts
18
18
  import { readFileSync } from "fs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "korely-memory",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "JavaScript / TypeScript SDK for Korely Agents: memory for AI agents with bi-temporal typed facts.",
5
5
  "keywords": [
6
6
  "ai",