korely-memory 0.1.17 → 0.2.0

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
@@ -1,987 +1,17 @@
1
1
  import {
2
- __require,
3
- keysOf,
4
- unknownOption
5
- } from "./chunk-6SD5RRK3.js";
6
-
7
- // src/errors.ts
8
- var KorelyError = class extends Error {
9
- constructor(message = "", opts = {}) {
10
- super(message || opts.code || "Korely error");
11
- this.name = "KorelyError";
12
- this.status = opts.status;
13
- this.code = opts.code;
14
- Object.setPrototypeOf(this, new.target.prototype);
15
- }
16
- };
17
- var APIError = class extends KorelyError {
18
- constructor(message = "", opts = {}) {
19
- super(message, opts);
20
- this.name = "APIError";
21
- this.retryAfter = opts.retryAfter;
22
- Object.setPrototypeOf(this, new.target.prototype);
23
- }
24
- };
25
- var AuthenticationError = class _AuthenticationError extends APIError {
26
- constructor(message = "", opts = {}) {
27
- super(message, opts);
28
- this.name = "AuthenticationError";
29
- Object.setPrototypeOf(this, _AuthenticationError.prototype);
30
- }
31
- };
32
- var NamespaceForbiddenError = class _NamespaceForbiddenError extends APIError {
33
- constructor(message = "", opts = {}) {
34
- super(message, opts);
35
- this.name = "NamespaceForbiddenError";
36
- Object.setPrototypeOf(this, _NamespaceForbiddenError.prototype);
37
- }
38
- };
39
- var NotFoundError = class _NotFoundError extends APIError {
40
- constructor(message = "", opts = {}) {
41
- super(message, opts);
42
- this.name = "NotFoundError";
43
- Object.setPrototypeOf(this, _NotFoundError.prototype);
44
- }
45
- };
46
- var ConflictError = class extends APIError {
47
- constructor(message = "", opts = {}) {
48
- super(message, opts);
49
- this.name = "ConflictError";
50
- this.currentFactId = opts.currentFactId;
51
- Object.setPrototypeOf(this, new.target.prototype);
52
- }
53
- };
54
- var StaleWriteError = class _StaleWriteError extends ConflictError {
55
- constructor(message = "", opts = {}) {
56
- super(message, opts);
57
- this.name = "StaleWriteError";
58
- Object.setPrototypeOf(this, _StaleWriteError.prototype);
59
- }
60
- };
61
- var QuotaExceededError = class extends APIError {
62
- constructor(message = "", opts = {}) {
63
- super(message, opts);
64
- this.name = "QuotaExceededError";
65
- this.limit = opts.limit;
66
- this.used = opts.used;
67
- this.resetsAt = opts.resetsAt;
68
- Object.setPrototypeOf(this, new.target.prototype);
69
- }
70
- };
71
- var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError {
72
- constructor(message = "", opts = {}) {
73
- super(message, opts);
74
- this.name = "TooManyBatchesError";
75
- Object.setPrototypeOf(this, _TooManyBatchesError.prototype);
76
- }
77
- };
78
-
79
- // src/client.ts
80
- var VERSION = "0.1.17";
81
- var REGIONS = { eu: "https://api.korely.ai" };
82
- var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch", "client");
83
- var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
84
- var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp", "kind");
85
- var SEARCH_KEYS = keysOf()(
86
- "user_id",
87
- "agent_id",
88
- "run_id",
89
- "metadata",
90
- "limit",
91
- "min_score",
92
- "exclude_sessions"
93
- );
94
- var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset", "exclude_sessions");
95
- var NAME_KEYS = keysOf()("user_id", "agent_id");
96
- var UPDATE_KEYS = keysOf()("content", "expected_updated_at");
97
- var USERS_KEYS = keysOf()("agent_id", "limit", "offset");
98
- var AGENTS_KEYS = keysOf()("limit", "offset");
99
- var EVENTS_KEYS = keysOf()("user_id", "status", "limit");
100
- var AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "limit", "offset");
101
- var ITER_AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "offset", "page_size");
102
- var FACTS_KEYS = keysOf()(
103
- "subject",
104
- "entity",
105
- "predicate",
106
- "predicate_family",
107
- "include_invalidated",
108
- "as_of",
109
- "known_as_of",
110
- "user_id",
111
- "agent_id",
112
- "limit",
113
- "offset",
114
- "exclude_sessions"
115
- );
116
- var TRIPLE_KEYS = keysOf()(
117
- "user_id",
118
- "agent_id",
119
- "run_id",
120
- "subject_type",
121
- "object_is_literal",
122
- "confidence",
123
- "valid_from",
124
- "tense"
125
- );
126
- var PROFILE_KEYS = keysOf()(
127
- "user_id",
128
- "agent_id",
129
- "as_of",
130
- "known_as_of",
131
- "exclude_sessions"
132
- );
133
- var CONTEXT_KEYS = keysOf()(
134
- "query",
135
- "user_id",
136
- "agent_id",
137
- "token_budget",
138
- "known_as_of",
139
- "exclude_sessions"
140
- );
141
- var CONTEXT_EXTRA_KEYS = keysOf()(
142
- "user_id",
143
- "agent_id",
144
- "token_budget",
145
- "known_as_of",
146
- "exclude_sessions"
147
- );
148
- function checkOptions(method, opts, known) {
149
- const problem = unknownOption(method, opts, known);
150
- if (problem) throw new KorelyError(problem);
151
- }
152
- function coerceContent(content) {
153
- if (typeof content === "string") return content;
154
- if (Array.isArray(content)) {
155
- const parts = [];
156
- for (const m of content) {
157
- if (m && typeof m === "object") {
158
- const role = String(m.role ?? "").trim();
159
- const raw = m.content;
160
- const body = raw == null ? "" : String(raw).trim();
161
- if (role && body) parts.push(`${role}: ${body}`);
162
- else if (body) parts.push(body);
163
- } else {
164
- const s = String(m).trim();
165
- if (s) parts.push(s);
166
- }
167
- }
168
- return parts.join("\n");
169
- }
170
- return String(content);
171
- }
172
- function seg(value, what) {
173
- if (value != null && typeof value !== "string" && !(typeof value === "number" && Number.isInteger(value))) {
174
- throw new KorelyError(`${what} must be a string id, not ${Array.isArray(value) ? "an array" : `a ${typeof value}`}.`);
175
- }
176
- const s = value == null ? "" : String(value);
177
- if (!s) throw new KorelyError(`${what} is empty.`);
178
- return encodeURIComponent(s);
179
- }
180
- function moment(value, what) {
181
- if (value == null) return void 0;
182
- if (typeof value === "string") return value;
183
- if (value instanceof Date) {
184
- if (Number.isNaN(value.getTime())) throw new KorelyError(`${what} is an invalid Date.`);
185
- return value.toISOString();
186
- }
187
- throw new KorelyError(`${what} must be an ISO 8601 string or a Date, not a ${typeof value}.`);
188
- }
189
- function auditFilters(opts) {
190
- for (const name of ["user_id", "action"]) {
191
- if (opts[name] === "") {
192
- throw new KorelyError(
193
- `${name} is empty: the server reads an empty filter as no filter. Leave it out to mean every ${name.split("_")[0]}.`
194
- );
195
- }
196
- }
197
- return {
198
- user_id: opts.user_id,
199
- action: opts.action,
200
- since: moment(opts.since, "since"),
201
- until: moment(opts.until, "until")
202
- };
203
- }
204
- function detailLine(detail) {
205
- if (typeof detail === "string") return detail.trim() ? detail : void 0;
206
- if (Array.isArray(detail) && detail.length) {
207
- const parts = detail.slice(0, 3).map((e) => {
208
- if (!e || typeof e !== "object") return String(e);
209
- const loc = Array.isArray(e.loc) ? e.loc : [];
210
- const where = loc.filter((x) => x !== "body").map(String).join(".");
211
- const msg = String(e.msg ?? "invalid");
212
- return where ? `${where}: ${msg}` : msg;
213
- });
214
- const more = detail.length - 3;
215
- return parts.join("; ") + (more > 0 ? ` (and ${more} more)` : "");
216
- }
217
- return void 0;
218
- }
219
- function errorFields(status, body) {
220
- const text2 = (v) => typeof v === "string" && v.trim() ? v : void 0;
221
- const b = body && typeof body === "object" ? body : {};
222
- const pair = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
223
- const code = text2(b.code) ?? text2(pair.code);
224
- const message = text2(b.message) ?? text2(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
225
- return { code, message };
226
- }
227
- function quotaFields(body) {
228
- const b = body && typeof body === "object" ? body : {};
229
- const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
230
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
231
- const str = (v) => typeof v === "string" && v ? v : void 0;
232
- return {
233
- limit: num(b.limit ?? d.limit),
234
- used: num(b.used ?? d.used),
235
- resetsAt: str(b.resets_at ?? d.resets_at)
236
- };
237
- }
238
- function conflictFields(body) {
239
- const b = body && typeof body === "object" ? body : {};
240
- const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
241
- const v = b.current_fact_id ?? d.current_fact_id;
242
- return { currentFactId: typeof v === "string" && v ? v : void 0 };
243
- }
244
- function retryAfterSeconds(raw) {
245
- if (raw == null) return void 0;
246
- const n = Math.ceil(Number(raw));
247
- return Number.isFinite(n) && n >= 0 ? n : void 0;
248
- }
249
- function fillPair(obj, current, deprecated) {
250
- if (obj[current] == null && obj[deprecated] != null) obj[current] = obj[deprecated];
251
- if (obj[deprecated] == null && obj[current] != null) obj[deprecated] = obj[current];
252
- }
253
- function iterableOver(page, key) {
254
- const out = page;
255
- Object.defineProperty(out, Symbol.iterator, {
256
- value: () => (page[key] ?? [])[Symbol.iterator](),
257
- enumerable: false
258
- });
259
- return out;
260
- }
261
- var OUR_HOSTS = ["korely.ai"];
262
- function isOurs(baseUrl) {
263
- let host = "";
264
- try {
265
- host = new URL(baseUrl).hostname.toLowerCase();
266
- } catch {
267
- return false;
268
- }
269
- return OUR_HOSTS.some((h) => host === h || host.endsWith("." + h));
270
- }
271
- function refuseAMismatchedPair(apiKey, baseUrl) {
272
- const ours = isOurs(baseUrl);
273
- if (apiKey.startsWith("kor_self_") && ours) {
274
- throw new KorelyError(
275
- `This key was issued by an install you run yourself (kor_self_), and ${baseUrl} is the hosted Korely service. It would be refused there, but the memory would arrive first. Point baseUrl at your own server, or set KORELY_BASE_URL.`
276
- );
277
- }
278
- if (apiKey.startsWith("kor_live_") && !ours) {
279
- throw new KorelyError(
280
- `This key was issued by the hosted Korely service (kor_live_), and ${baseUrl} is not it. Sending it there hands a credential we issued to a machine that is not ours. Use a key minted by that install (kor_self_), or drop baseUrl to reach the hosted service.`
281
- );
282
- }
283
- }
284
- async function exchange(t, method, path, opts = {}) {
285
- let url = t.baseUrl + path;
286
- if (opts.params) {
287
- const qs = new URLSearchParams();
288
- for (const [k, v] of Object.entries(opts.params)) {
289
- if (v !== void 0 && v !== null) qs.append(k, String(v));
290
- }
291
- const s = qs.toString();
292
- if (s) url += "?" + s;
293
- }
294
- const headers = {
295
- Accept: "application/json",
296
- "X-Korely-Client": t.client || `korely-js/${VERSION}`
297
- };
298
- if (t.apiKey) headers.Authorization = `Bearer ${t.apiKey}`;
299
- let body;
300
- if (opts.body !== void 0) {
301
- body = JSON.stringify(opts.body);
302
- headers["Content-Type"] = "application/json";
303
- }
304
- const controller = new AbortController();
305
- let timedOut = false;
306
- const timer = setTimeout(() => {
307
- timedOut = true;
308
- controller.abort();
309
- }, t.timeoutMs);
310
- const failed = (e) => new KorelyError(
311
- timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
312
- );
313
- let resp;
314
- let text2;
315
- try {
316
- try {
317
- resp = await t.fetchImpl(url, {
318
- method,
319
- headers,
320
- body,
321
- signal: controller.signal
322
- });
323
- } catch (e) {
324
- throw failed(e);
325
- }
326
- try {
327
- text2 = await resp.text();
328
- } catch (e) {
329
- throw failed(e);
330
- }
331
- } finally {
332
- clearTimeout(timer);
333
- }
334
- let parsed = {};
335
- if (text2) {
336
- try {
337
- parsed = JSON.parse(text2);
338
- } catch {
339
- if (resp.ok) {
340
- throw new KorelyError(
341
- `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text2.slice(0, 200))}`,
342
- { status: resp.status }
343
- );
344
- }
345
- parsed = { message: text2 };
346
- }
347
- }
348
- if (!resp.ok) {
349
- raiseFor(resp.status, parsed, resp.headers.get("retry-after"));
350
- }
351
- return parsed && typeof parsed === "object" ? parsed : {};
352
- }
353
- function raiseFor(status, body, retryAfter) {
354
- const { code, message: msg } = errorFields(status, body);
355
- const opts = {
356
- status,
357
- code,
358
- retryAfter: retryAfterSeconds(retryAfter ?? body?.retry_after ?? body?._retry_after)
359
- };
360
- if (status === 401) throw new AuthenticationError(msg, opts);
361
- if (status === 403) throw new NamespaceForbiddenError(msg, opts);
362
- if (status === 404) throw new NotFoundError(msg, opts);
363
- if (status === 409) {
364
- if (code === "stale_write") throw new StaleWriteError(msg, opts);
365
- throw new ConflictError(msg, { ...opts, ...conflictFields(body) });
366
- }
367
- if (status === 429) {
368
- const quota = { ...opts, ...quotaFields(body) };
369
- if (code === "too_many_batches") throw new TooManyBatchesError(msg, quota);
370
- throw new QuotaExceededError(msg, quota);
371
- }
372
- throw new APIError(msg, opts);
373
- }
374
- function savedConfig() {
375
- try {
376
- const proc = typeof process !== "undefined" ? process : void 0;
377
- if (!proc?.versions?.node) return {};
378
- const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof __require === "function" ? __require(id) : void 0;
379
- const fs = builtin("node:fs");
380
- const os = builtin("node:os");
381
- const path = builtin("node:path");
382
- if (!fs || !os || !path) return {};
383
- const home = proc.env?.KORELY_CONFIG_HOME || path.join(os.homedir(), ".korely");
384
- const data = JSON.parse(fs.readFileSync(path.join(home, "config.json"), "utf8"));
385
- return data && typeof data === "object" ? data : {};
386
- } catch {
387
- return {};
388
- }
389
- }
390
- function text(v) {
391
- return typeof v === "string" && v ? v : void 0;
392
- }
393
- var Korely = class {
394
- constructor(opts = {}) {
395
- checkOptions("Korely", opts, CLIENT_KEYS);
396
- const envKey = typeof process !== "undefined" ? process.env?.KORELY_API_KEY : void 0;
397
- const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
398
- const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
399
- const key = opts.apiKey ?? envKey ?? text(saved.api_key);
400
- if (!key) {
401
- throw new KorelyError(
402
- "No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
403
- );
404
- }
405
- this.apiKey = key;
406
- const envClient = typeof process !== "undefined" ? process.env?.KORELY_CLIENT : void 0;
407
- this.client = (opts.client ?? envClient ?? "").trim() || void 0;
408
- this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
409
- refuseAMismatchedPair(this.apiKey, this.baseUrl);
410
- this.timeoutMs = opts.timeoutMs ?? 3e4;
411
- const f = opts.fetch ?? globalThis.fetch;
412
- if (!f) {
413
- throw new KorelyError(
414
- "No fetch available. On Node < 18 pass a fetch implementation via { fetch }."
415
- );
416
- }
417
- this.fetchImpl = f;
418
- }
419
- /**
420
- * POST /v1/agents/init, with no key: sign up for a free hobby key.
421
- *
422
- * The one call that runs without a key, because it is how one is obtained,
423
- * so it is static: `await Korely.initAgent("my-app")`, then
424
- * `new Korely({ apiKey: result.api_key })`. `agentCaller` is a free-form
425
- * label of who signed up, kept for your reference. The answer carries the
426
- * key, shown once (save it), its `tier`, `region`, `scopes` and `quotas`.
427
- * The account it creates has no login: the key is the account, and
428
- * `deleteAccount({ confirm: true })` closes it.
429
- *
430
- * Cloud only. The server is `baseUrl`, else KORELY_BASE_URL, else the
431
- * region's. Refusals: 403 `signup_disabled` (NamespaceForbiddenError) when
432
- * self-signup is closed; 429 `signup_rate_limited` (QuotaExceededError, with
433
- * `retryAfter`) past the new accounts a network may open in a day. The
434
- * Self-hosted has no such route and answers 404, or 405 where it serves its
435
- * dashboard: its keys come from its own dashboard.
436
- */
437
- static async initAgent(agentCaller, opts = {}) {
438
- checkOptions("initAgent", opts, INIT_KEYS);
439
- const where = opts.processingRegion;
440
- if (where !== void 0 && where !== "eu" && where !== "global") {
441
- throw new KorelyError(`processingRegion is "eu" or "global", not ${JSON.stringify(where)}.`);
442
- }
443
- if (agentCaller != null && typeof agentCaller !== "string") {
444
- throw new KorelyError(
445
- `agentCaller is a label, a string, not ${Array.isArray(agentCaller) ? "an array" : `a ${typeof agentCaller}`}: Korely.initAgent('my-app', { baseUrl }).`
446
- );
447
- }
448
- const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
449
- const baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
450
- const fetchImpl = opts.fetch ?? globalThis.fetch;
451
- if (!fetchImpl) {
452
- throw new KorelyError(
453
- "No fetch available. On Node < 18 pass a fetch implementation via { fetch }."
454
- );
455
- }
456
- return exchange(
457
- { baseUrl, timeoutMs: opts.timeoutMs ?? 3e4, fetchImpl },
458
- "POST",
459
- "/v1/agents/init",
460
- {
461
- body: { agent_caller: agentCaller ?? void 0, processing_region: opts.processingRegion }
462
- }
463
- );
464
- }
465
- // ── transport ─────────────────────────────────────────────────────────────
466
- request(method, path, opts = {}) {
467
- return exchange(
468
- {
469
- baseUrl: this.baseUrl,
470
- timeoutMs: this.timeoutMs,
471
- fetchImpl: this.fetchImpl,
472
- apiKey: this.apiKey,
473
- client: this.client
474
- },
475
- method,
476
- path,
477
- opts
478
- );
479
- }
480
- // ── the key and its account ───────────────────────────────────────────────
481
- /**
482
- * GET /v1/ping: does this key work, and what may it do? Both products answer
483
- * it, with the same shape.
484
- *
485
- * The cheapest authenticated call there is: no scope, no rate limit, no
486
- * quota, so it is how to check a key that was just minted or rotated without
487
- * spending anything. `users()` was the usual stand-in, and it needs
488
- * `memories:read` and counts as a query.
489
- */
490
- async ping() {
491
- return this.request("GET", "/v1/ping");
492
- }
493
- /**
494
- * DELETE /v1/account?confirm=true: delete the account of this key for good,
495
- * with every key, project, memory, fact and webhook of it; the key stops
496
- * working. Cloud only, for an account made by `Korely.initAgent()` or
497
- * `korely init --agent`, which nobody signs in to: the key is the account,
498
- * and this is how it is closed (GDPR Art. 17).
499
- *
500
- * `{ confirm: true }` is required, and checked here, before anything is
501
- * sent: without it, a KorelyError whose `code` is `confirmation_required`,
502
- * the code the server gives the same refusal.
503
- *
504
- * An account with a Korely login rejects with 409 `account_has_login`
505
- * (ConflictError): a key that ended up in a log must not be able to delete
506
- * it, so it is closed from the app (Settings, Account). The Self-hosted has
507
- * no such route and answers 404 (NotFoundError), or 405 where it serves its
508
- * dashboard. No audit event survives: the trail is part of what goes.
509
- */
510
- async deleteAccount(opts = {}) {
511
- checkOptions("deleteAccount", opts, ["confirm"]);
512
- if (opts?.confirm !== true) {
513
- throw new KorelyError(
514
- "deleteAccount() deletes this key's account, every key, memory and fact of it, for good. Pass { confirm: true } to mean it.",
515
- { code: "confirmation_required" }
516
- );
517
- }
518
- return this.request("DELETE", "/v1/account", { params: { confirm: "true" } });
519
- }
520
- // ── audit ─────────────────────────────────────────────────────────────────
521
- /**
522
- * GET /v1/audit: what this key's project did, and what its agents read,
523
- * newest first (`ts` descending, then the event's id, so paging with
524
- * `offset` is stable). Both products; the key needs `memories:read`.
525
- *
526
- * `user_id` keeps the events that touched one end user, the shape of an
527
- * access or erasure request; `action` one kind ("read", "write", "erase"...;
528
- * an unknown one answers an empty page); `since` and `until` bound `ts`,
529
- * both inclusive, as ISO 8601 text or a Date. `limit` is 1 to 1000. To read
530
- * everything, use `iterAudit()`. The page is iterable.
531
- *
532
- * Reading the trail counts against no quota and is not itself written to
533
- * it; it does count against the rate limit. Scoped to the key's account and
534
- * project, like every read.
535
- */
536
- async audit(opts = {}) {
537
- checkOptions("audit", opts, AUDIT_KEYS);
538
- const page = await this.request(
539
- "GET",
540
- "/v1/audit",
541
- {
542
- params: { ...auditFilters(opts), limit: opts.limit ?? 100, offset: opts.offset ?? 0 }
543
- }
544
- );
545
- return iterableOver(page, "events");
546
- }
547
- /**
548
- * Every event `audit()` would page through, for an export:
549
- * `for await (const e of korely.iterAudit({ user_id }))`. The same filters,
550
- * `page_size` events per request (1000, the most the API gives),
551
- * `offset += page.length` until `total`.
552
- *
553
- * Without `until` the walk pins it to the newest event of its first page.
554
- * The trail grows while it is read, newest first, and every new event pushed
555
- * the rest one place down: the next page began with events already returned.
556
- * The pin makes the export the trail as it stood when it started.
557
- *
558
- * A rate limit rejects mid-way, as any call does, and the SDK does not
559
- * retry. To resume, call again with the same `until` (pin it yourself:
560
- * `until: new Date()`) and `offset` the number of events already read.
561
- */
562
- async *iterAudit(opts = {}) {
563
- checkOptions("iterAudit", opts, ITER_AUDIT_KEYS);
564
- const filters = auditFilters(opts);
565
- let offset = opts.offset ?? 0;
566
- let pin = filters.until === void 0 && offset === 0;
567
- for (; ; ) {
568
- const page = await this.audit({
569
- user_id: opts.user_id,
570
- action: opts.action,
571
- since: filters.since,
572
- until: filters.until,
573
- limit: opts.page_size ?? 1e3,
574
- offset
575
- });
576
- if (!page.events.length) return;
577
- yield* page.events;
578
- if (pin && page.events[0].ts) {
579
- filters.until = page.events[0].ts;
580
- pin = false;
581
- }
582
- offset += page.events.length;
583
- if (offset >= page.total) return;
584
- }
585
- }
586
- // ── memories ────────────────────────────────────────────────────────────
587
- /**
588
- * POST /v1/memories: store a memory; resolves to it with extracted facts.
589
- * `content` is a string, or a list of chat messages (role/content), joined
590
- * into one block before sending. Pass `timestamp` (ISO date/datetime) for
591
- * backfill: facts extracted inherit it as `valid_from`.
592
- */
593
- async add(content, opts = {}) {
594
- checkOptions("add", opts, ADD_KEYS);
595
- const text2 = coerceContent(content);
596
- if (!text2.trim()) {
597
- throw new KorelyError(
598
- "content is empty: pass a non-blank string or messages with content."
599
- );
600
- }
601
- return this.request("POST", "/v1/memories", {
602
- body: {
603
- content: text2,
604
- agent_id: opts.agent_id,
605
- user_id: opts.user_id,
606
- run_id: opts.run_id,
607
- metadata: opts.metadata,
608
- timestamp: opts.timestamp,
609
- kind: opts.kind
610
- }
611
- });
612
- }
613
- /**
614
- * POST /v1/memories/search: semantic search over raw memories, ranked by
615
- * score (vector similarity to the query). `run_id` scopes to one session,
616
- * `metadata` filters on what you stored at write time. `limit` defaults to
617
- * the server default (15), max 50.
618
- */
619
- async search(query, opts = {}) {
620
- checkOptions("search", opts, SEARCH_KEYS);
621
- const body = await this.request("POST", "/v1/memories/search", {
622
- body: {
623
- query,
624
- user_id: opts.user_id,
625
- agent_id: opts.agent_id,
626
- run_id: opts.run_id,
627
- metadata: opts.metadata,
628
- limit: opts.limit,
629
- min_score: opts.min_score,
630
- // Sent only when true: an older server does not know the field.
631
- exclude_sessions: opts.exclude_sessions ? true : void 0
632
- }
633
- });
634
- return body.results ?? [];
635
- }
636
- /**
637
- * GET /v1/memories: list a scope, newest first. The page is iterable.
638
- * `limit` goes up to 200 (the server capped it at 100 before 2026-09-28);
639
- * `total` and `offset` walk the rest.
640
- */
641
- async getAll(opts = {}) {
642
- checkOptions("getAll", opts, LIST_KEYS);
643
- const page = await this.request(
644
- "GET",
645
- "/v1/memories",
646
- {
647
- params: {
648
- user_id: opts.user_id,
649
- agent_id: opts.agent_id,
650
- run_id: opts.run_id,
651
- limit: opts.limit ?? 50,
652
- offset: opts.offset ?? 0,
653
- exclude_sessions: opts.exclude_sessions ? "true" : void 0
654
- }
655
- }
656
- );
657
- return iterableOver(page, "memories");
658
- }
659
- /**
660
- * POST /v1/users/:user_id/names: declare that this end user is also called
661
- * `name` (`declareName("Maria Rossi", { user_id: "maria" })`), Korely Agent
662
- * 0.1.42. The store never merges two names of a person by itself, since two
663
- * people can share one; after this the facts about `name` in the end user's
664
- * memory read as the end user's, those already written included. In the
665
- * key's project. Declaring the same name again answers the same; a name
666
- * already declared for somebody else in that memory rejects with a
667
- * ConflictError. Call it once per name the person is called by.
668
- */
669
- async declareName(name, opts) {
670
- checkOptions("declareName", opts, NAME_KEYS);
671
- if (typeof name !== "string" || !name.trim()) {
672
- throw new KorelyError("declareName needs a name.");
673
- }
674
- return this.request("POST", `/v1/users/${seg(opts.user_id, "user_id")}/names`, {
675
- body: { name, agent_id: opts.agent_id }
676
- });
677
- }
678
- /** GET /v1/memories/:id: full content, metadata, extracted facts. */
679
- async get(memoryId) {
680
- return this.request("GET", `/v1/memories/${seg(memoryId, "memoryId")}`);
681
- }
682
- /**
683
- * PATCH /v1/memories/:id: re-runs extraction. Pass `expected_updated_at`
684
- * for optimistic concurrency (throws StaleWriteError instead of clobbering).
685
- */
686
- async update(memoryId, opts) {
687
- checkOptions("update", opts, UPDATE_KEYS);
688
- return this.request("PATCH", `/v1/memories/${seg(memoryId, "memoryId")}`, {
689
- body: {
690
- content: opts.content,
691
- expected_updated_at: opts.expected_updated_at
692
- }
693
- });
694
- }
695
- /**
696
- * DELETE /v1/memories/:id: forget one memory. It drops out of every default
697
- * read, and the facts only it asserted are invalidated (kept as history,
698
- * audited). For erasure use `deleteAll`.
699
- */
700
- async delete(memoryId) {
701
- return this.request("DELETE", `/v1/memories/${seg(memoryId, "memoryId")}`);
702
- }
703
- /**
704
- * DELETE /v1/users/:user_id/memories: ERASE every memory and fact of one end
705
- * user (GDPR Art. 17). Physical deletion, not a flag: nothing is readable
706
- * afterwards. The audit row (counts, never content) survives.
707
- *
708
- * The receipt counts the rows in `memories_deleted` and `facts_deleted`.
709
- * `memories_forgotten` and `facts_invalidated` are deprecated aliases with
710
- * the same numbers; whichever pair the server sends fills both.
711
- */
712
- async deleteAll(opts) {
713
- checkOptions("deleteAll", opts, ["user_id"]);
714
- const r = await this.request(
715
- "DELETE",
716
- `/v1/users/${seg(opts.user_id, "user_id")}/memories`
717
- );
718
- const fields = r;
719
- fillPair(fields, "memories_deleted", "memories_forgotten");
720
- fillPair(fields, "facts_deleted", "facts_invalidated");
721
- return r;
722
- }
723
- /**
724
- * GET /v1/memories/:id/history: the lifecycle timeline of a memory,
725
- * created / updated / deleted, plus every typed fact it produced.
726
- */
727
- async history(memoryId) {
728
- return this.request("GET", `/v1/memories/${seg(memoryId, "memoryId")}/history`);
729
- }
730
- /**
731
- * GET /v1/users: the end users you've stored data for (distinct user_id
732
- * namespaces), each with active memory + fact counts and last-active time.
733
- */
734
- async users(opts = {}) {
735
- checkOptions("users", opts, USERS_KEYS);
736
- const page = await this.request(
737
- "GET",
738
- "/v1/users",
739
- {
740
- params: {
741
- agent_id: opts.agent_id,
742
- limit: opts.limit ?? 50,
743
- offset: opts.offset ?? 0
744
- }
745
- }
746
- );
747
- return iterableOver(page, "users");
748
- }
749
- // ── agents ────────────────────────────────────────────────────────────────
750
- /**
751
- * GET /v1/agents: the agent namespaces written under in this key's project
752
- * (the distinct non-null agent_id values), each with active memory + fact
753
- * counts and last-active time. The antidote to the agent-cap trap: when a
754
- * write is rejected with `agent_cap_exceeded`, call this to see which
755
- * namespaces already exist and reuse one instead of minting a new id.
756
- *
757
- * `total` counts this project's namespaces (exactly the ones this key can
758
- * delete); `used` counts the cap slots taken across the whole account, by
759
- * name, which is what the 403 compares with `cap`. `used` is above `total`
760
- * when other projects use names this one does not. A self-hosted install
761
- * sets no cap and answers `cap: 0`.
762
- */
763
- async listAgents(opts = {}) {
764
- checkOptions("listAgents", opts, AGENTS_KEYS);
765
- const page = await this.request("GET", "/v1/agents", {
766
- params: {
767
- limit: opts.limit ?? 50,
768
- offset: opts.offset ?? 0
769
- }
770
- });
771
- return iterableOver(page, "agents");
772
- }
773
- /**
774
- * DELETE /v1/agents/:agent_id: hard-delete an agent namespace, purging every
775
- * memory + fact written under this agent_id in this key's project
776
- * (soft-forgetting its data does NOT free its cap slot; this does). Resolves
777
- * to the purge counts, an audit id and `slot_freed`.
778
- *
779
- * The namespace must be one `listAgents()` shows for this key: anything else
780
- * rejects with NotFoundError, including a name only another project of the
781
- * account uses (the server answered 200 with zero counts for it before
782
- * 2026-09-28, and freed nothing). The cap counts a name across the account,
783
- * so while another project still uses the same agent_id its rows stay and
784
- * `slot_freed` is false.
785
- */
786
- async deleteAgent(agentId) {
787
- return this.request("DELETE", `/v1/agents/${seg(agentId, "agentId")}`);
788
- }
789
- // ── facts ─────────────────────────────────────────────────────────────────
790
- /**
791
- * GET /v1/facts: typed (subject, predicate, object) triples with bi-temporal
792
- * validity. Pass `as_of` (ISO date) for a point-in-time query, and
793
- * `known_as_of` (ISO date) for what the store knew on that date (Korely
794
- * Agent 0.1.26; older servers ignore it). Resolves to an array that also
795
- * carries `total`, the matches across all pages.
796
- */
797
- async getFacts(opts = {}) {
798
- checkOptions("getFacts", opts, FACTS_KEYS);
799
- const params = {
800
- subject: opts.subject,
801
- entity: opts.entity,
802
- predicate: opts.predicate,
803
- predicate_family: opts.predicate_family,
804
- as_of: opts.as_of,
805
- known_as_of: opts.known_as_of,
806
- user_id: opts.user_id,
807
- agent_id: opts.agent_id,
808
- limit: opts.limit ?? 50,
809
- offset: opts.offset ?? 0
810
- };
811
- if (opts.include_invalidated) params.include_invalidated = "true";
812
- if (opts.exclude_sessions) params.exclude_sessions = "true";
813
- const body = await this.request("GET", "/v1/facts", { params });
814
- const facts = [...body.facts ?? []];
815
- Object.defineProperty(facts, "total", {
816
- value: typeof body.total === "number" ? body.total : facts.length,
817
- enumerable: false
818
- });
819
- return facts;
820
- }
821
- /**
822
- * POST /v1/facts: write a typed (subject, predicate, object) triple directly,
823
- * skipping extraction. The server runs the contradiction check; the fact is
824
- * bi-temporal (pass `valid_from` for a historical fact, `tense: "past"` for
825
- * one that is over). Resolves to the written Fact, with `invalidated`
826
- * listing any fact ids it superseded.
827
- */
828
- async addFactTriple(subject, predicate, object, opts = {}) {
829
- checkOptions("addFactTriple", opts, TRIPLE_KEYS);
830
- const fact = await this.request("POST", "/v1/facts", {
831
- body: {
832
- subject,
833
- predicate,
834
- object,
835
- user_id: opts.user_id,
836
- agent_id: opts.agent_id,
837
- run_id: opts.run_id,
838
- subject_type: opts.subject_type ?? "unknown",
839
- object_is_literal: opts.object_is_literal ?? false,
840
- confidence: opts.confidence ?? 0.9,
841
- valid_from: opts.valid_from,
842
- tense: opts.tense
843
- }
844
- });
845
- return {
846
- ...fact,
847
- user_id: fact.user_id !== void 0 ? fact.user_id : opts.user_id,
848
- agent_id: fact.agent_id !== void 0 ? fact.agent_id : opts.agent_id
849
- };
850
- }
851
- /**
852
- * POST /v1/facts/:id/forget: close a fact; it stops being current and stays
853
- * in history.
854
- *
855
- * `at` is the date it STOPPED being true, not the date you noticed. Reading
856
- * `as_of` a date before it still returns the fact, which is the reason
857
- * history is kept rather than rows deleted.
858
- *
859
- * Idempotent: closing an already-closed fact changes nothing and comes back
860
- * with `status === "already_forgotten"`.
861
- *
862
- * This is the half that makes a no-model write path possible: an agent that
863
- * knows a fact is finished says so, and nothing has to infer it.
864
- */
865
- async forgetFact(factId, opts = {}) {
866
- checkOptions("forgetFact", opts, ["at"]);
867
- return this.request("POST", `/v1/facts/${seg(factId, "factId")}/forget`, {
868
- body: { at: opts.at }
869
- });
870
- }
871
- /**
872
- * PATCH /v1/facts/:id: supersede a fact with a corrected one.
873
- *
874
- * Not an edit: the old row keeps its dates and gains a pointer to the new
875
- * one, so `as_of` before the correction still returns what you believed then.
876
- * At least one of the three fields is required.
877
- *
878
- * Resolves to the new Fact in the write shape. Its `invalidated` lists every
879
- * fact the correction superseded: the corrected one first, then any other
880
- * that the contradiction check on the new fact closed. It is not always one
881
- * id. A correction that names the fact as it already stands (same subject,
882
- * predicate and object, still open) supersedes nothing: the server
883
- * reconfirms the fact and returns it, same `id`, with `invalidated: []`.
884
- */
885
- async correctFact(factId, changes) {
886
- return this.request("PATCH", `/v1/facts/${seg(factId, "factId")}`, {
887
- body: changes
888
- });
889
- }
890
- /**
891
- * GET /v1/profile: the assembled profile of one end user, the active typed
892
- * facts known about them, the end user's own facts first, grouped by family.
893
- * Pass `as_of` (ISO date) for the point-in-time profile, `known_as_of` for
894
- * the profile as the store knew it then.
895
- */
896
- async getProfile(opts) {
897
- checkOptions("getProfile", opts, PROFILE_KEYS);
898
- return this.request("GET", "/v1/profile", {
899
- params: {
900
- user_id: opts.user_id,
901
- agent_id: opts.agent_id,
902
- as_of: opts.as_of,
903
- known_as_of: opts.known_as_of,
904
- exclude_sessions: opts.exclude_sessions ? "true" : void 0
905
- }
906
- });
907
- }
908
- // ── context ─────────────────────────────────────────────────────────────
909
- /**
910
- * GET /v1/context: one call that assembles a prompt-ready context block
911
- * (profile + relevant facts + memories) within a token budget. With
912
- * `known_as_of` (ISO date), the block as the store could have built it then.
913
- */
914
- async getContext(opts, extra = {}) {
915
- if (typeof opts === "string") checkOptions("getContext", extra, CONTEXT_EXTRA_KEYS);
916
- else checkOptions("getContext", opts, CONTEXT_KEYS);
917
- const o = typeof opts === "string" ? { ...extra, query: opts } : opts;
918
- if (!o || typeof o.query !== "string" || !o.query.trim()) {
919
- throw new KorelyError("getContext needs a query.");
920
- }
921
- return this.request("GET", "/v1/context", {
922
- params: {
923
- query: o.query,
924
- user_id: o.user_id,
925
- agent_id: o.agent_id,
926
- token_budget: o.token_budget ?? 800,
927
- known_as_of: o.known_as_of,
928
- exclude_sessions: o.exclude_sessions ? "true" : void 0
929
- }
930
- });
931
- }
932
- // ── processing state ───────────────────────────────────────────────────────
933
- /**
934
- * GET /v1/events: which writes have finished being processed.
935
- *
936
- * `add()` resolves as soon as the memory is stored; fact extraction runs
937
- * behind it. Each event carries a memory's `status` ("processing", "ready"
938
- * or "error"), newest first. `status` filters before `limit` (up to 200) is
939
- * applied, so `{ status: "error" }` returns the latest errors however many
940
- * ready writes came after them. `processing` counts every write of this
941
- * key's project still in flight (of `user_id`, when given), whatever
942
- * `status` and `limit` say. No webhook fires when extraction finishes, so
943
- * this is how to know.
944
- */
945
- async events(opts = {}) {
946
- checkOptions("events", opts, EVENTS_KEYS);
947
- return this.request("GET", "/v1/events", {
948
- params: {
949
- user_id: opts.user_id,
950
- status: opts.status,
951
- limit: opts.limit ?? 50
952
- }
953
- });
954
- }
955
- // ── batch ─────────────────────────────────────────────────────────────────
956
- /**
957
- * POST /v1/batch: bulk import, up to 500 memory objects, processed
958
- * asynchronously. Each object is the body of one `add()` (see
959
- * `BatchMemory`): `content` and optionally `user_id`, `agent_id`, `run_id`,
960
- * `metadata` and `timestamp`.
961
- *
962
- * `timestamp` means what it means on `add()`: when the events happened.
963
- * The facts extracted from the item inherit it as `valid_from`, so a
964
- * migration keeps its real dates; without it an item is dated when it is
965
- * imported. A value that is not an ISO 8601 date or datetime refuses the
966
- * whole batch before anything is queued: a 422 (APIError,
967
- * `code === "invalid_request"`) whose message names the item, e.g.
968
- * `memories[3].timestamp`. Any key not listed above is refused the same
969
- * way. Servers older than 2026-09-28 refuse `timestamp` itself.
970
- *
971
- * On the Cloud a batch is also refused, before anything is stored, with a
972
- * 429: `quota_exceeded` (QuotaExceededError) when its memories do not fit in
973
- * what is left of the month, batches already queued included, and
974
- * `too_many_batches` (TooManyBatchesError) while three batches are still
975
- * being imported. The Self-hosted meters nothing and refuses neither.
976
- */
977
- async batch(memories) {
978
- return this.request("POST", "/v1/batch", { body: { memories } });
979
- }
980
- /** GET /v1/batch/:id: poll an import job. */
981
- async batchStatus(jobId) {
982
- return this.request("GET", `/v1/batch/${seg(jobId, "jobId")}`);
983
- }
984
- };
2
+ APIError,
3
+ AuthenticationError,
4
+ ConflictError,
5
+ Korely,
6
+ KorelyError,
7
+ NamespaceForbiddenError,
8
+ NotFoundError,
9
+ QuotaExceededError,
10
+ StaleWriteError,
11
+ TooManyBatchesError,
12
+ VERSION
13
+ } from "./chunk-VT7GXOPS.js";
14
+ import "./chunk-6SD5RRK3.js";
985
15
  export {
986
16
  APIError,
987
17
  AuthenticationError,