korely-memory 0.1.10 → 0.1.12

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
@@ -163,7 +163,9 @@ try {
163
163
 
164
164
  `AuthenticationError` (401) · `NamespaceForbiddenError` (403, e.g.
165
165
  `agent_cap_exceeded`) · `NotFoundError` (404) · `ConflictError` (409, e.g.
166
- `account_has_login`; `stale_write` is its subclass `StaleWriteError`) ·
166
+ `account_has_login`; `fact_not_current` from `correctFact()` of a fact that is
167
+ history, with `currentFactId` the fact to correct instead; `stale_write` is its
168
+ subclass `StaleWriteError`) ·
167
169
  `QuotaExceededError` (429: `retryAfter` is set for `rate_limit_exceeded`,
168
170
  undefined for the monthly `quota_exceeded`) · `TooManyBatchesError` (a
169
171
  `QuotaExceededError`: `too_many_batches` from `batch()`, Cloud only, three
@@ -178,11 +180,21 @@ SDK does not retry on its own.
178
180
  ```ts
179
181
  new Korely({
180
182
  apiKey: "kor_live_...", // or the KORELY_API_KEY env var
181
- region: "eu", // EU only: data stored and processed in the EU
183
+ region: "eu", // the API, api.korely.ai: data stored in the EU
182
184
  timeoutMs: 30000, // covers the whole request, response body included
183
185
  });
184
186
  ```
185
187
 
188
+ The data is stored in the EU (Helsinki). Which model reads a memory, and
189
+ where, is the project's region, chosen per project in the dashboard: Europe
190
+ (gpt-oss-120b on Scaleway, in Paris) or Global (Gemini, by Google), the
191
+ default. A memory written to a Global project is read by Google's model.
192
+
193
+ In Node, `new Korely()` with no key and no `KORELY_API_KEY` reads what
194
+ `korely init` saved (the key and the server, in `~/.korely/config.json`, or
195
+ `$KORELY_CONFIG_HOME/config.json`), as the Python client does. An argument
196
+ comes first, then the environment, then that file.
197
+
186
198
  ### Your own server (korely-agent)
187
199
 
188
200
  Point the client at your install with `baseUrl`, or with the `KORELY_BASE_URL`
package/dist/ai-sdk.cjs CHANGED
@@ -27,6 +27,27 @@ __export(ai_sdk_exports, {
27
27
  module.exports = __toCommonJS(ai_sdk_exports);
28
28
  var import_ai = require("ai");
29
29
  var import_korely_memory = require("korely-memory");
30
+
31
+ // src/options.ts
32
+ function keysOf() {
33
+ return (...keys) => keys;
34
+ }
35
+ function unknownOption(method, opts, known) {
36
+ if (opts === void 0 || opts === null) return void 0;
37
+ if (typeof opts !== "object" || Array.isArray(opts)) {
38
+ return `${method}: the options must be an object, got ${Array.isArray(opts) ? "an array" : typeof opts}.`;
39
+ }
40
+ for (const key of Object.keys(opts)) {
41
+ if (known.includes(key)) continue;
42
+ const snake = key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
43
+ const camel = key.replace(/_([a-z])/g, (_m, c) => c.toUpperCase());
44
+ const meant = known.includes(snake) ? snake : known.includes(camel) ? camel : void 0;
45
+ return `${method}: unknown option ${key}.` + (meant ? ` Did you mean ${meant}?` : "") + ` It takes: ${known.join(", ")}.`;
46
+ }
47
+ return void 0;
48
+ }
49
+
50
+ // src/ai-sdk.ts
30
51
  var QUERY_MAX = 2e3;
31
52
  var CONTENT_MAX = 16e3;
32
53
  var USER_MAX = 6e3;
@@ -36,7 +57,36 @@ var CONTEXT_REUSE_MS = 5 * 6e4;
36
57
  var FAILURE_REUSE_MS = 3e4;
37
58
  var DEFAULT_CONTEXT_TIMEOUT_MS = 5e3;
38
59
  var MAX_TIMER_MS = 2 ** 31 - 1;
39
- function scopeOf(options, caller) {
60
+ var TOOLS_KEYS = keysOf()(
61
+ "userId",
62
+ "agentId",
63
+ "runId",
64
+ "client",
65
+ "tokenBudget",
66
+ "includeDate",
67
+ "timeZone",
68
+ "contextTimeoutMs",
69
+ "onError"
70
+ );
71
+ var MEMORY_KEYS = keysOf()(
72
+ "userId",
73
+ "agentId",
74
+ "runId",
75
+ "client",
76
+ "tokenBudget",
77
+ "includeDate",
78
+ "timeZone",
79
+ "contextTimeoutMs",
80
+ "onError",
81
+ "remember",
82
+ "waitUntil"
83
+ );
84
+ function checkOptions(method, opts, known) {
85
+ const problem = unknownOption(method, opts, known);
86
+ if (problem) throw new import_korely_memory.KorelyError(problem);
87
+ }
88
+ function scopeOf(options, caller, known) {
89
+ checkOptions(caller, options, known);
40
90
  const o = options ?? {};
41
91
  if (typeof o.userId !== "string" || !o.userId.trim()) {
42
92
  throw new import_korely_memory.KorelyError(
@@ -168,7 +218,7 @@ function readWithin(read, limit) {
168
218
  });
169
219
  }
170
220
  function korelyMemoryMiddleware(options) {
171
- const scope = scopeOf(options, "korelyMemoryMiddleware");
221
+ const scope = scopeOf(options, "korelyMemoryMiddleware", MEMORY_KEYS);
172
222
  const remember = options.remember ?? true;
173
223
  const report = scope.report;
174
224
  const waitUntil = options.waitUntil;
@@ -286,7 +336,7 @@ function oneText(value, key, max) {
286
336
  return { success: true, value: { [key]: clip(raw.trim(), max) } };
287
337
  }
288
338
  function korelyTools(options) {
289
- const scope = scopeOf(options, "korelyTools");
339
+ const scope = scopeOf(options, "korelyTools", TOOLS_KEYS);
290
340
  const withDate = (text) => scope.today ? `${scope.today()}
291
341
 
292
342
  ${text}` : text;
package/dist/ai-sdk.js CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ keysOf,
3
+ unknownOption
4
+ } from "./chunk-6SD5RRK3.js";
5
+
1
6
  // src/ai-sdk.ts
2
7
  import { gateway, jsonSchema, tool, wrapLanguageModel } from "ai";
3
8
  import { Korely, KorelyError } from "korely-memory";
@@ -10,7 +15,36 @@ var CONTEXT_REUSE_MS = 5 * 6e4;
10
15
  var FAILURE_REUSE_MS = 3e4;
11
16
  var DEFAULT_CONTEXT_TIMEOUT_MS = 5e3;
12
17
  var MAX_TIMER_MS = 2 ** 31 - 1;
13
- function scopeOf(options, caller) {
18
+ var TOOLS_KEYS = keysOf()(
19
+ "userId",
20
+ "agentId",
21
+ "runId",
22
+ "client",
23
+ "tokenBudget",
24
+ "includeDate",
25
+ "timeZone",
26
+ "contextTimeoutMs",
27
+ "onError"
28
+ );
29
+ var MEMORY_KEYS = keysOf()(
30
+ "userId",
31
+ "agentId",
32
+ "runId",
33
+ "client",
34
+ "tokenBudget",
35
+ "includeDate",
36
+ "timeZone",
37
+ "contextTimeoutMs",
38
+ "onError",
39
+ "remember",
40
+ "waitUntil"
41
+ );
42
+ function checkOptions(method, opts, known) {
43
+ const problem = unknownOption(method, opts, known);
44
+ if (problem) throw new KorelyError(problem);
45
+ }
46
+ function scopeOf(options, caller, known) {
47
+ checkOptions(caller, options, known);
14
48
  const o = options ?? {};
15
49
  if (typeof o.userId !== "string" || !o.userId.trim()) {
16
50
  throw new KorelyError(
@@ -142,7 +176,7 @@ function readWithin(read, limit) {
142
176
  });
143
177
  }
144
178
  function korelyMemoryMiddleware(options) {
145
- const scope = scopeOf(options, "korelyMemoryMiddleware");
179
+ const scope = scopeOf(options, "korelyMemoryMiddleware", MEMORY_KEYS);
146
180
  const remember = options.remember ?? true;
147
181
  const report = scope.report;
148
182
  const waitUntil = options.waitUntil;
@@ -260,7 +294,7 @@ function oneText(value, key, max) {
260
294
  return { success: true, value: { [key]: clip(raw.trim(), max) } };
261
295
  }
262
296
  function korelyTools(options) {
263
- const scope = scopeOf(options, "korelyTools");
297
+ const scope = scopeOf(options, "korelyTools", TOOLS_KEYS);
264
298
  const withDate = (text) => scope.today ? `${scope.today()}
265
299
 
266
300
  ${text}` : text;
@@ -0,0 +1,31 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/options.ts
9
+ function keysOf() {
10
+ return (...keys) => keys;
11
+ }
12
+ function unknownOption(method, opts, known) {
13
+ if (opts === void 0 || opts === null) return void 0;
14
+ if (typeof opts !== "object" || Array.isArray(opts)) {
15
+ return `${method}: the options must be an object, got ${Array.isArray(opts) ? "an array" : typeof opts}.`;
16
+ }
17
+ for (const key of Object.keys(opts)) {
18
+ if (known.includes(key)) continue;
19
+ const snake = key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
20
+ const camel = key.replace(/_([a-z])/g, (_m, c) => c.toUpperCase());
21
+ const meant = known.includes(snake) ? snake : known.includes(camel) ? camel : void 0;
22
+ return `${method}: unknown option ${key}.` + (meant ? ` Did you mean ${meant}?` : "") + ` It takes: ${known.join(", ")}.`;
23
+ }
24
+ return void 0;
25
+ }
26
+
27
+ export {
28
+ __require,
29
+ keysOf,
30
+ unknownOption
31
+ };
package/dist/index.cjs CHANGED
@@ -77,6 +77,7 @@ var ConflictError = class extends APIError {
77
77
  constructor(message = "", opts = {}) {
78
78
  super(message, opts);
79
79
  this.name = "ConflictError";
80
+ this.currentFactId = opts.currentFactId;
80
81
  Object.setPrototypeOf(this, new.target.prototype);
81
82
  }
82
83
  };
@@ -91,6 +92,9 @@ var QuotaExceededError = class extends APIError {
91
92
  constructor(message = "", opts = {}) {
92
93
  super(message, opts);
93
94
  this.name = "QuotaExceededError";
95
+ this.limit = opts.limit;
96
+ this.used = opts.used;
97
+ this.resetsAt = opts.resetsAt;
94
98
  Object.setPrototypeOf(this, new.target.prototype);
95
99
  }
96
100
  };
@@ -102,9 +106,68 @@ var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError
102
106
  }
103
107
  };
104
108
 
109
+ // src/options.ts
110
+ function keysOf() {
111
+ return (...keys) => keys;
112
+ }
113
+ function unknownOption(method, opts, known) {
114
+ if (opts === void 0 || opts === null) return void 0;
115
+ if (typeof opts !== "object" || Array.isArray(opts)) {
116
+ return `${method}: the options must be an object, got ${Array.isArray(opts) ? "an array" : typeof opts}.`;
117
+ }
118
+ for (const key of Object.keys(opts)) {
119
+ if (known.includes(key)) continue;
120
+ const snake = key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
121
+ const camel = key.replace(/_([a-z])/g, (_m, c) => c.toUpperCase());
122
+ const meant = known.includes(snake) ? snake : known.includes(camel) ? camel : void 0;
123
+ return `${method}: unknown option ${key}.` + (meant ? ` Did you mean ${meant}?` : "") + ` It takes: ${known.join(", ")}.`;
124
+ }
125
+ return void 0;
126
+ }
127
+
105
128
  // src/client.ts
106
- var VERSION = "0.1.10";
129
+ var VERSION = "0.1.12";
107
130
  var REGIONS = { eu: "https://api.korely.ai" };
131
+ var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch");
132
+ var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
133
+ var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp");
134
+ var SEARCH_KEYS = keysOf()("user_id", "agent_id", "run_id", "metadata", "limit");
135
+ var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset");
136
+ var UPDATE_KEYS = keysOf()("content", "expected_updated_at");
137
+ var USERS_KEYS = keysOf()("agent_id", "limit", "offset");
138
+ var AGENTS_KEYS = keysOf()("limit", "offset");
139
+ var EVENTS_KEYS = keysOf()("user_id", "status", "limit");
140
+ var AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "limit", "offset");
141
+ var ITER_AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "offset", "page_size");
142
+ var FACTS_KEYS = keysOf()(
143
+ "subject",
144
+ "entity",
145
+ "predicate",
146
+ "predicate_family",
147
+ "include_invalidated",
148
+ "as_of",
149
+ "user_id",
150
+ "agent_id",
151
+ "limit",
152
+ "offset"
153
+ );
154
+ var TRIPLE_KEYS = keysOf()(
155
+ "user_id",
156
+ "agent_id",
157
+ "run_id",
158
+ "subject_type",
159
+ "object_is_literal",
160
+ "confidence",
161
+ "valid_from",
162
+ "tense"
163
+ );
164
+ var PROFILE_KEYS = keysOf()("user_id", "agent_id", "as_of");
165
+ var CONTEXT_KEYS = keysOf()("query", "user_id", "agent_id", "token_budget");
166
+ var CONTEXT_EXTRA_KEYS = keysOf()("user_id", "agent_id", "token_budget");
167
+ function checkOptions(method, opts, known) {
168
+ const problem = unknownOption(method, opts, known);
169
+ if (problem) throw new KorelyError(problem);
170
+ }
108
171
  function coerceContent(content) {
109
172
  if (typeof content === "string") return content;
110
173
  if (Array.isArray(content)) {
@@ -173,13 +236,30 @@ function detailLine(detail) {
173
236
  return void 0;
174
237
  }
175
238
  function errorFields(status, body) {
176
- const text = (v) => typeof v === "string" && v.trim() ? v : void 0;
239
+ const text2 = (v) => typeof v === "string" && v.trim() ? v : void 0;
177
240
  const b = body && typeof body === "object" ? body : {};
178
241
  const pair = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
179
- const code = text(b.code) ?? text(pair.code);
180
- const message = text(b.message) ?? text(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
242
+ const code = text2(b.code) ?? text2(pair.code);
243
+ const message = text2(b.message) ?? text2(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
181
244
  return { code, message };
182
245
  }
246
+ function quotaFields(body) {
247
+ const b = body && typeof body === "object" ? body : {};
248
+ const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
249
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
250
+ const str = (v) => typeof v === "string" && v ? v : void 0;
251
+ return {
252
+ limit: num(b.limit ?? d.limit),
253
+ used: num(b.used ?? d.used),
254
+ resetsAt: str(b.resets_at ?? d.resets_at)
255
+ };
256
+ }
257
+ function conflictFields(body) {
258
+ const b = body && typeof body === "object" ? body : {};
259
+ const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
260
+ const v = b.current_fact_id ?? d.current_fact_id;
261
+ return { currentFactId: typeof v === "string" && v ? v : void 0 };
262
+ }
183
263
  function retryAfterSeconds(raw) {
184
264
  if (raw == null) return void 0;
185
265
  const n = Math.ceil(Number(raw));
@@ -250,7 +330,7 @@ async function exchange(t, method, path, opts = {}) {
250
330
  timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
251
331
  );
252
332
  let resp;
253
- let text;
333
+ let text2;
254
334
  try {
255
335
  try {
256
336
  resp = await t.fetchImpl(url, {
@@ -263,7 +343,7 @@ async function exchange(t, method, path, opts = {}) {
263
343
  throw failed(e);
264
344
  }
265
345
  try {
266
- text = await resp.text();
346
+ text2 = await resp.text();
267
347
  } catch (e) {
268
348
  throw failed(e);
269
349
  }
@@ -271,17 +351,17 @@ async function exchange(t, method, path, opts = {}) {
271
351
  clearTimeout(timer);
272
352
  }
273
353
  let parsed = {};
274
- if (text) {
354
+ if (text2) {
275
355
  try {
276
- parsed = JSON.parse(text);
356
+ parsed = JSON.parse(text2);
277
357
  } catch {
278
358
  if (resp.ok) {
279
359
  throw new KorelyError(
280
- `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text.slice(0, 200))}`,
360
+ `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text2.slice(0, 200))}`,
281
361
  { status: resp.status }
282
362
  );
283
363
  }
284
- parsed = { message: text };
364
+ parsed = { message: text2 };
285
365
  }
286
366
  }
287
367
  if (!resp.ok) {
@@ -301,34 +381,48 @@ function raiseFor(status, body, retryAfter) {
301
381
  if (status === 404) throw new NotFoundError(msg, opts);
302
382
  if (status === 409) {
303
383
  if (code === "stale_write") throw new StaleWriteError(msg, opts);
304
- throw new ConflictError(msg, opts);
384
+ throw new ConflictError(msg, { ...opts, ...conflictFields(body) });
305
385
  }
306
386
  if (status === 429) {
307
- if (code === "too_many_batches") throw new TooManyBatchesError(msg, opts);
308
- throw new QuotaExceededError(msg, opts);
387
+ const quota = { ...opts, ...quotaFields(body) };
388
+ if (code === "too_many_batches") throw new TooManyBatchesError(msg, quota);
389
+ throw new QuotaExceededError(msg, quota);
309
390
  }
310
391
  throw new APIError(msg, opts);
311
392
  }
312
- function refusePythonSpelling(opts) {
313
- if (opts && Object.prototype.hasOwnProperty.call(opts, "base_url")) {
314
- throw new KorelyError(
315
- "Unknown option base_url: the JavaScript SDK takes baseUrl (new Korely({ baseUrl: 'https://...' })) or the KORELY_BASE_URL env var."
316
- );
393
+ function savedConfig() {
394
+ try {
395
+ const proc = typeof process !== "undefined" ? process : void 0;
396
+ if (!proc?.versions?.node) return {};
397
+ const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof require === "function" ? require(id) : void 0;
398
+ const fs = builtin("node:fs");
399
+ const os = builtin("node:os");
400
+ const path = builtin("node:path");
401
+ if (!fs || !os || !path) return {};
402
+ const home = proc.env?.KORELY_CONFIG_HOME || path.join(os.homedir(), ".korely");
403
+ const data = JSON.parse(fs.readFileSync(path.join(home, "config.json"), "utf8"));
404
+ return data && typeof data === "object" ? data : {};
405
+ } catch {
406
+ return {};
317
407
  }
318
408
  }
409
+ function text(v) {
410
+ return typeof v === "string" && v ? v : void 0;
411
+ }
319
412
  var Korely = class {
320
413
  constructor(opts = {}) {
321
- refusePythonSpelling(opts);
414
+ checkOptions("Korely", opts, CLIENT_KEYS);
322
415
  const envKey = typeof process !== "undefined" ? process.env?.KORELY_API_KEY : void 0;
323
- const key = opts.apiKey ?? envKey;
416
+ const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
417
+ const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
418
+ const key = opts.apiKey ?? envKey ?? text(saved.api_key);
324
419
  if (!key) {
325
420
  throw new KorelyError(
326
- "No API key. Pass { apiKey: 'kor_live_...' } or set KORELY_API_KEY."
421
+ "No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
327
422
  );
328
423
  }
329
424
  this.apiKey = key;
330
- const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
331
- this.baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
425
+ this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
332
426
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
333
427
  this.timeoutMs = opts.timeoutMs ?? 3e4;
334
428
  const f = opts.fetch ?? globalThis.fetch;
@@ -358,7 +452,11 @@ var Korely = class {
358
452
  * dashboard: its keys come from its own dashboard.
359
453
  */
360
454
  static async initAgent(agentCaller, opts = {}) {
361
- refusePythonSpelling(opts);
455
+ checkOptions("initAgent", opts, INIT_KEYS);
456
+ const where = opts.processingRegion;
457
+ if (where !== void 0 && where !== "eu" && where !== "global") {
458
+ throw new KorelyError(`processingRegion is "eu" or "global", not ${JSON.stringify(where)}.`);
459
+ }
362
460
  if (agentCaller != null && typeof agentCaller !== "string") {
363
461
  throw new KorelyError(
364
462
  `agentCaller is a label, a string, not ${Array.isArray(agentCaller) ? "an array" : `a ${typeof agentCaller}`}: Korely.initAgent('my-app', { baseUrl }).`
@@ -376,7 +474,9 @@ var Korely = class {
376
474
  { baseUrl, timeoutMs: opts.timeoutMs ?? 3e4, fetchImpl },
377
475
  "POST",
378
476
  "/v1/agents/init",
379
- { body: { agent_caller: agentCaller ?? void 0 } }
477
+ {
478
+ body: { agent_caller: agentCaller ?? void 0, processing_region: opts.processingRegion }
479
+ }
380
480
  );
381
481
  }
382
482
  // ── transport ─────────────────────────────────────────────────────────────
@@ -419,6 +519,7 @@ var Korely = class {
419
519
  * dashboard. No audit event survives: the trail is part of what goes.
420
520
  */
421
521
  async deleteAccount(opts = {}) {
522
+ checkOptions("deleteAccount", opts, ["confirm"]);
422
523
  if (opts?.confirm !== true) {
423
524
  throw new KorelyError(
424
525
  "deleteAccount() deletes this key's account, every key, memory and fact of it, for good. Pass { confirm: true } to mean it.",
@@ -444,6 +545,7 @@ var Korely = class {
444
545
  * project, like every read.
445
546
  */
446
547
  async audit(opts = {}) {
548
+ checkOptions("audit", opts, AUDIT_KEYS);
447
549
  const page = await this.request(
448
550
  "GET",
449
551
  "/v1/audit",
@@ -469,6 +571,7 @@ var Korely = class {
469
571
  * `until: new Date()`) and `offset` the number of events already read.
470
572
  */
471
573
  async *iterAudit(opts = {}) {
574
+ checkOptions("iterAudit", opts, ITER_AUDIT_KEYS);
472
575
  const filters = auditFilters(opts);
473
576
  let offset = opts.offset ?? 0;
474
577
  let pin = filters.until === void 0 && offset === 0;
@@ -499,15 +602,16 @@ var Korely = class {
499
602
  * backfill: facts extracted inherit it as `valid_from`.
500
603
  */
501
604
  async add(content, opts = {}) {
502
- const text = coerceContent(content);
503
- if (!text.trim()) {
605
+ checkOptions("add", opts, ADD_KEYS);
606
+ const text2 = coerceContent(content);
607
+ if (!text2.trim()) {
504
608
  throw new KorelyError(
505
609
  "content is empty: pass a non-blank string or messages with content."
506
610
  );
507
611
  }
508
612
  return this.request("POST", "/v1/memories", {
509
613
  body: {
510
- content: text,
614
+ content: text2,
511
615
  agent_id: opts.agent_id,
512
616
  user_id: opts.user_id,
513
617
  run_id: opts.run_id,
@@ -523,6 +627,7 @@ var Korely = class {
523
627
  * the server default (15), max 50.
524
628
  */
525
629
  async search(query, opts = {}) {
630
+ checkOptions("search", opts, SEARCH_KEYS);
526
631
  const body = await this.request("POST", "/v1/memories/search", {
527
632
  body: {
528
633
  query,
@@ -541,6 +646,7 @@ var Korely = class {
541
646
  * `total` and `offset` walk the rest.
542
647
  */
543
648
  async getAll(opts = {}) {
649
+ checkOptions("getAll", opts, LIST_KEYS);
544
650
  const page = await this.request(
545
651
  "GET",
546
652
  "/v1/memories",
@@ -565,6 +671,7 @@ var Korely = class {
565
671
  * for optimistic concurrency (throws StaleWriteError instead of clobbering).
566
672
  */
567
673
  async update(memoryId, opts) {
674
+ checkOptions("update", opts, UPDATE_KEYS);
568
675
  return this.request("PATCH", `/v1/memories/${seg(memoryId, "memoryId")}`, {
569
676
  body: {
570
677
  content: opts.content,
@@ -590,6 +697,7 @@ var Korely = class {
590
697
  * the same numbers; whichever pair the server sends fills both.
591
698
  */
592
699
  async deleteAll(opts) {
700
+ checkOptions("deleteAll", opts, ["user_id"]);
593
701
  const r = await this.request(
594
702
  "DELETE",
595
703
  `/v1/users/${seg(opts.user_id, "user_id")}/memories`
@@ -611,6 +719,7 @@ var Korely = class {
611
719
  * namespaces), each with active memory + fact counts and last-active time.
612
720
  */
613
721
  async users(opts = {}) {
722
+ checkOptions("users", opts, USERS_KEYS);
614
723
  const page = await this.request(
615
724
  "GET",
616
725
  "/v1/users",
@@ -639,6 +748,7 @@ var Korely = class {
639
748
  * sets no cap and answers `cap: 0`.
640
749
  */
641
750
  async listAgents(opts = {}) {
751
+ checkOptions("listAgents", opts, AGENTS_KEYS);
642
752
  const page = await this.request("GET", "/v1/agents", {
643
753
  params: {
644
754
  limit: opts.limit ?? 50,
@@ -670,6 +780,7 @@ var Korely = class {
670
780
  * array that also carries `total`, the matches across all pages.
671
781
  */
672
782
  async getFacts(opts = {}) {
783
+ checkOptions("getFacts", opts, FACTS_KEYS);
673
784
  const params = {
674
785
  subject: opts.subject,
675
786
  entity: opts.entity,
@@ -698,7 +809,8 @@ var Korely = class {
698
809
  * listing any fact ids it superseded.
699
810
  */
700
811
  async addFactTriple(subject, predicate, object, opts = {}) {
701
- return this.request("POST", "/v1/facts", {
812
+ checkOptions("addFactTriple", opts, TRIPLE_KEYS);
813
+ const fact = await this.request("POST", "/v1/facts", {
702
814
  body: {
703
815
  subject,
704
816
  predicate,
@@ -713,6 +825,11 @@ var Korely = class {
713
825
  tense: opts.tense
714
826
  }
715
827
  });
828
+ return {
829
+ ...fact,
830
+ user_id: fact.user_id !== void 0 ? fact.user_id : opts.user_id,
831
+ agent_id: fact.agent_id !== void 0 ? fact.agent_id : opts.agent_id
832
+ };
716
833
  }
717
834
  /**
718
835
  * POST /v1/facts/:id/forget: close a fact; it stops being current and stays
@@ -729,6 +846,7 @@ var Korely = class {
729
846
  * knows a fact is finished says so, and nothing has to infer it.
730
847
  */
731
848
  async forgetFact(factId, opts = {}) {
849
+ checkOptions("forgetFact", opts, ["at"]);
732
850
  return this.request("POST", `/v1/facts/${seg(factId, "factId")}/forget`, {
733
851
  body: { at: opts.at }
734
852
  });
@@ -758,6 +876,7 @@ var Korely = class {
758
876
  * Pass `as_of` (ISO date) for the point-in-time profile.
759
877
  */
760
878
  async getProfile(opts) {
879
+ checkOptions("getProfile", opts, PROFILE_KEYS);
761
880
  return this.request("GET", "/v1/profile", {
762
881
  params: {
763
882
  user_id: opts.user_id,
@@ -772,6 +891,8 @@ var Korely = class {
772
891
  * (profile + relevant facts + memories) within a token budget.
773
892
  */
774
893
  async getContext(opts, extra = {}) {
894
+ if (typeof opts === "string") checkOptions("getContext", extra, CONTEXT_EXTRA_KEYS);
895
+ else checkOptions("getContext", opts, CONTEXT_KEYS);
775
896
  const o = typeof opts === "string" ? { ...extra, query: opts } : opts;
776
897
  if (!o || typeof o.query !== "string" || !o.query.trim()) {
777
898
  throw new KorelyError("getContext needs a query.");
@@ -799,6 +920,7 @@ var Korely = class {
799
920
  * this is how to know.
800
921
  */
801
922
  async events(opts = {}) {
923
+ checkOptions("events", opts, EVENTS_KEYS);
802
924
  return this.request("GET", "/v1/events", {
803
925
  params: {
804
926
  user_id: opts.user_id,
package/dist/index.d.cts CHANGED
@@ -275,10 +275,18 @@ interface PingResponse {
275
275
  */
276
276
  tier: string;
277
277
  /**
278
- * Where the key's data is stored and processed, as the server declares it
279
- * ("eu-hel1" on the Cloud; on the Self-hosted, what its operator set).
278
+ * Where the key's data is stored, as the server declares it ("eu-hel1" on
279
+ * the Cloud; on the Self-hosted, what its operator set). Not where a memory
280
+ * is read by a model: on the Cloud that is the project's region, Europe or
281
+ * Global (Gemini, by Google).
280
282
  */
281
283
  region: string;
284
+ /**
285
+ * Where a memory is read by a model, "eu" or "global": the region of the
286
+ * key's project on the Cloud, of the writer the install uses on the
287
+ * Self-hosted. Absent from a server older than 2026-10-07; null with no writer.
288
+ */
289
+ processing_region?: "eu" | "global" | null;
282
290
  /** What the key may do, e.g. "memories:read". */
283
291
  scopes: string[];
284
292
  }
@@ -288,6 +296,8 @@ interface AgentInitResult {
288
296
  api_key: string;
289
297
  tier: string;
290
298
  region: string;
299
+ /** Where the new project's memories are read by a model. */
300
+ processing_region?: "eu" | "global";
291
301
  scopes: string[];
292
302
  /** The hobby allowance: writes_per_month, queries_per_month, agents, the monthly AI budget. */
293
303
  quotas: Record<string, unknown>;
@@ -464,11 +474,16 @@ interface ForgetReceipt {
464
474
 
465
475
  /** Must equal `version` in package.json (a test checks). It goes out in the
466
476
  * X-Korely-Client header, and said 0.1.1 from 0.1.1 to 0.1.6. */
467
- declare const VERSION = "0.1.10";
477
+ declare const VERSION = "0.1.12";
468
478
  interface KorelyOptions {
469
479
  /** Your `kor_live_...` key. Falls back to the KORELY_API_KEY env var. */
470
480
  apiKey?: string;
471
- /** EU only for now (data stored and processed in the EU). */
481
+ /**
482
+ * The API to call: "eu" (api.korely.ai), the only one today. The data is
483
+ * stored in the EU (Helsinki). The model that reads a memory is the
484
+ * project's region, set per project in the dashboard: Europe (gpt-oss-120b
485
+ * on Scaleway, in Paris) or Global (Gemini, by Google), the default.
486
+ */
472
487
  region?: "eu";
473
488
  /** Override the base URL (a self-hosted install, or testing). */
474
489
  baseUrl?: string;
@@ -479,7 +494,14 @@ interface KorelyOptions {
479
494
  }
480
495
  /** Where and how `Korely.initAgent()` signs up: the client options a call
481
496
  * without a key can use. */
482
- type InitAgentOptions = Pick<KorelyOptions, "region" | "baseUrl" | "timeoutMs" | "fetch">;
497
+ interface InitAgentOptions extends Pick<KorelyOptions, "region" | "baseUrl" | "timeoutMs" | "fetch"> {
498
+ /**
499
+ * Where the new project's memories are read by a model: "eu" (gpt-oss-120b
500
+ * on Scaleway, Paris) or "global" (Gemini, by Google), the server's default
501
+ * when left out. Sent only when given (servers since 2026-10-07).
502
+ */
503
+ processingRegion?: "eu" | "global";
504
+ }
483
505
  declare class Korely {
484
506
  readonly apiKey: string;
485
507
  readonly baseUrl: string;
@@ -816,12 +838,18 @@ declare class NamespaceForbiddenError extends APIError {
816
838
  declare class NotFoundError extends APIError {
817
839
  constructor(message?: string, opts?: APIErrorOptions);
818
840
  }
841
+ interface ConflictErrorOptions extends APIErrorOptions {
842
+ currentFactId?: string;
843
+ }
819
844
  /**
820
845
  * 409: the request conflicts with what the server holds. `code` names the
821
846
  * conflict: `stale_write` (update() with an expected_updated_at older than the
822
847
  * record, thrown as the subclass StaleWriteError), `account_has_login`
823
848
  * (`deleteAccount()` with the key of an account somebody signs in to, Cloud
824
- * only) or `conflict` (the Self-hosted's code for a 409 that names no other).
849
+ * only), `fact_not_current` (`correctFact()` of a fact that is history:
850
+ * superseded, forgotten or ended; `currentFactId` is the fact to correct
851
+ * instead) or `conflict` (the Self-hosted's code for a 409 that names no
852
+ * other).
825
853
  *
826
854
  * Until 2026-10-06 every 409 was a StaleWriteError, so a refusal that has
827
855
  * nothing to do with an update read as a lost write, and code written to
@@ -829,7 +857,15 @@ declare class NotFoundError extends APIError {
829
857
  * changes.
830
858
  */
831
859
  declare class ConflictError extends APIError {
832
- constructor(message?: string, opts?: APIErrorOptions);
860
+ /**
861
+ * On `fact_not_current` (2026-10-07): the id of the fact that holds now, the
862
+ * one to correct instead. Undefined when nothing superseded the fact asked
863
+ * (it was forgotten or ended: write the value of now with `addFactTriple()`),
864
+ * on any other conflict, and from a server that does not send it. Read
865
+ * this, never the message.
866
+ */
867
+ readonly currentFactId?: string;
868
+ constructor(message?: string, opts?: ConflictErrorOptions);
833
869
  }
834
870
  /**
835
871
  * 409 `stale_write`: update() with an expected_updated_at older than the
@@ -847,8 +883,22 @@ declare class StaleWriteError extends ConflictError {
847
883
  * `retryAfter` comes from APIError, which every error the server answers with
848
884
  * carries.
849
885
  */
886
+ interface QuotaErrorOptions extends APIErrorOptions {
887
+ limit?: number;
888
+ used?: number;
889
+ resetsAt?: string;
890
+ }
850
891
  declare class QuotaExceededError extends APIError {
851
- constructor(message?: string, opts?: APIErrorOptions);
892
+ /**
893
+ * On the Cloud's `quota_exceeded` (2026-10-07): the month's allowance (the
894
+ * plan plus the month's top-ups), what was used, and when it starts again
895
+ * (ISO date). Undefined from a server that does not send them. Read these,
896
+ * never the message, which says the same in words that change.
897
+ */
898
+ readonly limit?: number;
899
+ readonly used?: number;
900
+ readonly resetsAt?: string;
901
+ constructor(message?: string, opts?: QuotaErrorOptions);
852
902
  }
853
903
  /**
854
904
  * 429 `too_many_batches` (Cloud only): three `batch()` imports of the account
@@ -862,7 +912,7 @@ declare class QuotaExceededError extends APIError {
862
912
  * docs tell you to stop on that one, while this one clears in minutes.
863
913
  */
864
914
  declare class TooManyBatchesError extends QuotaExceededError {
865
- constructor(message?: string, opts?: APIErrorOptions);
915
+ constructor(message?: string, opts?: QuotaErrorOptions);
866
916
  }
867
917
 
868
918
  export { APIError, type AccountDeleteReceipt, type AddFactTripleOptions, type AddOptions, type AgentDeleteReceipt, type AgentInitResult, type AgentScope, type AgentsPage, type AuditAction, type AuditActor, type AuditEvent, type AuditOptions, type AuditPage, type AuditRead, AuthenticationError, type BatchJob, type BatchMemory, type BulkReceipt, ConflictError, type Context, type DeleteReceipt, type EventsOptions, type EventsResponse, type Fact, type FactList, type ForgetReceipt, type GetContextOptions, type GetFactsOptions, type GetProfileOptions, type HistoryEvent, type HistoryEventType, type InitAgentOptions, type IterAuditOptions, Korely, KorelyError, type KorelyOptions, type ListAgentsOptions, type ListOptions, type Memory, type MemoryEvent, type MemoryHistory, type MemoryPage, type Message, NamespaceForbiddenError, NotFoundError, type PingResponse, type Profile, QuotaExceededError, type SearchHit, type SearchOptions, StaleWriteError, TooManyBatchesError, type UpdateOptions, type UserScope, type UsersOptions, type UsersPage, VERSION };
package/dist/index.d.ts CHANGED
@@ -275,10 +275,18 @@ interface PingResponse {
275
275
  */
276
276
  tier: string;
277
277
  /**
278
- * Where the key's data is stored and processed, as the server declares it
279
- * ("eu-hel1" on the Cloud; on the Self-hosted, what its operator set).
278
+ * Where the key's data is stored, as the server declares it ("eu-hel1" on
279
+ * the Cloud; on the Self-hosted, what its operator set). Not where a memory
280
+ * is read by a model: on the Cloud that is the project's region, Europe or
281
+ * Global (Gemini, by Google).
280
282
  */
281
283
  region: string;
284
+ /**
285
+ * Where a memory is read by a model, "eu" or "global": the region of the
286
+ * key's project on the Cloud, of the writer the install uses on the
287
+ * Self-hosted. Absent from a server older than 2026-10-07; null with no writer.
288
+ */
289
+ processing_region?: "eu" | "global" | null;
282
290
  /** What the key may do, e.g. "memories:read". */
283
291
  scopes: string[];
284
292
  }
@@ -288,6 +296,8 @@ interface AgentInitResult {
288
296
  api_key: string;
289
297
  tier: string;
290
298
  region: string;
299
+ /** Where the new project's memories are read by a model. */
300
+ processing_region?: "eu" | "global";
291
301
  scopes: string[];
292
302
  /** The hobby allowance: writes_per_month, queries_per_month, agents, the monthly AI budget. */
293
303
  quotas: Record<string, unknown>;
@@ -464,11 +474,16 @@ interface ForgetReceipt {
464
474
 
465
475
  /** Must equal `version` in package.json (a test checks). It goes out in the
466
476
  * X-Korely-Client header, and said 0.1.1 from 0.1.1 to 0.1.6. */
467
- declare const VERSION = "0.1.10";
477
+ declare const VERSION = "0.1.12";
468
478
  interface KorelyOptions {
469
479
  /** Your `kor_live_...` key. Falls back to the KORELY_API_KEY env var. */
470
480
  apiKey?: string;
471
- /** EU only for now (data stored and processed in the EU). */
481
+ /**
482
+ * The API to call: "eu" (api.korely.ai), the only one today. The data is
483
+ * stored in the EU (Helsinki). The model that reads a memory is the
484
+ * project's region, set per project in the dashboard: Europe (gpt-oss-120b
485
+ * on Scaleway, in Paris) or Global (Gemini, by Google), the default.
486
+ */
472
487
  region?: "eu";
473
488
  /** Override the base URL (a self-hosted install, or testing). */
474
489
  baseUrl?: string;
@@ -479,7 +494,14 @@ interface KorelyOptions {
479
494
  }
480
495
  /** Where and how `Korely.initAgent()` signs up: the client options a call
481
496
  * without a key can use. */
482
- type InitAgentOptions = Pick<KorelyOptions, "region" | "baseUrl" | "timeoutMs" | "fetch">;
497
+ interface InitAgentOptions extends Pick<KorelyOptions, "region" | "baseUrl" | "timeoutMs" | "fetch"> {
498
+ /**
499
+ * Where the new project's memories are read by a model: "eu" (gpt-oss-120b
500
+ * on Scaleway, Paris) or "global" (Gemini, by Google), the server's default
501
+ * when left out. Sent only when given (servers since 2026-10-07).
502
+ */
503
+ processingRegion?: "eu" | "global";
504
+ }
483
505
  declare class Korely {
484
506
  readonly apiKey: string;
485
507
  readonly baseUrl: string;
@@ -816,12 +838,18 @@ declare class NamespaceForbiddenError extends APIError {
816
838
  declare class NotFoundError extends APIError {
817
839
  constructor(message?: string, opts?: APIErrorOptions);
818
840
  }
841
+ interface ConflictErrorOptions extends APIErrorOptions {
842
+ currentFactId?: string;
843
+ }
819
844
  /**
820
845
  * 409: the request conflicts with what the server holds. `code` names the
821
846
  * conflict: `stale_write` (update() with an expected_updated_at older than the
822
847
  * record, thrown as the subclass StaleWriteError), `account_has_login`
823
848
  * (`deleteAccount()` with the key of an account somebody signs in to, Cloud
824
- * only) or `conflict` (the Self-hosted's code for a 409 that names no other).
849
+ * only), `fact_not_current` (`correctFact()` of a fact that is history:
850
+ * superseded, forgotten or ended; `currentFactId` is the fact to correct
851
+ * instead) or `conflict` (the Self-hosted's code for a 409 that names no
852
+ * other).
825
853
  *
826
854
  * Until 2026-10-06 every 409 was a StaleWriteError, so a refusal that has
827
855
  * nothing to do with an update read as a lost write, and code written to
@@ -829,7 +857,15 @@ declare class NotFoundError extends APIError {
829
857
  * changes.
830
858
  */
831
859
  declare class ConflictError extends APIError {
832
- constructor(message?: string, opts?: APIErrorOptions);
860
+ /**
861
+ * On `fact_not_current` (2026-10-07): the id of the fact that holds now, the
862
+ * one to correct instead. Undefined when nothing superseded the fact asked
863
+ * (it was forgotten or ended: write the value of now with `addFactTriple()`),
864
+ * on any other conflict, and from a server that does not send it. Read
865
+ * this, never the message.
866
+ */
867
+ readonly currentFactId?: string;
868
+ constructor(message?: string, opts?: ConflictErrorOptions);
833
869
  }
834
870
  /**
835
871
  * 409 `stale_write`: update() with an expected_updated_at older than the
@@ -847,8 +883,22 @@ declare class StaleWriteError extends ConflictError {
847
883
  * `retryAfter` comes from APIError, which every error the server answers with
848
884
  * carries.
849
885
  */
886
+ interface QuotaErrorOptions extends APIErrorOptions {
887
+ limit?: number;
888
+ used?: number;
889
+ resetsAt?: string;
890
+ }
850
891
  declare class QuotaExceededError extends APIError {
851
- constructor(message?: string, opts?: APIErrorOptions);
892
+ /**
893
+ * On the Cloud's `quota_exceeded` (2026-10-07): the month's allowance (the
894
+ * plan plus the month's top-ups), what was used, and when it starts again
895
+ * (ISO date). Undefined from a server that does not send them. Read these,
896
+ * never the message, which says the same in words that change.
897
+ */
898
+ readonly limit?: number;
899
+ readonly used?: number;
900
+ readonly resetsAt?: string;
901
+ constructor(message?: string, opts?: QuotaErrorOptions);
852
902
  }
853
903
  /**
854
904
  * 429 `too_many_batches` (Cloud only): three `batch()` imports of the account
@@ -862,7 +912,7 @@ declare class QuotaExceededError extends APIError {
862
912
  * docs tell you to stop on that one, while this one clears in minutes.
863
913
  */
864
914
  declare class TooManyBatchesError extends QuotaExceededError {
865
- constructor(message?: string, opts?: APIErrorOptions);
915
+ constructor(message?: string, opts?: QuotaErrorOptions);
866
916
  }
867
917
 
868
918
  export { APIError, type AccountDeleteReceipt, type AddFactTripleOptions, type AddOptions, type AgentDeleteReceipt, type AgentInitResult, type AgentScope, type AgentsPage, type AuditAction, type AuditActor, type AuditEvent, type AuditOptions, type AuditPage, type AuditRead, AuthenticationError, type BatchJob, type BatchMemory, type BulkReceipt, ConflictError, type Context, type DeleteReceipt, type EventsOptions, type EventsResponse, type Fact, type FactList, type ForgetReceipt, type GetContextOptions, type GetFactsOptions, type GetProfileOptions, type HistoryEvent, type HistoryEventType, type InitAgentOptions, type IterAuditOptions, Korely, KorelyError, type KorelyOptions, type ListAgentsOptions, type ListOptions, type Memory, type MemoryEvent, type MemoryHistory, type MemoryPage, type Message, NamespaceForbiddenError, NotFoundError, type PingResponse, type Profile, QuotaExceededError, type SearchHit, type SearchOptions, StaleWriteError, TooManyBatchesError, type UpdateOptions, type UserScope, type UsersOptions, type UsersPage, VERSION };
package/dist/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ import {
2
+ __require,
3
+ keysOf,
4
+ unknownOption
5
+ } from "./chunk-6SD5RRK3.js";
6
+
1
7
  // src/errors.ts
2
8
  var KorelyError = class extends Error {
3
9
  constructor(message = "", opts = {}) {
@@ -41,6 +47,7 @@ var ConflictError = class extends APIError {
41
47
  constructor(message = "", opts = {}) {
42
48
  super(message, opts);
43
49
  this.name = "ConflictError";
50
+ this.currentFactId = opts.currentFactId;
44
51
  Object.setPrototypeOf(this, new.target.prototype);
45
52
  }
46
53
  };
@@ -55,6 +62,9 @@ var QuotaExceededError = class extends APIError {
55
62
  constructor(message = "", opts = {}) {
56
63
  super(message, opts);
57
64
  this.name = "QuotaExceededError";
65
+ this.limit = opts.limit;
66
+ this.used = opts.used;
67
+ this.resetsAt = opts.resetsAt;
58
68
  Object.setPrototypeOf(this, new.target.prototype);
59
69
  }
60
70
  };
@@ -67,8 +77,48 @@ var TooManyBatchesError = class _TooManyBatchesError extends QuotaExceededError
67
77
  };
68
78
 
69
79
  // src/client.ts
70
- var VERSION = "0.1.10";
80
+ var VERSION = "0.1.12";
71
81
  var REGIONS = { eu: "https://api.korely.ai" };
82
+ var CLIENT_KEYS = keysOf()("apiKey", "region", "baseUrl", "timeoutMs", "fetch");
83
+ var INIT_KEYS = keysOf()("region", "baseUrl", "timeoutMs", "fetch", "processingRegion");
84
+ var ADD_KEYS = keysOf()("agent_id", "user_id", "run_id", "metadata", "timestamp");
85
+ var SEARCH_KEYS = keysOf()("user_id", "agent_id", "run_id", "metadata", "limit");
86
+ var LIST_KEYS = keysOf()("user_id", "agent_id", "run_id", "limit", "offset");
87
+ var UPDATE_KEYS = keysOf()("content", "expected_updated_at");
88
+ var USERS_KEYS = keysOf()("agent_id", "limit", "offset");
89
+ var AGENTS_KEYS = keysOf()("limit", "offset");
90
+ var EVENTS_KEYS = keysOf()("user_id", "status", "limit");
91
+ var AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "limit", "offset");
92
+ var ITER_AUDIT_KEYS = keysOf()("user_id", "action", "since", "until", "offset", "page_size");
93
+ var FACTS_KEYS = keysOf()(
94
+ "subject",
95
+ "entity",
96
+ "predicate",
97
+ "predicate_family",
98
+ "include_invalidated",
99
+ "as_of",
100
+ "user_id",
101
+ "agent_id",
102
+ "limit",
103
+ "offset"
104
+ );
105
+ var TRIPLE_KEYS = keysOf()(
106
+ "user_id",
107
+ "agent_id",
108
+ "run_id",
109
+ "subject_type",
110
+ "object_is_literal",
111
+ "confidence",
112
+ "valid_from",
113
+ "tense"
114
+ );
115
+ var PROFILE_KEYS = keysOf()("user_id", "agent_id", "as_of");
116
+ var CONTEXT_KEYS = keysOf()("query", "user_id", "agent_id", "token_budget");
117
+ var CONTEXT_EXTRA_KEYS = keysOf()("user_id", "agent_id", "token_budget");
118
+ function checkOptions(method, opts, known) {
119
+ const problem = unknownOption(method, opts, known);
120
+ if (problem) throw new KorelyError(problem);
121
+ }
72
122
  function coerceContent(content) {
73
123
  if (typeof content === "string") return content;
74
124
  if (Array.isArray(content)) {
@@ -137,13 +187,30 @@ function detailLine(detail) {
137
187
  return void 0;
138
188
  }
139
189
  function errorFields(status, body) {
140
- const text = (v) => typeof v === "string" && v.trim() ? v : void 0;
190
+ const text2 = (v) => typeof v === "string" && v.trim() ? v : void 0;
141
191
  const b = body && typeof body === "object" ? body : {};
142
192
  const pair = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
143
- const code = text(b.code) ?? text(pair.code);
144
- const message = text(b.message) ?? text(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
193
+ const code = text2(b.code) ?? text2(pair.code);
194
+ const message = text2(b.message) ?? text2(pair.message) ?? detailLine(b.detail) ?? code ?? `HTTP ${status}`;
145
195
  return { code, message };
146
196
  }
197
+ function quotaFields(body) {
198
+ const b = body && typeof body === "object" ? body : {};
199
+ const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
200
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
201
+ const str = (v) => typeof v === "string" && v ? v : void 0;
202
+ return {
203
+ limit: num(b.limit ?? d.limit),
204
+ used: num(b.used ?? d.used),
205
+ resetsAt: str(b.resets_at ?? d.resets_at)
206
+ };
207
+ }
208
+ function conflictFields(body) {
209
+ const b = body && typeof body === "object" ? body : {};
210
+ const d = b.detail && typeof b.detail === "object" && !Array.isArray(b.detail) ? b.detail : {};
211
+ const v = b.current_fact_id ?? d.current_fact_id;
212
+ return { currentFactId: typeof v === "string" && v ? v : void 0 };
213
+ }
147
214
  function retryAfterSeconds(raw) {
148
215
  if (raw == null) return void 0;
149
216
  const n = Math.ceil(Number(raw));
@@ -214,7 +281,7 @@ async function exchange(t, method, path, opts = {}) {
214
281
  timedOut ? `Request timed out after ${t.timeoutMs} ms (${method} ${path}).` : `Connection error: ${e?.message ?? String(e)}`
215
282
  );
216
283
  let resp;
217
- let text;
284
+ let text2;
218
285
  try {
219
286
  try {
220
287
  resp = await t.fetchImpl(url, {
@@ -227,7 +294,7 @@ async function exchange(t, method, path, opts = {}) {
227
294
  throw failed(e);
228
295
  }
229
296
  try {
230
- text = await resp.text();
297
+ text2 = await resp.text();
231
298
  } catch (e) {
232
299
  throw failed(e);
233
300
  }
@@ -235,17 +302,17 @@ async function exchange(t, method, path, opts = {}) {
235
302
  clearTimeout(timer);
236
303
  }
237
304
  let parsed = {};
238
- if (text) {
305
+ if (text2) {
239
306
  try {
240
- parsed = JSON.parse(text);
307
+ parsed = JSON.parse(text2);
241
308
  } catch {
242
309
  if (resp.ok) {
243
310
  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))}`,
311
+ `The server answered ${resp.status} to ${method} ${path} with a body that is not JSON: ${JSON.stringify(text2.slice(0, 200))}`,
245
312
  { status: resp.status }
246
313
  );
247
314
  }
248
- parsed = { message: text };
315
+ parsed = { message: text2 };
249
316
  }
250
317
  }
251
318
  if (!resp.ok) {
@@ -265,34 +332,48 @@ function raiseFor(status, body, retryAfter) {
265
332
  if (status === 404) throw new NotFoundError(msg, opts);
266
333
  if (status === 409) {
267
334
  if (code === "stale_write") throw new StaleWriteError(msg, opts);
268
- throw new ConflictError(msg, opts);
335
+ throw new ConflictError(msg, { ...opts, ...conflictFields(body) });
269
336
  }
270
337
  if (status === 429) {
271
- if (code === "too_many_batches") throw new TooManyBatchesError(msg, opts);
272
- throw new QuotaExceededError(msg, opts);
338
+ const quota = { ...opts, ...quotaFields(body) };
339
+ if (code === "too_many_batches") throw new TooManyBatchesError(msg, quota);
340
+ throw new QuotaExceededError(msg, quota);
273
341
  }
274
342
  throw new APIError(msg, opts);
275
343
  }
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
- );
344
+ function savedConfig() {
345
+ try {
346
+ const proc = typeof process !== "undefined" ? process : void 0;
347
+ if (!proc?.versions?.node) return {};
348
+ const builtin = (id) => typeof proc.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : typeof __require === "function" ? __require(id) : void 0;
349
+ const fs = builtin("node:fs");
350
+ const os = builtin("node:os");
351
+ const path = builtin("node:path");
352
+ if (!fs || !os || !path) return {};
353
+ const home = proc.env?.KORELY_CONFIG_HOME || path.join(os.homedir(), ".korely");
354
+ const data = JSON.parse(fs.readFileSync(path.join(home, "config.json"), "utf8"));
355
+ return data && typeof data === "object" ? data : {};
356
+ } catch {
357
+ return {};
281
358
  }
282
359
  }
360
+ function text(v) {
361
+ return typeof v === "string" && v ? v : void 0;
362
+ }
283
363
  var Korely = class {
284
364
  constructor(opts = {}) {
285
- refusePythonSpelling(opts);
365
+ checkOptions("Korely", opts, CLIENT_KEYS);
286
366
  const envKey = typeof process !== "undefined" ? process.env?.KORELY_API_KEY : void 0;
287
- const key = opts.apiKey ?? envKey;
367
+ const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
368
+ const saved = opts.apiKey && (opts.baseUrl || envBase) ? {} : savedConfig();
369
+ const key = opts.apiKey ?? envKey ?? text(saved.api_key);
288
370
  if (!key) {
289
371
  throw new KorelyError(
290
- "No API key. Pass { apiKey: 'kor_live_...' } or set KORELY_API_KEY."
372
+ "No API key. Pass { apiKey: 'kor_live_...' }, set KORELY_API_KEY, or run `korely init`, which saves one to ~/.korely/config.json."
291
373
  );
292
374
  }
293
375
  this.apiKey = key;
294
- const envBase = typeof process !== "undefined" ? process.env?.KORELY_BASE_URL : void 0;
295
- this.baseUrl = (opts.baseUrl ?? envBase ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
376
+ this.baseUrl = (opts.baseUrl ?? envBase ?? text(saved.base_url) ?? REGIONS[opts.region ?? "eu"] ?? REGIONS.eu).replace(/\/+$/, "");
296
377
  refuseAMismatchedPair(this.apiKey, this.baseUrl);
297
378
  this.timeoutMs = opts.timeoutMs ?? 3e4;
298
379
  const f = opts.fetch ?? globalThis.fetch;
@@ -322,7 +403,11 @@ var Korely = class {
322
403
  * dashboard: its keys come from its own dashboard.
323
404
  */
324
405
  static async initAgent(agentCaller, opts = {}) {
325
- refusePythonSpelling(opts);
406
+ checkOptions("initAgent", opts, INIT_KEYS);
407
+ const where = opts.processingRegion;
408
+ if (where !== void 0 && where !== "eu" && where !== "global") {
409
+ throw new KorelyError(`processingRegion is "eu" or "global", not ${JSON.stringify(where)}.`);
410
+ }
326
411
  if (agentCaller != null && typeof agentCaller !== "string") {
327
412
  throw new KorelyError(
328
413
  `agentCaller is a label, a string, not ${Array.isArray(agentCaller) ? "an array" : `a ${typeof agentCaller}`}: Korely.initAgent('my-app', { baseUrl }).`
@@ -340,7 +425,9 @@ var Korely = class {
340
425
  { baseUrl, timeoutMs: opts.timeoutMs ?? 3e4, fetchImpl },
341
426
  "POST",
342
427
  "/v1/agents/init",
343
- { body: { agent_caller: agentCaller ?? void 0 } }
428
+ {
429
+ body: { agent_caller: agentCaller ?? void 0, processing_region: opts.processingRegion }
430
+ }
344
431
  );
345
432
  }
346
433
  // ── transport ─────────────────────────────────────────────────────────────
@@ -383,6 +470,7 @@ var Korely = class {
383
470
  * dashboard. No audit event survives: the trail is part of what goes.
384
471
  */
385
472
  async deleteAccount(opts = {}) {
473
+ checkOptions("deleteAccount", opts, ["confirm"]);
386
474
  if (opts?.confirm !== true) {
387
475
  throw new KorelyError(
388
476
  "deleteAccount() deletes this key's account, every key, memory and fact of it, for good. Pass { confirm: true } to mean it.",
@@ -408,6 +496,7 @@ var Korely = class {
408
496
  * project, like every read.
409
497
  */
410
498
  async audit(opts = {}) {
499
+ checkOptions("audit", opts, AUDIT_KEYS);
411
500
  const page = await this.request(
412
501
  "GET",
413
502
  "/v1/audit",
@@ -433,6 +522,7 @@ var Korely = class {
433
522
  * `until: new Date()`) and `offset` the number of events already read.
434
523
  */
435
524
  async *iterAudit(opts = {}) {
525
+ checkOptions("iterAudit", opts, ITER_AUDIT_KEYS);
436
526
  const filters = auditFilters(opts);
437
527
  let offset = opts.offset ?? 0;
438
528
  let pin = filters.until === void 0 && offset === 0;
@@ -463,15 +553,16 @@ var Korely = class {
463
553
  * backfill: facts extracted inherit it as `valid_from`.
464
554
  */
465
555
  async add(content, opts = {}) {
466
- const text = coerceContent(content);
467
- if (!text.trim()) {
556
+ checkOptions("add", opts, ADD_KEYS);
557
+ const text2 = coerceContent(content);
558
+ if (!text2.trim()) {
468
559
  throw new KorelyError(
469
560
  "content is empty: pass a non-blank string or messages with content."
470
561
  );
471
562
  }
472
563
  return this.request("POST", "/v1/memories", {
473
564
  body: {
474
- content: text,
565
+ content: text2,
475
566
  agent_id: opts.agent_id,
476
567
  user_id: opts.user_id,
477
568
  run_id: opts.run_id,
@@ -487,6 +578,7 @@ var Korely = class {
487
578
  * the server default (15), max 50.
488
579
  */
489
580
  async search(query, opts = {}) {
581
+ checkOptions("search", opts, SEARCH_KEYS);
490
582
  const body = await this.request("POST", "/v1/memories/search", {
491
583
  body: {
492
584
  query,
@@ -505,6 +597,7 @@ var Korely = class {
505
597
  * `total` and `offset` walk the rest.
506
598
  */
507
599
  async getAll(opts = {}) {
600
+ checkOptions("getAll", opts, LIST_KEYS);
508
601
  const page = await this.request(
509
602
  "GET",
510
603
  "/v1/memories",
@@ -529,6 +622,7 @@ var Korely = class {
529
622
  * for optimistic concurrency (throws StaleWriteError instead of clobbering).
530
623
  */
531
624
  async update(memoryId, opts) {
625
+ checkOptions("update", opts, UPDATE_KEYS);
532
626
  return this.request("PATCH", `/v1/memories/${seg(memoryId, "memoryId")}`, {
533
627
  body: {
534
628
  content: opts.content,
@@ -554,6 +648,7 @@ var Korely = class {
554
648
  * the same numbers; whichever pair the server sends fills both.
555
649
  */
556
650
  async deleteAll(opts) {
651
+ checkOptions("deleteAll", opts, ["user_id"]);
557
652
  const r = await this.request(
558
653
  "DELETE",
559
654
  `/v1/users/${seg(opts.user_id, "user_id")}/memories`
@@ -575,6 +670,7 @@ var Korely = class {
575
670
  * namespaces), each with active memory + fact counts and last-active time.
576
671
  */
577
672
  async users(opts = {}) {
673
+ checkOptions("users", opts, USERS_KEYS);
578
674
  const page = await this.request(
579
675
  "GET",
580
676
  "/v1/users",
@@ -603,6 +699,7 @@ var Korely = class {
603
699
  * sets no cap and answers `cap: 0`.
604
700
  */
605
701
  async listAgents(opts = {}) {
702
+ checkOptions("listAgents", opts, AGENTS_KEYS);
606
703
  const page = await this.request("GET", "/v1/agents", {
607
704
  params: {
608
705
  limit: opts.limit ?? 50,
@@ -634,6 +731,7 @@ var Korely = class {
634
731
  * array that also carries `total`, the matches across all pages.
635
732
  */
636
733
  async getFacts(opts = {}) {
734
+ checkOptions("getFacts", opts, FACTS_KEYS);
637
735
  const params = {
638
736
  subject: opts.subject,
639
737
  entity: opts.entity,
@@ -662,7 +760,8 @@ var Korely = class {
662
760
  * listing any fact ids it superseded.
663
761
  */
664
762
  async addFactTriple(subject, predicate, object, opts = {}) {
665
- return this.request("POST", "/v1/facts", {
763
+ checkOptions("addFactTriple", opts, TRIPLE_KEYS);
764
+ const fact = await this.request("POST", "/v1/facts", {
666
765
  body: {
667
766
  subject,
668
767
  predicate,
@@ -677,6 +776,11 @@ var Korely = class {
677
776
  tense: opts.tense
678
777
  }
679
778
  });
779
+ return {
780
+ ...fact,
781
+ user_id: fact.user_id !== void 0 ? fact.user_id : opts.user_id,
782
+ agent_id: fact.agent_id !== void 0 ? fact.agent_id : opts.agent_id
783
+ };
680
784
  }
681
785
  /**
682
786
  * POST /v1/facts/:id/forget: close a fact; it stops being current and stays
@@ -693,6 +797,7 @@ var Korely = class {
693
797
  * knows a fact is finished says so, and nothing has to infer it.
694
798
  */
695
799
  async forgetFact(factId, opts = {}) {
800
+ checkOptions("forgetFact", opts, ["at"]);
696
801
  return this.request("POST", `/v1/facts/${seg(factId, "factId")}/forget`, {
697
802
  body: { at: opts.at }
698
803
  });
@@ -722,6 +827,7 @@ var Korely = class {
722
827
  * Pass `as_of` (ISO date) for the point-in-time profile.
723
828
  */
724
829
  async getProfile(opts) {
830
+ checkOptions("getProfile", opts, PROFILE_KEYS);
725
831
  return this.request("GET", "/v1/profile", {
726
832
  params: {
727
833
  user_id: opts.user_id,
@@ -736,6 +842,8 @@ var Korely = class {
736
842
  * (profile + relevant facts + memories) within a token budget.
737
843
  */
738
844
  async getContext(opts, extra = {}) {
845
+ if (typeof opts === "string") checkOptions("getContext", extra, CONTEXT_EXTRA_KEYS);
846
+ else checkOptions("getContext", opts, CONTEXT_KEYS);
739
847
  const o = typeof opts === "string" ? { ...extra, query: opts } : opts;
740
848
  if (!o || typeof o.query !== "string" || !o.query.trim()) {
741
849
  throw new KorelyError("getContext needs a query.");
@@ -763,6 +871,7 @@ var Korely = class {
763
871
  * this is how to know.
764
872
  */
765
873
  async events(opts = {}) {
874
+ checkOptions("events", opts, EVENTS_KEYS);
766
875
  return this.request("GET", "/v1/events", {
767
876
  params: {
768
877
  user_id: opts.user_id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "korely-memory",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "description": "JavaScript / TypeScript SDK for Korely Agents: memory for AI agents with bi-temporal typed facts.",
5
5
  "keywords": [
6
6
  "ai",
@@ -23,7 +23,7 @@
23
23
  "url": "https://github.com/verdana86/korely-memory/issues"
24
24
  },
25
25
  "license": "MIT",
26
- "author": "Korely <hello@korely.ai>",
26
+ "author": "Korely <info@korely.ai>",
27
27
  "type": "module",
28
28
  "main": "./dist/index.cjs",
29
29
  "module": "./dist/index.js",