kagura-memory 0.3.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/dist/index.cjs CHANGED
@@ -31,8 +31,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  AgentsClient: () => AgentsClient,
34
+ DEFAULT_CLIENT_ID: () => DEFAULT_CLIENT_ID,
34
35
  DEFAULT_MCP_URL: () => DEFAULT_MCP_URL,
35
36
  DEFAULT_REST_BASE_URL: () => DEFAULT_REST_BASE_URL,
37
+ DEFAULT_SCOPE: () => DEFAULT_SCOPE,
38
+ DEVICE_FLOW_GRANT_TYPE: () => DEVICE_FLOW_GRANT_TYPE,
36
39
  FilesClient: () => FilesClient,
37
40
  KaguraAuthDeniedError: () => KaguraAuthDeniedError,
38
41
  KaguraAuthError: () => KaguraAuthError,
@@ -46,18 +49,41 @@ __export(index_exports, {
46
49
  KaguraIntegrityError: () => KaguraIntegrityError,
47
50
  KaguraLLMError: () => KaguraLLMError,
48
51
  KaguraNotFoundError: () => KaguraNotFoundError,
52
+ KaguraOAuth: () => KaguraOAuth,
49
53
  KaguraQuotaError: () => KaguraQuotaError,
50
54
  KaguraRateLimitError: () => KaguraRateLimitError,
51
55
  KaguraRestClient: () => KaguraRestClient,
52
56
  MIN_SERVER_VERSION: () => MIN_SERVER_VERSION,
57
+ READ_ONLY_SCOPE: () => READ_ONLY_SCOPE,
58
+ REFRESH_SKEW_SEC: () => REFRESH_SKEW_SEC,
59
+ REFRESH_TOKEN_GRANT_TYPE: () => REFRESH_TOKEN_GRANT_TYPE,
53
60
  ResourceClient: () => ResourceClient,
54
61
  SDK_VERSION: () => SDK_VERSION,
55
62
  SETUP_OAUTH_NOT_SUPPORTED_MSG: () => SETUP_OAUTH_NOT_SUPPORTED_MSG,
56
63
  VALID_ASSIGNABLE_ROLES: () => VALID_ASSIGNABLE_ROLES,
57
64
  VALID_INVITE_EXPIRES: () => VALID_INVITE_EXPIRES,
58
65
  WorkspaceClient: () => WorkspaceClient,
66
+ authorizeDevice: () => authorizeDevice,
67
+ defaultCredentialsPath: () => defaultCredentialsPath,
68
+ deleteCredentialsFile: () => deleteCredentialsFile,
69
+ deleteProfile: () => deleteProfile,
70
+ emptyCredentialsFile: () => emptyCredentialsFile,
71
+ getProfile: () => getProfile,
72
+ isExpired: () => isExpired,
59
73
  loadConfig: () => loadConfig,
60
- resolveAuth: () => resolveAuth
74
+ loadCredentialsFile: () => loadCredentialsFile,
75
+ login: () => login,
76
+ pollForToken: () => pollForToken,
77
+ refresh: () => refresh,
78
+ refreshAccessToken: () => refreshAccessToken,
79
+ removeProfile: () => removeProfile,
80
+ resolveAuth: () => resolveAuth,
81
+ revokeToken: () => revokeToken,
82
+ saveCredentialsFile: () => saveCredentialsFile,
83
+ setDefaultProfile: () => setDefaultProfile,
84
+ setProfile: () => setProfile,
85
+ updateProfile: () => updateProfile,
86
+ withRefreshed: () => withRefreshed
61
87
  });
62
88
  module.exports = __toCommonJS(index_exports);
63
89
 
@@ -200,7 +226,7 @@ var path3 = __toESM(require("path"), 1);
200
226
  var import_promises = require("timers/promises");
201
227
 
202
228
  // src/version.ts
203
- var SDK_VERSION = "0.1.0";
229
+ var SDK_VERSION = "0.5.0";
204
230
 
205
231
  // src/http.ts
