korely-memory 0.1.9 → 0.1.10

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.js CHANGED
@@ -12,6 +12,7 @@ var APIError = class extends KorelyError {
12
12
  constructor(message = "", opts = {}) {
13
13
  super(message, opts);
14
14
  this.name = "APIError";
15
+ this.retryAfter = opts.retryAfter;
15
16
  Object.setPrototypeOf(this, new.target.prototype);
16
17
  }
17
18
  };
@@ -36,24 +37,37 @@ var NotFoundError = class _NotFoundError extends APIError {
36
37
  Object.setPrototypeOf(this, _NotFoundError.prototype);
37
38
  }
38
39
  };
39
- var StaleWriteError = class _StaleWriteError extends APIError {
40
+ var ConflictError = class extends APIError {
41
+ constructor(message = "", opts = {}) {
42
+ super(message, opts);
43
+ this.name = "ConflictError";
44
+ Object.setPrototypeOf(this, new.target.prototype);
45
+ }
46
+ };
47
+ var StaleWriteError = class _StaleWriteError extends ConflictError {
40
48
  constructor(message = "", opts = {}) {
41
49
  super(message, opts);
42
50
  this.name = "StaleWriteError";
43
51
  Object.setPrototypeOf(this, _StaleWriteError.prototype);
44
52
  }
45
53
  };
46
- var QuotaExceededError = class _QuotaExceededError extends APIError {
54
+ var QuotaExceededError = class extends APIError {
47
55
  constructor(message = "", opts = {}) {
48
56
  super(message, opts);
49
57
  this.name = "QuotaExceededError";
50
- this.retryAfter = opts.retryAfter;
51
- Object.setPrototypeOf(this, _QuotaExceededError.prototype);
58
+ Object.setPrototypeOf(this, new.target.prototype);
59
+ }
60
+ };
61
+ var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError {
62
+ constructor(message = "", opts = {}) {
63
+ super(message, opts);
64
+ this.name = "TooManyBatchesError";
65
+ Object.setPrototypeOf(this, _TooManyBatchesError.prototype);
52
66
  }
53
67
  };
54
68
 
55
69
  // src/client.ts
56
- var VERSION = "0.1.9";
70
+ var VERSION = "0.1.10";
57
71
  var REGIONS = { eu: "https://api.korely.ai" };
58
72
  function coerceContent(content) {
59
73
  if (typeof content === "string") return content;
@@ -83,6 +97,30 @@ function seg(value, what) {
83
97
  if (!s) throw new KorelyError(`${what} is empty.`);
84
98
  return encodeURIComponent(s);
85
99
  }
100
+ function moment(value, what) {
101
+ if (value == null) return void 0;
102
+ if (typeof value === "string") return value;
103
+ if (value instanceof Date) {
104
+ if (Number.isNaN(value.getTime())) throw new KorelyError(`${what} is an invalid Date.`);
105
+ return value.toISOString();
106
+ }
107
+ throw new KorelyError(`${what} must be an ISO 8601 string or a Date, not a ${typeof value}.`);
108
+ }
109
+ function auditFilters(opts) {
110
+ for (const name of ["user_id", "action"]) {
111
+ if (opts[name] === "") {
112
+ throw new KorelyError(
113
+ `${name} is empty: the server reads an empty filter as no filter. Leave it out to mean every ${name.split("_")[0]}.`
114
+ );
115
+ }
116
+ }
117
+ return {
118
+ user_id: opts.user_id,
119
+ action: opts.action,
120
+ since: moment(opts.since, "since"),
121
+ until: moment(opts.until, "until")
122
+ };
123
+ }
86
124
  function detailLine(detail) {
87
125
  if (typeof detail === "string") return detail.trim() ? detail : void 0;
88
126
  if (Array.isArray(detail) && detail.length) {
@@ -106,6 +144,11 @@ function errorFields(status, body) {
106
144
  const message = text(b.message) ?? text(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
107
145
  return { code, message };
108
146
  }
147
+ function retryAfterSeconds(raw) {
148
+ if (raw == null) return void 0;
149
+ const n = Math.ceil(Number(raw));
150
+ return Number.isFinite(n) && n >= 0 ? n : void 0;
151
+ }
109
152
  function fillPair(obj, current, deprecated) {
110
153
  if (obj[current] == null && obj[deprecated] != null) obj[current] = obj[deprecated];
111
154
  if (obj[deprecated] == null && obj[current] != null) obj[deprecated] = obj[current];
@@ -141,13 +184,105 @@ function refuseAMismatchedPair(apiKey, baseUrl) {
141
184
  );
142
185
  }
143
186
  }
187
+ async function exchange(t, method, path, opts = {}) {
188
+ let url = t.baseUrl + path;
189
+ if (opts.params) {
190
+ const qs = new URLSearchParams();
191
+ for (const [k, v] of Object.entries(opts.params)) {
192
+ if (v !== void 0 && v !== null) qs.append(k, String(v));
193
+ }
194
+ const s = qs.toString();
195
+ if (s) url += "?" + s;
196
+ }
197
+ const headers = {
198
+ Accept: "application/json",
199
+ "X-Korely-Client": `korely-js/${VERSION}`
200
+ };
201
+ if (t.apiKey) headers.Authorization = `Bearer ${t.apiKey}`;
202
+ let body;
203
+ if (opts.body !== void 0) {
204
+ body = JSON.stringify(opts.body);
205
+ headers["Content-Type"] = "application/json";
206
+ }
207
+ const controller = new AbortController();
208
+ let timedOut = false;
209
+ const timer = setTimeout(() => {
210
+ timedOut = true;
211
+ controller.abort();
212
+ }, t.timeoutMs);
213
+ const failed = (e) => new KorelyError(
214
+ timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
215
+ );
216
+ let resp;
217
+ let text;
218
+ try {
219
+ try {
220
+ resp = await t.fetchImpl(url, {
221
+ method,
222
+ headers,
223
+ body,
224
+ signal: controller.signal
225
+ });
226
+ } catch (e) {
227
+ throw failed(e);
228
+ }
229
+ try {
230
+ text = await resp.text();
231
+ } catch (e) {
232
+ throw failed(e);
233
+ }
234
+ } finally {
235
+ clearTimeout(timer);
236
+ }
237
+ let parsed = {};
238
+ if (text) {
239
+ try {
240
+ parsed = JSON.parse(text);
241
+ } catch {
242
+ if (resp.ok) {
243
+ throw new KorelyError(
244
+ `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text.slice(0, 200))}`,
245
+ { status: resp.status }
246
+ );
247
+ }
248
+ parsed = { message: text };
249
+ }
250
+ }
251
+ if (!resp.ok) {
252
+ raiseFor(resp.status, parsed, resp.headers.get("retry-after"));
253
+ }
254
+ return parsed && typeof parsed === "object" ? parsed : {};
255
+ }
256
+ function raiseFor(status, body, retryAfter) {
257
+ const { code, message: msg } = errorFields(status, body);
258
+ const opts = {
259
+ status,
260
+ code,
261
+ retryAfter: retryAfterSeconds(retryAfter ?? body?.retry_after ?? body?._retry_after)
262
+ };
263
+ if (status === 401) throw new AuthenticationError(msg, opts);
264
+ if (status === 403) throw new NamespaceForbiddenError(msg, opts);
265
+ if (status === 404) throw new NotFoundError(msg, opts);
266
+ if (status === 409) {
267
+ if (code === "stale_write") throw new StaleWriteError(msg, opts);
268
+ throw new ConflictError(msg, opts);
269
+ }
270
+ if (status === 429) {
271
+ if (code === "too_many_batches") throw new TooManyBatchesError(msg, opts);
272
+ throw new QuotaExceededError(msg, opts);
273
+ }
274
+ throw new APIError(msg, opts);
275
+ }
276
+ function refusePythonSpelling(opts) {
277
+ if (opts && Object.prototype.hasOwnProperty.call(opts, "base_url")) {
278
+ throw new KorelyError(
279
+ "Unknown option base_url: the JavaScript SDK takes baseUrl (new Korely({ baseUrl: 'https://...' })) or the KORELY_BASE_URL env var."
280
+ );
281
+ }
282
+ }
144
283
  var Korely = class {
145
284
  constructor(opts = {}) {
146
- if (opts && Object.prototype.hasOwnProperty.call(opts, "base_url")) {
147
- throw new KorelyError(
148
- "Unknown option base_url: the JavaScript SDK takes baseUrl (new Korely({ baseUrl: 'https://...' })) or the KORELY_BASE_URL env var."
149
- );
150
- }
285
+ refusePythonSpelling(opts);
151
286
  const envKey = typeof process !== "undefined" ? process.env?.KORELY_API_KEY : void 0;
152
287
  const key = opts.apiKey ?? envKey;
153
288
  if (!key) {
@@ -168,92 +303,157 @@ var Korely = class {
168
303
  }
169
304
  this.fetchImpl = f;
170
305
  }
171
- // ── transport ─────────────────────────────────────────────────────────────
172
- async request(method, path, opts = {}) {
173
- let url = this.baseUrl + path;
174
- if (opts.params) {
175
- const qs = new URLSearchParams();
176
- for (const [k, v] of Object.entries(opts.params)) {
177
- if (v !== void 0 && v !== null) qs.append(k, String(v));
178
- }
179
- const s = qs.toString();
180
- if (s) url += "?" + s;
306
+ /**
307
+ * POST /v1/agents/init, with no key: sign up for a free hobby key.
308
+ *
309
+ * The one call that runs without a key, because it is how one is obtained,
310
+ * so it is static: `await Korely.initAgent("my-app")`, then
311
+ * `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
312
+ * label of who signed up, kept for your reference. The answer carries the
313
+ * key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
314
+ * The account it creates has no login: the key is the account, and
315
+ * `deleteAccount({ confirm: true })` closes it.
316
+ *
317
+ * Cloud only. The server is `baseUrl`, else KORELY_BASE_URL, else the
318
+ * region's. Refusals: 403 `signup_disabled` (NamespaceForbiddenError) when
319
+ * self-signup is closed; 429 `signup_rate_limited` (QuotaExceededError, with
320
+ * `retryAfter`) past the new accounts a network may open in a day. The
321
+ * Self-hosted has no such route and answers 404, or 405 where it serves its
322
+ * dashboard: its keys come from its own dashboard.
323
+ */
324
+ static async initAgent(agentCaller, opts = {}) {
325
+ refusePythonSpelling(opts);
326
+ if (agentCaller != null && typeof agentCaller !== "string") {
327
+ throw new KorelyError(
328
+ `agentCaller is a label, a string, not ${Array.isArray(agentCaller) ? "an array" : `a ${typeof agentCaller}`}: Korely.initAgent('my-app', { baseUrl }).`
329
+ );
181
330
  }
182
- const headers = {
183
- Authorization: `Bearer ${this.apiKey}`,
184
- Accept: "application/json",
185
- "X-Korely-Client": `korely-js/${VERSION}`
186
- };
187
- let body;
188
- if (opts.body !== void 0) {
189
- body = JSON.stringify(opts.body);
190
- headers["Content-Type"] = "application/json";
331
+ const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
332
+ const baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
333
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
334
+ if (!fetchImpl) {
335
+ throw new KorelyError(
336
+ "No fetch available. On Node < 18 pass a fetch implementation via { fetch }."
337
+ );
191
338
  }
192
- const controller = new AbortController();
193
- let timedOut = false;
194
- const timer = setTimeout(() => {
195
- timedOut = true;
196
- controller.abort();
197
- }, this.timeoutMs);
198
- const failed = (e) => new KorelyError(
199
- timedOut ? `Request timed out after ${this.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
339
+ return exchange(
340
+ { baseUrl, timeoutMs: opts.timeoutMs ?? 3e4, fetchImpl },
341
+ "POST",
342
+ "/v1/agents/init",
343
+ { body: { agent_caller: agentCaller ?? void 0 } }
200
344
  );
201
- let resp;
202
- let text;
203
- try {
204
- try {
205
- resp = await this.fetchImpl(url, {
206
- method,
207
- headers,
208
- body,
209
- signal: controller.signal
210
- });
211
- } catch (e) {
212
- throw failed(e);
213
- }
214
- try {
215
- text = await resp.text();
216
- } catch (e) {
217
- throw failed(e);
218
- }
219
- } finally {
220
- clearTimeout(timer);
345
+ }
346
+ // ── transport ─────────────────────────────────────────────────────────────
347
+ request(method, path, opts = {}) {
348
+ return exchange(
349
+ { baseUrl: this.baseUrl, timeoutMs: this.timeoutMs, fetchImpl: this.fetchImpl, apiKey: this.apiKey },
350
+ method,
351
+ path,
352
+ opts
353
+ );
354
+ }
355
+ // ── the key and its account ───────────────────────────────────────────────
356
+ /**
357
+ * GET /v1/ping: does this key work, and what may it do? Both products answer
358
+ * it, with the same shape.
359
+ *
360
+ * The cheapest authenticated call there is: no scope, no rate limit, no
361
+ * quota, so it is how to check a key that was just minted or rotated without
362
+ * spending anything. `users()` was the usual stand-in, and it needs
363
+ * `memories:read` and counts as a query.
364
+ */
365
+ async ping() {
366
+ return this.request("GET", "/v1/ping");
367
+ }
368
+ /**
369
+ * DELETE /v1/account?confirm=true: delete the account of this key for good,
370
+ * with every key, project, memory, fact and webhook of it; the key stops
371
+ * working. Cloud only, for an account made by `Korely.initAgent()` or
372
+ * `korely init --agent`, which nobody signs in to: the key is the account,
373
+ * and this is how it is closed (GDPR Art. 17).
374
+ *
375
+ * `{ confirm: true }` is required, and checked here, before anything is
376
+ * sent: without it, a KorelyError whose `code` is `confirmation_required`,
377
+ * the code the server gives the same refusal.
378
+ *
379
+ * An account with a Korely login rejects with 409 `account_has_login`
380
+ * (ConflictError): a key that ended up in a log must not be able to delete
381
+ * it, so it is closed from the app (Settings, Account). The Self-hosted has
382
+ * no such route and answers 404 (NotFoundError), or 405 where it serves its
383
+ * dashboard. No audit event survives: the trail is part of what goes.
384
+ */
385
+ async deleteAccount(opts = {}) {
386
+ if (opts?.confirm !== true) {
387
+ throw new KorelyError(
388
+ "deleteAccount() deletes this key's account, every key, memory and fact of it, for good. Pass { confirm: true } to mean it.",
389
+ { code: "confirmation_required" }
390
+ );
221
391
  }
222
- let parsed = {};
223
- if (text) {
224
- try {
225
- parsed = JSON.parse(text);
226
- } catch {
227
- if (resp.ok) {
228
- throw new KorelyError(
229
- `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text.slice(0, 200))}`,
230
- { status: resp.status }
231
- );
232
- }
233
- parsed = { message: text };
392
+ return this.request("DELETE", "/v1/account", { params: { confirm: "true" } });
393
+ }
394
+ // ── audit ─────────────────────────────────────────────────────────────────
395
+ /**
396
+ * GET /v1/audit: what this key's project did, and what its agents read,
397
+ * newest first (`ts` descending, then the event's id, so paging with
398
+ * `offset` is stable). Both products; the key needs `memories:read`.
399
+ *
400
+ * `user_id` keeps the events that touched one end user, the shape of an
401
+ * access or erasure request; `action` one kind ("read", "write", "erase"...;
402
+ * an unknown one answers an empty page); `since` and `until` bound `ts`,
403
+ * both inclusive, as ISO 8601 text or a Date. `limit` is 1 to 1000. To read
404
+ * everything, use `iterAudit()`. The page is iterable.
405
+ *
406
+ * Reading the trail counts against no quota and is not itself written to
407
+ * it; it does count against the rate limit. Scoped to the key's account and
408
+ * project, like every read.
409
+ */
410
+ async audit(opts = {}) {
411
+ const page = await this.request(
412
+ "GET",
413
+ "/v1/audit",
414
+ {
415
+ params: { ...auditFilters(opts), limit: opts.limit ?? 100, offset: opts.offset ?? 0 }
234
416
  }
235
- }
236
- if (!resp.ok) {
237
- this.raise(resp.status, parsed, resp.headers.get("retry-after"));
238
- }
239
- return parsed && typeof parsed === "object" ? parsed : {};
240
- }
241
- raise(status, body, retryAfter) {
242
- const { code, message: msg } = errorFields(status, body);
243
- if (status === 401) throw new AuthenticationError(msg, { status, code });
244
- if (status === 403) throw new NamespaceForbiddenError(msg, { status, code });
245
- if (status === 404) throw new NotFoundError(msg, { status, code });
246
- if (status === 409) throw new StaleWriteError(msg, { status, code });
247
- if (status === 429) {
248
- const raw = retryAfter ?? body?.retry_after ?? body?._retry_after;
249
- let ra;
250
- if (raw != null) {
251
- const n = Math.ceil(Number(raw));
252
- ra = Number.isFinite(n) && n >= 0 ? n : void 0;
417
+ );
418
+ return iterableOver(page, "events");
419
+ }
420
+ /**
421
+ * Every event `audit()` would page through, for an export:
422
+ * `for await (const e of korely.iterAudit({ user_id }))`. The same filters,
423
+ * `page_size` events per request (1000, the most the API gives),
424
+ * `offset += page.length` until `total`.
425
+ *
426
+ * Without `until` the walk pins it to the newest event of its first page.
427
+ * The trail grows while it is read, newest first, and every new event pushed
428
+ * the rest one place down: the next page began with events already returned.
429
+ * The pin makes the export the trail as it stood when it started.
430
+ *
431
+ * A rate limit rejects mid-way, as any call does, and the SDK does not
432
+ * retry. To resume, call again with the same `until` (pin it yourself:
433
+ * `until: new Date()`) and `offset` the number of events already read.
434
+ */
435
+ async *iterAudit(opts = {}) {
436
+ const filters = auditFilters(opts);
437
+ let offset = opts.offset ?? 0;
438
+ let pin = filters.until === void 0 && offset === 0;
439
+ for (; ; ) {
440
+ const page = await this.audit({
441
+ user_id: opts.user_id,
442
+ action: opts.action,
443
+ since: filters.since,
444
+ until: filters.until,
445
+ limit: opts.page_size ?? 1e3,
446
+ offset
447
+ });
448
+ if (!page.events.length) return;
449
+ yield* page.events;
450
+ if (pin && page.events[0].ts) {
451
+ filters.until = page.events[0].ts;
452
+ pin = false;
253
453
  }
254
- throw new QuotaExceededError(msg, { status, code, retryAfter: ra });
454
+ offset += page.events.length;
455
+ if (offset >= page.total) return;
255
456
  }
256
- throw new APIError(msg, { status, code });
257
457
  }
258
458
  // ── memories ────────────────────────────────────────────────────────────
259
459
  /**
@@ -586,6 +786,12 @@ var Korely = class {
586
786
  * `code === "invalid_request"`) whose message names the item, e.g.
587
787
  * `memories[3].timestamp`. Any key not listed above is refused the same
588
788
  * way. Servers older than 2026-09-28 refuse `timestamp` itself.
789
+ *
790
+ * On the Cloud a batch is also refused, before anything is stored, with a
791
+ * 429: `quota_exceeded` (QuotaExceededError) when its memories do not fit in
792
+ * what is left of the month, batches already queued included, and
793
+ * `too_many_batches` (TooManyBatchesError) while three batches are still
794
+ * being imported. The Self-hosted meters nothing and refuses neither.
589
795
  */
590
796
  async batch(memories) {
591
797
  return this.request("POST", "/v1/batch", { body: { memories } });
@@ -598,11 +804,13 @@ var Korely = class {
598
804
  export {
599
805
  APIError,
600
806
  AuthenticationError,
807
+ ConflictError,
601
808
  Korely,
602
809
  KorelyError,
603
810
  NamespaceForbiddenError,
604
811
  NotFoundError,
605
812
  QuotaExceededError,
606
813
  StaleWriteError,
814
+ TooManyBatchesError,
607
815
  VERSION
608
816
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "korely-memory",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "JavaScript / TypeScript SDK for Korely Agents: memory for AI agents with bi-temporal typed facts.",
5
5
  "keywords": [
6
6
  "ai",