korely-memory 0.2.1 → 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/README.md CHANGED
@@ -76,7 +76,7 @@ than `contextTimeoutMs` (5 s) to answer, the call goes on without memory,
76
76
  `onError` is told, and an answer that arrives later is dropped.
77
77
 
78
78
  Options: `userId` (required), `agentId`, `runId`, `client` (a configured
79
- `Korely`, default `new Korely()`), `tokenBudget` (800), `contextTimeoutMs`
79
+ `Korely`, default `new Korely()`), `tokenBudget` (1500, the API's own default), `contextTimeoutMs`
80
80
  (5000; 0 waits for the client's own 30 s), `includeDate` (true), `timeZone`
81
81
  ("UTC"), `remember` (true), `waitUntil`, `onError`.
82
82
 
@@ -94,7 +94,7 @@ Every method maps to one REST endpoint.
94
94
 
95
95
  | Method | Endpoint | |
96
96
  |---|---|---|
97
- | `add(content, opts?)` | `POST /v1/memories` | Write. `content` is a string or a list of chat messages. `opts.user_id` or `opts.agent_id` says whose memory it is (Korely 1.0.19 and later refuse neither). `opts.timestamp` (ISO) backfills the past: facts inherit it as `valid_from`. With `opts.idempotency_key`, the same write sent again with the same key is made once (Korely 1.0.27 and later; an older server ignores it): one new key per write, the same one only to send that write again. The client never retries by itself. |
97
+ | `add(content, opts?)` | `POST /v1/memories` | Write. `content` is a string or a list of chat messages. `opts.user_id` or `opts.agent_id` says whose memory it is (Korely 1.0.19 and later refuse neither). `opts.timestamp` (ISO) backfills the past: facts inherit it as `valid_from`. Every write carries an `Idempotency-Key` (`opts.idempotency_key`, else a new one), and one whose answer never came (a timeout, a failed connection) is sent once more with it, made once by Korely 1.0.27 and later (an older server ignores the key). No answer twice rejects with `KorelyError` `write_not_confirmed`, naming the key; `new Korely({ retryWrites: false })` sends once. |
98
98
  | `search(query, opts?)` | `POST /v1/memories/search` | Semantic search over memories; filter by `user_id`, `agent_id`, `run_id`, `metadata`; `min_score` (0 to 1) leaves out hits scored below it. `types: ["memories", "facts"]` searches the facts true now too (`["facts"]` them only), and each hit says its `type`, a fact's with its `fact`; `full_text: true` adds the whole text as `content` (`snippet` is its first 280 characters). Korely 1.0.13 and later; sent only when given. |
99
99
  | `getAll(opts?)` | `GET /v1/memories` | List a scope, newest first. The page is iterable; `limit` up to 200. |
100
100
  | `get(id)` | `GET /v1/memories/:id` | One memory, with its facts. |
@@ -147,7 +147,8 @@ and the `message` of the REST error envelope (`{code, message}`; a self-hosted
147
147
  install that answers FastAPI's `detail` is read the same way). The common
148
148
  statuses also have their own subclass.
149
149
  Everything subclasses `KorelyError`, which is also what a client-side problem
150
- throws (no key, a connection error, a timeout).
150
+ throws (no key, a connection error or a timeout, with `code === "connection_error"`,
151
+ and a write left unconfirmed after its retry, `write_not_confirmed`).
151
152
 
152
153
  ```ts
153
154
  import { Korely, APIError, QuotaExceededError } from "korely-memory";
@@ -179,7 +180,8 @@ of all of these, and everything else: 422, 503; a write that names neither
179
180
  later, and this client sends only the ids each call names). Every `APIError` has
180
181
  `retryAfter` when the server sent `Retry-After`: a rate limit, and the Cloud's
181
182
  503 `writes_paused` (writes that need a model are paused until 00:00 UTC). The
182
- SDK does not retry on its own.
183
+ SDK does not retry these: its one retry is of a write that got no answer at
184
+ all (see `add()`).
183
185
 
184
186
  A call that is not a `GET` (`add`, `update`, `delete`...) is never redirected:
185
187
  a 3xx rejects with an `APIError` of that status, its message naming the origin
@@ -194,6 +196,7 @@ new Korely({
194
196
  apiKey: "kor_live_...", // or the KORELY_API_KEY env var
195
197
  region: "eu", // the API, api.korely.ai: data stored in the EU
196
198
  timeoutMs: 30000, // covers the whole request, response body included
199
+ retryWrites: true, // a write with no answer is sent once more, same key
197
200
  });
198
201
  ```
199
202
 
package/dist/ai-sdk.cjs CHANGED
@@ -46,13 +46,13 @@ function unknownOption(method, opts, known) {
46
46
  }
47
47
  return void 0;
48
48
  }
49
+ var DEFAULT_TOKEN_BUDGET = 1500;
49
50
 
50
51
  // src/ai-sdk.ts
51
52
  var QUERY_MAX = 2e3;
52
53
  var CONTENT_MAX = 16e3;
53
54
  var USER_MAX = 6e3;
54
55
  var TURN_OVERHEAD = 18;
55
- var DEFAULT_TOKEN_BUDGET = 800;
56
56
  var CONTEXT_REUSE_MS = 5 * 6e4;
57
57
  var FAILURE_REUSE_MS = 3e4;
58
58
  var DEFAULT_CONTEXT_TIMEOUT_MS = 5e3;
package/dist/ai-sdk.d.cts CHANGED
@@ -47,7 +47,7 @@ interface KorelyToolsOptions {
47
47
  runId?: string;
48
48
  /** The client to use. Default: `new Korely()`, configured from the environment (KORELY_API_KEY, KORELY_BASE_URL). */
49
49
  client?: Korely;
50
- /** Token budget of the context block (`token_budget`). Default 800, the API's default. */
50
+ /** Token budget of the context block (`token_budget`). Default 1500, the API's default since Korely 1.0.35. */
51
51
  tokenBudget?: number;
52
52
  /** Add a "Current date: YYYY-MM-DD" line. Default true: the reader answers better when its prompt carries the date. */
53
53
  includeDate?: boolean;
package/dist/ai-sdk.d.ts CHANGED
@@ -47,7 +47,7 @@ interface KorelyToolsOptions {
47
47
  runId?: string;
48
48
  /** The client to use. Default: `new Korely()`, configured from the environment (KORELY_API_KEY, KORELY_BASE_URL). */
49
49
  client?: Korely;
50
- /** Token budget of the context block (`token_budget`). Default 800, the API's default. */
50
+ /** Token budget of the context block (`token_budget`). Default 1500, the API's default since Korely 1.0.35. */
51
51
  tokenBudget?: number;
52
52
  /** Add a "Current date: YYYY-MM-DD" line. Default true: the reader answers better when its prompt carries the date. */
53
53
  includeDate?: boolean;
package/dist/ai-sdk.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
+ DEFAULT_TOKEN_BUDGET,
2
3
  keysOf,
3
4
  unknownOption
4
- } from "./chunk-6SD5RRK3.js";
5
+ } from "./chunk-EQTA322A.js";
5
6
 
6
7
  // src/ai-sdk.ts
7
8
  import { gateway, jsonSchema, tool, wrapLanguageModel } from "ai";
@@ -10,7 +11,6 @@ var QUERY_MAX = 2e3;
10
11
  var CONTENT_MAX = 16e3;
11
12
  var USER_MAX = 6e3;
12
13
  var TURN_OVERHEAD = 18;
13
- var DEFAULT_TOKEN_BUDGET = 800;
14
14
  var CONTEXT_REUSE_MS = 5 * 6e4;
15
15
  var FAILURE_REUSE_MS = 3e4;
16
16
  var DEFAULT_CONTEXT_TIMEOUT_MS = 5e3;
@@ -23,9 +23,11 @@ function unknownOption(method, opts, known) {
23
23
  }
24
24
  return void 0;
25
25
  }
26
+ var DEFAULT_TOKEN_BUDGET = 1500;
26
27
 
27
28
  export {
28
29
  __require,
29
30
  keysOf,
30
- unknownOption
31
+ unknownOption,
32
+ DEFAULT_TOKEN_BUDGET
31
33
  };
@@ -1,8 +1,9 @@
1
1
  import {
2
+ DEFAULT_TOKEN_BUDGET,
2
3
  __require,
3
4
  keysOf,
4
5
  unknownOption
5
- } from "./chunk-6SD5RRK3.js";
6
+ } from "./chunk-EQTA322A.js";
6
7
 