206
232
  function baseUrlFromMcp(mcpUrl) {
@@ -292,17 +318,24 @@ function throwForKaguraStatus(status, headers, bodyText, fallbackMessage) {
292
318
  }
293
319
  throw new KaguraConnectionError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`);
294
320
  }
295
- var LOCALHOST_HTTP_RE = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/;
321
+ var PLAIN_HTTP_RE = /^http:\/\//i;
322
+ var LOCALHOST_HTTP_RE = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/i;
296
323
  function validateHttpsUrl(url, label = "URL") {
297
- if (url.startsWith("http://") && !LOCALHOST_HTTP_RE.test(url)) {
324
+ const candidate = url.trim();
325
+ if (PLAIN_HTTP_RE.test(candidate) && !LOCALHOST_HTTP_RE.test(candidate)) {
298
326
  throw new Error(
299
- `${label} must use HTTPS for security (got: ${url}). HTTP is only allowed for localhost development.`
327
+ `${label} must use HTTPS for security (got: ${candidate}). HTTP is only allowed for localhost development.`
300
328
  );
301
329
  }
302
330
  }
303
331
 
304
332
  // src/auth/deviceFlow.ts
333
+ var PATH_DEVICE_AUTHORIZE = "/api/v1/oauth/device/authorize";
305
334
  var PATH_TOKEN = "/api/v1/oauth/token/";
335
+ var PATH_REVOKE = "/api/v1/oauth/revoke";
336
+ var SLOW_DOWN_INCREMENT_SEC = 5;
337
+ var DEFAULT_CLIENT_ID = "kagura-cli";
338
+ var DEVICE_FLOW_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
306
339
  var REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
307
340
  function userAgent() {
308
341
  return `kagura-memory-sdk/${SDK_VERSION}`;
@@ -373,6 +406,126 @@ function tokenResponseFromBody(bodyText, status) {
373
406
  workspaceName: stringOr(body.workspace_name, "")
374
407
  };
375
408
  }
409
+ async function authorizeDevice(server, options = {}) {
410
+ const clientId = options.clientId ?? DEFAULT_CLIENT_ID;
411
+ const scope = options.scope ?? "memory:read";
412
+ const doFetch = options.fetch ?? globalThis.fetch;
413
+ const url = `${server.replace(/\/+$/, "")}${PATH_DEVICE_AUTHORIZE}`;
414
+ let response;
415
+ let text;
416
+ try {
417
+ response = await doFetch(url, {
418
+ method: "POST",
419
+ headers: {
420
+ "User-Agent": userAgent(),
421
+ "Content-Type": "application/json"
422
+ },
423
+ body: JSON.stringify({ client_id: clientId, scope })
424
+ });
425
+ text = await response.text();
426
+ } catch (e) {
427
+ throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });
428
+ }
429
+ if (!response.ok) {
430
+ const detail = extractDetail(text) || text;
431
+ throw new KaguraAuthError(
432
+ `Device authorization failed (HTTP ${response.status}): ${detail}
433
+ Verify the server URL and that '${clientId}' is registered.`
434
+ );
435
+ }
436
+ const body = safeJsonObject(text, response.status, "Device authorization");
437
+ const deviceCode = body.device_code;
438
+ const userCode = body.user_code;
439
+ const verificationUri = body.verification_uri;
440
+ const expiresIn = toInt(body.expires_in);
441
+ if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof verificationUri !== "string" || expiresIn === null) {
442
+ throw new KaguraAuthError(
443
+ `Device authorization returned HTTP 200 but body is missing required fields. Body keys: ${Object.keys(body).sort().join(", ")}`
444
+ );
445
+ }
446
+ return {
447
+ deviceCode,
448
+ userCode,
449
+ verificationUri,
450
+ verificationUriComplete: stringOr(body.verification_uri_complete, verificationUri),
451
+ expiresIn,
452
+ interval: toInt(body.interval) ?? 5,
453
+ expiresAt: new Date(Date.now() + expiresIn * 1e3)
454
+ };
455
+ }
456
+ async function pollForToken(server, options) {
457
+ const doFetch = options.fetch ?? globalThis.fetch;
458
+ const sleep2 = options.sleep ?? (async (ms) => void await (0, import_promises.setTimeout)(ms));
459
+ const url = tokenUrl(server);
460
+ let currentInterval = options.interval;
461
+ let firstPoll = true;
462
+ for (; ; ) {
463
+ if (Date.now() >= options.expiresAt.getTime()) {
464
+ throw new KaguraAuthExpiredError(
465
+ "Device code expired before user approval. Run: kagura auth login",
466
+ options.expiresAt
467
+ );
468
+ }
469
+ if (firstPoll) {
470
+ firstPoll = false;
471
+ } else {
472
+ await sleep2(currentInterval * 1e3);
473
+ }
474
+ let response;
475
+ let text;
476
+ try {
477
+ response = await doFetch(url, {
478
+ method: "POST",
479
+ headers: { "User-Agent": userAgent() },
480
+ body: new URLSearchParams({
481
+ grant_type: DEVICE_FLOW_GRANT_TYPE,
482
+ device_code: options.deviceCode,
483
+ client_id: options.clientId
484
+ })
485
+ });
486
+ text = await response.text();
487
+ } catch (e) {
488
+ throw new KaguraConnectionError(
489
+ `Lost connection while waiting for approval: ${excMessage(e)}
490
+ The login session may still be valid; re-run: kagura auth login`,
491
+ { cause: e }
492
+ );
493
+ }
494
+ if (response.status === 200) {
495
+ return tokenResponseFromBody(text, response.status);
496
+ }
497
+ const body = safeJson(text);
498
+ const error = stringOr(body.error, "");
499
+ if (error === "authorization_pending") {
500
+ continue;
501
+ }
502
+ if (error === "slow_down") {
503
+ currentInterval += SLOW_DOWN_INCREMENT_SEC;
504
+ continue;
505
+ }
506
+ if (error === "access_denied") {
507
+ throw new KaguraAuthDeniedError(
508
+ "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."
509
+ );
510
+ }
511
+ if (error === "expired_token") {
512
+ throw new KaguraAuthExpiredError(
513
+ "Device code expired before user approval. Run: kagura auth login",
514
+ options.expiresAt
515
+ );
516
+ }
517
+ const description = stringOr(body.error_description, "");
518
+ if (error || description) {
519
+ throw new KaguraAuthError(
520
+ `Token endpoint returned unexpected error '${error}': ${description}`
521
+ );
522
+ }
523
+ const detail = extractDetail(text) || text.slice(0, 200);
524
+ throw new KaguraAuthError(
525
+ `Token endpoint returned HTTP ${response.status} with no OAuth error code. Body: ${detail}`
526
+ );
527
+ }
528
+ }
376
529
  async function refreshAccessToken(server, options) {
377
530
  const doFetch = options.fetch ?? globalThis.fetch;
378
531
  const url = tokenUrl(server);
@@ -417,6 +570,23 @@ async function refreshAccessToken(server, options) {
417
570
  `Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`
418
571
  );
419
572
  }
573
+ async function revokeToken(server, options) {
574
+ const doFetch = options.fetch ?? globalThis.fetch;
575
+ const url = `${server.replace(/\/+$/, "")}${PATH_REVOKE}`;
576
+ try {
577
+ const response = await doFetch(url, {
578
+ method: "POST",
579
+ headers: { "User-Agent": userAgent() },
580
+ body: new URLSearchParams({
581
+ token: options.token,
582
+ client_id: options.clientId ?? DEFAULT_CLIENT_ID
583
+ })
584
+ });
585
+ return response.status === 200 || response.status === 204;
586
+ } catch {
587
+ return false;
588
+ }
589
+ }
420
590
 
421
591
  // src/auth/filelock.ts
422
592
  var fs2 = __toESM(require("fs"), 1);
@@ -597,6 +767,13 @@ function setProfile(cf, name, creds) {
597
767
  cf.defaultProfile = name;
598
768
  }
599
769
  }
770
+ function removeProfile(cf, name) {
771
+ delete cf.profiles[name];
772
+ const next = Object.keys(cf.profiles)[0];
773
+ if (cf.defaultProfile === name && next !== void 0) {
774
+ cf.defaultProfile = next;
775
+ }
776
+ }
600
777
  function credentialsFileToDict(cf) {
601
778
  const profiles = {};
602
779
  for (const [name, creds] of Object.entries(cf.profiles)) {
@@ -709,6 +886,39 @@ function loadCredentialsFile(credentialsPath) {
709
886
  function saveCredentialsFile(cf, credentialsPath) {
710
887
  atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);
711
888
  }
889
+ async function updateProfile(profileName, creds, credentialsPath) {
890
+ const p = resolvePath(credentialsPath);
891
+ await withFileLock(p, () => {
892
+ const cf = loadCredentialsFile(p);
893
+ setProfile(cf, profileName, creds);
894
+ saveCredentialsFile(cf, p);
895
+ });
896
+ }
897
+ async function setDefaultProfile(profileName, credentialsPath) {
898
+ const p = resolvePath(credentialsPath);
899
+ await withFileLock(p, () => {
900
+ const cf = loadCredentialsFile(p);
901
+ if (!(profileName in cf.profiles)) {
902
+ throw new Error(`profile '${profileName}' not found in credentials file`);
903
+ }
904
+ cf.defaultProfile = profileName;
905
+ saveCredentialsFile(cf, p);
906
+ });
907
+ }
908
+ async function deleteProfile(profileName, credentialsPath) {
909
+ const p = resolvePath(credentialsPath);
910
+ await withFileLock(p, () => {
911
+ const cf = loadCredentialsFile(p);
912
+ if (!(profileName in cf.profiles)) {
913
+ return;
914
+ }
915
+ removeProfile(cf, profileName);
916
+ saveCredentialsFile(cf, p);
917
+ });
918
+ }
919
+ function deleteCredentialsFile(credentialsPath) {
920
+ fs3.rmSync(resolvePath(credentialsPath), { force: true });
921
+ }
712
922
  var AsyncMutex = class {
713
923
  tail = Promise.resolve();
714
924
  runExclusive(fn) {
@@ -789,9 +999,11 @@ var KaguraOAuth = class {
789
999
  * Cross-process dedup is handled in `refreshLocked` via the
790
1000
  * rejected-token identity check.
791
1001
  */
792
- async forceRefresh() {
1002
+ async forceRefresh(options = {}) {
793
1003
  const rejectedToken = this.state.credentials.accessToken;
794
- await this.state.mutex.runExclusive(() => this.refreshLocked(rejectedToken));
1004
+ await this.state.mutex.runExclusive(
1005
+ () => this.refreshLocked(rejectedToken, options.scope)
1006
+ );
795
1007
  }
796
1008
  /**
797
1009
  * Refresh `/oauth/token/` once across all processes. Caller holds the
@@ -808,17 +1020,17 @@ var KaguraOAuth = class {
808
1020
  * on-disk token *differs* from the rejected one (a 401 is independent of
809
1021
  * `expiresAt`).
810
1022
  */
811
- async refreshLocked(expectedStaleToken) {
1023
+ async refreshLocked(expectedStaleToken, scope) {
812
1024
  const credPath = this.state.path;
813
1025
  const profileName = this.state.profileName;
814
1026
  await withFileLock(credPath, async () => {
815
1027
  const disk = getProfile(loadCredentialsFile(credPath), profileName);
816
- if (disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {
1028
+ if (scope === void 0 && disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {
817
1029
  this.state.credentials = disk;
818
1030
  return;
819
1031
  }
820
1032
  const base = disk ?? this.state.credentials;
821
- await this.networkRefreshAndSave(base, credPath, profileName);
1033
+ await this.networkRefreshAndSave(base, credPath, profileName, scope);
822
1034
  });
823
1035
  }
824
1036
  /** Whether `disk` shows another process already produced a usable token. */
@@ -829,17 +1041,27 @@ var KaguraOAuth = class {
829
1041
  return disk.accessToken !== expectedStaleToken;
830
1042
  }
831
1043
  /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */
832
- async networkRefreshAndSave(base, credPath, profileName) {
1044
+ async networkRefreshAndSave(base, credPath, profileName, scope) {
1045
+ if (!base.refreshToken) {
1046
+ throw new KaguraAuthExpiredError(
1047
+ "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`)",
1048
+ base.expiresAt
1049
+ );
1050
+ }
833
1051
  const token = await refreshAccessToken(base.server, {
834
1052
  clientId: base.clientId,
835
1053
  refreshToken: base.refreshToken,
1054
+ ...scope !== void 0 ? { scope } : {},
836
1055
  ...this.fetchImpl ? { fetch: this.fetchImpl } : {}
837
1056
  });
