kagura-memory 0.1.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 ADDED
@@ -0,0 +1,2896 @@
1
+ // src/config.ts
2
+ import * as fs from "fs";
3
+ import * as os from "os";
4
+ import * as path from "path";
5
+ function readConfigFile(filePath, label) {
6
+ let text;
7
+ try {
8
+ text = fs.readFileSync(filePath, "utf-8");
9
+ } catch (e) {
10
+ throw new Error(`Failed to read ${label}: ${e instanceof Error ? e.message : String(e)}`);
11
+ }
12
+ try {
13
+ const parsed = JSON.parse(text);
14
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
15
+ throw new Error("expected a JSON object");
16
+ }
17
+ return parsed;
18
+ } catch (e) {
19
+ throw new Error(
20
+ `Invalid JSON or encoding in ${label} (expected UTF-8): ${e instanceof Error ? e.message : String(e)}`
21
+ );
22
+ }
23
+ }
24
+ function loadConfig(options = {}) {
25
+ const cwd = options.cwd ?? process.cwd();
26
+ const home = options.home ?? os.homedir();
27
+ const env = options.env ?? process.env;
28
+ const localConfig = path.join(cwd, ".kagura.json");
29
+ if (fs.existsSync(localConfig)) {
30
+ return readConfigFile(localConfig, ".kagura.json");
31
+ }
32
+ const homeConfig = path.join(home, ".kagura.json");
33
+ if (fs.existsSync(homeConfig)) {
34
+ return readConfigFile(homeConfig, "~/.kagura.json");
35
+ }
36
+ return {
37
+ api_key: env.KAGURA_API_KEY ?? "",
38
+ mcp_url: env.KAGURA_MCP_URL ?? "https://memory.kagura-ai.com/mcp",
39
+ model: env.KAGURA_MODEL ?? "gpt-5.4-nano",
40
+ context_id: env.KAGURA_CONTEXT_ID ?? null
41
+ };
42
+ }
43
+
44
+ // src/errors.ts
45
+ function excMessage(e) {
46
+ if (e instanceof Error) {
47
+ return e.message || e.constructor.name;
48
+ }
49
+ const s = String(e);
50
+ return s || (typeof e === "object" && e !== null ? e.constructor.name : "unknown error");
51
+ }
52
+ var KaguraError = class extends Error {
53
+ constructor(message, options) {
54
+ super(message, options);
55
+ this.name = new.target.name;
56
+ }
57
+ };
58
+ var KaguraAuthError = class extends KaguraError {
59
+ };
60
+ var KaguraAuthExpiredError = class extends KaguraAuthError {
61
+ expiresAt;
62
+ constructor(message, expiresAt = null, options) {
63
+ super(message, options);
64
+ this.expiresAt = expiresAt;
65
+ }
66
+ };
67
+ var KaguraAuthDeniedError = class extends KaguraAuthError {
68
+ };
69
+ var KaguraConnectionError = class extends KaguraError {
70
+ };
71
+ var KaguraNotFoundError = class extends KaguraError {
72
+ };
73
+ var KaguraRateLimitError = class extends KaguraError {
74
+ retryAfter;
75
+ constructor(message, retryAfter = null, options) {
76
+ super(message, options);
77
+ this.retryAfter = retryAfter;
78
+ }
79
+ };
80
+ var KaguraLLMError = class extends KaguraError {
81
+ };
82
+ var KaguraContextError = class extends KaguraError {
83
+ };
84
+ var KaguraQuotaError = class extends KaguraError {
85
+ retryAfter;
86
+ constructor(message, retryAfter = null, options) {
87
+ super(message, options);
88
+ this.retryAfter = retryAfter;
89
+ }
90
+ };
91
+ var KaguraIntegrityError = class extends KaguraError {
92
+ };
93
+ var KaguraFetchError = class extends KaguraError {
94
+ url;
95
+ constructor(message, url = null, options) {
96
+ super(message, options);
97
+ this.url = url;
98
+ }
99
+ };
100
+ var KaguraIngestError = class extends KaguraError {
101
+ };
102
+
103
+ // src/auth/credentials.ts
104
+ import * as crypto from "crypto";
105
+ import * as fs3 from "fs";
106
+ import * as os2 from "os";
107
+ import * as path3 from "path";
108
+
109
+ // src/auth/deviceFlow.ts
110
+ import { setTimeout as sleepMs } from "timers/promises";
111
+
112
+ // src/version.ts
113
+ var SDK_VERSION = "0.1.0";
114
+
115
+ // src/http.ts
116
+ function baseUrlFromMcp(mcpUrl) {
117
+ const m = /\/mcp(?=\/|$)/.exec(mcpUrl);
118
+ return m ? mcpUrl.slice(0, m.index) : mcpUrl;
119
+ }
120
+ function formatValidationErrors(errors) {
121
+ const parts = [];
122
+ for (const entry of errors) {
123
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
124
+ continue;
125
+ }
126
+ const rec = entry;
127
+ const msg = rec.msg;
128
+ if (typeof msg !== "string" || !msg) {
129
+ continue;
130
+ }
131
+ const loc = rec.loc;
132
+ if (Array.isArray(loc) && loc.length > 0) {
133
+ parts.push(`${loc.map(String).join(".")}: ${msg}`);
134
+ } else {
135
+ parts.push(msg);
136
+ }
137
+ }
138
+ return parts.join("; ");
139
+ }
140
+ function extractDetail(bodyText) {
141
+ let body;
142
+ try {
143
+ body = JSON.parse(bodyText);
144
+ } catch {
145
+ return "";
146
+ }
147
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
148
+ return "";
149
+ }
150
+ const rec = body;
151
+ const detail = rec.detail;
152
+ if (typeof detail === "string") {
153
+ return detail;
154
+ }
155
+ if (Array.isArray(detail)) {
156
+ return formatValidationErrors(detail);
157
+ }
158
+ const message = rec.message;
159
+ if (typeof message === "string" && message) {
160
+ const details = rec.details;
161
+ if (typeof details === "object" && details !== null && !Array.isArray(details)) {
162
+ const errors = details.errors;
163
+ if (Array.isArray(errors)) {
164
+ const formatted = formatValidationErrors(errors);
165
+ if (formatted) {
166
+ return `${message}: ${formatted}`;
167
+ }
168
+ }
169
+ }
170
+ return message;
171
+ }
172
+ return "";
173
+ }
174
+ function sanitizeServerDetail(detail) {
175
+ if (!detail) {
176
+ return null;
177
+ }
178
+ const lowered = detail.toLowerCase();
179
+ if (lowered.includes("bearer") || lowered.includes("authorization") || lowered.includes("api_key=")) {
180
+ return null;
181
+ }
182
+ return detail;
183
+ }
184
+ function retryAfterSeconds(headers) {
185
+ const raw = headers.get("Retry-After");
186
+ if (raw === null) {
187
+ return null;
188
+ }
189
+ const trimmed = raw.trim();
190
+ return /^\d+$/.test(trimmed) ? parseInt(trimmed, 10) : null;
191
+ }
192
+ function throwForKaguraStatus(status, headers, bodyText, fallbackMessage) {
193
+ if (status === 401) {
194
+ throw new KaguraAuthError("Authentication failed. Check your API key.");
195
+ }
196
+ const detail = extractDetail(bodyText) || fallbackMessage || "";
197
+ if (status === 429) {
198
+ throw new KaguraRateLimitError(
199
+ `Rate limit exceeded (HTTP 429): ${detail || `HTTP ${status}`}`,
200
+ retryAfterSeconds(headers)
201
+ );
202
+ }
203
+ throw new KaguraConnectionError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`);
204
+ }
205
+ var LOCALHOST_HTTP_RE = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/;
206
+ function validateHttpsUrl(url, label = "URL") {
207
+ if (url.startsWith("http://") && !LOCALHOST_HTTP_RE.test(url)) {
208
+ throw new Error(
209
+ `${label} must use HTTPS for security (got: ${url}). HTTP is only allowed for localhost development.`
210
+ );
211
+ }
212
+ }
213
+
214
+ // src/auth/deviceFlow.ts
215
+ var PATH_TOKEN = "/api/v1/oauth/token/";
216
+ var REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
217
+ function userAgent() {
218
+ return `kagura-memory-sdk/${SDK_VERSION}`;
219
+ }
220
+ function tokenUrl(server) {
221
+ return `${server.replace(/\/+$/, "")}${PATH_TOKEN}`;
222
+ }
223
+ function toInt(value) {
224
+ if (typeof value === "number" && Number.isFinite(value)) {
225
+ return Math.trunc(value);
226
+ }
227
+ if (typeof value === "string" && value.trim() !== "") {
228
+ const n = Number(value);
229
+ return Number.isFinite(n) ? Math.trunc(n) : null;
230
+ }
231
+ return null;
232
+ }
233
+ function stringOr(value, fallback) {
234
+ return typeof value === "string" ? value : fallback;
235
+ }
236
+ function safeJsonObject(bodyText, status, endpoint) {
237
+ let body;
238
+ try {
239
+ body = JSON.parse(bodyText);
240
+ } catch (e) {
241
+ const detail = bodyText.slice(0, 200);
242
+ throw new KaguraAuthError(
243
+ `${endpoint} returned HTTP ${status} but body is not JSON: ${excMessage(e)}. Body: ${detail}`,
244
+ { cause: e }
245
+ );
246
+ }
247
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
248
+ throw new KaguraAuthError(
249
+ `${endpoint} returned HTTP ${status} but body is not a JSON object (got ${Array.isArray(body) ? "array" : typeof body})`
250
+ );
251
+ }
252
+ return body;
253
+ }
254
+ function safeJson(bodyText) {
255
+ let body;
256
+ try {
257
+ body = JSON.parse(bodyText);
258
+ } catch {
259
+ return {};
260
+ }
261
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
262
+ return {};
263
+ }
264
+ return body;
265
+ }
266
+ function tokenResponseFromBody(bodyText, status) {
267
+ const body = safeJsonObject(bodyText, status, "Token endpoint");
268
+ const accessToken = body.access_token;
269
+ const expiresIn = toInt(body.expires_in ?? 0);
270
+ if (typeof accessToken !== "string" || expiresIn === null) {
271
+ throw new KaguraAuthError(
272
+ `Token endpoint returned HTTP ${status} but body is missing required fields. Body keys: ${Object.keys(body).sort().join(", ")}`
273
+ );
274
+ }
275
+ return {
276
+ accessToken,
277
+ refreshToken: stringOr(body.refresh_token, ""),
278
+ tokenType: stringOr(body.token_type, "Bearer"),
279
+ expiresAt: new Date(Date.now() + expiresIn * 1e3),
280
+ scope: stringOr(body.scope, ""),
281
+ userEmail: stringOr(body.user_email, ""),
282
+ workspaceId: stringOr(body.workspace_id, ""),
283
+ workspaceName: stringOr(body.workspace_name, "")
284
+ };
285
+ }
286
+ async function refreshAccessToken(server, options) {
287
+ const doFetch = options.fetch ?? globalThis.fetch;
288
+ const url = tokenUrl(server);
289
+ const form = new URLSearchParams({
290
+ grant_type: REFRESH_TOKEN_GRANT_TYPE,
291
+ refresh_token: options.refreshToken,
292
+ client_id: options.clientId
293
+ });
294
+ if (options.scope !== void 0 && options.scope !== null) {
295
+ form.set("scope", options.scope);
296
+ }
297
+ let response;
298
+ let text;
299
+ try {
300
+ response = await doFetch(url, {
301
+ method: "POST",
302
+ headers: { "User-Agent": userAgent() },
303
+ body: form
304
+ });
305
+ text = await response.text();
306
+ } catch (e) {
307
+ throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });
308
+ }
309
+ if (response.status === 200) {
310
+ return tokenResponseFromBody(text, response.status);
311
+ }
312
+ const body = safeJson(text);
313
+ const error = stringOr(body.error, "");
314
+ if (error === "invalid_grant") {
315
+ throw new KaguraAuthExpiredError(
316
+ "Your login expired (refresh token is no longer valid).\n Run: kagura auth login\n Your server and workspace selection are preserved."
317
+ );
318
+ }
319
+ const description = stringOr(body.error_description, "");
320
+ if (error) {
321
+ throw new KaguraAuthError(
322
+ `Refresh failed: ${error}${description ? ` \u2014 ${description}` : ""}`
323
+ );
324
+ }
325
+ const detail = extractDetail(text) || text.slice(0, 200);
326
+ throw new KaguraAuthError(
327
+ `Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`
328
+ );
329
+ }
330
+
331
+ // src/auth/filelock.ts
332
+ import * as fs2 from "fs";
333
+ import * as path2 from "path";
334
+ import { setTimeout as sleep } from "timers/promises";
335
+ var DEFAULT_LOCK_RETRY_MS = 50;
336
+ var DEFAULT_LOCK_TIMEOUT_MS = 9e4;
337
+ var DEFAULT_LOCK_STALE_MS = 6e4;
338
+ var FileLockTimeoutError = class extends Error {
339
+ constructor(message) {
340
+ super(message);
341
+ this.name = "FileLockTimeoutError";
342
+ }
343
+ };
344
+ function lockPath(target) {
345
+ return `${target}.lock`;
346
+ }
347
+ function isErrnoException(e) {
348
+ return e instanceof Error && "code" in e;
349
+ }
350
+ async function acquireFileLock(target, options = {}) {
351
+ const timeoutMs = options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;
352
+ const retryMs = options.retryMs ?? DEFAULT_LOCK_RETRY_MS;
353
+ const staleMs = options.staleMs ?? DEFAULT_LOCK_STALE_MS;
354
+ const lockFile = lockPath(target);
355
+ fs2.mkdirSync(path2.dirname(lockFile), { recursive: true });
356
+ const deadline = Date.now() + timeoutMs;
357
+ for (; ; ) {
358
+ let fd = null;
359
+ try {
360
+ fd = fs2.openSync(lockFile, "wx", 384);
361
+ } catch (e) {
362
+ if (!isErrnoException(e) || e.code !== "EEXIST") {
363
+ throw e;
364
+ }
365
+ }
366
+ if (fd !== null) {
367
+ try {
368
+ fs2.writeSync(fd, `${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}
369
+ `);
370
+ } finally {
371
+ fs2.closeSync(fd);
372
+ }
373
+ let released = false;
374
+ return {
375
+ path: lockFile,
376
+ release() {
377
+ if (released) {
378
+ return;
379
+ }
380
+ released = true;
381
+ try {
382
+ fs2.unlinkSync(lockFile);
383
+ } catch {
384
+ }
385
+ }
386
+ };
387
+ }
388
+ let mtimeMs;
389
+ try {
390
+ mtimeMs = fs2.statSync(lockFile).mtimeMs;
391
+ } catch (e) {
392
+ if (isErrnoException(e) && e.code === "ENOENT") {
393
+ continue;
394
+ }
395
+ throw e;
396
+ }
397
+ if (Date.now() - mtimeMs > staleMs) {
398
+ try {
399
+ fs2.unlinkSync(lockFile);
400
+ } catch (e) {
401
+ if (!isErrnoException(e) || e.code !== "ENOENT") {
402
+ throw e;
403
+ }
404
+ }
405
+ continue;
406
+ }
407
+ if (Date.now() >= deadline) {
408
+ throw new FileLockTimeoutError(
409
+ `could not acquire credentials lock within ${timeoutMs / 1e3}s: ${lockFile}`
410
+ );
411
+ }
412
+ await sleep(retryMs);
413
+ }
414
+ }
415
+ async function withFileLock(target, fn, options = {}) {
416
+ const handle = await acquireFileLock(target, options);
417
+ try {
418
+ return await fn();
419
+ } finally {
420
+ handle.release();
421
+ }
422
+ }
423
+
424
+ // src/auth/credentials.ts
425
+ var REFRESH_SKEW_SEC = 300;
426
+ var CREDENTIALS_FILE_MODE = 384;
427
+ var CREDENTIALS_DIR_MODE = 448;
428
+ function defaultCredentialsPath(home) {
429
+ return path3.join(home ?? os2.homedir(), ".kagura", "credentials.json");
430
+ }
431
+ function isExpired(creds, skewSeconds = 0) {
432
+ return Date.now() >= creds.expiresAt.getTime() - skewSeconds * 1e3;
433
+ }
434
+ function withRefreshed(creds, fields) {
435
+ return {
436
+ ...creds,
437
+ accessToken: fields.accessToken,
438
+ refreshToken: fields.refreshToken ?? creds.refreshToken,
439
+ expiresAt: fields.expiresAt,
440
+ scope: fields.scope ?? creds.scope
441
+ };
442
+ }
443
+ function isoUtc(date) {
444
+ return `${date.toISOString().slice(0, 19)}Z`;
445
+ }
446
+ function parseIso(s) {
447
+ const normalized = /(?:Z|[+-]\d{2}:?\d{2})$/.test(s) ? s : `${s}Z`;
448
+ const date = new Date(normalized);
449
+ if (Number.isNaN(date.getTime())) {
450
+ throw new Error(`invalid ISO-8601 timestamp: ${s}`);
451
+ }
452
+ return date;
453
+ }
454
+ function credentialsToDict(creds) {
455
+ return {
456
+ server: creds.server,
457
+ mcp_url: creds.mcpUrl,
458
+ client_id: creds.clientId,
459
+ access_token: creds.accessToken,
460
+ refresh_token: creds.refreshToken,
461
+ token_type: creds.tokenType,
462
+ expires_at: isoUtc(creds.expiresAt),
463
+ scope: creds.scope,
464
+ workspace_id: creds.workspaceId,
465
+ workspace_name: creds.workspaceName,
466
+ user_email: creds.userEmail,
467
+ issued_at: isoUtc(creds.issuedAt)
468
+ };
469
+ }
470
+ function requireString(d, key) {
471
+ const value = d[key];
472
+ if (typeof value !== "string") {
473
+ throw new Error(`credentials profile missing required field '${key}'`);
474
+ }
475
+ return value;
476
+ }
477
+ function stringOr2(value, fallback) {
478
+ return typeof value === "string" ? value : fallback;
479
+ }
480
+ function credentialsFromDict(d) {
481
+ const issuedAtRaw = d.issued_at;
482
+ return {
483
+ server: requireString(d, "server"),
484
+ mcpUrl: requireString(d, "mcp_url"),
485
+ clientId: requireString(d, "client_id"),
486
+ accessToken: requireString(d, "access_token"),
487
+ refreshToken: requireString(d, "refresh_token"),
488
+ tokenType: stringOr2(d.token_type, "Bearer"),
489
+ expiresAt: parseIso(requireString(d, "expires_at")),
490
+ scope: stringOr2(d.scope, ""),
491
+ workspaceId: stringOr2(d.workspace_id, ""),
492
+ workspaceName: stringOr2(d.workspace_name, ""),
493
+ userEmail: stringOr2(d.user_email, ""),
494
+ issuedAt: typeof issuedAtRaw === "string" && issuedAtRaw ? parseIso(issuedAtRaw) : /* @__PURE__ */ new Date()
495
+ };
496
+ }
497
+ function emptyCredentialsFile() {
498
+ return { version: 1, defaultProfile: "default", profiles: {} };
499
+ }
500
+ function getProfile(cf, name) {
501
+ const key = name || cf.defaultProfile;
502
+ return cf.profiles[key] ?? null;
503
+ }
504
+ function setProfile(cf, name, creds) {
505
+ cf.profiles[name] = creds;
506
+ if (!(cf.defaultProfile in cf.profiles)) {
507
+ cf.defaultProfile = name;
508
+ }
509
+ }
510
+ function credentialsFileToDict(cf) {
511
+ const profiles = {};
512
+ for (const [name, creds] of Object.entries(cf.profiles)) {
513
+ profiles[name] = credentialsToDict(creds);
514
+ }
515
+ return {
516
+ version: cf.version,
517
+ default_profile: cf.defaultProfile,
518
+ profiles
519
+ };
520
+ }
521
+ function credentialsFileFromDict(d) {
522
+ const profilesRaw = d.profiles;
523
+ const profiles = {};
524
+ if (typeof profilesRaw === "object" && profilesRaw !== null && !Array.isArray(profilesRaw)) {
525
+ for (const [name, p] of Object.entries(profilesRaw)) {
526
+ if (typeof p !== "object" || p === null || Array.isArray(p)) {
527
+ throw new Error(`credentials profile '${name}' is not an object`);
528
+ }
529
+ profiles[name] = credentialsFromDict(p);
530
+ }
531
+ }
532
+ return {
533
+ version: typeof d.version === "number" ? d.version : 1,
534
+ defaultProfile: stringOr2(d.default_profile, "default"),
535
+ profiles
536
+ };
537
+ }
538
+ function enforceDirPerms(directory) {
539
+ try {
540
+ const mode = fs3.statSync(directory).mode & 511;
541
+ if (mode !== CREDENTIALS_DIR_MODE) {
542
+ fs3.chmodSync(directory, CREDENTIALS_DIR_MODE);
543
+ }
544
+ } catch {
545
+ }
546
+ }
547
+ function enforceFilePerms(filePath) {
548
+ try {
549
+ const mode = fs3.statSync(filePath).mode & 511;
550
+ if (mode !== CREDENTIALS_FILE_MODE) {
551
+ fs3.chmodSync(filePath, CREDENTIALS_FILE_MODE);
552
+ }
553
+ } catch {
554
+ }
555
+ }
556
+ function atomicWriteJson(filePath, data, mode = CREDENTIALS_FILE_MODE) {
557
+ const dir = path3.dirname(filePath);
558
+ fs3.mkdirSync(dir, { recursive: true });
559
+ enforceDirPerms(dir);
560
+ const tmp = path3.join(
561
+ dir,
562
+ `.${path3.basename(filePath)}.${crypto.randomBytes(6).toString("hex")}.tmp`
563
+ );
564
+ let fd = null;
565
+ try {
566
+ fd = fs3.openSync(tmp, "wx", 384);
567
+ fs3.writeSync(fd, `${JSON.stringify(data, null, 2)}
568
+ `);
569
+ fs3.fsyncSync(fd);
570
+ fs3.closeSync(fd);
571
+ fd = null;
572
+ fs3.chmodSync(tmp, mode);
573
+ fs3.renameSync(tmp, filePath);
574
+ try {
575
+ const dirFd = fs3.openSync(dir, "r");
576
+ try {
577
+ fs3.fsyncSync(dirFd);
578
+ } finally {
579
+ fs3.closeSync(dirFd);
580
+ }
581
+ } catch {
582
+ }
583
+ } catch (e) {
584
+ if (fd !== null) {
585
+ try {
586
+ fs3.closeSync(fd);
587
+ } catch {
588
+ }
589
+ }
590
+ fs3.rmSync(tmp, { force: true });
591
+ throw e;
592
+ }
593
+ }
594
+ function resolvePath(p) {
595
+ return p ?? defaultCredentialsPath();
596
+ }
597
+ function loadCredentialsFile(credentialsPath) {
598
+ const p = resolvePath(credentialsPath);
599
+ if (!fs3.existsSync(p)) {
600
+ return emptyCredentialsFile();
601
+ }
602
+ enforceDirPerms(path3.dirname(p));
603
+ enforceFilePerms(p);
604
+ let data;
605
+ try {
606
+ data = JSON.parse(fs3.readFileSync(p, "utf-8"));
607
+ } catch {
608
+ return emptyCredentialsFile();
609
+ }
610
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
611
+ return emptyCredentialsFile();
612
+ }
613
+ try {
614
+ return credentialsFileFromDict(data);
615
+ } catch {
616
+ return emptyCredentialsFile();
617
+ }
618
+ }
619
+ function saveCredentialsFile(cf, credentialsPath) {
620
+ atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);
621
+ }
622
+ var AsyncMutex = class {
623
+ tail = Promise.resolve();
624
+ runExclusive(fn) {
625
+ const run = this.tail.then(() => fn());
626
+ this.tail = run.catch(() => void 0);
627
+ return run;
628
+ }
629
+ };
630
+ var stateCache = /* @__PURE__ */ new Map();
631
+ var fileMutexes = /* @__PURE__ */ new Map();
632
+ function getFileMutex(p) {
633
+ let mutex = fileMutexes.get(p);
634
+ if (mutex === void 0) {
635
+ mutex = new AsyncMutex();
636
+ fileMutexes.set(p, mutex);
637
+ }
638
+ return mutex;
639
+ }
640
+ function getSharedState(credentialsPath, profile) {
641
+ const p = path3.resolve(resolvePath(credentialsPath));
642
+ const cf = loadCredentialsFile(p);
643
+ const creds = getProfile(cf, profile);
644
+ if (creds === null) {
645
+ return null;
646
+ }
647
+ const profileName = profile || cf.defaultProfile;
648
+ const key = JSON.stringify([p, profileName]);
649
+ let cached = stateCache.get(key);
650
+ if (cached === void 0) {
651
+ cached = {
652
+ credentials: creds,
653
+ profileName,
654
+ path: p,
655
+ mutex: getFileMutex(p)
656
+ };
657
+ stateCache.set(key, cached);
658
+ } else {
659
+ cached.credentials = creds;
660
+ }
661
+ return cached;
662
+ }
663
+ var KaguraOAuth = class {
664
+ state;
665
+ fetchImpl;
666
+ constructor(state, options = {}) {
667
+ this.state = state;
668
+ this.fetchImpl = options.fetch;
669
+ }
670
+ /**
671
+ * Return `Bearer <access_token>`, refreshing first when the token is
672
+ * within the skew window.
673
+ */
674
+ async getAuthHeader() {
675
+ await this.maybeRefresh();
676
+ return `Bearer ${this.state.credentials.accessToken}`;
677
+ }
678
+ /**
679
+ * Refresh the access token if it's within the skew window.
680
+ *
681
+ * The mutex is held across the entire read-check-refresh-persist
682
+ * sequence so a second caller waiting on it will find the token already
683
+ * rotated when it acquires.
684
+ */
685
+ async maybeRefresh() {
686
+ await this.state.mutex.runExclusive(async () => {
687
+ if (!isExpired(this.state.credentials, REFRESH_SKEW_SEC)) {
688
+ return;
689
+ }
690
+ await this.refreshLocked(null);
691
+ });
692
+ }
693
+ /**
694
+ * Unconditionally refresh the access token, ignoring the skew window.
695
+ *
696
+ * Used on an upstream 401: the token was rejected server-side (rotated /
697
+ * revoked out-of-band) even though it is not yet within the skew window.
698
+ * The same in-process mutex serializes this with skew-driven refreshes.
699
+ * Cross-process dedup is handled in `refreshLocked` via the
700
+ * rejected-token identity check.
701
+ */
702
+ async forceRefresh() {
703
+ const rejectedToken = this.state.credentials.accessToken;
704
+ await this.state.mutex.runExclusive(() => this.refreshLocked(rejectedToken));
705
+ }
706
+ /**
707
+ * Refresh `/oauth/token/` once across all processes. Caller holds the
708
+ * in-process mutex.
709
+ *
710
+ * After acquiring the cross-process file lock, re-read the credentials
711
+ * from disk and **skip the network call when another process already
712
+ * rotated the token** — "skip" means "adopt the on-disk result", never
713
+ * "leave the stale in-memory token in place".
714
+ *
715
+ * `expectedStaleToken` governs the "already rotated?" predicate:
716
+ * `null` (skew path) → skip when the on-disk token is no longer within
717
+ * the skew window. A token string (401 path) → skip only when the
718
+ * on-disk token *differs* from the rejected one (a 401 is independent of
719
+ * `expiresAt`).
720
+ */
721
+ async refreshLocked(expectedStaleToken) {
722
+ const credPath = this.state.path;
723
+ const profileName = this.state.profileName;
724
+ await withFileLock(credPath, async () => {
725
+ const disk = getProfile(loadCredentialsFile(credPath), profileName);
726
+ if (disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {
727
+ this.state.credentials = disk;
728
+ return;
729
+ }
730
+ const base = disk ?? this.state.credentials;
731
+ await this.networkRefreshAndSave(base, credPath, profileName);
732
+ });
733
+ }
734
+ /** Whether `disk` shows another process already produced a usable token. */
735
+ alreadyRotated(disk, expectedStaleToken) {
736
+ if (expectedStaleToken === null) {
737
+ return !isExpired(disk, REFRESH_SKEW_SEC);
738
+ }
739
+ return disk.accessToken !== expectedStaleToken;
740
+ }
741
+ /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */
742
+ async networkRefreshAndSave(base, credPath, profileName) {
743
+ const token = await refreshAccessToken(base.server, {
744
+ clientId: base.clientId,
745
+ refreshToken: base.refreshToken,
746
+ ...this.fetchImpl ? { fetch: this.fetchImpl } : {}
747
+ });
748
+ this.state.credentials = withRefreshed(base, {
749
+ accessToken: token.accessToken,
750
+ refreshToken: token.refreshToken || null,
751
+ expiresAt: token.expiresAt,
752
+ scope: token.scope
753
+ });
754
+ const cf = loadCredentialsFile(credPath);
755
+ setProfile(cf, profileName, this.state.credentials);
756
+ saveCredentialsFile(cf, credPath);
757
+ }
758
+ };
759
+
760
+ // src/auth/resolve.ts
761
+ var DEFAULT_MCP_URL = "https://memory.kagura-ai.com/mcp";
762
+ var logger = {
763
+ warn(message) {
764
+ console.warn(message);
765
+ }
766
+ };
767
+ var warnedProfiles = /* @__PURE__ */ new Set();
768
+ function strictProfileRequired(env) {
769
+ const raw = (env.KAGURA_REQUIRE_PROFILE ?? "").trim().toLowerCase();
770
+ return raw === "1" || raw === "true" || raw === "yes";
771
+ }
772
+ function checkProfileAmbiguity(state, env, credentialsPath) {
773
+ const cf = loadCredentialsFile(credentialsPath);
774
+ if (Object.keys(cf.profiles).length < 2) {
775
+ return;
776
+ }
777
+ const name = state.profileName;
778
+ const creds = state.credentials;
779
+ const workspace = creds.workspaceName || creds.workspaceId || "unknown workspace";
780
+ if (strictProfileRequired(env)) {
781
+ const available = Object.keys(cf.profiles).sort().join(", ");
782
+ throw new KaguraAuthError(
783
+ `Multiple profiles configured and none selected; refusing to use the implicit default '${name}' because KAGURA_REQUIRE_PROFILE is set.
784
+ Select one explicitly: kagura auth use <name>, --profile <name>, or KAGURA_PROFILE=<name>
785
+ Available profiles: ${available}`
786
+ );
787
+ }
788
+ const warnKey = JSON.stringify([state.path, name]);
789
+ if (!warnedProfiles.has(warnKey)) {
790
+ warnedProfiles.add(warnKey);
791
+ logger.warn(
792
+ `kagura: using profile '${name}' (workspace '${workspace}') \u2014 set a default with 'kagura auth use <name>' or pass --profile to silence this notice.`
793
+ );
794
+ }
795
+ }
796
+ function resolveAuth(options = {}) {
797
+ const env = options.env ?? process.env;
798
+ const mcpUrl = options.mcpUrl ?? null;
799
+ const apiKey = options.apiKey;
800
+ if (apiKey !== void 0 && apiKey !== null && apiKey.trim()) {
801
+ return {
802
+ kind: "static",
803
+ apiKey,
804
+ mcpUrl: mcpUrl || DEFAULT_MCP_URL,
805
+ source: "explicit"
806
+ };
807
+ }
808
+ const envKey = env.KAGURA_API_KEY;
809
+ if (envKey && envKey.trim()) {
810
+ return {
811
+ kind: "static",
812
+ apiKey: envKey,
813
+ mcpUrl: mcpUrl || env.KAGURA_MCP_URL || DEFAULT_MCP_URL,
814
+ source: "env"
815
+ };
816
+ }
817
+ const targetProfile = options.profile || env.KAGURA_PROFILE || null;
818
+ const credentialsPath = defaultCredentialsPath(options.home);
819
+ const state = getSharedState(credentialsPath, targetProfile);
820
+ if (state !== null) {
821
+ if (targetProfile === null) {
822
+ checkProfileAmbiguity(state, env, credentialsPath);
823
+ }
824
+ return {
825
+ kind: "oauth",
826
+ oauth: new KaguraOAuth(state),
827
+ mcpUrl: mcpUrl || state.credentials.mcpUrl,
828
+ workspaceId: state.credentials.workspaceId || null
829
+ };
830
+ }
831
+ if (targetProfile) {
832
+ const source = options.profile ? "profile argument" : "KAGURA_PROFILE env";
833
+ throw new KaguraAuthError(
834
+ `Profile '${targetProfile}' (from ${source}) not found in credentials.json.
835
+ Run: kagura auth login --profile ${targetProfile}
836
+ Or inspect ~/.kagura/credentials.json to see which profiles exist.`
837
+ );
838
+ }
839
+ const cfg = options.config ?? loadConfig({ ...options.home ? { home: options.home } : {}, env });
840
+ const cfgKey = cfg.api_key;
841
+ if (typeof cfgKey === "string" && cfgKey.trim()) {
842
+ return {
843
+ kind: "static",
844
+ apiKey: cfgKey,
845
+ mcpUrl: mcpUrl || cfg.mcp_url || DEFAULT_MCP_URL,
846
+ source: "config"
847
+ };
848
+ }
849
+ throw new KaguraAuthError(
850
+ 'No credentials found.\n Run: kagura auth login\n Or set: KAGURA_API_KEY=<your key>\n Or create: .kagura.json with {"api_key": "..."}'
851
+ );
852
+ }
853
+
854
+ // src/client.ts
855
+ var MIN_SERVER_VERSION = "0.17.1";
856
+ var MIN_SERVER_VERSION_TUPLE = MIN_SERVER_VERSION.split(".").slice(0, 3).map(Number);
857
+ var KaguraClient = class _KaguraClient {
858
+ mcpUrl;
859
+ timeoutMs;
860
+ baseUrl;
861
+ auth;
862
+ fetchImpl;
863
+ sessionId = null;
864
+ requestIdCounter = 1;
865
+ constructor(options = {}) {
866
+ const resolved = resolveAuth({
867
+ apiKey: options.apiKey ?? null,
868
+ mcpUrl: options.mcpUrl ?? null,
869
+ profile: options.profile ?? null,
870
+ env: options.env,
871
+ home: options.home
872
+ });
873
+ const strippedUrl = resolved.mcpUrl.replace(/\/+$/, "");
874
+ validateHttpsUrl(strippedUrl, "MCP URL");
875
+ this.mcpUrl = strippedUrl;
876
+ this.baseUrl = baseUrlFromMcp(strippedUrl);
877
+ this.timeoutMs = options.timeoutMs ?? 3e4;
878
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
879
+ if (resolved.kind === "static") {
880
+ const header = `Bearer ${resolved.apiKey}`;
881
+ this.auth = { getAuthHeader: async () => header };
882
+ } else {
883
+ this.auth = resolved.oauth;
884
+ }
885
+ }
886
+ /** Get next JSON-RPC request ID. */
887
+ nextRequestId() {
888
+ return this.requestIdCounter++;
889
+ }
890
+ async post(url, body, extraHeaders = {}) {
891
+ const headers = {
892
+ "content-type": "application/json",
893
+ accept: "application/json, text/event-stream",
894
+ authorization: await this.auth.getAuthHeader(),
895
+ "user-agent": `kagura-memory-sdk/${SDK_VERSION}`,
896
+ ...extraHeaders
897
+ };
898
+ try {
899
+ return await this.fetchImpl(url, {
900
+ method: "POST",
901
+ headers,
902
+ body: JSON.stringify(body),
903
+ signal: AbortSignal.timeout(this.timeoutMs)
904
+ });
905
+ } catch (e) {
906
+ throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });
907
+ }
908
+ }
909
+ /** Initialize the MCP session if not already initialized. */
910
+ async initializeSession() {
911
+ if (this.sessionId) {
912
+ return;
913
+ }
914
+ const body = {
915
+ jsonrpc: "2.0",
916
+ id: this.nextRequestId(),
917
+ method: "initialize",
918
+ params: {
919
+ protocolVersion: "2025-03-26",
920
+ capabilities: {},
921
+ clientInfo: { name: "kagura-memory-sdk", version: SDK_VERSION }
922
+ }
923
+ };
924
+ const response = await this.post(this.mcpUrl, body);
925
+ if (!response.ok) {
926
+ throwForKaguraStatus(response.status, response.headers, await this.safeText(response));
927
+ }
928
+ const sessionId = response.headers.get("mcp-session-id");
929
+ if (!sessionId) {
930
+ throw new KaguraConnectionError("No session ID returned from server");
931
+ }
932
+ this.sessionId = sessionId;
933
+ }
934
+ async safeText(response) {
935
+ try {
936
+ return await response.text();
937
+ } catch {
938
+ return "";
939
+ }
940
+ }
941
+ /** Make a JSON-RPC 2.0 request to the MCP server. */
942
+ async makeJsonRpcRequest(method, params) {
943
+ await this.initializeSession();
944
+ const body = {
945
+ jsonrpc: "2.0",
946
+ id: this.nextRequestId(),
947
+ method,
948
+ params
949
+ };
950
+ const headers = this.sessionId ? { "mcp-session-id": this.sessionId } : {};
951
+ const response = await this.post(this.mcpUrl, body, headers);
952
+ const text = await this.safeText(response);
953
+ if (!response.ok) {
954
+ throwForKaguraStatus(response.status, response.headers, text);
955
+ }
956
+ let data;
957
+ try {
958
+ data = text ? JSON.parse(text) : {};
959
+ } catch (e) {
960
+ throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, { cause: e });
961
+ }
962
+ if (data && typeof data === "object" && "error" in data) {
963
+ const error = data.error;
964
+ const message = error && typeof error === "object" ? error.message ?? JSON.stringify(error) : String(error);
965
+ throw new KaguraConnectionError(`MCP error: ${String(message)}`);
966
+ }
967
+ const result = data.result;
968
+ return typeof result === "object" && result !== null ? result : {};
969
+ }
970
+ /** GET a REST endpoint and parse the JSON body. */
971
+ async restGet(path5, params) {
972
+ let url = `${this.baseUrl}${path5}`;
973
+ if (params) {
974
+ const query = new URLSearchParams();
975
+ for (const [key, value] of Object.entries(params)) {
976
+ if (value !== void 0 && value !== null) {
977
+ query.set(key, String(value));
978
+ }
979
+ }
980
+ const qs = query.toString();
981
+ if (qs) {
982
+ url += `?${qs}`;
983
+ }
984
+ }
985
+ let response;
986
+ try {
987
+ response = await this.fetchImpl(url, {
988
+ method: "GET",
989
+ headers: {
990
+ authorization: await this.auth.getAuthHeader(),
991
+ "user-agent": `kagura-memory-sdk/${SDK_VERSION}`
992
+ },
993
+ signal: AbortSignal.timeout(this.timeoutMs)
994
+ });
995
+ } catch (e) {
996
+ throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });
997
+ }
998
+ const text = await this.safeText(response);
999
+ if (!response.ok) {
1000
+ throwForKaguraStatus(response.status, response.headers, text);
1001
+ }
1002
+ try {
1003
+ return JSON.parse(text);
1004
+ } catch (e) {
1005
+ throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, { cause: e });
1006
+ }
1007
+ }
1008
+ /**
1009
+ * Call an MCP tool via JSON-RPC and parse `content[0].text` as JSON.
1010
+ */
1011
+ async callTool(toolName, args) {
1012
+ const result = await this.makeJsonRpcRequest("tools/call", {
1013
+ name: toolName,
1014
+ arguments: args
1015
+ });
1016
+ const content = result.content;
1017
+ if (Array.isArray(content) && content.length > 0) {
1018
+ const first = content[0];
1019
+ const text = typeof first.text === "string" ? first.text : "{}";
1020
+ try {
1021
+ return JSON.parse(text);
1022
+ } catch (e) {
1023
+ throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, {
1024
+ cause: e
1025
+ });
1026
+ }
1027
+ }
1028
+ return {};
1029
+ }
1030
+ /**
1031
+ * Call an MCP tool and translate domain errors into exceptions.
1032
+ *
1033
+ * A server `{"status": "error", ...}` response throws
1034
+ * KaguraNotFoundError / KaguraError instead of being returned as data.
1035
+ */
1036
+ async callToolChecked(toolName, args) {
1037
+ const result = await this.callTool(toolName, args);
1038
+ _KaguraClient.raiseForMcpError(result, toolName);
1039
+ return result;
1040
+ }
1041
+ /**
1042
+ * Translate an MCP tool's structured error response to an SDK error.
1043
+ *
1044
+ * The server's MCP tools return `{"status": "error", "error": <code>,
1045
+ * "message": <str>, ...}` for domain errors the JSON-RPC transport
1046
+ * cannot represent. HTTP-level errors are handled by the request layer.
1047
+ */
1048
+ static raiseForMcpError(result, operation) {
1049
+ if (result.status !== "error") {
1050
+ return;
1051
+ }
1052
+ const code = typeof result.error === "string" ? result.error : "unknown";
1053
+ const message = typeof result.message === "string" ? result.message : "Unknown error";
1054
+ if (code === "report_not_found" || code === "context_not_found" || code === "memory_not_found") {
1055
+ throw new KaguraNotFoundError(`${operation}: ${message}`);
1056
+ }
1057
+ throw new KaguraError(`${operation} failed (${code}): ${message}`);
1058
+ }
1059
+ /** Store a memory. Returns the API response with `memory_id`. */
1060
+ async remember(options) {
1061
+ const args = {
1062
+ context_id: options.contextId,
1063
+ summary: options.summary,
1064
+ content: options.content,
1065
+ type: options.type ?? "note",
1066
+ importance: options.importance ?? 0.5
1067
+ };
1068
+ if (options.tags !== void 0) {
1069
+ args.tags = options.tags;
1070
+ }
1071
+ if (options.sourceUri !== void 0) {
1072
+ args.source_uri = options.sourceUri;
1073
+ }
1074
+ if (options.sourceType !== void 0) {
1075
+ args.source_type = options.sourceType;
1076
+ }
1077
+ if (options.deliveryMode !== void 0 && options.deliveryMode !== "on_recall") {
1078
+ args.delivery_mode = options.deliveryMode;
1079
+ }
1080
+ if (options.contextSummary !== void 0) {
1081
+ args.context_summary = options.contextSummary;
1082
+ }
1083
+ if (options.details !== void 0) {
1084
+ args.details = options.details;
1085
+ }
1086
+ if (options.context !== void 0) {
1087
+ args.context = options.context;
1088
+ }
1089
+ if (options.linkedMemoryIds !== void 0) {
1090
+ args.linked_memory_ids = options.linkedMemoryIds;
1091
+ }
1092
+ if (options.linkedSourceUris !== void 0) {
1093
+ args.linked_source_uris = options.linkedSourceUris;
1094
+ }
1095
+ return this.callToolChecked("remember", args);
1096
+ }
1097
+ /**
1098
+ * Search memories. Returns the API response with a `results` list.
1099
+ *
1100
+ * @throws Error if `query` is empty/whitespace; if neither `contextId`
1101
+ * nor `contextIds` is provided; if `contextIds` has fewer than 2 or
1102
+ * more than 20 IDs; or if `searchMode` is invalid.
1103
+ */
1104
+ async recall(options) {
1105
+ const { query, contextId, contextIds, searchMode } = options;
1106
+ if (typeof query !== "string" || !query.trim()) {
1107
+ throw new Error("query must be a non-empty string");
1108
+ }
1109
+ if (contextIds !== void 0) {
1110
+ if (contextIds.length < 2 || contextIds.length > 20) {
1111
+ throw new Error(`contextIds must contain 2-20 IDs, got ${contextIds.length}`);
1112
+ }
1113
+ } else if (contextId === void 0) {
1114
+ throw new Error("Either contextId or contextIds must be provided");
1115
+ }
1116
+ const args = {
1117
+ query,
1118
+ k: options.k ?? 5
1119
+ };
1120
+ if (contextIds !== void 0) {
1121
+ args.context_ids = contextIds;
1122
+ } else {
1123
+ args.context_id = contextId;
1124
+ }
1125
+ if (options.useRerank) {
1126
+ args.use_rerank = true;
1127
+ }
1128
+ if (options.filters && Object.keys(options.filters).length > 0) {
1129
+ args.filters = options.filters;
1130
+ }
1131
+ if (searchMode) {
1132
+ if (searchMode !== "hybrid" && searchMode !== "semantic" && searchMode !== "keyword") {
1133
+ throw new Error(`Invalid searchMode: ${JSON.stringify(searchMode)}`);
1134
+ }
1135
+ args.search_mode = searchMode;
1136
+ }
1137
+ if (options.includeExploreHints) {
1138
+ args.include_explore_hints = true;
1139
+ }
1140
+ return this.callToolChecked("recall", args);
1141
+ }
1142
+ /**
1143
+ * List Time Memories whose scheduled window overlaps a range, soonest
1144
+ * first. A deterministic time query over `type="time"` memories — not
1145
+ * semantic search, no Hebbian side-effects.
1146
+ */
1147
+ async recallUpcoming(options) {
1148
+ const args = {
1149
+ context_id: options.contextId,
1150
+ k: options.k ?? 20
1151
+ };
1152
+ if (options.from !== void 0) {
1153
+ args.from = options.from;
1154
+ }
1155
+ if (options.until !== void 0) {
1156
+ args.until = options.until;
1157
+ }
1158
+ return this.callToolChecked("recall_upcoming", args);
1159
+ }
1160
+ /**
1161
+ * Deterministically load a context's pinned (`delivery_mode="always"`)
1162
+ * memories — the complete, unranked pinned set on every call.
1163
+ *
1164
+ * The set is bounded, never silently dropped: when more pinned memories
1165
+ * exist than `cap`, the response `truncated` flag is true and
1166
+ * `total_available` reports the real count.
1167
+ */
1168
+ async loadPinned(options) {
1169
+ const args = { context_id: options.contextId };
1170
+ if (options.cap !== void 0) {
1171
+ args.cap = options.cap;
1172
+ }
1173
+ return this.callToolChecked("load_pinned", args);
1174
+ }
1175
+ /**
1176
+ * Record whether a recalled memory was useful for a query — an
1177
+ * append-only usefulness signal, kept in a separate lane from knowledge
1178
+ * (never pollutes recall).
1179
+ */
1180
+ async feedback(options) {
1181
+ const args = {
1182
+ context_id: options.contextId,
1183
+ memory_id: options.memoryId,
1184
+ helpful: options.helpful
1185
+ };
1186
+ if (options.query !== void 0) {
1187
+ args.query = options.query;
1188
+ }
1189
+ if (options.note !== void 0) {
1190
+ args.note = options.note;
1191
+ }
1192
+ return this.callToolChecked("feedback", args);
1193
+ }
1194
+ /**
1195
+ * Set ephemeral agent run-state at `(contextId, key)` — a TTL-bounded
1196
+ * key/value lane kept separate from memories and excluded from recall.
1197
+ * Use remember() for durable knowledge.
1198
+ */
1199
+ async setState(options) {
1200
+ const args = {
1201
+ context_id: options.contextId,
1202
+ key: options.key,
1203
+ value: options.value
1204
+ };
1205
+ if (options.ttlSeconds !== void 0) {
1206
+ args.ttl_seconds = options.ttlSeconds;
1207
+ }
1208
+ return this.callToolChecked("set_state", args);
1209
+ }
1210
+ /**
1211
+ * Read ephemeral agent run-state. Supply `key` to read one value, omit
1212
+ * it to list all live keys for the context.
1213
+ */
1214
+ async getState(options) {
1215
+ const args = { context_id: options.contextId };
1216
+ if (options.key !== void 0) {
1217
+ args.key = options.key;
1218
+ }
1219
+ return this.callToolChecked("get_state", args);
1220
+ }
1221
+ /** List available contexts. */
1222
+ async listContexts() {
1223
+ return this.callToolChecked("list_contexts", {});
1224
+ }
1225
+ /**
1226
+ * List the tag vocabulary in a context with usage counts and recency.
1227
+ *
1228
+ * Call before remember() to reuse existing tag spellings, or before
1229
+ * recall() with tag filters. Requires memory-cloud server v0.15.4+.
1230
+ */
1231
+ async listTags(options) {
1232
+ const limit = options.limit ?? 50;
1233
+ const minCount = options.minCount ?? 1;
1234
+ const prefix = options.prefix ?? "";
1235
+ if (limit < 1 || limit > 500) {
1236
+ throw new Error(`limit must be between 1 and 500, got ${limit}`);
1237
+ }
1238
+ if (minCount < 1 || minCount > 1e4) {
1239
+ throw new Error(`minCount must be between 1 and 10000, got ${minCount}`);
1240
+ }
1241
+ if (prefix.length > 200) {
1242
+ throw new Error(`prefix must be at most 200 characters, got ${prefix.length}`);
1243
+ }
1244
+ const args = {
1245
+ context_id: options.contextId,
1246
+ limit,
1247
+ min_count: minCount,
1248
+ sort: options.sort ?? "count"
1249
+ };
1250
+ if (prefix) {
1251
+ args.prefix = prefix;
1252
+ }
1253
+ const result = await this.callToolChecked("list_tags", args);
1254
+ return result;
1255
+ }
1256
+ /**
1257
+ * Call tools/list to get available MCP tool definitions (names,
1258
+ * descriptions, parameter schemas).
1259
+ */
1260
+ async getToolDefinitions() {
1261
+ const result = await this.makeJsonRpcRequest("tools/list", {});
1262
+ const tools = result.tools;
1263
+ return Array.isArray(tools) ? tools : [];
1264
+ }
1265
+ /** Neural graph traversal from a seed memory. */
1266
+ async explore(options) {
1267
+ return this.callToolChecked("explore", {
1268
+ context_id: options.contextId,
1269
+ memory_id: options.memoryId,
1270
+ depth: options.depth ?? 2,
1271
+ min_weight: options.minWeight ?? 0.05
1272
+ });
1273
+ }
1274
+ /**
1275
+ * Get full memory details. Memory data is in `result.memory`.
1276
+ */
1277
+ async reference(options) {
1278
+ return this.callToolChecked("reference", {
1279
+ context_id: options.contextId,
1280
+ memory_id: options.memoryId
1281
+ });
1282
+ }
1283
+ /**
1284
+ * Update an existing memory in-place (memoryId) or upsert by external
1285
+ * ID (externalId — requires summary, content, and type).
1286
+ *
1287
+ * @throws Error unless exactly one of memoryId/externalId is provided.
1288
+ */
1289
+ async updateMemory(options) {
1290
+ if (!options.memoryId && !options.externalId) {
1291
+ throw new Error("Provide exactly one of memoryId or externalId");
1292
+ }
1293
+ if (options.memoryId && options.externalId) {
1294
+ throw new Error("Provide exactly one of memoryId or externalId");
1295
+ }
1296
+ const args = { context_id: options.contextId };
1297
+ if (options.memoryId !== void 0) {
1298
+ args.memory_id = options.memoryId;
1299
+ }
1300
+ if (options.externalId !== void 0) {
1301
+ args.external_id = options.externalId;
1302
+ }
1303
+ if (options.summary !== void 0) {
1304
+ args.summary = options.summary;
1305
+ }
1306
+ if (options.content !== void 0) {
1307
+ args.content = options.content;
1308
+ }
1309
+ if (options.type !== void 0) {
1310
+ args.type = options.type;
1311
+ }
1312
+ if (options.importance !== void 0) {
1313
+ args.importance = options.importance;
1314
+ }
1315
+ if (options.tags !== void 0) {
1316
+ args.tags = options.tags;
1317
+ }
1318
+ if (options.contextSummary !== void 0) {
1319
+ args.context_summary = options.contextSummary;
1320
+ }
1321
+ if (options.deliveryMode !== void 0) {
1322
+ args.delivery_mode = options.deliveryMode;
1323
+ }
1324
+ return this.callToolChecked("update_memory", args);
1325
+ }
1326
+ /**
1327
+ * Soft-delete memories (30-day retention) by specific memoryId or by
1328
+ * search query.
1329
+ *
1330
+ * @throws Error if neither memoryId nor query is provided.
1331
+ */
1332
+ async forget(options) {
1333
+ if (!options.memoryId && !options.query) {
1334
+ throw new Error("Provide either memoryId or query");
1335
+ }
1336
+ const args = { context_id: options.contextId };
1337
+ if (options.memoryId) {
1338
+ args.memory_id = options.memoryId;
1339
+ }
1340
+ if (options.query) {
1341
+ args.query = options.query;
1342
+ args.k = options.k ?? 10;
1343
+ }
1344
+ return this.callToolChecked("forget", args);
1345
+ }
1346
+ /**
1347
+ * Create a new context in the current workspace.
1348
+ *
1349
+ * @throws KaguraQuotaError when the workspace context limit is reached.
1350
+ */
1351
+ async createContext(options) {
1352
+ const contexts = await this.listContexts();
1353
+ const canCreate = "can_create" in contexts ? contexts.can_create : true;
1354
+ if (!canCreate) {
1355
+ const count = contexts.count ?? null;
1356
+ const limit = contexts.limit ?? null;
1357
+ throw new KaguraQuotaError(
1358
+ `Context limit reached (${count === null ? "?" : String(count)}/${limit === null ? "?" : String(limit)}). Delete unused contexts or upgrade your plan.`
1359
+ );
1360
+ }
1361
+ const args = {
1362
+ name: options.name,
1363
+ is_private: options.isPrivate ?? true
1364
+ };
1365
+ if (options.displayName !== void 0) {
1366
+ args.display_name = options.displayName;
1367
+ }
1368
+ if (options.description !== void 0) {
1369
+ args.description = options.description;
1370
+ }
1371
+ if (options.summary !== void 0) {
1372
+ args.summary = options.summary;
1373
+ }
1374
+ if (options.usageGuide !== void 0) {
1375
+ args.usage_guide = options.usageGuide;
1376
+ }
1377
+ if (options.resourceId !== void 0) {
1378
+ args.resource_id = options.resourceId;
1379
+ }
1380
+ if (options.embeddingModel !== void 0) {
1381
+ args.embedding_model = options.embeddingModel;
1382
+ }
1383
+ return this.callToolChecked("create_context", args);
1384
+ }
1385
+ /** Soft-delete a context and all its memories. */
1386
+ async deleteContext(contextId) {
1387
+ return this.callToolChecked("delete_context", { context_id: contextId });
1388
+ }
1389
+ /** Update an existing context's settings. */
1390
+ async updateContext(options) {
1391
+ const args = { context_id: options.contextId };
1392
+ if (options.displayName !== void 0) {
1393
+ args.display_name = options.displayName;
1394
+ }
1395
+ if (options.description !== void 0) {
1396
+ args.description = options.description;
1397
+ }
1398
+ if (options.summary !== void 0) {
1399
+ args.summary = options.summary;
1400
+ }
1401
+ if (options.usageGuide !== void 0) {
1402
+ args.usage_guide = options.usageGuide;
1403
+ }
1404
+ if (options.resourceId !== void 0) {
1405
+ args.resource_id = options.resourceId;
1406
+ }
1407
+ if (options.isPublic !== void 0) {
1408
+ args.is_public = options.isPublic;
1409
+ }
1410
+ if (options.isLocked !== void 0) {
1411
+ args.is_locked = options.isLocked;
1412
+ }
1413
+ return this.callToolChecked("update_context", args);
1414
+ }
1415
+ /**
1416
+ * Atomically create Context + Resource entity + ingestion token in a
1417
+ * single server-side transaction. The returned `token` is plaintext and
1418
+ * shown once.
1419
+ */
1420
+ async setupResource(options) {
1421
+ const args = {
1422
+ resource_id: options.resourceId,
1423
+ quota_events_per_hour: options.quotaEventsPerHour ?? 1e3
1424
+ };
1425
+ if (options.name !== void 0) {
1426
+ args.name = options.name;
1427
+ }
1428
+ if (options.summary !== void 0) {
1429
+ args.summary = options.summary;
1430
+ }
1431
+ if (options.description !== void 0) {
1432
+ args.description = options.description;
1433
+ }
1434
+ return this.callToolChecked("setup_resource", args);
1435
+ }
1436
+ /**
1437
+ * Merge memories from one context into another. Both contexts must use
1438
+ * the same embedding model and belong to the same workspace.
1439
+ *
1440
+ * @throws Error if sourceId and targetId are the same.
1441
+ */
1442
+ async mergeContexts(options) {
1443
+ if (options.sourceId === options.targetId) {
1444
+ throw new Error("sourceId and targetId must be different");
1445
+ }
1446
+ const args = {
1447
+ source_context_id: options.sourceId,
1448
+ target_context_id: options.targetId
1449
+ };
1450
+ if (options.deleteSource) {
1451
+ args.delete_source = true;
1452
+ }
1453
+ return this.callToolChecked("merge_contexts", args);
1454
+ }
1455
+ /**
1456
+ * List neural memory edges connected to a memory (outgoing and
1457
+ * incoming, deduplicated).
1458
+ *
1459
+ * Note: the server applies `limit` to outgoing AND incoming queries
1460
+ * independently, so the practical maximum returned is `2 * limit`
1461
+ * minus dedup overlap.
1462
+ */
1463
+ async listEdges(options) {
1464
+ const args = {
1465
+ context_id: options.contextId,
1466
+ memory_id: options.memoryId,
1467
+ min_weight: options.minWeight ?? 0
1468
+ };
1469
+ if (options.edgeTypes !== void 0) {
1470
+ args.edge_types = options.edgeTypes;
1471
+ }
1472
+ if (options.limit !== void 0) {
1473
+ args.limit = options.limit;
1474
+ }
1475
+ const result = await this.callToolChecked("list_edges", args);
1476
+ const edges = result.edges;
1477
+ return Array.isArray(edges) ? edges : [];
1478
+ }
1479
+ /**
1480
+ * Create or upsert a neural memory edge from source to target.
1481
+ *
1482
+ * The server uses `(user_id, source_id, target_id)` as a unique key
1483
+ * with max-weight UPSERT semantics — not a pure INSERT.
1484
+ *
1485
+ * @throws Error if sourceId === targetId (self-loops are rejected).
1486
+ */
1487
+ async createEdge(options) {
1488
+ if (options.sourceId === options.targetId) {
1489
+ throw new Error("sourceId and targetId must be different (self-loops are not allowed)");
1490
+ }
1491
+ const result = await this.callToolChecked("create_edge", {
1492
+ context_id: options.contextId,
1493
+ source_id: options.sourceId,
1494
+ target_id: options.targetId,
1495
+ edge_type: options.edgeType ?? "related_to",
1496
+ weight: options.weight ?? 0.5,
1497
+ confidence: options.confidence ?? 1
1498
+ });
1499
+ return result.edge ?? result;
1500
+ }
1501
+ /**
1502
+ * Update an existing edge's weight and/or edge type, identified by the
1503
+ * `(sourceId, targetId)` pair. Omit a field to leave it unchanged.
1504
+ */
1505
+ async updateEdge(options) {
1506
+ const args = {
1507
+ context_id: options.contextId,
1508
+ source_id: options.sourceId,
1509
+ target_id: options.targetId
1510
+ };
1511
+ if (options.weight !== void 0) {
1512
+ args.weight = options.weight;
1513
+ }
1514
+ if (options.edgeType !== void 0) {
1515
+ args.edge_type = options.edgeType;
1516
+ }
1517
+ const result = await this.callToolChecked("update_edge", args);
1518
+ return result.edge ?? result;
1519
+ }
1520
+ /**
1521
+ * Delete the edge between sourceId and targetId. Returns true once the
1522
+ * server confirms deletion.
1523
+ */
1524
+ async deleteEdge(options) {
1525
+ const result = await this.callToolChecked("delete_edge", {
1526
+ context_id: options.contextId,
1527
+ source_id: options.sourceId,
1528
+ target_id: options.targetId
1529
+ });
1530
+ return result.deleted === void 0 ? true : Boolean(result.deleted);
1531
+ }
1532
+ /** Get workspace usage and quota limits. */
1533
+ async getUsage() {
1534
+ const result = await this.callToolChecked("get_usage", {});
1535
+ return result;
1536
+ }
1537
+ /** Get context information, usage guidelines, and search config. */
1538
+ async getContextInfo(options) {
1539
+ const result = await this.callToolChecked("get_context_info", {
1540
+ context_id: options.contextId,
1541
+ include_details: options.includeDetails ?? true
1542
+ });
1543
+ return result;
1544
+ }
1545
+ /**
1546
+ * Update hybrid search configuration for a context. Weights must sum
1547
+ * to 1.0 (±0.01). Requires owner or editor permission.
1548
+ */
1549
+ async updateSearchConfig(options) {
1550
+ const args = { context_id: options.contextId };
1551
+ if (options.semanticWeight !== void 0) {
1552
+ args.semantic_weight = options.semanticWeight;
1553
+ }
1554
+ if (options.bm25Weight !== void 0) {
1555
+ args.bm25_weight = options.bm25Weight;
1556
+ }
1557
+ if (options.fetchFactor !== void 0) {
1558
+ args.fetch_factor = options.fetchFactor;
1559
+ }
1560
+ if (options.useRerank !== void 0) {
1561
+ args.use_rerank = options.useRerank;
1562
+ }
1563
+ if (options.rerankerProvider !== void 0) {
1564
+ args.reranker_provider = options.rerankerProvider;
1565
+ }
1566
+ if (options.rerankerModel !== void 0) {
1567
+ args.reranker_model = options.rerankerModel;
1568
+ }
1569
+ return this.callToolChecked("update_search_config", args);
1570
+ }
1571
+ /** Get server name, version, environment, and feature flags. */
1572
+ async getServerInfo() {
1573
+ return this.restGet("/api/v1/system/info");
1574
+ }
1575
+ /**
1576
+ * Check the connected server's version against the SDK's tested
1577
+ * minimum. Advisory only — logs a warning, never throws on mismatch.
1578
+ */
1579
+ async checkServerVersion() {
1580
+ const info = await this.getServerInfo();
1581
+ const components = info.version.split(".").slice(0, 3);
1582
+ if (components.length === 0 || !components.every((c) => /^\d+$/.test(c))) {
1583
+ return info;
1584
+ }
1585
+ const parts = components.map(Number);
1586
+ for (let i = 0; i < MIN_SERVER_VERSION_TUPLE.length; i++) {
1587
+ const server = parts[i] ?? 0;
1588
+ const min = MIN_SERVER_VERSION_TUPLE[i] ?? 0;
1589
+ if (server < min) {
1590
+ console.warn(
1591
+ `Server version ${info.version} is below the SDK's tested minimum ${MIN_SERVER_VERSION}. Some features may not work; older servers may silently ignore unknown parameters.`
1592
+ );
1593
+ break;
1594
+ }
1595
+ if (server > min) {
1596
+ break;
1597
+ }
1598
+ }
1599
+ return info;
1600
+ }
1601
+ /** Get embedding queue status for the workspace. */
1602
+ async getEmbeddingStatus() {
1603
+ return this.restGet("/api/v1/workspace/embedding-status");
1604
+ }
1605
+ /** Get per-memory usage statistics for a context. */
1606
+ async getMemoryStats(options) {
1607
+ return this.restGet(
1608
+ `/api/v1/contexts/${options.contextId}/memory-stats`,
1609
+ {
1610
+ sort_by: options.sortBy ?? "use_count",
1611
+ sort_order: options.sortOrder ?? "desc",
1612
+ limit: options.limit ?? 50,
1613
+ offset: options.offset ?? 0
1614
+ }
1615
+ );
1616
+ }
1617
+ /** Find duplicate memory pairs in a context. */
1618
+ async findDuplicates(options) {
1619
+ return this.restGet(`/api/v1/contexts/${options.contextId}/duplicates`, {
1620
+ threshold: options.threshold ?? 0.9,
1621
+ limit: options.limit ?? 50
1622
+ });
1623
+ }
1624
+ /**
1625
+ * List memories with optional substring, facet, and time-window
1626
+ * filters. Without `contextId` this returns the caller's own memories
1627
+ * across all contexts. `q` matches summaries only — use recall() for
1628
+ * semantic search.
1629
+ */
1630
+ async listMemories(options = {}) {
1631
+ const params = {
1632
+ limit: options.limit ?? 50,
1633
+ offset: options.offset ?? 0
1634
+ };
1635
+ if (options.contextId !== void 0) {
1636
+ params.context_id = options.contextId;
1637
+ }
1638
+ const qNormalized = (options.q ?? "").trim();
1639
+ if (qNormalized) {
1640
+ params.q = qNormalized;
1641
+ }
1642
+ if (options.scope !== void 0) {
1643
+ params.scope = options.scope;
1644
+ }
1645
+ if (options.type !== void 0) {
1646
+ params.type = options.type;
1647
+ }
1648
+ if (options.triggerFrom !== void 0) {
1649
+ params.trigger_from = options.triggerFrom;
1650
+ }
1651
+ if (options.triggerUntil !== void 0) {
1652
+ params.trigger_until = options.triggerUntil;
1653
+ }
1654
+ if (options.orderBy !== void 0) {
1655
+ params.order_by = options.orderBy;
1656
+ }
1657
+ return this.restGet("/api/v1/memory/list", params);
1658
+ }
1659
+ /**
1660
+ * List recent Sleep Maintenance runs for a context, newest first.
1661
+ */
1662
+ async getSleepHistory(options) {
1663
+ const result = await this.callToolChecked("get_sleep_history", {
1664
+ context_id: options.contextId,
1665
+ limit: options.limit ?? 10
1666
+ });
1667
+ const reports = result.reports;
1668
+ if (!Array.isArray(reports)) {
1669
+ throw new KaguraConnectionError(
1670
+ "Unexpected get_sleep_history response: missing 'reports' array."
1671
+ );
1672
+ }
1673
+ return reports;
1674
+ }
1675
+ /**
1676
+ * Get a detailed Sleep Maintenance report including the per-action
1677
+ * audit log.
1678
+ */
1679
+ async getSleepReport(options) {
1680
+ const result = await this.callToolChecked("get_sleep_report", {
1681
+ context_id: options.contextId,
1682
+ report_id: options.reportId
1683
+ });
1684
+ const report = result.report;
1685
+ if (typeof report !== "object" || report === null || Array.isArray(report)) {
1686
+ throw new KaguraConnectionError(
1687
+ "Unexpected get_sleep_report response: missing 'report' envelope."
1688
+ );
1689
+ }
1690
+ return {
1691
+ ...report,
1692
+ actions: result.actions,
1693
+ action_count: result.action_count
1694
+ };
1695
+ }
1696
+ /**
1697
+ * Reverse the effects of a completed Sleep Maintenance run. The server
1698
+ * processes actions in reverse order with per-step commits — a partial
1699
+ * failure means SOME actions may have been reversed before the error.
1700
+ */
1701
+ async rollbackSleepRun(options) {
1702
+ const result = await this.callToolChecked("rollback_sleep_run", {
1703
+ context_id: options.contextId,
1704
+ report_id: options.reportId
1705
+ });
1706
+ return result;
1707
+ }
1708
+ /** List available embedding models with provider info and availability. */
1709
+ async listEmbeddingModels() {
1710
+ return this.restGet("/api/v1/system/embedding/models");
1711
+ }
1712
+ /** Release resources. (fetch has no persistent connection to close; kept for API parity.) */
1713
+ async close() {
1714
+ this.sessionId = null;
1715
+ }
1716
+ };
1717
+
1718
+ // src/restBase.ts
1719
+ var DEFAULT_REST_BASE_URL = "https://memory.kagura-ai.com";
1720
+ function jsonTypeName(value) {
1721
+ return value === null ? "null" : typeof value;
1722
+ }
1723
+ var KaguraRestClient = class {
1724
+ baseUrl;
1725
+ timeoutMs;
1726
+ /** Supplies the Authorization header for every request (static or OAuth). */
1727
+ auth;
1728
+ /** Non-null exactly when constructed in OAuth mode (flavors the 401 hint). */
1729
+ oauth;
1730
+ /** Which resolution branch produced the credentials (403 hint flavoring). */
1731
+ authSource;
1732
+ /** Workspace bound to the credential source — display only. */
1733
+ workspaceIdHint;
1734
+ fetchImpl;
1735
+ /**
1736
+ * Initialize with a static API key or a pre-built OAuth provider.
1737
+ *
1738
+ * @throws Error if neither `apiKey` nor `oauth` is given, or the base
1739
+ * URL is plain HTTP on a non-loopback host.
1740
+ */
1741
+ constructor(options = {}) {
1742
+ if (options.apiKey === void 0 && options.oauth === void 0) {
1743
+ const name = new.target.name;
1744
+ throw new Error(
1745
+ `${name} requires apiKey, or use ${name}.fromMcpUrl(...) to resolve credentials from environment, OAuth profile, or .kagura.json.`
1746
+ );
1747
+ }
1748
+ const strippedUrl = (options.baseUrl ?? DEFAULT_REST_BASE_URL).replace(/\/+$/, "");
1749
+ validateHttpsUrl(strippedUrl, "Base URL");
1750
+ this.baseUrl = strippedUrl;
1751
+ this.timeoutMs = options.timeoutMs ?? 3e4;
1752
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
1753
+ if (options.oauth !== void 0) {
1754
+ this.auth = options.oauth;
1755
+ this.oauth = options.oauth;
1756
+ } else {
1757
+ const header = `Bearer ${options.apiKey}`;
1758
+ this.auth = { getAuthHeader: async () => header };
1759
+ this.oauth = null;
1760
+ }
1761
+ this.authSource = options.authSource ?? null;
1762
+ this.workspaceIdHint = options.workspaceIdHint ?? null;
1763
+ }
1764
+ // -------------------------------------------------------------------
1765
+ // Factories
1766
+ // -------------------------------------------------------------------
1767
+ /**
1768
+ * Create a client by resolving credentials from the SDK chain.
1769
+ *
1770
+ * Precedence: explicit `apiKey` > `KAGURA_API_KEY` env > OAuth profile
1771
+ * from `~/.kagura/credentials.json` > `.kagura.json`. The REST
1772
+ * `baseUrl` is derived from the resolved MCP URL (strips `/mcp` and any
1773
+ * `/mcp/w/{workspaceId}` suffix); a static key bakes the Bearer header
1774
+ * once, an OAuth profile installs an auto-refreshing `AuthProvider`.
1775
+ *
1776
+ * Declared with a polymorphic `this` so every subclass inherits a
1777
+ * factory returning its own type: `FilesClient.fromMcpUrl(...)` is a
1778
+ * `FilesClient`.
1779
+ */
1780
+ static fromMcpUrl(options = {}) {
1781
+ const resolved = resolveAuth({
1782
+ apiKey: options.apiKey ?? null,
1783
+ mcpUrl: options.mcpUrl ?? null,
1784
+ profile: options.profile ?? null,
1785
+ env: options.env,
1786
+ home: options.home
1787
+ });
1788
+ return this.fromResolvedAuth(resolved, {
1789
+ timeoutMs: options.timeoutMs,
1790
+ fetch: options.fetch
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Construct from a pre-resolved auth — internal CLI helper.
1795
+ *
1796
+ * Shared by {@link fromMcpUrl} (SDK entry) and CLI command runners,
1797
+ * which resolve once so apiKey and workspace can be paired from the
1798
+ * same credential source (#115).
1799
+ *
1800
+ * `workspaceIdHint` threads the workspace bound to a static apiKey into
1801
+ * the client for 403 hint display. On the OAuth branch the resolver
1802
+ * already carries `workspaceId`, so the hint is taken from there and
1803
+ * the option is ignored.
1804
+ */
1805
+ static fromResolvedAuth(resolved, options = {}) {
1806
+ const baseUrl = baseUrlFromMcp(resolved.mcpUrl.replace(/\/+$/, ""));
1807
+ const shared = { baseUrl };
1808
+ if (options.timeoutMs !== void 0) {
1809
+ shared.timeoutMs = options.timeoutMs;
1810
+ }
1811
+ if (options.fetch !== void 0) {
1812
+ shared.fetch = options.fetch;
1813
+ }
1814
+ if (resolved.kind === "static") {
1815
+ return new this({
1816
+ ...shared,
1817
+ apiKey: resolved.apiKey,
1818
+ authSource: resolved.source,
1819
+ workspaceIdHint: options.workspaceIdHint ?? null
1820
+ });
1821
+ }
1822
+ return new this({
1823
+ ...shared,
1824
+ oauth: resolved.oauth,
1825
+ authSource: "oauth",
1826
+ workspaceIdHint: resolved.workspaceId
1827
+ });
1828
+ }
1829
+ // -------------------------------------------------------------------
1830
+ // Lifecycle
1831
+ // -------------------------------------------------------------------
1832
+ /** Release resources. (fetch has no persistent pool to close; kept for API parity.) */
1833
+ async close() {
1834
+ }
1835
+ // -------------------------------------------------------------------
1836
+ // Request spine
1837
+ // -------------------------------------------------------------------
1838
+ /**
1839
+ * Make an authenticated request with standard error mapping.
1840
+ *
1841
+ * Returns the {@link RestResponse} envelope for 2xx; throws the mapped
1842
+ * {@link KaguraError} for any other status and wraps transport/abort
1843
+ * failures in {@link KaguraConnectionError}.
1844
+ */
1845
+ async request(method, path5, opts = {}) {
1846
+ let url = `${this.baseUrl}${path5}`;
1847
+ if (opts.params) {
1848
+ const query = new URLSearchParams();
1849
+ for (const [key, value] of Object.entries(opts.params)) {
1850
+ if (value !== void 0 && value !== null) {
1851
+ query.set(key, String(value));
1852
+ }
1853
+ }
1854
+ const qs = query.toString();
1855
+ if (qs) {
1856
+ url += `?${qs}`;
1857
+ }
1858
+ }
1859
+ const headers = {
1860
+ authorization: await this.auth.getAuthHeader(),
1861
+ "user-agent": `kagura-memory-sdk/${SDK_VERSION}`
1862
+ };
1863
+ const init = {
1864
+ method,
1865
+ headers,
1866
+ signal: AbortSignal.timeout(this.timeoutMs)
1867
+ };
1868
+ if (opts.json !== void 0) {
1869
+ headers["content-type"] = "application/json";
1870
+ init.body = JSON.stringify(opts.json);
1871
+ }
1872
+ Object.assign(headers, opts.extraHeaders);
1873
+ let response;
1874
+ try {
1875
+ response = await this.fetchImpl(url, init);
1876
+ } catch (e) {
1877
+ throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });
1878
+ }
1879
+ const envelope = {
1880
+ status: response.status,
1881
+ headers: response.headers,
1882
+ text: await this.safeText(response),
1883
+ method,
1884
+ path: path5
1885
+ };
1886
+ if (response.status < 200 || response.status >= 300) {
1887
+ throw this.mapStatusError(envelope, {
1888
+ requestJson: opts.json,
1889
+ requestParams: opts.params
1890
+ });
1891
+ }
1892
+ return envelope;
1893
+ }
1894
+ async safeText(response) {
1895
+ try {
1896
+ return await response.text();
1897
+ } catch {
1898
+ return "";
1899
+ }
1900
+ }
1901
+ /**
1902
+ * Build the Kagura error for a non-2xx response.
1903
+ *
1904
+ * Hooks RETURN the error rather than throwing it so {@link request}
1905
+ * owns the single throw site — one uniform chain and a compiler-checked
1906
+ * `KaguraError` contract on every hook.
1907
+ */
1908
+ mapStatusError(response, context) {
1909
+ const status = response.status;
1910
+ if (status === 401) {
1911
+ return this.error401(response);
1912
+ }
1913
+ if (status === 403) {
1914
+ return this.error403(response, context);
1915
+ }
1916
+ if (status === 404) {
1917
+ return new KaguraNotFoundError(extractDetail(response.text) || "Not found");
1918
+ }
1919
+ if (status === 429) {
1920
+ return this.error429(response);
1921
+ }
1922
+ return this.genericError(response);
1923
+ }
1924
+ // ---- per-status hooks (override where the wire contract differs) ----
1925
+ /** 401 → auth error with a recovery hint matching the auth mode. */
1926
+ error401(response) {
1927
+ const hint = this.oauth !== null ? "Re-run `kagura auth login` or inspect ~/.kagura/credentials.json." : "Check your API key.";
1928
+ return new KaguraAuthError(`Authentication failed. ${hint}`);
1929
+ }
1930
+ /**
1931
+ * 403 → generic mapping by default; clients with a richer story
1932
+ * (workspace hints, secret existence-hiding) override this.
1933
+ */
1934
+ error403(response, context) {
1935
+ return this.genericError(response);
1936
+ }
1937
+ /** 429 → quota error with a tolerant `Retry-After` parse. */
1938
+ error429(response) {
1939
+ return new KaguraQuotaError(
1940
+ "Quota exceeded. Try again later.",
1941
+ retryAfterSeconds(response.headers)
1942
+ );
1943
+ }
1944
+ /** Any other status → `HTTP <status>: <detail>` connection error. */
1945
+ genericError(response) {
1946
+ const detail = extractDetail(response.text);
1947
+ const msg = detail ? `HTTP ${response.status}: ${detail}` : `HTTP ${response.status}`;
1948
+ return new KaguraConnectionError(msg);
1949
+ }
1950
+ // -------------------------------------------------------------------
1951
+ // Response-body helpers
1952
+ // -------------------------------------------------------------------
1953
+ /**
1954
+ * Parse a 2xx body as JSON, mapping garbage to a Kagura error.
1955
+ *
1956
+ * A proxy/CDN can 200 with an HTML maintenance page; that must not
1957
+ * surface as a raw `SyntaxError`.
1958
+ */
1959
+ json(response) {
1960
+ try {
1961
+ return JSON.parse(response.text);
1962
+ } catch (e) {
1963
+ throw new KaguraConnectionError(
1964
+ `Server returned a non-JSON body (HTTP ${response.status}) for ${response.method} ${response.path}.`,
1965
+ { cause: e }
1966
+ );
1967
+ }
1968
+ }
1969
+ /** Parse a 2xx body that the contract says is a JSON array. */
1970
+ expectList(response) {
1971
+ const payload = this.json(response);
1972
+ if (!Array.isArray(payload)) {
1973
+ throw new KaguraConnectionError(
1974
+ `Unexpected response shape for ${response.method} ${response.path}: expected a JSON array, got ${jsonTypeName(payload)}.`
1975
+ );
1976
+ }
1977
+ return payload;
1978
+ }
1979
+ };
1980
+
1981
+ // src/filesClient.ts
1982
+ import { createHash } from "crypto";
1983
+ import { readFile } from "fs/promises";
1984
+ import * as path4 from "path";
1985
+
1986
+ // src/auth/types.ts
1987
+ var SOURCE_LABEL = {
1988
+ explicit: "explicit apiKey argument",
1989
+ env: "KAGURA_API_KEY env",
1990
+ config: ".kagura.json",
1991
+ oauth: "OAuth profile (~/.kagura/credentials.json)"
1992
+ };
1993
+
1994
+ // src/uuid.ts
1995
+ var CANONICAL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1996
+ function parseUuid(value) {
1997
+ if (typeof value !== "string") {
1998
+ throw new Error(`expected a UUID string, got ${typeof value}`);
1999
+ }
2000
+ let hex = value.trim().toLowerCase();
2001
+ if (hex.startsWith("urn:uuid:")) {
2002
+ hex = hex.slice("urn:uuid:".length);
2003
+ }
2004
+ if (hex.startsWith("{") && hex.endsWith("}")) {
2005
+ hex = hex.slice(1, -1);
2006
+ }
2007
+ hex = hex.replace(/-/g, "");
2008
+ if (!/^[0-9a-f]{32}$/.test(hex)) {
2009
+ throw new Error(`invalid UUID: ${value}`);
2010
+ }
2011
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2012
+ }
2013
+ function isUuid(value) {
2014
+ if (CANONICAL_RE.test(value)) {
2015
+ return true;
2016
+ }
2017
+ try {
2018
+ parseUuid(value);
2019
+ return true;
2020
+ } catch {
2021
+ return false;
2022
+ }
2023
+ }
2024
+
2025
+ // src/filesClient.ts
2026
+ var CONTENT_TYPE_BY_EXT = {
2027
+ ".txt": "text/plain",
2028
+ ".md": "text/markdown",
2029
+ ".html": "text/html",
2030
+ ".htm": "text/html",
2031
+ ".json": "application/json",
2032
+ ".csv": "text/csv",
2033
+ ".pdf": "application/pdf",
2034
+ ".png": "image/png",
2035
+ ".jpg": "image/jpeg",
2036
+ ".jpeg": "image/jpeg",
2037
+ ".gif": "image/gif",
2038
+ ".svg": "image/svg+xml",
2039
+ ".zip": "application/zip",
2040
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2041
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2042
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2043
+ ".epub": "application/epub+zip",
2044
+ ".mp3": "audio/mpeg",
2045
+ ".mp4": "video/mp4",
2046
+ ".wav": "audio/wav"
2047
+ };
2048
+ var FilesClient = class extends KaguraRestClient {
2049
+ uploadTimeoutMs;
2050
+ constructor(options = {}) {
2051
+ super(options);
2052
+ this.uploadTimeoutMs = options.uploadTimeoutMs ?? 3e5;
2053
+ }
2054
+ // -------------------------------------------------------------------
2055
+ // Public API
2056
+ // -------------------------------------------------------------------
2057
+ /**
2058
+ * Upload a file to Kagura Memory Cloud, driving reserve → presigned PUT
2059
+ * → confirm. Returns the finalized {@link FileObject}.
2060
+ *
2061
+ * When the file already exists with the same sha256 in the workspace,
2062
+ * the server returns 409 and this surfaces the existing FileObject
2063
+ * (dedup happy-path) rather than throwing.
2064
+ *
2065
+ * @throws Error if `source` is bytes and `filename` is not provided.
2066
+ * @throws KaguraIntegrityError if R2 rejected the body sha256 binding.
2067
+ */
2068
+ async upload(options) {
2069
+ validateContextId(options.contextId);
2070
+ const { filename, body, sha256Hex, sha256Base64 } = await prepareSource(
2071
+ options.source,
2072
+ options.filename
2073
+ );
2074
+ const sizeBytes = body.byteLength;
2075
+ const contentType = resolveContentType(options.contentType, filename);
2076
+ const reserveBody = {
2077
+ workspace_id: options.contextId,
2078
+ filename,
2079
+ content_type: contentType,
2080
+ size_bytes: sizeBytes,
2081
+ sha256: sha256Hex
2082
+ };
2083
+ if (options.bindingContextId !== void 0) {
2084
+ reserveBody.context_id = options.bindingContextId;
2085
+ }
2086
+ let reserveResp;
2087
+ try {
2088
+ reserveResp = await this.request("POST", "/api/v1/files/reserve", { json: reserveBody });
2089
+ } catch (e) {
2090
+ const existing = extractExistingFile(e);
2091
+ if (existing !== null) {
2092
+ return existing;
2093
+ }
2094
+ throw e;
2095
+ }
2096
+ const reserve = this.json(reserveResp);
2097
+ await this.putToObjectStore(reserve.upload_url, body, sha256Base64, contentType);
2098
+ const confirmResp = await this.request("POST", `/api/v1/files/${reserve.file_id}/confirm`, {
2099
+ params: { workspace_id: options.contextId },
2100
+ json: { sha256: sha256Hex }
2101
+ });
2102
+ return this.json(confirmResp);
2103
+ }
2104
+ /** Return a short-lived presigned GET URL for `fileId`. */
2105
+ async downloadUrl(fileId, options) {
2106
+ validateContextId(options.contextId);
2107
+ const response = await this.request("GET", `/api/v1/files/${fileId}/download-url`, {
2108
+ params: { workspace_id: options.contextId }
2109
+ });
2110
+ return this.json(response).download_url;
2111
+ }
2112
+ /** Soft-delete a file by id (server hard-deletes after retention). */
2113
+ async delete(fileId, options) {
2114
+ validateContextId(options.contextId);
2115
+ await this.request("DELETE", `/api/v1/files/${fileId}`, {
2116
+ params: { workspace_id: options.contextId }
2117
+ });
2118
+ }
2119
+ /** List uploaded files in a workspace, newest first. */
2120
+ async list(options) {
2121
+ validateContextId(options.contextId);
2122
+ const params = {
2123
+ workspace_id: options.contextId,
2124
+ limit: options.limit ?? 50
2125
+ };
2126
+ if (options.cursor !== void 0) {
2127
+ params.cursor = options.cursor;
2128
+ }
2129
+ const response = await this.request("GET", "/api/v1/files", { params });
2130
+ const raw = this.json(response);
2131
+ if (Array.isArray(raw)) {
2132
+ return { files: raw, next_cursor: null };
2133
+ }
2134
+ return raw;
2135
+ }
2136
+ // -------------------------------------------------------------------
2137
+ // R2 PUT (unauthenticated by design)
2138
+ // -------------------------------------------------------------------
2139
+ /**
2140
+ * PUT `body` to the presigned R2 URL with checksum binding. Sends
2141
+ * `x-amz-checksum-sha256` (base64 of the raw digest) only when the
2142
+ * presign signed it; a 400 from the store → {@link KaguraIntegrityError}.
2143
+ */
2144
+ async putToObjectStore(uploadUrl, body, sha256Base64, contentType) {
2145
+ const headers = {
2146
+ "content-type": contentType,
2147
+ "user-agent": `kagura-memory-sdk/${SDK_VERSION}`
2148
+ };
2149
+ if (presignSignsChecksum(uploadUrl)) {
2150
+ headers["x-amz-checksum-sha256"] = sha256Base64;
2151
+ }
2152
+ let response;
2153
+ try {
2154
+ response = await this.fetchImpl(uploadUrl, {
2155
+ method: "PUT",
2156
+ headers,
2157
+ body,
2158
+ signal: AbortSignal.timeout(this.uploadTimeoutMs)
2159
+ });
2160
+ } catch (e) {
2161
+ throw new KaguraConnectionError(`Object store PUT failed: ${excMessage(e)}`, { cause: e });
2162
+ }
2163
+ if (response.status === 400) {
2164
+ throw new KaguraIntegrityError(
2165
+ "Object store rejected upload with HTTP 400 \u2014 most commonly R2 BadDigest (body sha256 did not match the presigned PUT binding). Verify that the SDK is computing sha256 over the exact bytes being PUT."
2166
+ );
2167
+ }
2168
+ if (response.status < 200 || response.status >= 300) {
2169
+ throw new KaguraConnectionError(`Object store PUT failed: HTTP ${response.status}`);
2170
+ }
2171
+ }
2172
+ // -------------------------------------------------------------------
2173
+ // Hooks
2174
+ // -------------------------------------------------------------------
2175
+ /**
2176
+ * 403 → a workspace-mismatch hint (issue #115): surface the credential
2177
+ * source and requested workspace prefix without leaking the api_key.
2178
+ */
2179
+ error403(response, context) {
2180
+ return new KaguraConnectionError(
2181
+ formatWorkspace403Hint({
2182
+ authSource: this.authSource,
2183
+ sourceWorkspaceHint: this.workspaceIdHint,
2184
+ requestedWorkspace: extractRequestedWorkspace(context.requestJson, context.requestParams),
2185
+ serverDetail: extractDetail(response.text)
2186
+ })
2187
+ );
2188
+ }
2189
+ /** Stash the raw non-2xx body so the 409 dedup path can recover `existing_file`. */
2190
+ genericError(response) {
2191
+ const err = super.genericError(response);
2192
+ err.responseStatus = response.status;
2193
+ err.responseText = response.text;
2194
+ return err;
2195
+ }
2196
+ };
2197
+ function shortWorkspace(uuidStr) {
2198
+ if (!uuidStr) {
2199
+ return "<none>";
2200
+ }
2201
+ return `${uuidStr.slice(0, 8)}\u2026`;
2202
+ }
2203
+ function extractRequestedWorkspace(json, params) {
2204
+ if (json !== void 0) {
2205
+ const ws = json.workspace_id;
2206
+ if (typeof ws === "string") {
2207
+ return ws;
2208
+ }
2209
+ }
2210
+ if (params !== void 0) {
2211
+ const ws = params.workspace_id;
2212
+ if (typeof ws === "string") {
2213
+ return ws;
2214
+ }
2215
+ }
2216
+ return null;
2217
+ }
2218
+ function formatWorkspace403Hint(args) {
2219
+ const { authSource, sourceWorkspaceHint, requestedWorkspace, serverDetail } = args;
2220
+ if (authSource === null) {
2221
+ const safeDetail2 = sanitizeServerDetail(serverDetail);
2222
+ return safeDetail2 ? `HTTP 403: ${safeDetail2}` : "HTTP 403";
2223
+ }
2224
+ const sourceLabel = SOURCE_LABEL[authSource] ?? String(authSource);
2225
+ const heading = requestedWorkspace ? "HTTP 403 \u2014 workspace not accessible with current credentials." : "HTTP 403 \u2014 access denied with current credentials.";
2226
+ const lines = [
2227
+ heading,
2228
+ ` api_key source: ${sourceLabel} (workspace=${shortWorkspace(sourceWorkspaceHint)})`
2229
+ ];
2230
+ if (requestedWorkspace) {
2231
+ lines.push(` workspace requested: ${shortWorkspace(requestedWorkspace)}`);
2232
+ lines.push(" Hint: contextId may not match the workspace bound to your api_key.");
2233
+ }
2234
+ const safeDetail = sanitizeServerDetail(serverDetail);
2235
+ if (safeDetail) {
2236
+ lines.push(` server detail: ${safeDetail}`);
2237
+ }
2238
+ return lines.join("\n");
2239
+ }
2240
+ function extractExistingFile(error) {
2241
+ if (!(error instanceof KaguraConnectionError)) {
2242
+ return null;
2243
+ }
2244
+ const withResponse = error;
2245
+ if (withResponse.responseStatus !== 409 || withResponse.responseText === void 0) {
2246
+ return null;
2247
+ }
2248
+ let body;
2249
+ try {
2250
+ body = JSON.parse(withResponse.responseText);
2251
+ } catch {
2252
+ return null;
2253
+ }
2254
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
2255
+ return null;
2256
+ }
2257
+ const existing = body.existing_file;
2258
+ if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
2259
+ return null;
2260
+ }
2261
+ return existing;
2262
+ }
2263
+ function validateContextId(contextId) {
2264
+ if (!isUuid(contextId)) {
2265
+ throw new Error(
2266
+ `contextId must be a UUID; got ${JSON.stringify(contextId)}. Use the OAuth profile's workspace_id, a UUID from \`kagura context list\`, or run \`kagura auth login\` first.`
2267
+ );
2268
+ }
2269
+ }
2270
+ function presignSignsChecksum(uploadUrl) {
2271
+ let signed = "";
2272
+ try {
2273
+ signed = new URL(uploadUrl).searchParams.get("X-Amz-SignedHeaders") ?? "";
2274
+ } catch {
2275
+ return false;
2276
+ }
2277
+ return signed.toLowerCase().includes("x-amz-checksum-sha256");
2278
+ }
2279
+ function resolveContentType(contentType, filename) {
2280
+ if (contentType) {
2281
+ return contentType;
2282
+ }
2283
+ const ext = path4.extname(filename).toLowerCase();
2284
+ return CONTENT_TYPE_BY_EXT[ext] ?? "application/octet-stream";
2285
+ }
2286
+ async function prepareSource(source, filename) {
2287
+ let body;
2288
+ let resolvedFilename;
2289
+ if (typeof source === "string") {
2290
+ body = await readFile(source);
2291
+ resolvedFilename = filename ?? path4.basename(source);
2292
+ } else {
2293
+ if (!filename) {
2294
+ throw new Error(
2295
+ "filename is required when source is bytes (the server requires a non-empty filename)."
2296
+ );
2297
+ }
2298
+ body = source;
2299
+ resolvedFilename = filename;
2300
+ }
2301
+ const digest = createHash("sha256").update(body).digest();
2302
+ return {
2303
+ filename: resolvedFilename,
2304
+ body,
2305
+ sha256Hex: digest.toString("hex"),
2306
+ sha256Base64: digest.toString("base64")
2307
+ };
2308
+ }
2309
+
2310
+ // src/resourceClient.ts
2311
+ var SETUP_OAUTH_NOT_SUPPORTED_MSG = "setupResource() is not yet available in OAuth mode. To run it, switch to a credential source that outranks OAuth: set KAGURA_API_KEY (and KAGURA_MCP_URL too if your api_key is not for the default cloud server \u2014 the env branch uses KAGURA_MCP_URL or the default URL, not the OAuth profile's stored mcp_url) and retry, or remove the active OAuth profile (e.g. `kagura auth logout`, or `kagura auth logout --profile <name>` for named profiles selected via KAGURA_PROFILE) so .kagura.json is consulted. The CRUD/ingest endpoints continue to work in OAuth mode.";
2312
+ function serializeEvent(event) {
2313
+ const wire = {
2314
+ op: event.op,
2315
+ doc_id: event.docId
2316
+ };
2317
+ if (event.version !== void 0 && event.version !== null) {
2318
+ wire.version = event.version;
2319
+ }
2320
+ if (event.payload !== void 0 && event.payload !== null) {
2321
+ wire.payload = event.payload;
2322
+ }
2323
+ if (event.idempotencyKey !== void 0 && event.idempotencyKey !== null) {
2324
+ wire.idempotency_key = event.idempotencyKey;
2325
+ }
2326
+ wire.event_metadata = event.eventMetadata ?? {};
2327
+ if (event.importance !== void 0 && event.importance !== null) {
2328
+ wire.importance = event.importance;
2329
+ }
2330
+ return wire;
2331
+ }
2332
+ var ResourceClient = class extends KaguraRestClient {
2333
+ /**
2334
+ * Original MCP URL — `null` until {@link fromResolvedAuth} stamps it.
2335
+ * {@link setupResource} needs the ORIGINAL MCP URL, which the REST
2336
+ * `baseUrl` no longer carries.
2337
+ */
2338
+ mcpUrlValue = null;
2339
+ /** MCP URL captured by `fromMcpUrl` (null for bare construction). */
2340
+ get mcpUrl() {
2341
+ return this.mcpUrlValue;
2342
+ }
2343
+ /**
2344
+ * Construct from a pre-resolved auth, stamping the MCP URL.
2345
+ *
2346
+ * `setupResource()` needs the ORIGINAL MCP URL to build its MCP
2347
+ * session — the resolved auth always carries one, whether sourced from
2348
+ * the OAuth profile or the priority-4 config.
2349
+ */
2350
+ static fromResolvedAuth(resolved, options = {}) {
2351
+ const instance = super.fromResolvedAuth(resolved, options);
2352
+ instance.mcpUrlValue = resolved.mcpUrl.replace(/\/+$/, "");
2353
+ return instance;
2354
+ }
2355
+ // -------------------------------------------------------------------
2356
+ // Token CRUD (Bearer auth)
2357
+ // -------------------------------------------------------------------
2358
+ /**
2359
+ * Create a new resource token.
2360
+ *
2361
+ * @returns Created token including plaintext token (shown only once).
2362
+ */
2363
+ async createToken(options) {
2364
+ const body = { resource_id: options.resourceId };
2365
+ if (options.description !== void 0 && options.description !== null) {
2366
+ body.description = options.description;
2367
+ }
2368
+ body.quota_events_per_hour = options.quotaEventsPerHour ?? 1e3;
2369
+ const response = await this.request("POST", "/api/v1/resource-tokens", { json: body });
2370
+ return this.json(response);
2371
+ }
2372
+ /**
2373
+ * List resource tokens with optional filtering.
2374
+ *
2375
+ * @returns Paginated (`limit`/`offset`) list of resource tokens.
2376
+ */
2377
+ async listTokens(options = {}) {
2378
+ const params = {
2379
+ limit: options.limit ?? 50,
2380
+ offset: options.offset ?? 0
2381
+ };
2382
+ if (options.resourceId !== void 0 && options.resourceId !== null) {
2383
+ params.resource_id = options.resourceId;
2384
+ }
2385
+ const response = await this.request("GET", "/api/v1/resource-tokens", { params });
2386
+ return this.json(response);
2387
+ }
2388
+ /**
2389
+ * Update a resource token's metadata. Only fields that are set are
2390
+ * sent on the wire.
2391
+ *
2392
+ * @param tokenId Token database ID.
2393
+ * @returns Updated token metadata.
2394
+ */
2395
+ async updateToken(tokenId, options = {}) {
2396
+ const body = {};
2397
+ if (options.description !== void 0 && options.description !== null) {
2398
+ body.description = options.description;
2399
+ }
2400
+ if (options.quotaEventsPerHour !== void 0 && options.quotaEventsPerHour !== null) {
2401
+ body.quota_events_per_hour = options.quotaEventsPerHour;
2402
+ }
2403
+ const response = await this.request("PATCH", `/api/v1/resource-tokens/${tokenId}`, {
2404
+ json: body
2405
+ });
2406
+ return this.json(response);
2407
+ }
2408
+ /**
2409
+ * Revoke (soft-delete) a resource token.
2410
+ *
2411
+ * @param tokenId Token database ID.
2412
+ */
2413
+ async revokeToken(tokenId) {
2414
+ await this.request("DELETE", `/api/v1/resource-tokens/${tokenId}`);
2415
+ }
2416
+ // -------------------------------------------------------------------
2417
+ // Setup helper
2418
+ // -------------------------------------------------------------------
2419
+ /**
2420
+ * Atomically set up a resource for data ingestion (server v0.14+).
2421
+ *
2422
+ * Calls the server-side atomic `setup_resource` MCP tool which creates
2423
+ * Context + Resource entity + token in a single transaction. On
2424
+ * failure, no orphan Context rows are left on the server. Requires the
2425
+ * client to be created via `fromMcpUrl()`.
2426
+ *
2427
+ * @returns ResourceSetupResponse with plaintext token (shown only once).
2428
+ * @throws Error if the client was not created via `fromMcpUrl()`, or
2429
+ * was constructed via the OAuth resolution path (`setupResource`
2430
+ * currently requires a static apiKey — see
2431
+ * {@link SETUP_OAUTH_NOT_SUPPORTED_MSG}).
2432
+ * @throws KaguraAuthError if the Authorization header is missing or
2433
+ * malformed in the static path.
2434
+ *
2435
+ * Note: Idempotency for repeated calls with the same `resourceId` is
2436
+ * not guaranteed; server-side behavior may evolve. Avoid retrying
2437
+ * setup for an existing `resourceId` without first verifying state.
2438
+ */
2439
+ async setupResource(options) {
2440
+ if (!this.mcpUrlValue) {
2441
+ throw new Error(
2442
+ "setupResource() requires MCP URL. Create the client via ResourceClient.fromMcpUrl()."
2443
+ );
2444
+ }
2445
+ if (this.oauth !== null) {
2446
+ throw new Error(SETUP_OAUTH_NOT_SUPPORTED_MSG);
2447
+ }
2448
+ const auth = await this.auth.getAuthHeader();
2449
+ if (!auth.startsWith("Bearer ")) {
2450
+ throw new KaguraAuthError("Authorization header missing or invalid");
2451
+ }
2452
+ const apiKey = auth.slice(7);
2453
+ const mcp = new KaguraClient({
2454
+ apiKey,
2455
+ mcpUrl: this.mcpUrlValue,
2456
+ timeoutMs: this.timeoutMs,
2457
+ fetch: this.fetchImpl
2458
+ });
2459
+ try {
2460
+ const result = await mcp.setupResource({
2461
+ resourceId: options.resourceId,
2462
+ name: options.contextName,
2463
+ summary: options.summary,
2464
+ description: options.description,
2465
+ quotaEventsPerHour: options.quotaEventsPerHour ?? 1e3
2466
+ });
2467
+ return result;
2468
+ } finally {
2469
+ await mcp.close();
2470
+ }
2471
+ }
2472
+ // -------------------------------------------------------------------
2473
+ // Resource Stats (Bearer auth)
2474
+ // -------------------------------------------------------------------
2475
+ /**
2476
+ * Get impact statistics for a resource.
2477
+ *
2478
+ * @returns Resource impact stats (token_count, memory_count, schema version).
2479
+ */
2480
+ async getResourceImpact(resourceId) {
2481
+ const response = await this.request("GET", `/api/v1/resources/${resourceId}/impact`);
2482
+ return this.json(response);
2483
+ }
2484
+ /**
2485
+ * List all resources in the caller's workspace (server v0.14+).
2486
+ *
2487
+ * Returns workspace-scoped resources with aggregated stats
2488
+ * (token_count, memory_count, current_schema_version, ...). The
2489
+ * endpoint is currently non-paginated; the server caps a workspace at
2490
+ * well under 50 resources by design.
2491
+ *
2492
+ * Workspace owners only — non-owners receive 403.
2493
+ */
2494
+ async listResources() {
2495
+ const response = await this.request("GET", "/api/v1/resources");
2496
+ return this.json(response);
2497
+ }
2498
+ /**
2499
+ * Get indexer state and recent ingest events for a resource.
2500
+ *
2501
+ * `state` is `null` when the indexer has never run for this resource —
2502
+ * a normal 200 response, distinct from a 404. `recent_events` is
2503
+ * server-capped at 5.
2504
+ *
2505
+ * @throws KaguraNotFoundError Resource slug does not exist in the
2506
+ * caller's workspace (404; cross-workspace probe protection).
2507
+ */
2508
+ async getIndexerStatus(resourceId) {
2509
+ const response = await this.request("GET", `/api/v1/resources/${resourceId}/indexer-status`);
2510
+ return this.json(response);
2511
+ }
2512
+ /**
2513
+ * Get field definitions for a resource.
2514
+ *
2515
+ * @param schemaVersion Specific schema version to retrieve; omit for
2516
+ * the latest version.
2517
+ * @returns Resource schema with field definitions, or `null` if no
2518
+ * schema is registered for the resource.
2519
+ */
2520
+ async getResourceSchema(resourceId, schemaVersion) {
2521
+ const opts = {};
2522
+ if (schemaVersion !== void 0 && schemaVersion !== null) {
2523
+ opts.params = { schema_version: schemaVersion };
2524
+ }
2525
+ try {
2526
+ const response = await this.request("GET", `/api/v1/resources/${resourceId}/schema`, opts);
2527
+ return this.json(response);
2528
+ } catch (e) {
2529
+ if (e instanceof KaguraNotFoundError) {
2530
+ return null;
2531
+ }
2532
+ throw e;
2533
+ }
2534
+ }
2535
+ /**
2536
+ * List ingested events for a resource (server v0.15+).
2537
+ *
2538
+ * Mirrors `GET /api/v1/resources/{resource_id}/events`. Results are
2539
+ * cursor-paginated: pass the returned `next_cursor` back as `cursor`
2540
+ * to fetch the next page (`next_cursor` is `null` on the last page).
2541
+ * Note this method uses `limit`/`cursor` pagination, unlike
2542
+ * {@link listTokens} which uses `limit`/`offset`.
2543
+ *
2544
+ * Uses Bearer auth (workspace read), not the `X-Resource-API-Key`
2545
+ * ingestion credential. An unknown `resourceId` returns an empty page
2546
+ * (`events=[]`, `next_cursor=null`) rather than a 404 — observed
2547
+ * against memory-cloud production.
2548
+ *
2549
+ * @throws KaguraNotFoundError The server returned 404 for this
2550
+ * resource (cross-workspace probe protection); applies only if the
2551
+ * server does respond with 404.
2552
+ */
2553
+ async listResourceEvents(resourceId, options = {}) {
2554
+ const params = { limit: options.limit ?? 50 };
2555
+ if (options.cursor !== void 0 && options.cursor !== null) {
2556
+ params.cursor = options.cursor;
2557
+ }
2558
+ if (options.op !== void 0 && options.op !== null) {
2559
+ params.op = options.op;
2560
+ }
2561
+ if (options.docId !== void 0 && options.docId !== null) {
2562
+ params.doc_id = options.docId;
2563
+ }
2564
+ if (options.version !== void 0 && options.version !== null) {
2565
+ params.version = options.version;
2566
+ }
2567
+ if (options.since !== void 0 && options.since !== null) {
2568
+ params.since = options.since instanceof Date ? options.since.toISOString() : options.since;
2569
+ }
2570
+ const response = await this.request("GET", `/api/v1/resources/${resourceId}/events`, {
2571
+ params
2572
+ });
2573
+ return this.json(response);
2574
+ }
2575
+ // -------------------------------------------------------------------
2576
+ // Event Ingestion (X-Resource-API-Key auth)
2577
+ // -------------------------------------------------------------------
2578
+ /**
2579
+ * Ingest a single resource event.
2580
+ *
2581
+ * @param resourceApiKey Resource API key (`X-Resource-API-Key`
2582
+ * header) — sent per-call, never stored on the client.
2583
+ * @returns Ingestion result with `event_id`.
2584
+ */
2585
+ async ingestEvent(resourceId, resourceApiKey, event) {
2586
+ const response = await this.request("POST", `/api/v1/resources/${resourceId}/events`, {
2587
+ json: serializeEvent(event),
2588
+ extraHeaders: { "X-Resource-API-Key": resourceApiKey }
2589
+ });
2590
+ return this.json(response);
2591
+ }
2592
+ /**
2593
+ * Ingest a batch of resource events (1-100; the server validates the
2594
+ * bound).
2595
+ *
2596
+ * @param resourceApiKey Resource API key (`X-Resource-API-Key`
2597
+ * header) — sent per-call, never stored on the client.
2598
+ * @returns Batch ingestion result with created/failed counts.
2599
+ */
2600
+ async ingestEvents(resourceId, resourceApiKey, events) {
2601
+ const response = await this.request("POST", `/api/v1/resources/${resourceId}/events/batch`, {
2602
+ json: { events: events.map(serializeEvent) },
2603
+ extraHeaders: { "X-Resource-API-Key": resourceApiKey }
2604
+ });
2605
+ return this.json(response);
2606
+ }
2607
+ };
2608
+
2609
+ // src/workspaceClient.ts
2610
+ var VALID_ASSIGNABLE_ROLES = ["member", "admin", "viewer"];
2611
+ var VALID_INVITE_EXPIRES = [7, 30, 90, 365];
2612
+ var UNIFORM_403 = "Insufficient permissions";
2613
+ var UUID_HEX_RE = /^[0-9a-f]{32}$/i;
2614
+ function normalizeWorkspaceId(workspaceId) {
2615
+ const stripped = String(workspaceId).replace(/^urn:/, "").replace(/^uuid:/, "").replace(/^[{}]+|[{}]+$/g, "").replace(/-/g, "");
2616
+ if (!UUID_HEX_RE.test(stripped)) {
2617
+ throw new Error(`workspaceId must be a UUID, got ${JSON.stringify(workspaceId)}`);
2618
+ }
2619
+ const hex = stripped.toLowerCase();
2620
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2621
+ }
2622
+ function requireInt(value, label) {
2623
+ if (typeof value !== "number" || !Number.isInteger(value)) {
2624
+ throw new Error(`${label} must be an integer, got ${JSON.stringify(value)}`);
2625
+ }
2626
+ return value;
2627
+ }
2628
+ var WorkspaceClient = class extends KaguraRestClient {
2629
+ // -------------------------------------------------------------------
2630
+ // Members
2631
+ // -------------------------------------------------------------------
2632
+ /**
2633
+ * List workspace members (owner key required).
2634
+ *
2635
+ * Rows are ordered owner→viewer then by join date and include
2636
+ * `user_name`/`user_email` when the member has logged in.
2637
+ */
2638
+ async listMembers(workspaceId) {
2639
+ const ws = normalizeWorkspaceId(workspaceId);
2640
+ const resp = await this.request("GET", `/api/v1/workspaces/${ws}/members`);
2641
+ return this.expectList(resp);
2642
+ }
2643
+ /**
2644
+ * Add an already-registered user to the workspace.
2645
+ *
2646
+ * The server does NOT validate that `userId` exists (v0.42.0) — a typo
2647
+ * creates a dangling membership row that lists with null name/email.
2648
+ * Prefer {@link createInvitation} for onboarding; use this only with a
2649
+ * user_id copied from a trusted source. Duplicate members are rejected
2650
+ * with 422.
2651
+ */
2652
+ async addMember(workspaceId, userId, role = "member") {
2653
+ const ws = normalizeWorkspaceId(workspaceId);
2654
+ this.validateRole(role);
2655
+ const resp = await this.request("POST", `/api/v1/workspaces/${ws}/members`, {
2656
+ json: { user_id: userId, role }
2657
+ });
2658
+ return this.json(resp);
2659
+ }
2660
+ /** Change a member's role (member/admin/viewer only). */
2661
+ async updateMemberRole(workspaceId, userId, role) {
2662
+ const ws = normalizeWorkspaceId(workspaceId);
2663
+ this.validateRole(role);
2664
+ const resp = await this.request(
2665
+ "PUT",
2666
+ `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}`,
2667
+ { json: { role } }
2668
+ );
2669
+ return this.json(resp);
2670
+ }
2671
+ /** Remove a member from the workspace (server returns 204). */
2672
+ async removeMember(workspaceId, userId) {
2673
+ const ws = normalizeWorkspaceId(workspaceId);
2674
+ await this.request("DELETE", `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}`);
2675
+ }
2676
+ // -------------------------------------------------------------------
2677
+ // Invitations
2678
+ // -------------------------------------------------------------------
2679
+ /**
2680
+ * Invite a not-yet-registered user by email.
2681
+ *
2682
+ * The returned invitation carries `token`/`invitation_url` — the only
2683
+ * response that ever exposes them to programmatic callers; treat them
2684
+ * as join credentials.
2685
+ *
2686
+ * @param workspaceId Target workspace UUID.
2687
+ * @param email Invitee email (must match their Google account).
2688
+ * @param options Role, context grant, and expiry preset.
2689
+ */
2690
+ async createInvitation(workspaceId, email, options = {}) {
2691
+ const ws = normalizeWorkspaceId(workspaceId);
2692
+ const role = options.role ?? "member";
2693
+ this.validateRole(role);
2694
+ const { allowedContextIds, expiresInDays } = options;
2695
+ if ((role === "member" || role === "viewer") && (allowedContextIds === void 0 || allowedContextIds.length === 0)) {
2696
+ throw new Error(
2697
+ "allowedContextIds is required (min 1) for member/viewer invitations \u2014 the server rejects them without a context grant."
2698
+ );
2699
+ }
2700
+ if (expiresInDays !== void 0 && !VALID_INVITE_EXPIRES.includes(expiresInDays)) {
2701
+ throw new Error(
2702
+ `expiresInDays must be one of ${VALID_INVITE_EXPIRES.join(", ")} or omitted (server-side preset list).`
2703
+ );
2704
+ }
2705
+ const body = { email, role };
2706
+ if (allowedContextIds !== void 0) {
2707
+ body.allowed_context_ids = allowedContextIds;
2708
+ }
2709
+ if (expiresInDays !== void 0) {
2710
+ body.expires_in_days = expiresInDays;
2711
+ }
2712
+ const resp = await this.request("POST", `/api/v1/workspaces/${ws}/invitations`, {
2713
+ json: body
2714
+ });
2715
+ return this.json(resp);
2716
+ }
2717
+ /**
2718
+ * List invitations. `token`/`invitation_url` arrive as null for
2719
+ * programmatic callers (server-side token hygiene, #1164).
2720
+ */
2721
+ async listInvitations(workspaceId, options = {}) {
2722
+ const ws = normalizeWorkspaceId(workspaceId);
2723
+ const resp = await this.request(
2724
+ "GET",
2725
+ `/api/v1/workspaces/${ws}/invitations`,
2726
+ options.includeAccepted ? { params: { include_accepted: "true" } } : {}
2727
+ );
2728
+ return this.expectList(resp);
2729
+ }
2730
+ /** Revoke a pending invitation (server returns 200 `{"success": true}`). */
2731
+ async revokeInvitation(workspaceId, invitationId) {
2732
+ const ws = normalizeWorkspaceId(workspaceId);
2733
+ await this.request(
2734
+ "DELETE",
2735
+ `/api/v1/workspaces/${ws}/invitations/${requireInt(invitationId, "invitationId")}`
2736
+ );
2737
+ }
2738
+ // -------------------------------------------------------------------
2739
+ // Member API keys (#201, memory-cloud#1165)
2740
+ // -------------------------------------------------------------------
2741
+ /**
2742
+ * Mint an API key for ANOTHER member (owner key required).
2743
+ *
2744
+ * Privilege-downgrade provisioning only: the server 403s self-targets
2745
+ * ("An owner key cannot mint keys for itself") and owner/admin targets
2746
+ * — mint for member/viewer service identities. `expiresDays` is
2747
+ * required by the server for owner-provisioned mints (never-expiring
2748
+ * CI keys are not allowed). The returned `plaintext_key` is shown
2749
+ * exactly once — owner-provisioned keys are force-hidden at creation,
2750
+ * so no later call returns it.
2751
+ */
2752
+ async mintMemberKey(workspaceId, userId, name, expiresDays) {
2753
+ const ws = normalizeWorkspaceId(workspaceId);
2754
+ const days = requireInt(expiresDays, "expiresDays");
2755
+ if (days < 1 || days > 3650) {
2756
+ throw new Error(`expiresDays must be 1-3650, got ${JSON.stringify(days)}`);
2757
+ }
2758
+ const resp = await this.request(
2759
+ "POST",
2760
+ `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials/api-keys`,
2761
+ { json: { name, expires_days: days } }
2762
+ );
2763
+ const payload = this.json(resp);
2764
+ if (isMintShape(payload)) {
2765
+ return payload;
2766
+ }
2767
+ const plaintext = typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload.plaintext_key : void 0;
2768
+ if (typeof plaintext === "string" && plaintext) {
2769
+ throw new KaguraError(
2770
+ `Server returned an unexpected mint response shape, but the key WAS created. Save the plaintext now: ${plaintext}`
2771
+ );
2772
+ }
2773
+ throw new KaguraError(
2774
+ "Server returned an unexpected mint response shape; the key may have been created without displaying its plaintext \u2014 check `kagura auth list-keys` and revoke/re-mint if present."
2775
+ );
2776
+ }
2777
+ /**
2778
+ * List a member's API keys — metadata only.
2779
+ *
2780
+ * The server wraps the rows in a `MemberCredentialsResponse` envelope
2781
+ * (`api_keys` + `target_user_role`) and always nulls `plaintext_key`
2782
+ * for programmatic callers.
2783
+ */
2784
+ async listMemberKeys(workspaceId, userId) {
2785
+ const ws = normalizeWorkspaceId(workspaceId);
2786
+ const resp = await this.request(
2787
+ "GET",
2788
+ `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials`
2789
+ );
2790
+ const payload = this.json(resp);
2791
+ const rows = typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload.api_keys : void 0;
2792
+ if (!Array.isArray(rows)) {
2793
+ throw new KaguraConnectionError(
2794
+ "Unexpected response shape from the member-credentials endpoint (expected an object carrying an 'api_keys' array)."
2795
+ );
2796
+ }
2797
+ return rows;
2798
+ }
2799
+ /**
2800
+ * Revoke a member's API key.
2801
+ *
2802
+ * Owner-provisioned revocations are SOFT server-side (`revoked_at`
2803
+ * set, row retained for forensics); success is 200 with a status body,
2804
+ * and an already-revoked key surfaces as a uniform 404.
2805
+ */
2806
+ async revokeMemberKey(workspaceId, userId, keyId) {
2807
+ const ws = normalizeWorkspaceId(workspaceId);
2808
+ await this.request(
2809
+ "DELETE",
2810
+ `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials/api-keys/${requireInt(keyId, "keyId")}`
2811
+ );
2812
+ }
2813
+ // -------------------------------------------------------------------
2814
+ // Internal helpers
2815
+ // -------------------------------------------------------------------
2816
+ validateRole(role) {
2817
+ if (!VALID_ASSIGNABLE_ROLES.includes(role)) {
2818
+ throw new Error(
2819
+ `role must be one of ${VALID_ASSIGNABLE_ROLES.join(", ")}, got ${JSON.stringify(role)}. Assigning 'owner' is not supported programmatically \u2014 the server directs owner changes to the ownership transfer flow.`
2820
+ );
2821
+ }
2822
+ }
2823
+ /**
2824
+ * Build the 403 message, appending the owner-key hint only when useful.
2825
+ *
2826
+ * v0.42.0 sends purpose-built 403 messages on this surface (OAuth
2827
+ * rejection, deployment kill-switch, plan gate, self-role-change,
2828
+ * key/workspace mismatch) — those pass through untouched. Only the
2829
+ * deliberately uniform denial gets the owner-key hint, because that is
2830
+ * the one a non-owner static key actually hits.
2831
+ */
2832
+ format403(serverDetail) {
2833
+ const safeDetail = sanitizeServerDetail(serverDetail);
2834
+ if (safeDetail && safeDetail !== UNIFORM_403) {
2835
+ return safeDetail;
2836
+ }
2837
+ const parts = [
2838
+ "Access denied (HTTP 403): workspace member/invitation/credential management requires the workspace OWNER's API key when called programmatically (OAuth tokens are not accepted)."
2839
+ ];
2840
+ if (this.authSource !== null) {
2841
+ let hint = `credential source: ${SOURCE_LABEL[this.authSource]}`;
2842
+ if (this.workspaceIdHint) {
2843
+ hint += ` (workspace=${this.workspaceIdHint.slice(0, 8)}\u2026)`;
2844
+ }
2845
+ parts.push(hint + " \u2014 is this key the workspace owner's?");
2846
+ }
2847
+ return parts.join(" ");
2848
+ }
2849
+ // ---- KaguraRestClient hooks -----------------------------------------
2850
+ error403(response, _context) {
2851
+ return new KaguraConnectionError(this.format403(extractDetail(response.text)));
2852
+ }
2853
+ error429(response) {
2854
+ return new KaguraQuotaError(
2855
+ extractDetail(response.text) || "Quota exceeded. Try again later.",
2856
+ retryAfterSeconds(response.headers)
2857
+ );
2858
+ }
2859
+ };
2860
+ function isMintShape(payload) {
2861
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
2862
+ return false;
2863
+ }
2864
+ const rec = payload;
2865
+ return typeof rec.id === "number" && typeof rec.name === "string" && typeof rec.key_prefix === "string";
2866
+ }
2867
+ export {
2868
+ DEFAULT_MCP_URL,
2869
+ DEFAULT_REST_BASE_URL,
2870
+ FilesClient,
2871
+ KaguraAuthDeniedError,
2872
+ KaguraAuthError,
2873
+ KaguraAuthExpiredError,
2874
+ KaguraClient,
2875
+ KaguraConnectionError,
2876
+ KaguraContextError,
2877
+ KaguraError,
2878
+ KaguraFetchError,
2879
+ KaguraIngestError,
2880
+ KaguraIntegrityError,
2881
+ KaguraLLMError,
2882
+ KaguraNotFoundError,
2883
+ KaguraQuotaError,
2884
+ KaguraRateLimitError,
2885
+ KaguraRestClient,
2886
+ MIN_SERVER_VERSION,
2887
+ ResourceClient,
2888
+ SDK_VERSION,
2889
+ SETUP_OAUTH_NOT_SUPPORTED_MSG,
2890
+ VALID_ASSIGNABLE_ROLES,
2891
+ VALID_INVITE_EXPIRES,
2892
+ WorkspaceClient,
2893
+ loadConfig,
2894
+ resolveAuth
2895
+ };
2896
+ //# sourceMappingURL=index.js.map