7
8
  // src/errors.ts
8
9
  var KorelyError = class extends Error {
@@ -77,9 +78,17 @@ var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError
77
78
  };
78
79
 
79
80
  // src/client.ts
80
- var VERSION = "0.2.1";
81
+ var VERSION = "0.2.2";
81
82
  var REGIONS = { eu: "https://api.korely.ai" };
82
- var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch", "client");
83
+ var CLIENT_KEYS = keysOf()(
84
+ "apiKey",
85
+ "region",
86
+ "baseUrl",
87
+ "timeoutMs",
88
+ "fetch",
89
+ "client",
90
+ "retryWrites"
91
+ );
83
92
  var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
84
93
  var ADD_KEYS = keysOf()(
85
94
  "agent_id",
@@ -90,6 +99,15 @@ var ADD_KEYS = keysOf()(
90
99
  "kind",
91
100
  "idempotency_key"
92
101
  );
102
+ var WRITE_RETRY_DELAY_MS = 500;
103
+ function newIdempotencyKey() {
104
+ const c = globalThis.crypto;
105
+ if (c?.randomUUID) return c.randomUUID().replace(/-/g, "");
106
+ const bytes = new Uint8Array(16);
107
+ if (c?.getRandomValues) c.getRandomValues(bytes);
108
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
109
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
110
+ }
93
111
  function idempotencyHeader(key) {
94
112
  if (key === void 0) return void 0;
95
113
  if (typeof key !== "string" || !/^[\x20-\x7e]{1,255}$/.test(key)) {
@@ -334,7 +352,8 @@ async function exchange(t, method, path, opts = {}) {
334
352
  controller.abort();
335
353
  }, t.timeoutMs);
336
354
  const failed = (e) => new KorelyError(
337
- timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
355
+ timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`,
356
+ { code: "connection_error" }
338
357
  );
339
358
  let resp;
340
359
  let text2;
@@ -486,6 +505,7 @@ var Korely = class {
486
505
  this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
487
506
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
488
507
  this.timeoutMs = opts.timeoutMs ?? 3e4;
508
+ this.retryWrites = opts.retryWrites ?? true;
489
509
  const f = opts.fetch ?? globalThis.fetch;
490
510
  if (!f) {
491
511
  throw new KorelyError(
@@ -558,6 +578,40 @@ var Korely = class {
558
578
  opts
559
579
  );
560
580
  }
581
+ /**
582
+ * POST a write that creates (`add`, `batch`) with an Idempotency-Key: the
583
+ * caller's, else one made here, the same on both tries. A try with no
584
+ * answer (`connection_error`) may have been made, so it is sent once more
585
+ * after WRITE_RETRY_DELAY_MS, unless `retryWrites` is false. Only a
586
+ * success of the retry tells what became of the first try: anything else it
587
+ * meets (no answer, a 409 `idempotency_key_in_use` for a first try still
588
+ * being made, a 5xx, a 429) leaves the write unconfirmed, as does a first
589
+ * try with no answer and no retry. That rejects with KorelyError
590
+ * `write_not_confirmed`, naming the key and the cause. Never a third try,
591
+ * never a first try the server answered, never a read. `how` is how a
592
+ * caller reads to look for it, for the message.
593
+ */
594
+ async write(path, body, given, how) {
595
+ const key = given ?? newIdempotencyKey();
596
+ const headers = idempotencyHeader(key);
597
+ const tries = this.retryWrites ? 2 : 1;
598
+ const failed = [];
599
+ for (let attempt = 0; attempt < tries; attempt++) {
600
+ if (attempt) await new Promise((resolve) => setTimeout(resolve, WRITE_RETRY_DELAY_MS));
601
+ try {
602
+ return await this.request("POST", path, { body, headers });
603
+ } catch (e) {
604
+ if (!(e instanceof KorelyError) || attempt === 0 && e.code !== "connection_error") throw e;
605
+ failed.push(e);
606
+ }
607
+ }
608
+ const causes = failed.map((e) => e.status ? `${e.message} (HTTP ${e.status})` : e.message);
609
+ const what = tries > 1 ? causes.join("; the retry with the same key: ") : `${causes[0]} (sent once: retryWrites is false)`;
610
+ throw new KorelyError(
611
+ `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}).`,
612
+ { code: "write_not_confirmed" }
613
+ );
614
+ }
561
615
  // ── the key and its account ───────────────────────────────────────────────
562
616
  /**
563
617
  * GET /v1/ping: does this key work, and what may it do? Both products answer
@@ -760,18 +814,15 @@ var Korely = class {
760
814
  "content is empty: pass a non-blank string or messages with content."
761
815
  );
762
816
  }
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
- });
817
+ return this.write("/v1/memories", {
818
+ content: text2,
819
+ agent_id: opts.agent_id,
820
+ user_id: opts.user_id,
821
+ run_id: opts.run_id,
822
+ metadata: opts.metadata,
823
+ timestamp: opts.timestamp,
824
+ kind: opts.kind
825
+ }, opts.idempotency_key, "getAll() or search()");
775
826
  }
776
827
  /**
777
828
  * POST /v1/memories/search: semantic search over raw memories, ranked by
@@ -1095,7 +1146,7 @@ var Korely = class {
1095
1146
  query: o.query,
1096
1147
  user_id: o.user_id,
1097
1148
  agent_id: o.agent_id,
1098
- token_budget: o.token_budget ?? 800,
1149
+ token_budget: o.token_budget ?? DEFAULT_TOKEN_BUDGET,
1099
1150
  known_as_of: o.known_as_of,
1100
1151
  exclude_sessions: o.exclude_sessions ? "true" : void 0
1101
1152
  }
@@ -1150,10 +1201,7 @@ var Korely = class {
1150
1201
  * being imported. The Self-hosted meters nothing and refuses neither.
1151
1202
  */
1152
1203
  async batch(memories, opts = {}) {
1153
- return this.request("POST", "/v1/batch", {
1154
- body: { memories },
1155
- headers: idempotencyHeader(opts.idempotency_key)
1156
- });
1204
+ return this.write("/v1/batch", { memories }, opts.idempotency_key, "getAll() once the import has run");
1157
1205
  }
1158
1206
  /** GET /v1/batch/:id: poll an import job. */
1159
1207
  async batchStatus(jobId) {
package/dist/index.cjs CHANGED
@@ -124,11 +124,20 @@ function unknownOption(method, opts, known) {
124
124
  }
125
125
  return void 0;
126
126
  }
127
+ var DEFAULT_TOKEN_BUDGET = 1500;
127
128
 
128
129
  // src/client.ts
129
- var VERSION = "0.2.1";
130
+ var VERSION = "0.2.2";
130
131
  var REGIONS = { eu: "https://api.korely.ai" };
131
- var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch", "client");
132
+ var CLIENT_KEYS = keysOf()(
133
+ "apiKey",
134
+ "region",
135
+ "baseUrl",
136
+ "timeoutMs",
137
+ "fetch",
138
+ "client",
139
+ "retryWrites"
140
+ );
132
141
  var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
133
142
  var ADD_KEYS = keysOf()(
134
143
  "agent_id",
@@ -139,6 +148,15 @@ var ADD_KEYS = keysOf()(
139
148
  "kind",
140
149
  "idempotency_key"
141
150
  );
151
+ var WRITE_RETRY_DELAY_MS = 500;
152
+ function newIdempotencyKey() {
153
+ const c = globalThis.crypto;
154
+ if (c?.randomUUID) return c.randomUUID().replace(/-/g, "");
155
+ const bytes = new Uint8Array(16);
156
+ if (c?.getRandomValues) c.getRandomValues(bytes);
157
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
158
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
159
+ }
142
160
  function idempotencyHeader(key) {
143
161
  if (key === void 0) return void 0;
144
162
  if (typeof key !== "string" || !/^[\x20-\x7e]{1,255}$/.test(key)) {
@@ -383,7 +401,8 @@ async function exchange(t, method, path, opts = {}) {
383
401
  controller.abort();
384
402
  }, t.timeoutMs);
385
403
  const failed = (e) => new KorelyError(
386
- timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
404
+ timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`,
405
+ { code: "connection_error" }
387
406
  );
