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