kagura-memory 0.2.0 → 0.5.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 -21
- package/README.md +392 -162
- package/dist/cli.js +1294 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +426 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +595 -82
- package/dist/index.d.ts +595 -82
- package/dist/index.js +399 -12
- package/dist/index.js.map +1 -1
- package/package.json +66 -63
package/dist/index.js
CHANGED
|
@@ -137,7 +137,7 @@ import * as path3 from "path";
|
|
|
137
137
|
import { setTimeout as sleepMs } from "timers/promises";
|
|
138
138
|
|
|
139
139
|
// src/version.ts
|
|
140
|
-
var SDK_VERSION = "0.
|
|
140
|
+
var SDK_VERSION = "0.5.0";
|
|
141
141
|
|
|
142
142
|
// src/http.ts
|
|
143
143
|
function baseUrlFromMcp(mcpUrl) {
|
|
@@ -229,17 +229,24 @@ function throwForKaguraStatus(status, headers, bodyText, fallbackMessage) {
|
|
|
229
229
|
}
|
|
230
230
|
throw new KaguraConnectionError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`);
|
|
231
231
|
}
|
|
232
|
-
var
|
|
232
|
+
var PLAIN_HTTP_RE = /^http:\/\//i;
|
|
233
|
+
var LOCALHOST_HTTP_RE = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/i;
|
|
233
234
|
function validateHttpsUrl(url, label = "URL") {
|
|
234
|
-
|
|
235
|
+
const candidate = url.trim();
|
|
236
|
+
if (PLAIN_HTTP_RE.test(candidate) && !LOCALHOST_HTTP_RE.test(candidate)) {
|
|
235
237
|
throw new Error(
|
|
236
|
-
`${label} must use HTTPS for security (got: ${
|
|
238
|
+
`${label} must use HTTPS for security (got: ${candidate}). HTTP is only allowed for localhost development.`
|
|
237
239
|
);
|
|
238
240
|
}
|
|
239
241
|
}
|
|
240
242
|
|
|
241
243
|
// src/auth/deviceFlow.ts
|
|
244
|
+
var PATH_DEVICE_AUTHORIZE = "/api/v1/oauth/device/authorize";
|
|
242
245
|
var PATH_TOKEN = "/api/v1/oauth/token/";
|
|
246
|
+
var PATH_REVOKE = "/api/v1/oauth/revoke";
|
|
247
|
+
var SLOW_DOWN_INCREMENT_SEC = 5;
|
|
248
|
+
var DEFAULT_CLIENT_ID = "kagura-cli";
|
|
249
|
+
var DEVICE_FLOW_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
243
250
|
var REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
|
|
244
251
|
function userAgent() {
|
|
245
252
|
return `kagura-memory-sdk/${SDK_VERSION}`;
|
|
@@ -310,6 +317,126 @@ function tokenResponseFromBody(bodyText, status) {
|
|
|
310
317
|
workspaceName: stringOr(body.workspace_name, "")
|
|
311
318
|
};
|
|
312
319
|
}
|
|
320
|
+
async function authorizeDevice(server, options = {}) {
|
|
321
|
+
const clientId = options.clientId ?? DEFAULT_CLIENT_ID;
|
|
322
|
+
const scope = options.scope ?? "memory:read";
|
|
323
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
324
|
+
const url = `${server.replace(/\/+$/, "")}${PATH_DEVICE_AUTHORIZE}`;
|
|
325
|
+
let response;
|
|
326
|
+
let text;
|
|
327
|
+
try {
|
|
328
|
+
response = await doFetch(url, {
|
|
329
|
+
method: "POST",
|
|
330
|
+
headers: {
|
|
331
|
+
"User-Agent": userAgent(),
|
|
332
|
+
"Content-Type": "application/json"
|
|
333
|
+
},
|
|
334
|
+
body: JSON.stringify({ client_id: clientId, scope })
|
|
335
|
+
});
|
|
336
|
+
text = await response.text();
|
|
337
|
+
} catch (e) {
|
|
338
|
+
throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });
|
|
339
|
+
}
|
|
340
|
+
if (!response.ok) {
|
|
341
|
+
const detail = extractDetail(text) || text;
|
|
342
|
+
throw new KaguraAuthError(
|
|
343
|
+
`Device authorization failed (HTTP ${response.status}): ${detail}
|
|
344
|
+
Verify the server URL and that '${clientId}' is registered.`
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
const body = safeJsonObject(text, response.status, "Device authorization");
|
|
348
|
+
const deviceCode = body.device_code;
|
|
349
|
+
const userCode = body.user_code;
|
|
350
|
+
const verificationUri = body.verification_uri;
|
|
351
|
+
const expiresIn = toInt(body.expires_in);
|
|
352
|
+
if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof verificationUri !== "string" || expiresIn === null) {
|
|
353
|
+
throw new KaguraAuthError(
|
|
354
|
+
`Device authorization returned HTTP 200 but body is missing required fields. Body keys: ${Object.keys(body).sort().join(", ")}`
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
deviceCode,
|
|
359
|
+
userCode,
|
|
360
|
+
verificationUri,
|
|
361
|
+
verificationUriComplete: stringOr(body.verification_uri_complete, verificationUri),
|
|
362
|
+
expiresIn,
|
|
363
|
+
interval: toInt(body.interval) ?? 5,
|
|
364
|
+
expiresAt: new Date(Date.now() + expiresIn * 1e3)
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async function pollForToken(server, options) {
|
|
368
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
369
|
+
const sleep2 = options.sleep ?? (async (ms) => void await sleepMs(ms));
|
|
370
|
+
const url = tokenUrl(server);
|
|
371
|
+
let currentInterval = options.interval;
|
|
372
|
+
let firstPoll = true;
|
|
373
|
+
for (; ; ) {
|
|
374
|
+
if (Date.now() >= options.expiresAt.getTime()) {
|
|
375
|
+
throw new KaguraAuthExpiredError(
|
|
376
|
+
"Device code expired before user approval. Run: kagura auth login",
|
|
377
|
+
options.expiresAt
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
if (firstPoll) {
|
|
381
|
+
firstPoll = false;
|
|
382
|
+
} else {
|
|
383
|
+
await sleep2(currentInterval * 1e3);
|
|
384
|
+
}
|
|
385
|
+
let response;
|
|
386
|
+
let text;
|
|
387
|
+
try {
|
|
388
|
+
response = await doFetch(url, {
|
|
389
|
+
method: "POST",
|
|
390
|
+
headers: { "User-Agent": userAgent() },
|
|
391
|
+
body: new URLSearchParams({
|
|
392
|
+
grant_type: DEVICE_FLOW_GRANT_TYPE,
|
|
393
|
+
device_code: options.deviceCode,
|
|
394
|
+
client_id: options.clientId
|
|
395
|
+
})
|
|
396
|
+
});
|
|
397
|
+
text = await response.text();
|
|
398
|
+
} catch (e) {
|
|
399
|
+
throw new KaguraConnectionError(
|
|
400
|
+
`Lost connection while waiting for approval: ${excMessage(e)}
|
|
401
|
+
The login session may still be valid; re-run: kagura auth login`,
|
|
402
|
+
{ cause: e }
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
if (response.status === 200) {
|
|
406
|
+
return tokenResponseFromBody(text, response.status);
|
|
407
|
+
}
|
|
408
|
+
const body = safeJson(text);
|
|
409
|
+
const error = stringOr(body.error, "");
|
|
410
|
+
if (error === "authorization_pending") {
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (error === "slow_down") {
|
|
414
|
+
currentInterval += SLOW_DOWN_INCREMENT_SEC;
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (error === "access_denied") {
|
|
418
|
+
throw new KaguraAuthDeniedError(
|
|
419
|
+
"Authorization denied at the consent screen.\n Re-run: kagura auth login\n To use a different workspace, log in with that account in your browser first."
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
if (error === "expired_token") {
|
|
423
|
+
throw new KaguraAuthExpiredError(
|
|
424
|
+
"Device code expired before user approval. Run: kagura auth login",
|
|
425
|
+
options.expiresAt
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
const description = stringOr(body.error_description, "");
|
|
429
|
+
if (error || description) {
|
|
430
|
+
throw new KaguraAuthError(
|
|
431
|
+
`Token endpoint returned unexpected error '${error}': ${description}`
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
const detail = extractDetail(text) || text.slice(0, 200);
|
|
435
|
+
throw new KaguraAuthError(
|
|
436
|
+
`Token endpoint returned HTTP ${response.status} with no OAuth error code. Body: ${detail}`
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
313
440
|
async function refreshAccessToken(server, options) {
|
|
314
441
|
const doFetch = options.fetch ?? globalThis.fetch;
|
|
315
442
|
const url = tokenUrl(server);
|
|
@@ -354,6 +481,23 @@ async function refreshAccessToken(server, options) {
|
|
|
354
481
|
`Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`
|
|
355
482
|
);
|
|
356
483
|
}
|
|
484
|
+
async function revokeToken(server, options) {
|
|
485
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
486
|
+
const url = `${server.replace(/\/+$/, "")}${PATH_REVOKE}`;
|
|
487
|
+
try {
|
|
488
|
+
const response = await doFetch(url, {
|
|
489
|
+
method: "POST",
|
|
490
|
+
headers: { "User-Agent": userAgent() },
|
|
491
|
+
body: new URLSearchParams({
|
|
492
|
+
token: options.token,
|
|
493
|
+
client_id: options.clientId ?? DEFAULT_CLIENT_ID
|
|
494
|
+
})
|
|
495
|
+
});
|
|
496
|
+
return response.status === 200 || response.status === 204;
|
|
497
|
+
} catch {
|
|
498
|
+
return false;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
357
501
|
|
|
358
502
|
// src/auth/filelock.ts
|
|
359
503
|
import * as fs2 from "fs";
|
|
@@ -534,6 +678,13 @@ function setProfile(cf, name, creds) {
|
|
|
534
678
|
cf.defaultProfile = name;
|
|
535
679
|
}
|
|
536
680
|
}
|
|
681
|
+
function removeProfile(cf, name) {
|
|
682
|
+
delete cf.profiles[name];
|
|
683
|
+
const next = Object.keys(cf.profiles)[0];
|
|
684
|
+
if (cf.defaultProfile === name && next !== void 0) {
|
|
685
|
+
cf.defaultProfile = next;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
537
688
|
function credentialsFileToDict(cf) {
|
|
538
689
|
const profiles = {};
|
|
539
690
|
for (const [name, creds] of Object.entries(cf.profiles)) {
|
|
@@ -646,6 +797,39 @@ function loadCredentialsFile(credentialsPath) {
|
|
|
646
797
|
function saveCredentialsFile(cf, credentialsPath) {
|
|
647
798
|
atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);
|
|
648
799
|
}
|
|
800
|
+
async function updateProfile(profileName, creds, credentialsPath) {
|
|
801
|
+
const p = resolvePath(credentialsPath);
|
|
802
|
+
await withFileLock(p, () => {
|
|
803
|
+
const cf = loadCredentialsFile(p);
|
|
804
|
+
setProfile(cf, profileName, creds);
|
|
805
|
+
saveCredentialsFile(cf, p);
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
async function setDefaultProfile(profileName, credentialsPath) {
|
|
809
|
+
const p = resolvePath(credentialsPath);
|
|
810
|
+
await withFileLock(p, () => {
|
|
811
|
+
const cf = loadCredentialsFile(p);
|
|
812
|
+
if (!(profileName in cf.profiles)) {
|
|
813
|
+
throw new Error(`profile '${profileName}' not found in credentials file`);
|
|
814
|
+
}
|
|
815
|
+
cf.defaultProfile = profileName;
|
|
816
|
+
saveCredentialsFile(cf, p);
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
async function deleteProfile(profileName, credentialsPath) {
|
|
820
|
+
const p = resolvePath(credentialsPath);
|
|
821
|
+
await withFileLock(p, () => {
|
|
822
|
+
const cf = loadCredentialsFile(p);
|
|
823
|
+
if (!(profileName in cf.profiles)) {
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
removeProfile(cf, profileName);
|
|
827
|
+
saveCredentialsFile(cf, p);
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
function deleteCredentialsFile(credentialsPath) {
|
|
831
|
+
fs3.rmSync(resolvePath(credentialsPath), { force: true });
|
|
832
|
+
}
|
|
649
833
|
var AsyncMutex = class {
|
|
650
834
|
tail = Promise.resolve();
|
|
651
835
|
runExclusive(fn) {
|
|
@@ -726,9 +910,11 @@ var KaguraOAuth = class {
|
|
|
726
910
|
* Cross-process dedup is handled in `refreshLocked` via the
|
|
727
911
|
* rejected-token identity check.
|
|
728
912
|
*/
|
|
729
|
-
async forceRefresh() {
|
|
913
|
+
async forceRefresh(options = {}) {
|
|
730
914
|
const rejectedToken = this.state.credentials.accessToken;
|
|
731
|
-
await this.state.mutex.runExclusive(
|
|
915
|
+
await this.state.mutex.runExclusive(
|
|
916
|
+
() => this.refreshLocked(rejectedToken, options.scope)
|
|
917
|
+
);
|
|
732
918
|
}
|
|
733
919
|
/**
|
|
734
920
|
* Refresh `/oauth/token/` once across all processes. Caller holds the
|
|
@@ -745,17 +931,17 @@ var KaguraOAuth = class {
|
|
|
745
931
|
* on-disk token *differs* from the rejected one (a 401 is independent of
|
|
746
932
|
* `expiresAt`).
|
|
747
933
|
*/
|
|
748
|
-
async refreshLocked(expectedStaleToken) {
|
|
934
|
+
async refreshLocked(expectedStaleToken, scope) {
|
|
749
935
|
const credPath = this.state.path;
|
|
750
936
|
const profileName = this.state.profileName;
|
|
751
937
|
await withFileLock(credPath, async () => {
|
|
752
938
|
const disk = getProfile(loadCredentialsFile(credPath), profileName);
|
|
753
|
-
if (disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {
|
|
939
|
+
if (scope === void 0 && disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {
|
|
754
940
|
this.state.credentials = disk;
|
|
755
941
|
return;
|
|
756
942
|
}
|
|
757
943
|
const base = disk ?? this.state.credentials;
|
|
758
|
-
await this.networkRefreshAndSave(base, credPath, profileName);
|
|
944
|
+
await this.networkRefreshAndSave(base, credPath, profileName, scope);
|
|
759
945
|
});
|
|
760
946
|
}
|
|
761
947
|
/** Whether `disk` shows another process already produced a usable token. */
|
|
@@ -766,17 +952,27 @@ var KaguraOAuth = class {
|
|
|
766
952
|
return disk.accessToken !== expectedStaleToken;
|
|
767
953
|
}
|
|
768
954
|
/** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */
|
|
769
|
-
async networkRefreshAndSave(base, credPath, profileName) {
|
|
955
|
+
async networkRefreshAndSave(base, credPath, profileName, scope) {
|
|
956
|
+
if (!base.refreshToken) {
|
|
957
|
+
throw new KaguraAuthExpiredError(
|
|
958
|
+
"This profile was stored without a refresh token, so it cannot be refreshed \u2014 log in again to get one.\n Run: kagura auth login (or `npx kagura-memory auth login`)",
|
|
959
|
+
base.expiresAt
|
|
960
|
+
);
|
|
961
|
+
}
|
|
770
962
|
const token = await refreshAccessToken(base.server, {
|
|
771
963
|
clientId: base.clientId,
|
|
772
964
|
refreshToken: base.refreshToken,
|
|
965
|
+
...scope !== void 0 ? { scope } : {},
|
|
773
966
|
...this.fetchImpl ? { fetch: this.fetchImpl } : {}
|
|
774
967
|
});
|
|
775
968
|
this.state.credentials = withRefreshed(base, {
|
|
776
969
|
accessToken: token.accessToken,
|
|
777
970
|
refreshToken: token.refreshToken || null,
|
|
778
971
|
expiresAt: token.expiresAt,
|
|
779
|
-
|
|
972
|
+
// `||` not `??`: TokenResponse.scope defaults to "" when the server
|
|
973
|
+
// omits it, and withRefreshed's `?? creds.scope` only catches
|
|
974
|
+
// null/undefined — so an omitted scope used to blank the stored one.
|
|
975
|
+
scope: token.scope || null
|
|
780
976
|
});
|
|
781
977
|
const cf = loadCredentialsFile(credPath);
|
|
782
978
|
setProfile(cf, profileName, this.state.credentials);
|
|
@@ -1119,6 +1315,9 @@ var KaguraClient = class _KaguraClient {
|
|
|
1119
1315
|
if (options.linkedSourceUris !== void 0) {
|
|
1120
1316
|
args.linked_source_uris = options.linkedSourceUris;
|
|
1121
1317
|
}
|
|
1318
|
+
if (options.supersedes !== void 0) {
|
|
1319
|
+
args.supersedes = options.supersedes;
|
|
1320
|
+
}
|
|
1122
1321
|
return this.callToolChecked("remember", args);
|
|
1123
1322
|
}
|
|
1124
1323
|
/**
|
|
@@ -1184,6 +1383,44 @@ var KaguraClient = class _KaguraClient {
|
|
|
1184
1383
|
}
|
|
1185
1384
|
return this.callToolChecked("recall_upcoming", args);
|
|
1186
1385
|
}
|
|
1386
|
+
/**
|
|
1387
|
+
* List memories near a geographic point, nearest first, each carrying
|
|
1388
|
+
* `distance_m`. The WHERE axis — a deterministic spatial query over
|
|
1389
|
+
* stored `details.location` coordinates, not semantic search (use
|
|
1390
|
+
* {@link recall} for topic search). Mirrors {@link recallUpcoming}.
|
|
1391
|
+
*
|
|
1392
|
+
* Store a location with
|
|
1393
|
+
* `remember({ details: { location: { lat, lon, label } } })`; see
|
|
1394
|
+
* {@link MemoryLocation}. Any memory type can carry one.
|
|
1395
|
+
*
|
|
1396
|
+
* Note: {@link updateMemory} replaces `details` wholesale, so resend
|
|
1397
|
+
* `location` when updating details or the memory drops off this axis.
|
|
1398
|
+
*
|
|
1399
|
+
* `radiusM` is clamped server-side to [1, 1_000_000]; it is forwarded
|
|
1400
|
+
* unchanged rather than pre-clamped here, so the server stays the single
|
|
1401
|
+
* authority on the bound.
|
|
1402
|
+
*
|
|
1403
|
+
* @throws Error if `lat`/`lon` are not finite numbers in range. The
|
|
1404
|
+
* server rejects these with HTTP 422; failing locally turns the common
|
|
1405
|
+
* swapped-lat/lon mistake into an immediate, named error.
|
|
1406
|
+
*/
|
|
1407
|
+
async recallNearby(options) {
|
|
1408
|
+
const { lat, lon } = options;
|
|
1409
|
+
if (!Number.isFinite(lat) || lat < -90 || lat > 90) {
|
|
1410
|
+
throw new Error(`lat must be a finite number between -90 and 90, got ${lat}`);
|
|
1411
|
+
}
|
|
1412
|
+
if (!Number.isFinite(lon) || lon < -180 || lon > 180) {
|
|
1413
|
+
throw new Error(`lon must be a finite number between -180 and 180, got ${lon}`);
|
|
1414
|
+
}
|
|
1415
|
+
const result = await this.callToolChecked("recall_nearby", {
|
|
1416
|
+
context_id: options.contextId,
|
|
1417
|
+
lat,
|
|
1418
|
+
lon,
|
|
1419
|
+
radius_m: options.radiusM ?? 1e3,
|
|
1420
|
+
k: options.k ?? 20
|
|
1421
|
+
});
|
|
1422
|
+
return result;
|
|
1423
|
+
}
|
|
1187
1424
|
/**
|
|
1188
1425
|
* Deterministically load a context's pinned (`delivery_mode="always"`)
|
|
1189
1426
|
* memories — the complete, unranked pinned set on every call.
|
|
@@ -1525,6 +1762,9 @@ var KaguraClient = class _KaguraClient {
|
|
|
1525
1762
|
if (prefix) {
|
|
1526
1763
|
args.prefix = prefix;
|
|
1527
1764
|
}
|
|
1765
|
+
if (options.withTags !== void 0 && options.withTags.length > 0) {
|
|
1766
|
+
args.with_tags = options.withTags;
|
|
1767
|
+
}
|
|
1528
1768
|
const result = await this.callToolChecked("list_tags", args);
|
|
1529
1769
|
return result;
|
|
1530
1770
|
}
|
|
@@ -1593,6 +1833,9 @@ var KaguraClient = class _KaguraClient {
|
|
|
1593
1833
|
if (options.contextSummary !== void 0) {
|
|
1594
1834
|
args.context_summary = options.contextSummary;
|
|
1595
1835
|
}
|
|
1836
|
+
if (options.details !== void 0) {
|
|
1837
|
+
args.details = options.details;
|
|
1838
|
+
}
|
|
1596
1839
|
if (options.deliveryMode !== void 0) {
|
|
1597
1840
|
args.delivery_mode = options.deliveryMode;
|
|
1598
1841
|
}
|
|
@@ -3157,10 +3400,131 @@ function isMintShape(payload) {
|
|
|
3157
3400
|
const rec = payload;
|
|
3158
3401
|
return typeof rec.id === "number" && typeof rec.name === "string" && typeof rec.key_prefix === "string";
|
|
3159
3402
|
}
|
|
3403
|
+
|
|
3404
|
+
// src/auth/login.ts
|
|
3405
|
+
var DEFAULT_SCOPE = "memory:read memory:write";
|
|
3406
|
+
var READ_ONLY_SCOPE = "memory:read";
|
|
3407
|
+
async function login(options = {}) {
|
|
3408
|
+
const env = options.env ?? process.env;
|
|
3409
|
+
const mcpUrl = options.mcpUrl?.trim() || env.KAGURA_MCP_URL?.trim() || DEFAULT_MCP_URL;
|
|
3410
|
+
validateHttpsUrl(mcpUrl, "MCP URL");
|
|
3411
|
+
const server = baseUrlFromMcp(mcpUrl);
|
|
3412
|
+
const clientId = options.clientId ?? DEFAULT_CLIENT_ID;
|
|
3413
|
+
const profile = options.profile ?? "default";
|
|
3414
|
+
const authorization = await authorizeDevice(server, {
|
|
3415
|
+
clientId,
|
|
3416
|
+
scope: options.scope ?? DEFAULT_SCOPE,
|
|
3417
|
+
...options.fetch !== void 0 ? { fetch: options.fetch } : {}
|
|
3418
|
+
});
|
|
3419
|
+
await options.onUserCode?.(authorization);
|
|
3420
|
+
const token = await pollForToken(server, {
|
|
3421
|
+
clientId,
|
|
3422
|
+
deviceCode: authorization.deviceCode,
|
|
3423
|
+
interval: authorization.interval,
|
|
3424
|
+
expiresAt: authorization.expiresAt,
|
|
3425
|
+
...options.fetch !== void 0 ? { fetch: options.fetch } : {},
|
|
3426
|
+
...options.sleep !== void 0 ? { sleep: options.sleep } : {}
|
|
3427
|
+
});
|
|
3428
|
+
if (!token.refreshToken) {
|
|
3429
|
+
console.warn(
|
|
3430
|
+
`Logged in, but the token response carried no refresh_token: this profile cannot auto-refresh and will need another login when the access token expires. Verify the '${clientId}' client is allowed offline access on ${server}.`
|
|
3431
|
+
);
|
|
3432
|
+
}
|
|
3433
|
+
const credentials = {
|
|
3434
|
+
server,
|
|
3435
|
+
mcpUrl,
|
|
3436
|
+
clientId,
|
|
3437
|
+
accessToken: token.accessToken,
|
|
3438
|
+
refreshToken: token.refreshToken,
|
|
3439
|
+
tokenType: token.tokenType,
|
|
3440
|
+
expiresAt: token.expiresAt,
|
|
3441
|
+
scope: token.scope,
|
|
3442
|
+
workspaceId: token.workspaceId,
|
|
3443
|
+
workspaceName: token.workspaceName,
|
|
3444
|
+
userEmail: token.userEmail,
|
|
3445
|
+
issuedAt: /* @__PURE__ */ new Date()
|
|
3446
|
+
};
|
|
3447
|
+
await updateProfile(profile, credentials, options.credentialsPath);
|
|
3448
|
+
if (options.setAsDefault) {
|
|
3449
|
+
await setDefaultProfile(profile, options.credentialsPath);
|
|
3450
|
+
}
|
|
3451
|
+
return credentials;
|
|
3452
|
+
}
|
|
3453
|
+
|
|
3454
|
+
// src/auth/refresh.ts
|
|
3455
|
+
function isScopeRejection(error) {
|
|
3456
|
+
if (!(error instanceof KaguraAuthError)) {
|
|
3457
|
+
return false;
|
|
3458
|
+
}
|
|
3459
|
+
const message = error.message.toLowerCase();
|
|
3460
|
+
return message.includes("insufficient_scope") || message.includes("invalid_scope");
|
|
3461
|
+
}
|
|
3462
|
+
async function refresh(options = {}) {
|
|
3463
|
+
const cf = loadCredentialsFile(options.credentialsPath);
|
|
3464
|
+
const target = options.profile || cf.defaultProfile;
|
|
3465
|
+
const stored = cf.profiles[target];
|
|
3466
|
+
if (stored === void 0) {
|
|
3467
|
+
throw new Error(`No profile named '${target}'. Run a login first.`);
|
|
3468
|
+
}
|
|
3469
|
+
const httpOptions = options.fetch !== void 0 ? { fetch: options.fetch } : {};
|
|
3470
|
+
const state = getSharedState(options.credentialsPath, target);
|
|
3471
|
+
if (state === null) {
|
|
3472
|
+
throw new Error(`No profile named '${target}'. Run a login first.`);
|
|
3473
|
+
}
|
|
3474
|
+
const provider = new KaguraOAuth(state, httpOptions);
|
|
3475
|
+
try {
|
|
3476
|
+
await provider.forceRefresh(options.scope !== void 0 ? { scope: options.scope } : {});
|
|
3477
|
+
return state.credentials;
|
|
3478
|
+
} catch (e) {
|
|
3479
|
+
if (options.scope === void 0 || !isScopeRejection(e)) {
|
|
3480
|
+
throw e;
|
|
3481
|
+
}
|
|
3482
|
+
const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);
|
|
3483
|
+
await updateProfile(target, next, options.credentialsPath);
|
|
3484
|
+
state.credentials = next;
|
|
3485
|
+
return next;
|
|
3486
|
+
}
|
|
3487
|
+
}
|
|
3488
|
+
async function consentToWiderScope(stored, scope, options, httpOptions) {
|
|
3489
|
+
if (options.onUserCode === void 0) {
|
|
3490
|
+
throw new KaguraAuthError(
|
|
3491
|
+
`Widening the scope to '${scope}' needs fresh consent, which requires showing the user a device code \u2014 pass onUserCode to refresh(). Narrowing a scope does not need consent and works without it.`
|
|
3492
|
+
);
|
|
3493
|
+
}
|
|
3494
|
+
const authorization = await authorizeDevice(stored.server, {
|
|
3495
|
+
clientId: stored.clientId,
|
|
3496
|
+
scope,
|
|
3497
|
+
...httpOptions
|
|
3498
|
+
});
|
|
3499
|
+
await options.onUserCode(authorization);
|
|
3500
|
+
const token = await pollForToken(stored.server, {
|
|
3501
|
+
clientId: stored.clientId,
|
|
3502
|
+
deviceCode: authorization.deviceCode,
|
|
3503
|
+
interval: authorization.interval,
|
|
3504
|
+
expiresAt: authorization.expiresAt,
|
|
3505
|
+
...httpOptions,
|
|
3506
|
+
...options.sleep !== void 0 ? { sleep: options.sleep } : {}
|
|
3507
|
+
});
|
|
3508
|
+
return {
|
|
3509
|
+
...stored,
|
|
3510
|
+
accessToken: token.accessToken,
|
|
3511
|
+
refreshToken: token.refreshToken || stored.refreshToken,
|
|
3512
|
+
tokenType: token.tokenType,
|
|
3513
|
+
expiresAt: token.expiresAt,
|
|
3514
|
+
scope: token.scope || scope,
|
|
3515
|
+
workspaceId: token.workspaceId || stored.workspaceId,
|
|
3516
|
+
workspaceName: token.workspaceName || stored.workspaceName,
|
|
3517
|
+
userEmail: token.userEmail || stored.userEmail,
|
|
3518
|
+
issuedAt: /* @__PURE__ */ new Date()
|
|
3519
|
+
};
|
|
3520
|
+
}
|
|
3160
3521
|
export {
|
|
3161
3522
|
AgentsClient,
|
|
3523
|
+
DEFAULT_CLIENT_ID,
|
|
3162
3524
|
DEFAULT_MCP_URL,
|
|
3163
3525
|
DEFAULT_REST_BASE_URL,
|
|
3526
|
+
DEFAULT_SCOPE,
|
|
3527
|
+
DEVICE_FLOW_GRANT_TYPE,
|
|
3164
3528
|
FilesClient,
|
|
3165
3529
|
KaguraAuthDeniedError,
|
|
3166
3530
|
KaguraAuthError,
|
|
@@ -3174,17 +3538,40 @@ export {
|
|
|
3174
3538
|
KaguraIntegrityError,
|
|
3175
3539
|
KaguraLLMError,
|
|
3176
3540
|
KaguraNotFoundError,
|
|
3541
|
+
KaguraOAuth,
|
|
3177
3542
|
KaguraQuotaError,
|
|
3178
3543
|
KaguraRateLimitError,
|
|
3179
3544
|
KaguraRestClient,
|
|
3180
3545
|
MIN_SERVER_VERSION,
|
|
3546
|
+
READ_ONLY_SCOPE,
|
|
3547
|
+
REFRESH_SKEW_SEC,
|
|
3548
|
+
REFRESH_TOKEN_GRANT_TYPE,
|
|
3181
3549
|
ResourceClient,
|
|
3182
3550
|
SDK_VERSION,
|
|
3183
3551
|
SETUP_OAUTH_NOT_SUPPORTED_MSG,
|
|
3184
3552
|
VALID_ASSIGNABLE_ROLES,
|
|
3185
3553
|
VALID_INVITE_EXPIRES,
|
|
3186
3554
|
WorkspaceClient,
|
|
3555
|
+
authorizeDevice,
|
|
3556
|
+
defaultCredentialsPath,
|
|
3557
|
+
deleteCredentialsFile,
|
|
3558
|
+
deleteProfile,
|
|
3559
|
+
emptyCredentialsFile,
|
|
3560
|
+
getProfile,
|
|
3561
|
+
isExpired,
|
|
3187
3562
|
loadConfig,
|
|
3188
|
-
|
|
3563
|
+
loadCredentialsFile,
|
|
3564
|
+
login,
|
|
3565
|
+
pollForToken,
|
|
3566
|
+
refresh,
|
|
3567
|
+
refreshAccessToken,
|
|
3568
|
+
removeProfile,
|
|
3569
|
+
resolveAuth,
|
|
3570
|
+
revokeToken,
|
|
3571
|
+
saveCredentialsFile,
|
|
3572
|
+
setDefaultProfile,
|
|
3573
|
+
setProfile,
|
|
3574
|
+
updateProfile,
|
|
3575
|
+
withRefreshed
|
|
3189
3576
|
};
|
|
3190
3577
|
//# sourceMappingURL=index.js.map
|