388
407
  let resp;
389
408
  let text2;
@@ -532,6 +551,7 @@ var Korely = class {
532
551
  this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
533
552
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
534
553
  this.timeoutMs = opts.timeoutMs ?? 3e4;
554
+ this.retryWrites = opts.retryWrites ?? true;
535
555
  const f = opts.fetch ?? globalThis.fetch;
536
556
  if (!f) {
537
557
  throw new KorelyError(
@@ -604,6 +624,40 @@ var Korely = class {
604
624
  opts
605
625
  );
606
626
  }
627
+ /**
628
+ * POST a write that creates (`add`, `batch`) with an Idempotency-Key: the
629
+ * caller's, else one made here, the same on both tries. A try with no
630
+ * answer (`connection_error`) may have been made, so it is sent once more
631
+ * after WRITE_RETRY_DELAY_MS, unless `retryWrites` is false. Only a
632
+ * success of the retry tells what became of the first try: anything else it
633
+ * meets (no answer, a 409 `idempotency_key_in_use` for a first try still
634
+ * being made, a 5xx, a 429) leaves the write unconfirmed, as does a first
635
+ * try with no answer and no retry. That rejects with KorelyError
636
+ * `write_not_confirmed`, naming the key and the cause. Never a third try,
637
+ * never a first try the server answered, never a read. `how` is how a
638
+ * caller reads to look for it, for the message.
639
+ */
640
+ async write(path, body, given, how) {
641
+ const key = given ?? newIdempotencyKey();
642
+ const headers = idempotencyHeader(key);
643
+ const tries = this.retryWrites ? 2 : 1;
644
+ const failed = [];
645
+ for (let attempt = 0; attempt < tries; attempt++) {
646
+ if (attempt) await new Promise((resolve) => setTimeout(resolve, WRITE_RETRY_DELAY_MS));
647
+ try {
648
+ return await this.request("POST", path, { body, headers });
649
+ } catch (e) {
650
+ if (!(e instanceof KorelyError) || attempt === 0 && e.code !== "connection_error") throw e;
651
+ failed.push(e);
652
+ }
653
+ }
654
+ const causes = failed.map((e) => e.status ? `${e.message} (HTTP ${e.status})` : e.message);
655
+ const what = tries > 1 ? causes.join("; the retry with the same key: ") : `${causes[0]} (sent once: retryWrites is false)`;
656
+ throw new KorelyError(
657
+ `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}).`,
658
+ { code: "write_not_confirmed" }
659
+ );
660
+ }
607
661
  // ── the key and its account ───────────────────────────────────────────────
608
662
  /**
609
663
  * GET /v1/ping: does this key work, and what may it do? Both products answer
@@ -806,18 +860,15 @@ var Korely = class {
806
860
  "content is empty: pass a non-blank string or messages with content."
807
861
  );
808
862
  }
809
- return this.request("POST", "/v1/memories", {
810
- body: {
811
- content: text2,
812
- agent_id: opts.agent_id,
813
- user_id: opts.user_id,
814
- run_id: opts.run_id,
815
- metadata: opts.metadata,
816
- timestamp: opts.timestamp,
817
- kind: opts.kind
818
- },
819
- headers: idempotencyHeader(opts.idempotency_key)
820
- });
863
+ return this.write("/v1/memories", {
864
+ content: text2,
865
+ agent_id: opts.agent_id,
866
+ user_id: opts.user_id,
867
+ run_id: opts.run_id,
868
+ metadata: opts.metadata,
869
+ timestamp: opts.timestamp,
870
+ kind: opts.kind
871
+ }, opts.idempotency_key, "getAll() or search()");
821
872
  }
822
873
  /**
823
874
  * POST /v1/memories/search: semantic search over raw memories, ranked by
@@ -1141,7 +1192,7 @@ var Korely = class {
1141
1192
  query: o.query,
1142
1193
  user_id: o.user_id,
1143
1194
  agent_id: o.agent_id,
1144
- token_budget: o.token_budget ?? 800,
1195
+ token_budget: o.token_budget ?? DEFAULT_TOKEN_BUDGET,
1145
1196
  known_as_of: o.known_as_of,
1146
1197
  exclude_sessions: o.exclude_sessions ? "true" : void 0
1147
1198
  }
@@ -1196,10 +1247,7 @@ var Korely = class {
1196
1247
  * being imported. The Self-hosted meters nothing and refuses neither.
1197
1248
  */
1198
1249
  async batch(memories, opts = {}) {
1199
- return this.request("POST", "/v1/batch", {
1200
- body: { memories },
1201
- headers: idempotencyHeader(opts.idempotency_key)
1202
- });
1250
+ return this.write("/v1/batch", { memories }, opts.idempotency_key, "getAll() once the import has run");
1203
1251
  }
1204
1252
  /** GET /v1/batch/:id: poll an import job. */
1205
1253
  async batchStatus(jobId) {
package/dist/index.d.cts CHANGED
@@ -440,11 +440,14 @@ interface AddOptions {
440
440
  */
441
441
  kind?: "note" | "session";
442
442
  /**
443
- * Send the same write again with the same key and it is made once (Korely
444
- * Agent 1.0.27 and later; an older server ignores it). One new key per
445
- * write, the same one only to send that write again: a write whose answer
446
- * never came (a timeout, a 502 while the server restarted) may have been
447
- * made, and without a key a resend makes it twice.
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.
448
451
  */
449
452
  idempotency_key?: string;
450
453
  }
@@ -604,6 +607,7 @@ interface GetContextOptions {
604
607
  query: string;
605
608
  user_id?: string;
606
609
  agent_id?: string;
610
+ /** 50 to 8000 tokens. Default 1500, the API's default since Korely 1.0.35. */
607
611
  token_budget?: number;
608
612
  /**
609
613
  * ISO date: the block as the store could have built it then, the facts it
@@ -625,7 +629,7 @@ interface ForgetReceipt {
625
629
 
626
630
  /** Must equal `version` in package.json (a test checks). It goes out in the
627
631
  * X-Korely-Client header, and said 0.1.1 from 0.1.1 to 0.1.6. */
628
- declare const VERSION = "0.2.1";
632
+ declare const VERSION = "0.2.2";
629
633
  interface KorelyOptions {
630
634
  /** Your `kor_live_...` key. Falls back to the KORELY_API_KEY env var. */
631
635
  apiKey?: string;
@@ -648,6 +652,16 @@ interface KorelyOptions {
648
652
  * label no agent cap counts. Left out, the header names this library.
649
653
  */
650
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;
651
665
  }
652
666
  /** Where and how `Korely.initAgent()` signs up: the client options a call
653
667
  * without a key can use. */
@@ -664,6 +678,8 @@ declare class Korely {
664
678
  readonly baseUrl: string;
665
679
  readonly timeoutMs: number;
666
680
  readonly client?: string;
681
+ /** Whether a write that got no answer is sent once more with its key. */
682
+ readonly retryWrites: boolean;
667
683
  private readonly fetchImpl;
668
684
  constructor(opts?: KorelyOptions);
669
685
  /**
@@ -689,6 +705,20 @@ declare class Korely {
689
705
  */
690
706
  static initAgent(agentCaller?: string, opts?: InitAgentOptions): Promise<AgentInitResult>;
691
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;
692
722
  /**
693
723
  * GET /v1/ping: does this key work, and what may it do? Both products answer
694
724
  * it, with the same shape.
@@ -1006,7 +1036,8 @@ declare class Korely {
1006
1036
  *
1007
1037
  * A KorelyError that is not an APIError never reached the server, or got no
1008
1038
  * usable answer: no API key, a key and address that do not belong together,
1009
- * 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()`).
1010
1041
  */
1011
1042
  interface KorelyErrorOptions {
1012
1043
  status?: number;
package/dist/index.d.ts CHANGED
@@ -440,11 +440,14 @@ interface AddOptions {
440
440
  */
441
441
  kind?: "note" | "session";
442
442
  /**
443
- * Send the same write again with the same key and it is made once (Korely
444
- * Agent 1.0.27 and later; an older server ignores it). One new key per
445
- * write, the same one only to send that write again: a write whose answer
446
- * never came (a timeout, a 502 while the server restarted) may have been
447
- * made, and without a key a resend makes it twice.
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.
448
451
  */
449
452
  idempotency_key?: string;
450
453
  }
@@ -604,6 +607,7 @@ interface GetContextOptions {
604
607
  query: string;
605
608
  user_id?: string;
606
609
  agent_id?: string;
610
+ /** 50 to 8000 tokens. Default 1500, the API's default since Korely 1.0.35. */
607
611
  token_budget?: number;
608
612
  /**
609
613
  * ISO date: the block as the store could have built it then, the facts it
@@ -625,7 +629,7 @@ interface ForgetReceipt {
625
629
 
626
630
  /** Must equal `version` in package.json (a test checks). It goes out in the
627
631
  * X-Korely-Client header, and said 0.1.1 from 0.1.1 to 0.1.6. */
628
- declare const VERSION = "0.2.1";
632
+ declare const VERSION = "0.2.2";
629
633
  interface KorelyOptions {
630
634
  /** Your `kor_live_...` key. Falls back to the KORELY_API_KEY env var. */
631
635
  apiKey?: string;
@@ -648,6 +652,16 @@ interface KorelyOptions {
648
652
  * label no agent cap counts. Left out, the header names this library.
649
653
  */
650
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;
651
665
  }
652
666
  /** Where and how `Korely.initAgent()` signs up: the client options a call
653
667
  * without a key can use. */
@@ -664,6 +678,8 @@ declare class Korely {
664
678
  readonly baseUrl: string;
665
679
  readonly timeoutMs: number;
666
680
  readonly client?: string;
681
+ /** Whether a write that got no answer is sent once more with its key. */
682
+ readonly retryWrites: boolean;
667
683
  private readonly fetchImpl;
668
684
  constructor(opts?: KorelyOptions);
669
685
  /**
@@ -689,6 +705,20 @@ declare class Korely {
689
705
  */
690
706
  static initAgent(agentCaller?: string, opts?: InitAgentOptions): Promise<AgentInitResult>;
691
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;
692
722
  /**
693
723
  * GET /v1/ping: does this key work, and what may it do? Both products answer
694
724
  * it, with the same shape.
@@ -1006,7 +1036,8 @@ declare class Korely {
1006
1036
  *
1007
1037
  * A KorelyError that is not an APIError never reached the server, or got no
1008
1038
  * usable answer: no API key, a key and address that do not belong together,
1009
- * 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()`).
1010
1041
  */
1011
1042
  interface KorelyErrorOptions {
1012
1043
  status?: number;
package/dist/index.js CHANGED
@@ -10,8 +10,8 @@ import {
10
10
  StaleWriteError,
11
11
  TooManyBatchesError,
12
12
  VERSION
13
- } from "./chunk-MZLXQMBY.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,11 +127,20 @@ 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.1";
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
145
  var ADD_KEYS = keysOf()(
137
146
  "agent_id",
@@ -142,6 +151,15 @@ var ADD_KEYS = keysOf()(
142
151
  "kind",
143
152
  "idempotency_key"
144
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
+ }
145
163
  function idempotencyHeader(key) {
146
164
  if (key === void 0) return void 0;
147
165
  if (typeof key !== "string" || !/^[\x20-\x7e]{1,255}$/.test(key)) {
@@ -386,7 +404,8 @@ async function exchange(t, method, path, opts = {}) {
386
404
  controller.abort();
387
405
  }, t.timeoutMs);
388
406
  const failed = (e) => new KorelyError(
389
- 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" }
390
409
  );
391
410
  let resp;
392
411
  let text2;
@@ -538,6 +557,7 @@ var Korely = class {
538
557
  this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
539
558
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
540
559
  this.timeoutMs = opts.timeoutMs ?? 3e4;
560
+ this.retryWrites = opts.retryWrites ?? true;
541
561
  const f = opts.fetch ?? globalThis.fetch;
542
562
  if (!f) {
543
563
  throw new KorelyError(
@@ -610,6 +630,40 @@ var Korely = class {
610
630
  opts
611
631
  );
612
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
+ }
613
667
  // ── the key and its account ───────────────────────────────────────────────
614
668
  /**
615
669
  * GET /v1/ping: does this key work, and what may it do? Both products answer
@@ -812,18 +866,15 @@ var Korely = class {
812
866
  "content is empty: pass a non-blank string or messages with content."
813
867
  );
814
868
  }
815
- return this.request("POST", "/v1/memories", {
816
- body: {
817
- content: text2,
818
- agent_id: opts.agent_id,
819
- user_id: opts.user_id,
820
- run_id: opts.run_id,
821
- metadata: opts.metadata,
822
- timestamp: opts.timestamp,
823
- kind: opts.kind
824
- },
825
- headers: idempotencyHeader(opts.idempotency_key)
826
- });
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()");
827
878
  }
828
879
  /**
829
880
  * POST /v1/memories/search: semantic search over raw memories, ranked by
@@ -1147,7 +1198,7 @@ var Korely = class {
1147
1198
  query: o.query,
1148
1199
  user_id: o.user_id,
1149
1200
  agent_id: o.agent_id,
1150
- token_budget: o.token_budget ?? 800,
1201
+ token_budget: o.token_budget ?? DEFAULT_TOKEN_BUDGET,
1151
1202
  known_as_of: o.known_as_of,
1152
1203
  exclude_sessions: o.exclude_sessions ? "true" : void 0
1153
1204
  }
@@ -1202,10 +1253,7 @@ var Korely = class {
1202
1253
  * being imported. The Self-hosted meters nothing and refuses neither.
1203
1254
  */
1204
1255
  async batch(memories, opts = {}) {
1205
- return this.request("POST", "/v1/batch", {
1206
- body: { memories },
1207
- headers: idempotencyHeader(opts.idempotency_key)
1208
- });
1256
+ return this.write("/v1/batch", { memories }, opts.idempotency_key, "getAll() once the import has run");
1209
1257
  }
1210
1258
  /** GET /v1/batch/:id: poll an import job. */
1211
1259
  async batchStatus(jobId) {
@@ -11,8 +11,8 @@ import {
11
11
  TooManyBatchesError,
12
12
  VERSION,
13
13
  useNodeFiles
14
- } from "./chunk-MZLXQMBY.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.1",
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",