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/cli.js ADDED
@@ -0,0 +1,1294 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import * as readline from "readline/promises";
5
+
6
+ // src/errors.ts
7
+ function excMessage(e) {
8
+ if (e instanceof Error) {
9
+ return e.message || e.constructor.name;
10
+ }
11
+ const s = String(e);
12
+ return s || (typeof e === "object" && e !== null ? e.constructor.name : "unknown error");
13
+ }
14
+ var KaguraError = class extends Error {
15
+ constructor(message, options) {
16
+ super(message, options);
17
+ this.name = new.target.name;
18
+ }
19
+ };
20
+ var KaguraAuthError = class extends KaguraError {
21
+ };
22
+ var KaguraAuthExpiredError = class extends KaguraAuthError {
23
+ expiresAt;
24
+ constructor(message, expiresAt = null, options) {
25
+ super(message, options);
26
+ this.expiresAt = expiresAt;
27
+ }
28
+ };
29
+ var KaguraAuthDeniedError = class extends KaguraAuthError {
30
+ };
31
+ var KaguraConnectionError = class extends KaguraError {
32
+ };
33
+
34
+ // src/version.ts
35
+ var SDK_VERSION = "0.5.0";
36
+
37
+ // src/http.ts
38
+ function baseUrlFromMcp(mcpUrl) {
39
+ const m = /\/mcp(?=\/|$)/.exec(mcpUrl);
40
+ return m ? mcpUrl.slice(0, m.index) : mcpUrl;
41
+ }
42
+ function formatValidationErrors(errors) {
43
+ const parts = [];
44
+ for (const entry of errors) {
45
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
46
+ continue;
47
+ }
48
+ const rec = entry;
49
+ const msg = rec.msg;
50
+ if (typeof msg !== "string" || !msg) {
51
+ continue;
52
+ }
53
+ const loc = rec.loc;
54
+ if (Array.isArray(loc) && loc.length > 0) {
55
+ parts.push(`${loc.map(String).join(".")}: ${msg}`);
56
+ } else {
57
+ parts.push(msg);
58
+ }
59
+ }
60
+ return parts.join("; ");
61
+ }
62
+ function extractDetail(bodyText) {
63
+ let body;
64
+ try {
65
+ body = JSON.parse(bodyText);
66
+ } catch {
67
+ return "";
68
+ }
69
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
70
+ return "";
71
+ }
72
+ const rec = body;
73
+ const detail = rec.detail;
74
+ if (typeof detail === "string") {
75
+ return detail;
76
+ }
77
+ if (Array.isArray(detail)) {
78
+ return formatValidationErrors(detail);
79
+ }
80
+ const message = rec.message;
81
+ if (typeof message === "string" && message) {
82
+ const details = rec.details;
83
+ if (typeof details === "object" && details !== null && !Array.isArray(details)) {
84
+ const errors = details.errors;
85
+ if (Array.isArray(errors)) {
86
+ const formatted = formatValidationErrors(errors);
87
+ if (formatted) {
88
+ return `${message}: ${formatted}`;
89
+ }
90
+ }
91
+ }
92
+ return message;
93
+ }
94
+ return "";
95
+ }
96
+ var PLAIN_HTTP_RE = /^http:\/\//i;
97
+ var LOCALHOST_HTTP_RE = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/i;
98
+ function validateHttpsUrl(url, label = "URL") {
99
+ const candidate = url.trim();
100
+ if (PLAIN_HTTP_RE.test(candidate) && !LOCALHOST_HTTP_RE.test(candidate)) {
101
+ throw new Error(
102
+ `${label} must use HTTPS for security (got: ${candidate}). HTTP is only allowed for localhost development.`
103
+ );
104
+ }
105
+ }
106
+
107
+ // src/auth/credentials.ts
108
+ import * as crypto from "crypto";
109
+ import * as fs2 from "fs";
110
+ import * as os from "os";
111
+ import * as path2 from "path";
112
+
113
+ // src/auth/deviceFlow.ts
114
+ import { setTimeout as sleepMs } from "timers/promises";
115
+ var PATH_DEVICE_AUTHORIZE = "/api/v1/oauth/device/authorize";
116
+ var PATH_TOKEN = "/api/v1/oauth/token/";
117
+ var SLOW_DOWN_INCREMENT_SEC = 5;
118
+ var DEFAULT_CLIENT_ID = "kagura-cli";
119
+ var DEVICE_FLOW_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
120
+ var REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
121
+ function userAgent() {
122
+ return `kagura-memory-sdk/${SDK_VERSION}`;
123
+ }
124
+ function tokenUrl(server) {
125
+ return `${server.replace(/\/+$/, "")}${PATH_TOKEN}`;
126
+ }
127
+ function toInt(value) {
128
+ if (typeof value === "number" && Number.isFinite(value)) {
129
+ return Math.trunc(value);
130
+ }
131
+ if (typeof value === "string" && value.trim() !== "") {
132
+ const n = Number(value);
133
+ return Number.isFinite(n) ? Math.trunc(n) : null;
134
+ }
135
+ return null;
136
+ }
137
+ function stringOr(value, fallback) {
138
+ return typeof value === "string" ? value : fallback;
139
+ }
140
+ function safeJsonObject(bodyText, status, endpoint) {
141
+ let body;
142
+ try {
143
+ body = JSON.parse(bodyText);
144
+ } catch (e) {
145
+ const detail = bodyText.slice(0, 200);
146
+ throw new KaguraAuthError(
147
+ `${endpoint} returned HTTP ${status} but body is not JSON: ${excMessage(e)}. Body: ${detail}`,
148
+ { cause: e }
149
+ );
150
+ }
151
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
152
+ throw new KaguraAuthError(
153
+ `${endpoint} returned HTTP ${status} but body is not a JSON object (got ${Array.isArray(body) ? "array" : typeof body})`
154
+ );
155
+ }
156
+ return body;
157
+ }
158
+ function safeJson(bodyText) {
159
+ let body;
160
+ try {
161
+ body = JSON.parse(bodyText);
162
+ } catch {
163
+ return {};
164
+ }
165
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
166
+ return {};
167
+ }
168
+ return body;
169
+ }
170
+ function tokenResponseFromBody(bodyText, status) {
171
+ const body = safeJsonObject(bodyText, status, "Token endpoint");
172
+ const accessToken = body.access_token;
173
+ const expiresIn = toInt(body.expires_in ?? 0);
174
+ if (typeof accessToken !== "string" || expiresIn === null) {
175
+ throw new KaguraAuthError(
176
+ `Token endpoint returned HTTP ${status} but body is missing required fields. Body keys: ${Object.keys(body).sort().join(", ")}`
177
+ );
178
+ }
179
+ return {
180
+ accessToken,
181
+ refreshToken: stringOr(body.refresh_token, ""),
182
+ tokenType: stringOr(body.token_type, "Bearer"),
183
+ expiresAt: new Date(Date.now() + expiresIn * 1e3),
184
+ scope: stringOr(body.scope, ""),
185
+ userEmail: stringOr(body.user_email, ""),
186
+ workspaceId: stringOr(body.workspace_id, ""),
187
+ workspaceName: stringOr(body.workspace_name, "")
188
+ };
189
+ }
190
+ async function authorizeDevice(server, options = {}) {
191
+ const clientId = options.clientId ?? DEFAULT_CLIENT_ID;
192
+ const scope = options.scope ?? "memory:read";
193
+ const doFetch = options.fetch ?? globalThis.fetch;
194
+ const url = `${server.replace(/\/+$/, "")}${PATH_DEVICE_AUTHORIZE}`;
195
+ let response;
196
+ let text;
197
+ try {
198
+ response = await doFetch(url, {
199
+ method: "POST",
200
+ headers: {
201
+ "User-Agent": userAgent(),
202
+ "Content-Type": "application/json"
203
+ },
204
+ body: JSON.stringify({ client_id: clientId, scope })
205
+ });
206
+ text = await response.text();
207
+ } catch (e) {
208
+ throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });
209
+ }
210
+ if (!response.ok) {
211
+ const detail = extractDetail(text) || text;
212
+ throw new KaguraAuthError(
213
+ `Device authorization failed (HTTP ${response.status}): ${detail}
214
+ Verify the server URL and that '${clientId}' is registered.`
215
+ );
216
+ }
217
+ const body = safeJsonObject(text, response.status, "Device authorization");
218
+ const deviceCode = body.device_code;
219
+ const userCode = body.user_code;
220
+ const verificationUri = body.verification_uri;
221
+ const expiresIn = toInt(body.expires_in);
222
+ if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof verificationUri !== "string" || expiresIn === null) {
223
+ throw new KaguraAuthError(
224
+ `Device authorization returned HTTP 200 but body is missing required fields. Body keys: ${Object.keys(body).sort().join(", ")}`
225
+ );
226
+ }
227
+ return {
228
+ deviceCode,
229
+ userCode,
230
+ verificationUri,
231
+ verificationUriComplete: stringOr(body.verification_uri_complete, verificationUri),
232
+ expiresIn,
233
+ interval: toInt(body.interval) ?? 5,
234
+ expiresAt: new Date(Date.now() + expiresIn * 1e3)
235
+ };
236
+ }
237
+ async function pollForToken(server, options) {
238
+ const doFetch = options.fetch ?? globalThis.fetch;
239
+ const sleep2 = options.sleep ?? (async (ms) => void await sleepMs(ms));
240
+ const url = tokenUrl(server);
241
+ let currentInterval = options.interval;
242
+ let firstPoll = true;
243
+ for (; ; ) {
244
+ if (Date.now() >= options.expiresAt.getTime()) {
245
+ throw new KaguraAuthExpiredError(
246
+ "Device code expired before user approval. Run: kagura auth login",
247
+ options.expiresAt
248
+ );
249
+ }
250
+ if (firstPoll) {
251
+ firstPoll = false;
252
+ } else {
253
+ await sleep2(currentInterval * 1e3);
254
+ }
255
+ let response;
256
+ let text;
257
+ try {
258
+ response = await doFetch(url, {
259
+ method: "POST",
260
+ headers: { "User-Agent": userAgent() },
261
+ body: new URLSearchParams({
262
+ grant_type: DEVICE_FLOW_GRANT_TYPE,
263
+ device_code: options.deviceCode,
264
+ client_id: options.clientId
265
+ })
266
+ });
267
+ text = await response.text();
268
+ } catch (e) {
269
+ throw new KaguraConnectionError(
270
+ `Lost connection while waiting for approval: ${excMessage(e)}
271
+ The login session may still be valid; re-run: kagura auth login`,
272
+ { cause: e }
273
+ );
274
+ }
275
+ if (response.status === 200) {
276
+ return tokenResponseFromBody(text, response.status);
277
+ }
278
+ const body = safeJson(text);
279
+ const error = stringOr(body.error, "");
280
+ if (error === "authorization_pending") {
281
+ continue;
282
+ }
283
+ if (error === "slow_down") {
284
+ currentInterval += SLOW_DOWN_INCREMENT_SEC;
285
+ continue;
286
+ }
287
+ if (error === "access_denied") {
288
+ throw new KaguraAuthDeniedError(
289
+ "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."
290
+ );
291
+ }
292
+ if (error === "expired_token") {
293
+ throw new KaguraAuthExpiredError(
294
+ "Device code expired before user approval. Run: kagura auth login",
295
+ options.expiresAt
296
+ );
297
+ }
298
+ const description = stringOr(body.error_description, "");
299
+ if (error || description) {
300
+ throw new KaguraAuthError(
301
+ `Token endpoint returned unexpected error '${error}': ${description}`
302
+ );
303
+ }
304
+ const detail = extractDetail(text) || text.slice(0, 200);
305
+ throw new KaguraAuthError(
306
+ `Token endpoint returned HTTP ${response.status} with no OAuth error code. Body: ${detail}`
307
+ );
308
+ }
309
+ }
310
+ async function refreshAccessToken(server, options) {
311
+ const doFetch = options.fetch ?? globalThis.fetch;
312
+ const url = tokenUrl(server);
313
+ const form = new URLSearchParams({
314
+ grant_type: REFRESH_TOKEN_GRANT_TYPE,
315
+ refresh_token: options.refreshToken,
316
+ client_id: options.clientId
317
+ });
318
+ if (options.scope !== void 0 && options.scope !== null) {
319
+ form.set("scope", options.scope);
320
+ }
321
+ let response;
322
+ let text;
323
+ try {
324
+ response = await doFetch(url, {
325
+ method: "POST",
326
+ headers: { "User-Agent": userAgent() },
327
+ body: form
328
+ });
329
+ text = await response.text();
330
+ } catch (e) {
331
+ throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });
332
+ }
333
+ if (response.status === 200) {
334
+ return tokenResponseFromBody(text, response.status);
335
+ }
336
+ const body = safeJson(text);
337
+ const error = stringOr(body.error, "");
338
+ if (error === "invalid_grant") {
339
+ throw new KaguraAuthExpiredError(
340
+ "Your login expired (refresh token is no longer valid).\n Run: kagura auth login\n Your server and workspace selection are preserved."
341
+ );
342
+ }
343
+ const description = stringOr(body.error_description, "");
344
+ if (error) {
345
+ throw new KaguraAuthError(
346
+ `Refresh failed: ${error}${description ? ` \u2014 ${description}` : ""}`
347
+ );
348
+ }
349
+ const detail = extractDetail(text) || text.slice(0, 200);
350
+ throw new KaguraAuthError(
351
+ `Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`
352
+ );
353
+ }
354
+
355
+ // src/auth/filelock.ts
356
+ import * as fs from "fs";
357
+ import * as path from "path";
358
+ import { setTimeout as sleep } from "timers/promises";
359
+ var DEFAULT_LOCK_RETRY_MS = 50;
360
+ var DEFAULT_LOCK_TIMEOUT_MS = 9e4;
361
+ var DEFAULT_LOCK_STALE_MS = 6e4;
362
+ var FileLockTimeoutError = class extends Error {
363
+ constructor(message) {
364
+ super(message);
365
+ this.name = "FileLockTimeoutError";
366
+ }
367
+ };
368
+ function lockPath(target) {
369
+ return `${target}.lock`;
370
+ }
371
+ function isErrnoException(e) {
372
+ return e instanceof Error && "code" in e;
373
+ }
374
+ async function acquireFileLock(target, options = {}) {
375
+ const timeoutMs = options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;
376
+ const retryMs = options.retryMs ?? DEFAULT_LOCK_RETRY_MS;
377
+ const staleMs = options.staleMs ?? DEFAULT_LOCK_STALE_MS;
378
+ const lockFile = lockPath(target);
379
+ fs.mkdirSync(path.dirname(lockFile), { recursive: true });
380
+ const deadline = Date.now() + timeoutMs;
381
+ for (; ; ) {
382
+ let fd = null;
383
+ try {
384
+ fd = fs.openSync(lockFile, "wx", 384);
385
+ } catch (e) {
386
+ if (!isErrnoException(e) || e.code !== "EEXIST") {
387
+ throw e;
388
+ }
389
+ }
390
+ if (fd !== null) {
391
+ try {
392
+ fs.writeSync(fd, `${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}
393
+ `);
394
+ } finally {
395
+ fs.closeSync(fd);
396
+ }
397
+ let released = false;
398
+ return {
399
+ path: lockFile,
400
+ release() {
401
+ if (released) {
402
+ return;
403
+ }
404
+ released = true;
405
+ try {
406
+ fs.unlinkSync(lockFile);
407
+ } catch {
408
+ }
409
+ }
410
+ };
411
+ }
412
+ let mtimeMs;
413
+ try {
414
+ mtimeMs = fs.statSync(lockFile).mtimeMs;
415
+ } catch (e) {
416
+ if (isErrnoException(e) && e.code === "ENOENT") {
417
+ continue;
418
+ }
419
+ throw e;
420
+ }
421
+ if (Date.now() - mtimeMs > staleMs) {
422
+ try {
423
+ fs.unlinkSync(lockFile);
424
+ } catch (e) {
425
+ if (!isErrnoException(e) || e.code !== "ENOENT") {
426
+ throw e;
427
+ }
428
+ }
429
+ continue;
430
+ }
431
+ if (Date.now() >= deadline) {
432
+ throw new FileLockTimeoutError(
433
+ `could not acquire credentials lock within ${timeoutMs / 1e3}s: ${lockFile}`
434
+ );
435
+ }
436
+ await sleep(retryMs);
437
+ }
438
+ }
439
+ async function withFileLock(target, fn, options = {}) {
440
+ const handle = await acquireFileLock(target, options);
441
+ try {
442
+ return await fn();
443
+ } finally {
444
+ handle.release();
445
+ }
446
+ }
447
+
448
+ // src/auth/credentials.ts
449
+ var REFRESH_SKEW_SEC = 300;
450
+ var CREDENTIALS_FILE_MODE = 384;
451
+ var CREDENTIALS_DIR_MODE = 448;
452
+ function defaultCredentialsPath(home) {
453
+ return path2.join(home ?? os.homedir(), ".kagura", "credentials.json");
454
+ }
455
+ function isExpired(creds, skewSeconds = 0) {
456
+ return Date.now() >= creds.expiresAt.getTime() - skewSeconds * 1e3;
457
+ }
458
+ function withRefreshed(creds, fields) {
459
+ return {
460
+ ...creds,
461
+ accessToken: fields.accessToken,
462
+ refreshToken: fields.refreshToken ?? creds.refreshToken,
463
+ expiresAt: fields.expiresAt,
464
+ scope: fields.scope ?? creds.scope
465
+ };
466
+ }
467
+ function isoUtc(date) {
468
+ return `${date.toISOString().slice(0, 19)}Z`;
469
+ }
470
+ function parseIso(s) {
471
+ const normalized = /(?:Z|[+-]\d{2}:?\d{2})$/.test(s) ? s : `${s}Z`;
472
+ const date = new Date(normalized);
473
+ if (Number.isNaN(date.getTime())) {
474
+ throw new Error(`invalid ISO-8601 timestamp: ${s}`);
475
+ }
476
+ return date;
477
+ }
478
+ function credentialsToDict(creds) {
479
+ return {
480
+ server: creds.server,
481
+ mcp_url: creds.mcpUrl,
482
+ client_id: creds.clientId,
483
+ access_token: creds.accessToken,
484
+ refresh_token: creds.refreshToken,
485
+ token_type: creds.tokenType,
486
+ expires_at: isoUtc(creds.expiresAt),
487
+ scope: creds.scope,
488
+ workspace_id: creds.workspaceId,
489
+ workspace_name: creds.workspaceName,
490
+ user_email: creds.userEmail,
491
+ issued_at: isoUtc(creds.issuedAt)
492
+ };
493
+ }
494
+ function requireString(d, key) {
495
+ const value = d[key];
496
+ if (typeof value !== "string") {
497
+ throw new Error(`credentials profile missing required field '${key}'`);
498
+ }
499
+ return value;
500
+ }
501
+ function stringOr2(value, fallback) {
502
+ return typeof value === "string" ? value : fallback;
503
+ }
504
+ function credentialsFromDict(d) {
505
+ const issuedAtRaw = d.issued_at;
506
+ return {
507
+ server: requireString(d, "server"),
508
+ mcpUrl: requireString(d, "mcp_url"),
509
+ clientId: requireString(d, "client_id"),
510
+ accessToken: requireString(d, "access_token"),
511
+ refreshToken: requireString(d, "refresh_token"),
512
+ tokenType: stringOr2(d.token_type, "Bearer"),
513
+ expiresAt: parseIso(requireString(d, "expires_at")),
514
+ scope: stringOr2(d.scope, ""),
515
+ workspaceId: stringOr2(d.workspace_id, ""),
516
+ workspaceName: stringOr2(d.workspace_name, ""),
517
+ userEmail: stringOr2(d.user_email, ""),
518
+ issuedAt: typeof issuedAtRaw === "string" && issuedAtRaw ? parseIso(issuedAtRaw) : /* @__PURE__ */ new Date()
519
+ };
520
+ }
521
+ function emptyCredentialsFile() {
522
+ return { version: 1, defaultProfile: "default", profiles: {} };
523
+ }
524
+ function getProfile(cf, name) {
525
+ const key = name || cf.defaultProfile;
526
+ return cf.profiles[key] ?? null;
527
+ }
528
+ function setProfile(cf, name, creds) {
529
+ cf.profiles[name] = creds;
530
+ if (!(cf.defaultProfile in cf.profiles)) {
531
+ cf.defaultProfile = name;
532
+ }
533
+ }
534
+ function removeProfile(cf, name) {
535
+ delete cf.profiles[name];
536
+ const next = Object.keys(cf.profiles)[0];
537
+ if (cf.defaultProfile === name && next !== void 0) {
538
+ cf.defaultProfile = next;
539
+ }
540
+ }
541
+ function credentialsFileToDict(cf) {
542
+ const profiles = {};
543
+ for (const [name, creds] of Object.entries(cf.profiles)) {
544
+ profiles[name] = credentialsToDict(creds);
545
+ }
546
+ return {
547
+ version: cf.version,
548
+ default_profile: cf.defaultProfile,
549
+ profiles
550
+ };
551
+ }
552
+ function credentialsFileFromDict(d) {
553
+ const profilesRaw = d.profiles;
554
+ const profiles = {};
555
+ if (typeof profilesRaw === "object" && profilesRaw !== null && !Array.isArray(profilesRaw)) {
556
+ for (const [name, p] of Object.entries(profilesRaw)) {
557
+ if (typeof p !== "object" || p === null || Array.isArray(p)) {
558
+ throw new Error(`credentials profile '${name}' is not an object`);
559
+ }
560
+ profiles[name] = credentialsFromDict(p);
561
+ }
562
+ }
563
+ return {
564
+ version: typeof d.version === "number" ? d.version : 1,
565
+ defaultProfile: stringOr2(d.default_profile, "default"),
566
+ profiles
567
+ };
568
+ }
569
+ function enforceDirPerms(directory) {
570
+ try {
571
+ const mode = fs2.statSync(directory).mode & 511;
572
+ if (mode !== CREDENTIALS_DIR_MODE) {
573
+ fs2.chmodSync(directory, CREDENTIALS_DIR_MODE);
574
+ }
575
+ } catch {
576
+ }
577
+ }
578
+ function enforceFilePerms(filePath) {
579
+ try {
580
+ const mode = fs2.statSync(filePath).mode & 511;
581
+ if (mode !== CREDENTIALS_FILE_MODE) {
582
+ fs2.chmodSync(filePath, CREDENTIALS_FILE_MODE);
583
+ }
584
+ } catch {
585
+ }
586
+ }
587
+ function atomicWriteJson(filePath, data, mode = CREDENTIALS_FILE_MODE) {
588
+ const dir = path2.dirname(filePath);
589
+ fs2.mkdirSync(dir, { recursive: true });
590
+ enforceDirPerms(dir);
591
+ const tmp = path2.join(
592
+ dir,
593
+ `.${path2.basename(filePath)}.${crypto.randomBytes(6).toString("hex")}.tmp`
594
+ );
595
+ let fd = null;
596
+ try {
597
+ fd = fs2.openSync(tmp, "wx", 384);
598
+ fs2.writeSync(fd, `${JSON.stringify(data, null, 2)}
599
+ `);
600
+ fs2.fsyncSync(fd);
601
+ fs2.closeSync(fd);
602
+ fd = null;
603
+ fs2.chmodSync(tmp, mode);
604
+ fs2.renameSync(tmp, filePath);
605
+ try {
606
+ const dirFd = fs2.openSync(dir, "r");
607
+ try {
608
+ fs2.fsyncSync(dirFd);
609
+ } finally {
610
+ fs2.closeSync(dirFd);
611
+ }
612
+ } catch {
613
+ }
614
+ } catch (e) {
615
+ if (fd !== null) {
616
+ try {
617
+ fs2.closeSync(fd);
618
+ } catch {
619
+ }
620
+ }
621
+ fs2.rmSync(tmp, { force: true });
622
+ throw e;
623
+ }
624
+ }
625
+ function resolvePath(p) {
626
+ return p ?? defaultCredentialsPath();
627
+ }
628
+ function loadCredentialsFile(credentialsPath) {
629
+ const p = resolvePath(credentialsPath);
630
+ if (!fs2.existsSync(p)) {
631
+ return emptyCredentialsFile();
632
+ }
633
+ enforceDirPerms(path2.dirname(p));
634
+ enforceFilePerms(p);
635
+ let data;
636
+ try {
637
+ data = JSON.parse(fs2.readFileSync(p, "utf-8"));
638
+ } catch {
639
+ return emptyCredentialsFile();
640
+ }
641
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
642
+ return emptyCredentialsFile();
643
+ }
644
+ try {
645
+ return credentialsFileFromDict(data);
646
+ } catch {
647
+ return emptyCredentialsFile();
648
+ }
649
+ }
650
+ function saveCredentialsFile(cf, credentialsPath) {
651
+ atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);
652
+ }
653
+ async function updateProfile(profileName, creds, credentialsPath) {
654
+ const p = resolvePath(credentialsPath);
655
+ await withFileLock(p, () => {
656
+ const cf = loadCredentialsFile(p);
657
+ setProfile(cf, profileName, creds);
658
+ saveCredentialsFile(cf, p);
659
+ });
660
+ }
661
+ async function setDefaultProfile(profileName, credentialsPath) {
662
+ const p = resolvePath(credentialsPath);
663
+ await withFileLock(p, () => {
664
+ const cf = loadCredentialsFile(p);
665
+ if (!(profileName in cf.profiles)) {
666
+ throw new Error(`profile '${profileName}' not found in credentials file`);
667
+ }
668
+ cf.defaultProfile = profileName;
669
+ saveCredentialsFile(cf, p);
670
+ });
671
+ }
672
+ async function deleteProfile(profileName, credentialsPath) {
673
+ const p = resolvePath(credentialsPath);
674
+ await withFileLock(p, () => {
675
+ const cf = loadCredentialsFile(p);
676
+ if (!(profileName in cf.profiles)) {
677
+ return;
678
+ }
679
+ removeProfile(cf, profileName);
680
+ saveCredentialsFile(cf, p);
681
+ });
682
+ }
683
+ function deleteCredentialsFile(credentialsPath) {
684
+ fs2.rmSync(resolvePath(credentialsPath), { force: true });
685
+ }
686
+ var AsyncMutex = class {
687
+ tail = Promise.resolve();
688
+ runExclusive(fn) {
689
+ const run = this.tail.then(() => fn());
690
+ this.tail = run.catch(() => void 0);
691
+ return run;
692
+ }
693
+ };
694
+ var stateCache = /* @__PURE__ */ new Map();
695
+ var fileMutexes = /* @__PURE__ */ new Map();
696
+ function getFileMutex(p) {
697
+ let mutex = fileMutexes.get(p);
698
+ if (mutex === void 0) {
699
+ mutex = new AsyncMutex();
700
+ fileMutexes.set(p, mutex);
701
+ }
702
+ return mutex;
703
+ }
704
+ function getSharedState(credentialsPath, profile) {
705
+ const p = path2.resolve(resolvePath(credentialsPath));
706
+ const cf = loadCredentialsFile(p);
707
+ const creds = getProfile(cf, profile);
708
+ if (creds === null) {
709
+ return null;
710
+ }
711
+ const profileName = profile || cf.defaultProfile;
712
+ const key = JSON.stringify([p, profileName]);
713
+ let cached = stateCache.get(key);
714
+ if (cached === void 0) {
715
+ cached = {
716
+ credentials: creds,
717
+ profileName,
718
+ path: p,
719
+ mutex: getFileMutex(p)
720
+ };
721
+ stateCache.set(key, cached);
722
+ } else {
723
+ cached.credentials = creds;
724
+ }
725
+ return cached;
726
+ }
727
+ var KaguraOAuth = class {
728
+ state;
729
+ fetchImpl;
730
+ constructor(state, options = {}) {
731
+ this.state = state;
732
+ this.fetchImpl = options.fetch;
733
+ }
734
+ /**
735
+ * Return `Bearer <access_token>`, refreshing first when the token is
736
+ * within the skew window.
737
+ */
738
+ async getAuthHeader() {
739
+ await this.maybeRefresh();
740
+ return `Bearer ${this.state.credentials.accessToken}`;
741
+ }
742
+ /**
743
+ * Refresh the access token if it's within the skew window.
744
+ *
745
+ * The mutex is held across the entire read-check-refresh-persist
746
+ * sequence so a second caller waiting on it will find the token already
747
+ * rotated when it acquires.
748
+ */
749
+ async maybeRefresh() {
750
+ await this.state.mutex.runExclusive(async () => {
751
+ if (!isExpired(this.state.credentials, REFRESH_SKEW_SEC)) {
752
+ return;
753
+ }
754
+ await this.refreshLocked(null);
755
+ });
756
+ }
757
+ /**
758
+ * Unconditionally refresh the access token, ignoring the skew window.
759
+ *
760
+ * Used on an upstream 401: the token was rejected server-side (rotated /
761
+ * revoked out-of-band) even though it is not yet within the skew window.
762
+ * The same in-process mutex serializes this with skew-driven refreshes.
763
+ * Cross-process dedup is handled in `refreshLocked` via the
764
+ * rejected-token identity check.
765
+ */
766
+ async forceRefresh(options = {}) {
767
+ const rejectedToken = this.state.credentials.accessToken;
768
+ await this.state.mutex.runExclusive(
769
+ () => this.refreshLocked(rejectedToken, options.scope)
770
+ );
771
+ }
772
+ /**
773
+ * Refresh `/oauth/token/` once across all processes. Caller holds the
774
+ * in-process mutex.
775
+ *
776
+ * After acquiring the cross-process file lock, re-read the credentials
777
+ * from disk and **skip the network call when another process already
778
+ * rotated the token** — "skip" means "adopt the on-disk result", never
779
+ * "leave the stale in-memory token in place".
780
+ *
781
+ * `expectedStaleToken` governs the "already rotated?" predicate:
782
+ * `null` (skew path) → skip when the on-disk token is no longer within
783
+ * the skew window. A token string (401 path) → skip only when the
784
+ * on-disk token *differs* from the rejected one (a 401 is independent of
785
+ * `expiresAt`).
786
+ */
787
+ async refreshLocked(expectedStaleToken, scope) {
788
+ const credPath = this.state.path;
789
+ const profileName = this.state.profileName;
790
+ await withFileLock(credPath, async () => {
791
+ const disk = getProfile(loadCredentialsFile(credPath), profileName);
792
+ if (scope === void 0 && disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {
793
+ this.state.credentials = disk;
794
+ return;
795
+ }
796
+ const base = disk ?? this.state.credentials;
797
+ await this.networkRefreshAndSave(base, credPath, profileName, scope);
798
+ });
799
+ }
800
+ /** Whether `disk` shows another process already produced a usable token. */
801
+ alreadyRotated(disk, expectedStaleToken) {
802
+ if (expectedStaleToken === null) {
803
+ return !isExpired(disk, REFRESH_SKEW_SEC);
804
+ }
805
+ return disk.accessToken !== expectedStaleToken;
806
+ }
807
+ /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */
808
+ async networkRefreshAndSave(base, credPath, profileName, scope) {
809
+ if (!base.refreshToken) {
810
+ throw new KaguraAuthExpiredError(
811
+ "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`)",
812
+ base.expiresAt
813
+ );
814
+ }
815
+ const token = await refreshAccessToken(base.server, {
816
+ clientId: base.clientId,
817
+ refreshToken: base.refreshToken,
818
+ ...scope !== void 0 ? { scope } : {},
819
+ ...this.fetchImpl ? { fetch: this.fetchImpl } : {}
820
+ });
821
+ this.state.credentials = withRefreshed(base, {
822
+ accessToken: token.accessToken,
823
+ refreshToken: token.refreshToken || null,
824
+ expiresAt: token.expiresAt,
825
+ // `||` not `??`: TokenResponse.scope defaults to "" when the server
826
+ // omits it, and withRefreshed's `?? creds.scope` only catches
827
+ // null/undefined — so an omitted scope used to blank the stored one.
828
+ scope: token.scope || null
829
+ });
830
+ const cf = loadCredentialsFile(credPath);
831
+ setProfile(cf, profileName, this.state.credentials);
832
+ saveCredentialsFile(cf, credPath);
833
+ }
834
+ };
835
+
836
+ // src/config.ts
837
+ import * as fs3 from "fs";
838
+ import * as os2 from "os";
839
+ import * as path3 from "path";
840
+
841
+ // src/auth/resolve.ts
842
+ var DEFAULT_MCP_URL = "https://memory.kagura-ai.com/mcp";
843
+
844
+ // src/auth/login.ts
845
+ var DEFAULT_SCOPE = "memory:read memory:write";
846
+ var READ_ONLY_SCOPE = "memory:read";
847
+ async function login(options = {}) {
848
+ const env = options.env ?? process.env;
849
+ const mcpUrl = options.mcpUrl?.trim() || env.KAGURA_MCP_URL?.trim() || DEFAULT_MCP_URL;
850
+ validateHttpsUrl(mcpUrl, "MCP URL");
851
+ const server = baseUrlFromMcp(mcpUrl);
852
+ const clientId = options.clientId ?? DEFAULT_CLIENT_ID;
853
+ const profile = options.profile ?? "default";
854
+ const authorization = await authorizeDevice(server, {
855
+ clientId,
856
+ scope: options.scope ?? DEFAULT_SCOPE,
857
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
858
+ });
859
+ await options.onUserCode?.(authorization);
860
+ const token = await pollForToken(server, {
861
+ clientId,
862
+ deviceCode: authorization.deviceCode,
863
+ interval: authorization.interval,
864
+ expiresAt: authorization.expiresAt,
865
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {},
866
+ ...options.sleep !== void 0 ? { sleep: options.sleep } : {}
867
+ });
868
+ if (!token.refreshToken) {
869
+ console.warn(
870
+ `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}.`
871
+ );
872
+ }
873
+ const credentials = {
874
+ server,
875
+ mcpUrl,
876
+ clientId,
877
+ accessToken: token.accessToken,
878
+ refreshToken: token.refreshToken,
879
+ tokenType: token.tokenType,
880
+ expiresAt: token.expiresAt,
881
+ scope: token.scope,
882
+ workspaceId: token.workspaceId,
883
+ workspaceName: token.workspaceName,
884
+ userEmail: token.userEmail,
885
+ issuedAt: /* @__PURE__ */ new Date()
886
+ };
887
+ await updateProfile(profile, credentials, options.credentialsPath);
888
+ if (options.setAsDefault) {
889
+ await setDefaultProfile(profile, options.credentialsPath);
890
+ }
891
+ return credentials;
892
+ }
893
+
894
+ // src/auth/refresh.ts
895
+ function isScopeRejection(error) {
896
+ if (!(error instanceof KaguraAuthError)) {
897
+ return false;
898
+ }
899
+ const message = error.message.toLowerCase();
900
+ return message.includes("insufficient_scope") || message.includes("invalid_scope");
901
+ }
902
+ async function refresh(options = {}) {
903
+ const cf = loadCredentialsFile(options.credentialsPath);
904
+ const target = options.profile || cf.defaultProfile;
905
+ const stored = cf.profiles[target];
906
+ if (stored === void 0) {
907
+ throw new Error(`No profile named '${target}'. Run a login first.`);
908
+ }
909
+ const httpOptions = options.fetch !== void 0 ? { fetch: options.fetch } : {};
910
+ const state = getSharedState(options.credentialsPath, target);
911
+ if (state === null) {
912
+ throw new Error(`No profile named '${target}'. Run a login first.`);
913
+ }
914
+ const provider = new KaguraOAuth(state, httpOptions);
915
+ try {
916
+ await provider.forceRefresh(options.scope !== void 0 ? { scope: options.scope } : {});
917
+ return state.credentials;
918
+ } catch (e) {
919
+ if (options.scope === void 0 || !isScopeRejection(e)) {
920
+ throw e;
921
+ }
922
+ const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);
923
+ await updateProfile(target, next, options.credentialsPath);
924
+ state.credentials = next;
925
+ return next;
926
+ }
927
+ }
928
+ async function consentToWiderScope(stored, scope, options, httpOptions) {
929
+ if (options.onUserCode === void 0) {
930
+ throw new KaguraAuthError(
931
+ `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.`
932
+ );
933
+ }
934
+ const authorization = await authorizeDevice(stored.server, {
935
+ clientId: stored.clientId,
936
+ scope,
937
+ ...httpOptions
938
+ });
939
+ await options.onUserCode(authorization);
940
+ const token = await pollForToken(stored.server, {
941
+ clientId: stored.clientId,
942
+ deviceCode: authorization.deviceCode,
943
+ interval: authorization.interval,
944
+ expiresAt: authorization.expiresAt,
945
+ ...httpOptions,
946
+ ...options.sleep !== void 0 ? { sleep: options.sleep } : {}
947
+ });
948
+ return {
949
+ ...stored,
950
+ accessToken: token.accessToken,
951
+ refreshToken: token.refreshToken || stored.refreshToken,
952
+ tokenType: token.tokenType,
953
+ expiresAt: token.expiresAt,
954
+ scope: token.scope || scope,
955
+ workspaceId: token.workspaceId || stored.workspaceId,
956
+ workspaceName: token.workspaceName || stored.workspaceName,
957
+ userEmail: token.userEmail || stored.userEmail,
958
+ issuedAt: /* @__PURE__ */ new Date()
959
+ };
960
+ }
961
+
962
+ // src/cli/openBrowser.ts
963
+ import { spawn } from "child_process";
964
+ function browserCommand(platform, url) {
965
+ if (platform === "win32") {
966
+ return ["explorer.exe", [url]];
967
+ }
968
+ if (platform === "darwin") {
969
+ return ["open", [url]];
970
+ }
971
+ return ["xdg-open", [url]];
972
+ }
973
+ function isOpenableUrl(url) {
974
+ try {
975
+ const protocol = new URL(url).protocol;
976
+ if (protocol !== "https:" && protocol !== "http:") {
977
+ return false;
978
+ }
979
+ validateHttpsUrl(url, "Verification URL");
980
+ return true;
981
+ } catch {
982
+ return false;
983
+ }
984
+ }
985
+ async function openBrowser(url, spawnImpl = spawn) {
986
+ if (!isOpenableUrl(url)) {
987
+ return false;
988
+ }
989
+ const [command, args] = browserCommand(process.platform, url);
990
+ return new Promise((resolve2) => {
991
+ let settled = false;
992
+ const settle = (ok) => {
993
+ if (!settled) {
994
+ settled = true;
995
+ resolve2(ok);
996
+ }
997
+ };
998
+ try {
999
+ const child = spawnImpl(command, args, { stdio: "ignore", detached: true });
1000
+ child.once("spawn", () => settle(true));
1001
+ child.once("error", () => settle(false));
1002
+ child.unref();
1003
+ } catch {
1004
+ settle(false);
1005
+ }
1006
+ });
1007
+ }
1008
+
1009
+ // src/cli/parseArgs.ts
1010
+ var VALUE_FLAGS = /* @__PURE__ */ new Set(["profile", "server", "scope"]);
1011
+ var SWITCHES = /* @__PURE__ */ new Set(["read-only", "no-browser", "all", "yes", "help"]);
1012
+ function parseArgs(argv) {
1013
+ const positionals = [];
1014
+ const flags = /* @__PURE__ */ new Set();
1015
+ const values = {};
1016
+ const unknown = [];
1017
+ const missingValue = [];
1018
+ for (let i = 0; i < argv.length; i++) {
1019
+ const token = argv[i];
1020
+ if (token === "-h") {
1021
+ flags.add("help");
1022
+ continue;
1023
+ }
1024
+ if (!token.startsWith("--")) {
1025
+ if (token.startsWith("-") && token.length > 1) {
1026
+ unknown.push(token);
1027
+ continue;
1028
+ }
1029
+ positionals.push(token);
1030
+ continue;
1031
+ }
1032
+ const eq = token.indexOf("=");
1033
+ const name = eq === -1 ? token.slice(2) : token.slice(2, eq);
1034
+ if (VALUE_FLAGS.has(name)) {
1035
+ if (eq !== -1) {
1036
+ values[name] = token.slice(eq + 1);
1037
+ continue;
1038
+ }
1039
+ const next = argv[i + 1];
1040
+ if (next === void 0 || next.startsWith("-")) {
1041
+ missingValue.push(token);
1042
+ continue;
1043
+ }
1044
+ values[name] = next;
1045
+ i++;
1046
+ continue;
1047
+ }
1048
+ if (SWITCHES.has(name)) {
1049
+ flags.add(name);
1050
+ continue;
1051
+ }
1052
+ unknown.push(token);
1053
+ }
1054
+ return {
1055
+ command: positionals.shift() ?? "",
1056
+ positionals,
1057
+ flags,
1058
+ values,
1059
+ unknown,
1060
+ missingValue
1061
+ };
1062
+ }
1063
+
1064
+ // src/cli/run.ts
1065
+ var USAGE = `kagura-memory auth \u2014 manage Kagura Memory credentials
1066
+
1067
+ Usage:
1068
+ kagura-memory auth login [--profile <name>] [--server <url>]
1069
+ [--scope "<scopes>" | --read-only] [--no-browser]
1070
+ kagura-memory auth refresh [--profile <name>] [--scope "<scopes>"] [--no-browser]
1071
+ kagura-memory auth status [--profile <name>]
1072
+ kagura-memory auth use <profile>
1073
+ kagura-memory auth logout [--profile <name>] [--all] [--yes]
1074
+
1075
+ Credentials live in ~/.kagura/credentials.json and are shared with the
1076
+ Python CLI, so either tool can create or use a profile.
1077
+
1078
+ Scopes:
1079
+ memory:read read memories, contexts, files
1080
+ memory:write create/update/delete memories, contexts, files
1081
+
1082
+ Default scope is "${DEFAULT_SCOPE}"; --read-only requests "${READ_ONLY_SCOPE}".
1083
+ Narrowing a scope on refresh is silent; widening needs consent, so it
1084
+ re-runs the device flow.`;
1085
+ function devicePrompt(deps, openBrowserFlag) {
1086
+ return async (auth) => {
1087
+ const url = auth.verificationUriComplete || auth.verificationUri;
1088
+ deps.write("");
1089
+ deps.write(` First copy your one-time code: ${auth.userCode}`);
1090
+ deps.write(" Then approve at:");
1091
+ deps.write(` ${url}`);
1092
+ deps.write("");
1093
+ if (!openBrowserFlag) {
1094
+ deps.write(" (--no-browser: not opening a browser; still polling here.)");
1095
+ return;
1096
+ }
1097
+ if (!await deps.openBrowser(url)) {
1098
+ deps.write(" (Could not open a browser \u2014 use the URL above.)");
1099
+ }
1100
+ };
1101
+ }
1102
+ function workspaceLabel(creds) {
1103
+ return creds.workspaceName || creds.workspaceId || "(unknown)";
1104
+ }
1105
+ function describeProfile(name, creds, isDefault) {
1106
+ const expired = isExpired(creds);
1107
+ const refreshable = Boolean(creds.refreshToken);
1108
+ const state = !expired ? "active" : refreshable ? "expired (refreshable)" : "expired";
1109
+ return [
1110
+ `${isDefault ? "*" : " "} ${name}`,
1111
+ ` account: ${creds.userEmail || "(unknown)"}`,
1112
+ ` workspace: ${workspaceLabel(creds)}`,
1113
+ ` server: ${creds.server}`,
1114
+ ` scope: ${creds.scope || "(unknown)"}`,
1115
+ ` expires: ${creds.expiresAt.toISOString()}`,
1116
+ ` state: ${state}`,
1117
+ ` refreshable: ${refreshable}`
1118
+ ];
1119
+ }
1120
+ async function cmdLogin(deps, args) {
1121
+ const readOnly = args.flags.has("read-only");
1122
+ const scope = args.values.scope;
1123
+ if (readOnly && scope !== void 0) {
1124
+ deps.writeError("--read-only and --scope are mutually exclusive; pick one.");
1125
+ return 2;
1126
+ }
1127
+ const options = {
1128
+ onUserCode: devicePrompt(deps, !args.flags.has("no-browser"))
1129
+ };
1130
+ if (args.values.profile !== void 0) options.profile = args.values.profile;
1131
+ if (args.values.server !== void 0) options.mcpUrl = args.values.server;
1132
+ if (readOnly) options.scope = READ_ONLY_SCOPE;
1133
+ else if (scope !== void 0) options.scope = scope;
1134
+ if (deps.credentialsPath !== void 0) options.credentialsPath = deps.credentialsPath;
1135
+ const creds = await deps.login(options);
1136
+ deps.write(
1137
+ `Logged in as ${creds.userEmail || "(unknown)"} \u2014 workspace ${workspaceLabel(creds)}.`
1138
+ );
1139
+ deps.write(`Profile '${args.values.profile ?? "default"}' saved. Scope: ${creds.scope}`);
1140
+ return 0;
1141
+ }
1142
+ async function cmdRefresh(deps, args) {
1143
+ const options = {
1144
+ onUserCode: devicePrompt(deps, !args.flags.has("no-browser"))
1145
+ };
1146
+ if (args.values.profile !== void 0) options.profile = args.values.profile;
1147
+ if (args.values.scope !== void 0) options.scope = args.values.scope;
1148
+ if (deps.credentialsPath !== void 0) options.credentialsPath = deps.credentialsPath;
1149
+ const creds = await deps.refresh(options);
1150
+ deps.write(`Refreshed. Expires ${creds.expiresAt.toISOString()}. Scope: ${creds.scope}`);
1151
+ return 0;
1152
+ }
1153
+ function cmdStatus(deps, args) {
1154
+ const cf = loadCredentialsFile(deps.credentialsPath);
1155
+ const names = Object.keys(cf.profiles);
1156
+ if (names.length === 0) {
1157
+ deps.write("No profiles. Run: kagura-memory auth login");
1158
+ return 0;
1159
+ }
1160
+ const only = args.values.profile;
1161
+ if (only !== void 0) {
1162
+ const creds = cf.profiles[only];
1163
+ if (creds === void 0) {
1164
+ deps.writeError(`No profile named '${only}'.`);
1165
+ return 1;
1166
+ }
1167
+ for (const line of describeProfile(only, creds, cf.defaultProfile === only)) {
1168
+ deps.write(line);
1169
+ }
1170
+ return 0;
1171
+ }
1172
+ for (const name of names) {
1173
+ for (const line of describeProfile(name, cf.profiles[name], cf.defaultProfile === name)) {
1174
+ deps.write(line);
1175
+ }
1176
+ }
1177
+ return 0;
1178
+ }
1179
+ async function cmdUse(deps, args) {
1180
+ const name = args.positionals[0];
1181
+ if (name === void 0) {
1182
+ deps.writeError("Usage: kagura-memory auth use <profile>");
1183
+ return 2;
1184
+ }
1185
+ await setDefaultProfile(name, deps.credentialsPath);
1186
+ deps.write(`Default profile is now '${name}'.`);
1187
+ return 0;
1188
+ }
1189
+ async function cmdLogout(deps, args) {
1190
+ const all = args.flags.has("all");
1191
+ const target = args.values.profile;
1192
+ if (all && target !== void 0) {
1193
+ deps.writeError("--all and --profile are mutually exclusive; pick one.");
1194
+ return 2;
1195
+ }
1196
+ const cf = loadCredentialsFile(deps.credentialsPath);
1197
+ if (!all && target === void 0 && Object.keys(cf.profiles).length === 0) {
1198
+ deps.write("No profiles stored; nothing to do.");
1199
+ return 0;
1200
+ }
1201
+ const name = target ?? cf.defaultProfile;
1202
+ const question = all ? "Remove ALL stored profiles?" : `Remove profile '${name}'?`;
1203
+ if (!args.flags.has("yes") && !await deps.confirm(question)) {
1204
+ deps.write("Cancelled.");
1205
+ return 1;
1206
+ }
1207
+ if (all) {
1208
+ deleteCredentialsFile(deps.credentialsPath);
1209
+ deps.write("All profiles removed.");
1210
+ return 0;
1211
+ }
1212
+ const existed = cf.profiles[name] !== void 0;
1213
+ await deleteProfile(name, deps.credentialsPath);
1214
+ deps.write(existed ? `Profile '${name}' removed.` : `No profile named '${name}'.`);
1215
+ return existed ? 0 : 1;
1216
+ }
1217
+ async function runCli(argv, deps) {
1218
+ const args = parseArgs(argv);
1219
+ const empty = Object.entries(args.values).filter(([, value]) => value !== void 0 && value.trim() === "").map(([name]) => `--${name}`);
1220
+ if (args.unknown.length > 0 || args.missingValue.length > 0 || empty.length > 0) {
1221
+ for (const flag of args.unknown) {
1222
+ deps.writeError(`Unknown option: ${flag}`);
1223
+ }
1224
+ for (const flag of args.missingValue) {
1225
+ deps.writeError(`Option ${flag} needs a value.`);
1226
+ }
1227
+ for (const flag of empty) {
1228
+ deps.writeError(`Option ${flag} needs a non-empty value.`);
1229
+ }
1230
+ deps.writeError(USAGE);
1231
+ return 2;
1232
+ }
1233
+ if (args.flags.has("help") || args.command === "" || args.command === "help") {
1234
+ deps.write(USAGE);
1235
+ return args.command === "" && !args.flags.has("help") ? 2 : 0;
1236
+ }
1237
+ let args2 = args;
1238
+ if (args.command === "auth") {
1239
+ const next = args.positionals[0];
1240
+ args2 = { ...args, command: next ?? "", positionals: args.positionals.slice(1) };
1241
+ if (args2.command === "") {
1242
+ deps.write(USAGE);
1243
+ return 2;
1244
+ }
1245
+ }
1246
+ try {
1247
+ switch (args2.command) {
1248
+ case "login":
1249
+ return await cmdLogin(deps, args2);
1250
+ case "refresh":
1251
+ return await cmdRefresh(deps, args2);
1252
+ case "status":
1253
+ return cmdStatus(deps, args2);
1254
+ case "use":
1255
+ return await cmdUse(deps, args2);
1256
+ case "logout":
1257
+ return await cmdLogout(deps, args2);
1258
+ default:
1259
+ deps.writeError(`Unknown command: ${args2.command}`);
1260
+ deps.writeError(USAGE);
1261
+ return 2;
1262
+ }
1263
+ } catch (e) {
1264
+ deps.writeError(excMessage(e));
1265
+ return 1;
1266
+ }
1267
+ }
1268
+
1269
+ // src/cli.ts
1270
+ async function confirm(question) {
1271
+ if (!process.stdin.isTTY) {
1272
+ process.stderr.write("Refusing to prompt on a non-interactive stdin. Re-run with --yes.\n");
1273
+ return false;
1274
+ }
1275
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1276
+ try {
1277
+ const answer = await rl.question(`${question} [y/N] `);
1278
+ return /^y(es)?$/i.test(answer.trim());
1279
+ } finally {
1280
+ rl.close();
1281
+ }
1282
+ }
1283
+ var code = await runCli(process.argv.slice(2), {
1284
+ write: (line) => process.stdout.write(`${line}
1285
+ `),
1286
+ writeError: (line) => process.stderr.write(`${line}
1287
+ `),
1288
+ confirm,
1289
+ openBrowser,
1290
+ login,
1291
+ refresh
1292
+ });
1293
+ process.exitCode = code;
1294
+ //# sourceMappingURL=cli.js.map