838
1057
  this.state.credentials = withRefreshed(base, {
839
1058
  accessToken: token.accessToken,
840
1059
  refreshToken: token.refreshToken || null,
841
1060
  expiresAt: token.expiresAt,
842
- scope: token.scope
1061
+ // `||` not `??`: TokenResponse.scope defaults to "" when the server
1062
+ // omits it, and withRefreshed's `?? creds.scope` only catches
1063
+ // null/undefined — so an omitted scope used to blank the stored one.
1064
+ scope: token.scope || null
843
1065
  });
844
1066
  const cf = loadCredentialsFile(credPath);
845
1067
  setProfile(cf, profileName, this.state.credentials);
@@ -1182,6 +1404,9 @@ var KaguraClient = class _KaguraClient {
1182
1404
  if (options.linkedSourceUris !== void 0) {
1183
1405
  args.linked_source_uris = options.linkedSourceUris;
1184
1406
  }
1407
+ if (options.supersedes !== void 0) {
1408
+ args.supersedes = options.supersedes;
1409
+ }
1185
1410
  return this.callToolChecked("remember", args);
1186
1411
  }
1187
1412
  /**
@@ -1247,6 +1472,44 @@ var KaguraClient = class _KaguraClient {
1247
1472
  }
1248
1473
  return this.callToolChecked("recall_upcoming", args);
1249
1474
  }
1475
+ /**
1476
+ * List memories near a geographic point, nearest first, each carrying
1477
+ * `distance_m`. The WHERE axis — a deterministic spatial query over
1478
+ * stored `details.location` coordinates, not semantic search (use
1479
+ * {@link recall} for topic search). Mirrors {@link recallUpcoming}.
1480
+ *
1481
+ * Store a location with
1482
+ * `remember({ details: { location: { lat, lon, label } } })`; see
1483
+ * {@link MemoryLocation}. Any memory type can carry one.
1484
+ *
1485
+ * Note: {@link updateMemory} replaces `details` wholesale, so resend
1486
+ * `location` when updating details or the memory drops off this axis.
1487
+ *
1488
+ * `radiusM` is clamped server-side to [1, 1_000_000]; it is forwarded
1489
+ * unchanged rather than pre-clamped here, so the server stays the single
1490
+ * authority on the bound.
1491
+ *
1492
+ * @throws Error if `lat`/`lon` are not finite numbers in range. The
1493
+ * server rejects these with HTTP 422; failing locally turns the common
1494
+ * swapped-lat/lon mistake into an immediate, named error.
1495
+ */
1496
+ async recallNearby(options) {
1497
+ const { lat, lon } = options;
1498
+ if (!Number.isFinite(lat) || lat < -90 || lat > 90) {
1499
+ throw new Error(`lat must be a finite number between -90 and 90, got ${lat}`);
1500
+ }
1501
+ if (!Number.isFinite(lon) || lon < -180 || lon > 180) {
1502
+ throw new Error(`lon must be a finite number between -180 and 180, got ${lon}`);
1503
+ }
1504
+ const result = await this.callToolChecked("recall_nearby", {
1505
+ context_id: options.contextId,
1506
+ lat,
1507
+ lon,
1508
+ radius_m: options.radiusM ?? 1e3,
1509
+ k: options.k ?? 20
1510
+ });
1511
+ return result;
1512
+ }
1250
1513
  /**
1251
1514
  * Deterministically load a context's pinned (`delivery_mode="always"`)
1252
1515
  * memories — the complete, unranked pinned set on every call.
@@ -1588,6 +1851,9 @@ var KaguraClient = class _KaguraClient {
1588
1851
  if (prefix) {
1589
1852
  args.prefix = prefix;
1590
1853
  }
1854
+ if (options.withTags !== void 0 && options.withTags.length > 0) {
1855
+ args.with_tags = options.withTags;
1856
+ }
1591
1857
  const result = await this.callToolChecked("list_tags", args);
1592
1858
  return result;
1593
1859
  }
@@ -1656,6 +1922,9 @@ var KaguraClient = class _KaguraClient {
1656
1922
  if (options.contextSummary !== void 0) {
1657
1923
  args.context_summary = options.contextSummary;
1658
1924
  }
1925
+ if (options.details !== void 0) {
1926
+ args.details = options.details;
1927
+ }
1659
1928
  if (options.deliveryMode !== void 0) {
1660
1929
  args.delivery_mode = options.deliveryMode;
1661
1930
  }
@@ -3220,11 +3489,132 @@ function isMintShape(payload) {
3220
3489
  const rec = payload;
3221
3490
  return typeof rec.id === "number" && typeof rec.name === "string" && typeof rec.key_prefix === "string";
3222
3491
  }
3492
+
3493
+ // src/auth/login.ts
3494
+ var DEFAULT_SCOPE = "memory:read memory:write";
3495
+ var READ_ONLY_SCOPE = "memory:read";
3496
+ async function login(options = {}) {
3497
+ const env = options.env ?? process.env;
3498
+ const mcpUrl = options.mcpUrl?.trim() || env.KAGURA_MCP_URL?.trim() || DEFAULT_MCP_URL;
3499
+ validateHttpsUrl(mcpUrl, "MCP URL");
3500
+ const server = baseUrlFromMcp(mcpUrl);
3501
+ const clientId = options.clientId ?? DEFAULT_CLIENT_ID;
3502
+ const profile = options.profile ?? "default";
3503
+ const authorization = await authorizeDevice(server, {
3504
+ clientId,
3505
+ scope: options.scope ?? DEFAULT_SCOPE,
3506
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
3507
+ });
3508
+ await options.onUserCode?.(authorization);
3509
+ const token = await pollForToken(server, {
3510
+ clientId,
3511
+ deviceCode: authorization.deviceCode,
3512
+ interval: authorization.interval,
3513
+ expiresAt: authorization.expiresAt,
3514
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {},
3515
+ ...options.sleep !== void 0 ? { sleep: options.sleep } : {}
3516
+ });
3517
+ if (!token.refreshToken) {
3518
+ console.warn(
3519
+ `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}.`
3520
+ );
3521
+ }
3522
+ const credentials = {
3523
+ server,
3524
+ mcpUrl,
3525
+ clientId,
3526
+ accessToken: token.accessToken,
3527
+ refreshToken: token.refreshToken,
3528
+ tokenType: token.tokenType,
3529
+ expiresAt: token.expiresAt,
3530
+ scope: token.scope,
3531
+ workspaceId: token.workspaceId,
3532
+ workspaceName: token.workspaceName,
3533
+ userEmail: token.userEmail,
3534
+ issuedAt: /* @__PURE__ */ new Date()
3535
+ };
3536
+ await updateProfile(profile, credentials, options.credentialsPath);
3537
+ if (options.setAsDefault) {
3538
+ await setDefaultProfile(profile, options.credentialsPath);
3539
+ }
3540
+ return credentials;
3541
+ }
3542
+
3543
+ // src/auth/refresh.ts
3544
+ function isScopeRejection(error) {
3545
+ if (!(error instanceof KaguraAuthError)) {
3546
+ return false;
3547
+ }
3548
+ const message = error.message.toLowerCase();
3549
+ return message.includes("insufficient_scope") || message.includes("invalid_scope");
3550
+ }
3551
+ async function refresh(options = {}) {
3552
+ const cf = loadCredentialsFile(options.credentialsPath);
3553
+ const target = options.profile || cf.defaultProfile;
3554
+ const stored = cf.profiles[target];
3555
+ if (stored === void 0) {
3556
+ throw new Error(`No profile named '${target}'. Run a login first.`);
3557
+ }
3558
+ const httpOptions = options.fetch !== void 0 ? { fetch: options.fetch } : {};
3559
+ const state = getSharedState(options.credentialsPath, target);
3560
+ if (state === null) {
3561
+ throw new Error(`No profile named '${target}'. Run a login first.`);
3562
+ }
3563
+ const provider = new KaguraOAuth(state, httpOptions);
3564
+ try {
3565
+ await provider.forceRefresh(options.scope !== void 0 ? { scope: options.scope } : {});
3566
+ return state.credentials;
3567
+ } catch (e) {
3568
+ if (options.scope === void 0 || !isScopeRejection(e)) {
3569
+ throw e;
3570
+ }
3571
+ const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);
3572
+ await updateProfile(target, next, options.credentialsPath);
3573
+ state.credentials = next;
3574
+ return next;
3575
+ }
3576
+ }
3577
+ async function consentToWiderScope(stored, scope, options, httpOptions) {
3578
+ if (options.onUserCode === void 0) {
3579
+ throw new KaguraAuthError(
3580
+ `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.`
3581
+ );
3582
+ }
3583
+ const authorization = await authorizeDevice(stored.server, {
3584
+ clientId: stored.clientId,
3585
+ scope,
3586
+ ...httpOptions
3587
+ });
3588
+ await options.onUserCode(authorization);
3589
+ const token = await pollForToken(stored.server, {
3590
+ clientId: stored.clientId,
3591
+ deviceCode: authorization.deviceCode,
3592
+ interval: authorization.interval,
3593
+ expiresAt: authorization.expiresAt,
3594
+ ...httpOptions,
3595
+ ...options.sleep !== void 0 ? { sleep: options.sleep } : {}
3596
+ });
3597
+ return {
3598
+ ...stored,
3599
+ accessToken: token.accessToken,
3600
+ refreshToken: token.refreshToken || stored.refreshToken,
3601
+ tokenType: token.tokenType,
3602
+ expiresAt: token.expiresAt,
3603
+ scope: token.scope || scope,
3604
+ workspaceId: token.workspaceId || stored.workspaceId,
3605
+ workspaceName: token.workspaceName || stored.workspaceName,
3606
+ userEmail: token.userEmail || stored.userEmail,
3607
+ issuedAt: /* @__PURE__ */ new Date()
3608
+ };
3609
+ }
3223
3610
  // Annotate the CommonJS export names for ESM import in node:
