@oddessentials/agent-guild 0.1.1 → 0.3.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.
@@ -19,6 +19,10 @@ const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
19
19
 
20
20
  export class UsageError extends Error {}
21
21
 
22
+ function notSignedIn(message) {
23
+ return Object.assign(new UsageError(message), { notSignedIn: true });
24
+ }
25
+
22
26
  function shortPath(file) {
23
27
  const home = os.homedir();
24
28
  return file.startsWith(home) ? `~${file.slice(home.length)}` : file;
@@ -112,7 +116,7 @@ export async function readClaudeCredentials({
112
116
  try {
113
117
  raw = await fs.promises.readFile(file, 'utf8');
114
118
  } catch {
115
- throw new UsageError(`Claude Code is not signed in on this machine (no ${keychain ? 'keychain item or ' : ''}${shortPath(file)})`);
119
+ throw notSignedIn(`Claude Code is not signed in on this machine (no ${keychain ? 'keychain item or ' : ''}${shortPath(file)})`);
116
120
  }
117
121
  }
118
122
  let creds;
@@ -195,7 +199,7 @@ export async function readCodexCredentials({ file = codexAuthFile() } = {}) {
195
199
  try {
196
200
  raw = await fs.promises.readFile(file, 'utf8');
197
201
  } catch {
198
- throw new UsageError(`Codex CLI is not signed in on this machine (no ${shortPath(file)})`);
202
+ throw notSignedIn(`Codex CLI is not signed in on this machine (no ${shortPath(file)})`);
199
203
  }
200
204
  let auth;
201
205
  try { auth = JSON.parse(raw); } catch { throw new UsageError('Codex CLI credentials could not be parsed'); }
@@ -260,11 +264,37 @@ export function geminiCredentialsFile(env = process.env) {
260
264
  return path.join(env.GEMINI_CLI_HOME || os.homedir(), '.gemini', 'oauth_creds.json');
261
265
  }
262
266
 
267
+ export function geminiKeychainFile(env = process.env) {
268
+ return path.join(env.GEMINI_CLI_HOME || os.homedir(), '.gemini', 'gemini-credentials.json');
269
+ }
270
+
271
+ export function geminiFileKey({ hostname = os.hostname(), username = os.userInfo().username } = {}) {
272
+ return crypto.scryptSync(GEMINI_KEYCHAIN_SERVICE, `${hostname}-${username}-gemini-cli`, 32);
273
+ }
274
+
263
275
  /**
264
- * Gemini CLI keeps its OAuth token in the OS keychain (service
265
- * "gemini-cli-oauth", account "main-account") and, before it did, in
266
- * oauth_creds.json. Its encrypted-file fallback cannot be read from here.
276
+ * The item Gemini CLI keeps in its own encrypted file when it does not use
277
+ * the OS keychain: AES-256-GCM as iv:tag:ciphertext in hex, over a JSON
278
+ * map of service to account to secret.
267
279
  */
280
+ export async function readGeminiFileKeychain(file, { key = geminiFileKey() } = {}) {
281
+ let raw;
282
+ try {
283
+ raw = await fs.promises.readFile(file, 'utf8');
284
+ } catch {
285
+ return null;
286
+ }
287
+ try {
288
+ const [iv, tag, encrypted] = raw.trim().split(':').map((part) => Buffer.from(part, 'hex'));
289
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv, { authTagLength: 16 });
290
+ decipher.setAuthTag(tag);
291
+ const json = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
292
+ return JSON.parse(json)?.[GEMINI_KEYCHAIN_SERVICE]?.[GEMINI_KEYCHAIN_ACCOUNT] ?? null;
293
+ } catch {
294
+ throw new UsageError(`Gemini CLI credentials file ${shortPath(file)} could not be decrypted`);
295
+ }
296
+ }
297
+
268
298
  export function geminiKeychainLookup(platform) {
269
299
  if (platform === 'darwin') return { file: 'security', args: ['find-generic-password', '-s', GEMINI_KEYCHAIN_SERVICE, '-a', GEMINI_KEYCHAIN_ACCOUNT, '-w'] };
270
300
  // keytar stores libsecret items with the attributes "service" and "account".
@@ -272,18 +302,54 @@ export function geminiKeychainLookup(platform) {
272
302
  return null;
273
303
  }
274
304
 
275
- function readGeminiKeychainItem(platform) {
305
+ /**
306
+ * What the OS keychain holds for Gemini CLI: the item, or that it is
307
+ * absent, that there is no keychain to ask (so the tool keeps its own
308
+ * encrypted file instead), or that it is one this manager cannot read.
309
+ */
310
+ export async function readGeminiKeychainItem(platform) {
276
311
  const spec = geminiKeychainLookup(platform);
277
- if (!spec) return Promise.resolve(null);
278
- return runSpec(spec, { timeoutMs: 30000 }).then((r) => r.stdout, () => null);
312
+ if (!spec) return { status: platform === 'win32' ? 'unreadable' : 'unavailable' };
313
+ try {
314
+ const { stdout } = await runSpec(spec, { timeoutMs: 30000 });
315
+ return stdout.trim() ? { status: 'found', item: stdout } : { status: 'absent' };
316
+ } catch (err) {
317
+ // security exits 44 for a missing item; secret-tool exits 1 for one and
318
+ // says why on stderr when it has no Secret Service at all.
319
+ if (platform === 'darwin' && err.code === 44) return { status: 'absent' };
320
+ if (platform === 'linux' && err.code === 1 && !String(err.stderr || '').trim()) return { status: 'absent' };
321
+ return { status: 'unavailable' };
322
+ }
279
323
  }
280
324
 
325
+ /** Gemini CLI's own storage choice, read from the environment the tool runs with. */
326
+ export function geminiStorageMode(env = process.env) {
327
+ return { encrypted: env.GEMINI_FORCE_ENCRYPTED_FILE_STORAGE === 'true', fileStorage: env.GEMINI_FORCE_FILE_STORAGE === 'true' };
328
+ }
329
+
330
+ /**
331
+ * Reads the sign-in from where Gemini CLI keeps it: oauth_creds.json, or
332
+ * with GEMINI_FORCE_ENCRYPTED_FILE_STORAGE the OS keychain item, or its
333
+ * encrypted file when GEMINI_FORCE_FILE_STORAGE is set or there is no
334
+ * keychain. An absent item falls back to oauth_creds.json, as the tool
335
+ * itself migrates it from there.
336
+ */
281
337
  export async function readGeminiCredentials({
282
338
  file = geminiCredentialsFile(),
339
+ keychainFile = geminiKeychainFile(),
283
340
  platform = process.platform,
341
+ encrypted = false,
342
+ fileStorage = false,
284
343
  readKeychain = readGeminiKeychainItem,
344
+ readFileKeychain = readGeminiFileKeychain,
285
345
  } = {}) {
286
- const raw = await readKeychain(platform);
346
+ let raw = null;
347
+ if (encrypted) {
348
+ const keychain = fileStorage ? { status: 'unavailable' } : await readKeychain(platform);
349
+ if (keychain.status === 'found') raw = keychain.item;
350
+ else if (keychain.status === 'unavailable') raw = await readFileKeychain(keychainFile);
351
+ else if (keychain.status === 'unreadable') throw new UsageError('Gemini CLI keeps its sign-in in the Windows Credential Manager, which cannot be read from here');
352
+ }
287
353
  if (raw && raw.trim()) {
288
354
  let item;
289
355
  try { item = JSON.parse(raw); } catch { throw new UsageError('Gemini CLI credentials could not be parsed'); }
@@ -295,7 +361,7 @@ export async function readGeminiCredentials({
295
361
  try {
296
362
  legacy = JSON.parse(await fs.promises.readFile(file, 'utf8'));
297
363
  } catch {
298
- throw new UsageError(`Gemini CLI is not signed in on this machine (no "${GEMINI_KEYCHAIN_SERVICE}" keychain item or ${shortPath(file)})`);
364
+ throw notSignedIn(`Gemini CLI is not signed in on this machine (no "${GEMINI_KEYCHAIN_SERVICE}" keychain item or ${shortPath(file)})`);
299
365
  }
300
366
  if (typeof legacy?.access_token !== 'string' || !legacy.access_token) throw new UsageError('Gemini CLI credentials could not be parsed');
301
367
  const client = typeof legacy.client_id === 'string' && typeof legacy.client_secret === 'string'
@@ -471,28 +537,35 @@ export class UsageMonitor {
471
537
  this.gemini = new Map();
472
538
  }
473
539
 
474
- /** Snapshots for every provider that has a usage source. */
540
+ /** Snapshots for every account of every provider that has a usage source. */
475
541
  all() {
476
- return Promise.all(this.registry.providers.filter((p) => p.usage).map((p) => this.snapshot(p)));
542
+ const jobs = [];
543
+ for (const provider of this.registry.providers) {
544
+ if (!provider.usage) continue;
545
+ for (const account of this.registry.accountsFor(provider)) jobs.push(this.snapshot(provider, account));
546
+ }
547
+ return Promise.all(jobs);
477
548
  }
478
549
 
479
- snapshot(provider) {
480
- const entry = this.cache.get(provider.id);
550
+ snapshot(provider, account = this.registry.account(provider)) {
551
+ const key = `${provider.id}\0${account.id}`;
552
+ const entry = this.cache.get(key);
481
553
  const now = Date.now();
482
554
  if (entry?.inflight) return entry.inflight;
483
555
  if (entry && now - entry.at < entry.ttl) return Promise.resolve(entry.snapshot);
484
- const inflight = this._fetch(provider).then((snapshot) => {
556
+ const inflight = this._fetch(provider, account, key).then((snapshot) => {
485
557
  const ttl = snapshot.rateLimited ? RATE_LIMITED_TTL_MS : this.ttlMs;
486
- this.cache.set(provider.id, { snapshot, at: Date.now(), ttl });
558
+ this.cache.set(key, { snapshot, at: Date.now(), ttl });
487
559
  return snapshot;
488
560
  });
489
- this.cache.set(provider.id, { ...entry, inflight });
561
+ this.cache.set(key, { ...entry, inflight });
490
562
  return inflight;
491
563
  }
492
564
 
493
- async _fetch(provider) {
494
- const base = { providerId: provider.id, plan: null, windows: [], credits: null, fetchedAt: new Date().toISOString(), error: null };
495
- const env = { ...this.env, ...provider.env };
565
+ async _fetch(provider, account, key) {
566
+ const base = { providerId: provider.id, accountId: account.id, plan: null, windows: [], credits: null, signedIn: null, fetchedAt: new Date().toISOString(), error: null };
567
+ const env = { ...this.env, ...provider.env, ...account.env };
568
+ let signedIn = null;
496
569
  try {
497
570
  let result;
498
571
  if (provider.usage === 'claude') {
@@ -501,16 +574,24 @@ export class UsageMonitor {
501
574
  keychain: this.platform === 'darwin',
502
575
  service: claudeKeychainService(env),
503
576
  });
577
+ signedIn = true;
504
578
  result = await fetchClaudeUsage({ ...creds, version: this.registry.versions.get(provider.id)?.installed, fetchImpl: this.fetchImpl });
505
579
  } else if (provider.usage === 'codex') {
506
580
  const creds = await this.readers.codex({ file: codexAuthFile(env) });
581
+ signedIn = true;
507
582
  result = await fetchCodexUsage({ ...creds, fetchImpl: this.fetchImpl });
508
583
  } else if (provider.usage === 'gemini') {
509
- const creds = await this.readers.gemini({ file: geminiCredentialsFile(env), platform: this.platform });
584
+ const creds = await this.readers.gemini({
585
+ file: geminiCredentialsFile(env),
586
+ keychainFile: geminiKeychainFile(env),
587
+ platform: this.platform,
588
+ ...geminiStorageMode(env),
589
+ });
590
+ signedIn = true;
510
591
  // The refreshed token, project and plan belong to one sign-in; a new
511
592
  // sign-in (another account, or the same one again) starts over.
512
593
  const signIn = creds.refreshToken || creds.accessToken;
513
- const cached = this.gemini.get(provider.id);
594
+ const cached = this.gemini.get(key);
514
595
  const known = cached?.signIn === signIn ? cached : {};
515
596
  const fresh = known.token && known.token.expiresAt > Date.now() + 60000 ? known.token : null;
516
597
  const { plan, windows, project, token } = await fetchGeminiUsage({
@@ -521,15 +602,15 @@ export class UsageMonitor {
521
602
  version: this.registry.versions.get(provider.id)?.installed,
522
603
  fetchImpl: this.fetchImpl,
523
604
  });
524
- this.gemini.set(provider.id, { signIn, project, token, plan: plan ?? known.plan ?? null });
605
+ this.gemini.set(key, { signIn, project, token, plan: plan ?? known.plan ?? null });
525
606
  result = { plan: plan ?? known.plan ?? null, windows };
526
607
  } else {
527
608
  result = await commandUsage(provider.usage, env, this.platform);
528
609
  }
529
- return { ...base, ...result };
610
+ return { ...base, signedIn, ...result };
530
611
  } catch (err) {
531
612
  const message = err instanceof UsageError ? err.message : `usage check failed: ${err.name === 'TimeoutError' ? 'timed out' : err.message}`;
532
- return { ...base, error: message, ...(err.rateLimited ? { rateLimited: true } : {}) };
613
+ return { ...base, signedIn: err.notSignedIn ? false : signedIn, error: message, ...(err.rateLimited ? { rateLimited: true } : {}) };
533
614
  }
534
615
  }
535
616
  }