3224
3611
  0 && (module.exports = {
3225
3612
  AgentsClient,
3613
+ DEFAULT_CLIENT_ID,
3226
3614
  DEFAULT_MCP_URL,
3227
3615
  DEFAULT_REST_BASE_URL,
3616
+ DEFAULT_SCOPE,
3617
+ DEVICE_FLOW_GRANT_TYPE,
3228
3618
  FilesClient,
3229
3619
  KaguraAuthDeniedError,
3230
3620
  KaguraAuthError,
@@ -3238,17 +3628,40 @@ function isMintShape(payload) {
3238
3628
  KaguraIntegrityError,
3239
3629
  KaguraLLMError,
3240
3630
  KaguraNotFoundError,
3631
+ KaguraOAuth,
3241
3632
  KaguraQuotaError,
3242
3633
  KaguraRateLimitError,
3243
3634
  KaguraRestClient,
3244
3635
  MIN_SERVER_VERSION,
3636
+ READ_ONLY_SCOPE,
3637
+ REFRESH_SKEW_SEC,
3638
+ REFRESH_TOKEN_GRANT_TYPE,
3245
3639
  ResourceClient,
3246
3640
  SDK_VERSION,
3247
3641
  SETUP_OAUTH_NOT_SUPPORTED_MSG,
3248
3642
  VALID_ASSIGNABLE_ROLES,
3249
3643
  VALID_INVITE_EXPIRES,
3250
3644
  WorkspaceClient,
3645
+ authorizeDevice,
3646
+ defaultCredentialsPath,
3647
+ deleteCredentialsFile,
3648
+ deleteProfile,
3649
+ emptyCredentialsFile,
3650
+ getProfile,
3651
+ isExpired,
3251
3652
  loadConfig,
3252
- resolveAuth
3653
+ loadCredentialsFile,
3654
+ login,
3655
+ pollForToken,
3656
+ refresh,
3657
+ refreshAccessToken,
3658
+ removeProfile,
3659
+ resolveAuth,
3660
+ revokeToken,
3661
+ saveCredentialsFile,
3662
+ setDefaultProfile,
3663
+ setProfile,
3664
+ updateProfile,
3665
+ withRefreshed
3253
3666
  });
3254
3667
  //# sourceMappingURL=index.cjs.map