dsh-keys-manager 0.2.6 → 0.2.8

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/lib/index.js CHANGED
@@ -21,6 +21,8 @@ import { KEY_LIMIT, TEST_SUCCESS_FINISH_KINDS, accountRef, applyFailureCooldown,
21
21
  import { signInCapable, signInProvider } from './oauth/providers.js';
22
22
  import { SignInCancelledError, runSignIn } from './oauth/signin.js';
23
23
  import { EXTRA_PROVIDER_MAP, EXTRA_PROVIDERS } from './providers.js';
24
+ import { QuotaCache } from './quota/cache.js';
25
+ import { resolveQuota } from './quota/providers.js';
24
26
  import { KeysManagerStore, ensureStateFile, statePath } from './store.js';
25
27
  export const name = 'keys-manager';
26
28
  export const inject = ['llm', 'credentials', 'typert', 'authorization'];
@@ -256,6 +258,10 @@ const INVOCATIONS = [
256
258
  // cursor or binding writes) so a user can tell a bad credential from a bad
257
259
  // route without waiting for a chat failure.
258
260
  endpoint('testKey', ['provider', 'keyId']),
261
+ // Pull-only plan usage (issue #22, D2): the card asks, the host probes the
262
+ // managed rows of that one provider and answers with the refreshed state.
263
+ // Never runs on the getState path, never writes cooldown or failure state.
264
+ endpoint('quotaRefresh', ['provider']),
259
265
  // Transport accounts (llm-omp-transports/<route>): managed beside the pi-ai
260
266
  // pool, never through it. The sign-in reuses the same attempt machinery and
261
267
  // is polled through `accountAttempt` above.
@@ -461,7 +467,7 @@ function missingHeaders(declared, stored) {
461
467
  return missing;
462
468
  }
463
469
  /** Public, secret-free key row. */
464
- function publicKey(key, now, projectedAccountId) {
470
+ function publicKey(key, now, projectedAccountId, quota) {
465
471
  return {
466
472
  id: key.id,
467
473
  alias: key.alias,
@@ -492,6 +498,8 @@ function publicKey(key, now, projectedAccountId) {
492
498
  : {}),
493
499
  }
494
500
  : {}),
501
+ // Additive and pull-only: absent until a quota refresh ran for this row.
502
+ ...(quota === undefined ? {} : { quota }),
495
503
  };
496
504
  }
497
505
  /**
@@ -570,15 +578,17 @@ const DEVIN_ROUTE = 'devin';
570
578
  * The catalog accessor each transport route ships in the transports package.
571
579
  *
572
580
  * One exported function per route, the `cursorCatalogModels`/`devinCatalogModels`
573
- * shape. An installed transport build may predate the Google pair's exports, and
574
- * `factory-droid` is probed while its route stays unshipped (`I-000253`), so a
575
- * probe can legitimately find nothing.
581
+ * shape. An installed transport build may predate a route's export (every route
582
+ * added after the installed build, including the Google pair, `factory-droid`
583
+ * and the GitLab pair), so a probe can legitimately find nothing.
576
584
  */
577
585
  const TRANSPORT_CATALOG_EXPORTS = Object.freeze({
578
586
  [DEVIN_ROUTE]: 'devinCatalogModels',
579
587
  'google-gemini-cli': 'googleGeminiCliCatalogModels',
580
588
  'google-antigravity': 'googleAntigravityCatalogModels',
581
589
  'factory-droid': 'factoryDroidCatalogModels',
590
+ 'gitlab-duo': 'gitlabDuoCatalogModels',
591
+ 'gitlab-duo-agent': 'gitlabDuoAgentCatalogModels',
582
592
  });
583
593
  /**
584
594
  * The catalog a transport route advertises to its model picker.
@@ -1065,6 +1075,17 @@ export class KeysManagerService {
1065
1075
  * channel.
1066
1076
  */
1067
1077
  unattributedRequests = new Map();
1078
+ /**
1079
+ * Plan-usage snapshots per provider (issue #22, D1). In-memory only and
1080
+ * never persisted: a restart loses them and the next card open re-probes.
1081
+ * One cache per provider so single-flight and backoff are scoped to it.
1082
+ */
1083
+ quotaCaches = new Map();
1084
+ /**
1085
+ * Test/embedding seam for the quota probes, mirroring `signInAdapter`.
1086
+ * Production leaves it undefined and the probes use the platform `fetch`.
1087
+ */
1088
+ quotaFetch;
1068
1089
  /** Channels whose lost-subscription warning already fired (warn once). */
1069
1090
  subscriptionLostWarnings = new Set();
1070
1091
  /** Disposer for the `authorization/settled` subscription. */
@@ -2353,21 +2374,19 @@ export class KeysManagerService {
2353
2374
  return this.transportRemovals.get(route) ?? 0;
2354
2375
  }
2355
2376
  /**
2356
- * Explain a registered transport flow that has no catalog.
2377
+ * Record that a registered transport flow has no catalog.
2357
2378
  *
2358
2379
  * An empty list is also the legitimate all-models state, so the only honest
2359
- * way to tell a stale transport build apart is to say so. The message rides
2360
- * every read whose accessor is missing — a once-only gate would leave a
2361
- * remounted or reloaded picker unexplained — while `catalogReports` keeps
2362
- * the state warning to one push per route.
2380
+ * way to tell a stale transport build apart is to say so. The read answers a
2381
+ * stable marker (never host copy — the picker owns the localized wording),
2382
+ * while `catalogReports` keeps the human-readable state warning to one push
2383
+ * per route.
2363
2384
  */
2364
2385
  reportMissingCatalog(route) {
2365
- const message = `The installed dsh-llm-omp-transports build registers "${route}" but ships no catalog for it; the model list stays empty until the transport package is rebuilt or upgraded`;
2366
- if (!this.catalogReports.has(route)) {
2367
- this.catalogReports.add(route);
2368
- this.pushWarning(message);
2369
- }
2370
- return message;
2386
+ if (this.catalogReports.has(route))
2387
+ return;
2388
+ this.catalogReports.add(route);
2389
+ this.pushWarning(`The installed dsh-llm-omp-transports build registers "${route}" but ships no catalog for it; the model list stays empty until the transport package is rebuilt or upgraded`);
2371
2390
  }
2372
2391
  /**
2373
2392
  * Remote: read one transport route's catalog and configured allow-list.
@@ -2381,14 +2400,17 @@ export class KeysManagerService {
2381
2400
  async transportModels(route) {
2382
2401
  this.assertTransportRoute(route);
2383
2402
  const configured = this.transportModelIds(route);
2384
- let warning;
2385
- const catalog = transportCatalogOf(route, missing => { warning = this.reportMissingCatalog(missing); });
2403
+ let missingCatalog = false;
2404
+ const catalog = transportCatalogOf(route, missing => {
2405
+ missingCatalog = true;
2406
+ this.reportMissingCatalog(missing);
2407
+ });
2386
2408
  // A settings profile can outlive a catalog id; the picker renders the
2387
2409
  // catalog, so an unknown id would count toward {n} of {total} while
2388
2410
  // matching no checkbox and failing every save.
2389
2411
  const known = new Set(catalog.map(row => row.id));
2390
2412
  const models = configured.filter(id => known.has(id));
2391
- return warning === undefined ? { catalog, models } : { catalog, models, warning };
2413
+ return missingCatalog ? { catalog, models, missingCatalog: true } : { catalog, models };
2392
2414
  }
2393
2415
  /**
2394
2416
  * Remote: replace one transport route's model allow-list.
@@ -6269,64 +6291,17 @@ export class KeysManagerService {
6269
6291
  for (const entry of directory) {
6270
6292
  if (entry.provider === 'deepseek-account' || entry.settingsNs === 'deepseek-account' || entry.provider.startsWith('deepseek-account'))
6271
6293
  continue;
6272
- const namespace = this.namespace(descriptor, entry.settingsNs);
6273
- const profile = namespace === undefined ? undefined : asProfile(getPath(namespace.value, entry.settingsPath));
6274
- const managed = this.store.provider(entry.provider);
6275
- const extra = EXTRA_PROVIDER_MAP.get(entry.provider);
6276
- // A transport route names its own credential record and registers no
6277
- // settings namespace, so the profile/capability read below can only
6278
- // describe the route wrongly: it is neither a DSH route nor key-pool
6279
- // capable, and it is never adoptable.
6280
- const transport = entry.settingsNs === TRANSPORT_CREDENTIAL_SCOPE;
6281
- const oauthFlow = this.oauthFlowAvailable(entry.provider);
6282
- const signIn = signInCapable(entry.provider);
6283
- const caps = capabilityOf(entry, profile, oauthFlow, signIn);
6284
- const support = { supported: caps.keys, ...(caps.reason === undefined ? {} : { reason: caps.reason }) };
6285
- const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
6286
- const apiKeyEnv = profile !== undefined && typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv : null;
6287
- const binding = managed === undefined ? undefined : this.bindingState(managed, descriptor);
6288
- const bindingHealthy = binding === 'healthy' ? true : binding === 'mismatch' ? false : undefined;
6289
- const projectedAccountId = managed === undefined ? null : this.oauthOwnerFor(managed.provider);
6290
- const keys = managed !== undefined ? managed.keys.map(key => publicKey(key, now, projectedAccountId)) : [];
6291
- const warning = binding === 'mismatch'
6292
- ? 'The provider profile no longer points at Keys Manager. Re-adopt it after releasing it, or repair the provider in Models.'
6293
- : undefined;
6294
- const models = profile !== undefined ? normalizeModels(profile.models) : extra?.models ?? managed?.models ?? [];
6295
- views.push({
6296
- provider: entry.provider,
6297
- displayName: extra?.name ?? entry.displayName ?? entry.provider,
6298
- source: extra !== undefined ? 'extra' : 'dsh',
6299
- origin: extra !== undefined || transport ? 'plugin' : entry.declared === true ? 'custom' : 'dsh',
6300
- managed: managed !== undefined,
6301
- createdProfile: managed?.createdProfile ?? false,
6302
- configured: active.has(entry.provider) || profile !== undefined,
6303
- active: active.has(entry.provider),
6304
- supported: transport ? false : support.supported,
6305
- ...(transport
6306
- ? { reason: 'This route is served by a transport plugin; manage its account from this provider card.' }
6307
- : support.reason === undefined ? {} : { reason: support.reason }),
6308
- accountSupported: transport ? false : accountSupport.supported,
6309
- ...(transport ? { transport: true } : {}),
6310
- settingsNs: entry.settingsNs,
6311
- settingsPath: [...entry.settingsPath],
6312
- apiKeyEnv,
6313
- brokerRef: managed?.brokerRef ?? null,
6314
- ...(bindingHealthy === undefined ? {} : { bindingHealthy }),
6315
- extra: extra !== undefined,
6316
- extraId: extra?.id ?? managed?.extraId ?? null,
6317
- api: profile?.api ?? extra?.api ?? managed?.api ?? null,
6318
- baseURL: profile?.baseURL ?? extra?.baseURL ?? entry.defaultBaseURL ?? managed?.baseURL ?? null,
6319
- env: [...(extra?.env ?? entry.nativeAuth?.env ?? [])],
6320
- defaultBaseURL: entry.defaultBaseURL ?? extra?.baseURL ?? null,
6321
- nativeAuth: entry.nativeAuth === undefined ? null : { env: [...entry.nativeAuth.env], oauth: entry.nativeAuth.oauth },
6322
- models,
6323
- keyCount: keys.length,
6324
- healthyKeyCount: keys.filter(key => key.status === 'active').length,
6325
- status: managed !== undefined ? statusOfProvider(managed.keys, now) : 'unmanaged',
6326
- keys,
6327
- ...(warning === undefined ? {} : { warning }),
6328
- ...this.unattributedView(entry.provider),
6329
- });
6294
+ views.push(this.providerViewOf(entry, descriptor, active, now));
6295
+ seen.add(entry.provider);
6296
+ }
6297
+ // A transport route whose credential record is absent is withdrawn from
6298
+ // the directory by the transports plugin (signed-in routes only), but its
6299
+ // Keys Manager card — and the sign-in button on it — must stay. Union the
6300
+ // package's static list in for anything the directory no longer lists.
6301
+ for (const entry of transportModule.TRANSPORT_PROVIDERS) {
6302
+ if (seen.has(entry.provider))
6303
+ continue;
6304
+ views.push(this.providerViewOf(entry, descriptor, active, now));
6330
6305
  seen.add(entry.provider);
6331
6306
  }
6332
6307
  for (const extra of EXTRA_PROVIDERS) {
@@ -6335,7 +6310,7 @@ export class KeysManagerService {
6335
6310
  const managed = this.store.provider(extra.id);
6336
6311
  const binding = managed === undefined ? undefined : this.bindingState(managed, descriptor);
6337
6312
  const projectedAccountId = managed === undefined ? null : this.oauthOwnerFor(managed.provider);
6338
- const keys = managed !== undefined ? managed.keys.map(key => publicKey(key, now, projectedAccountId)) : [];
6313
+ const keys = managed !== undefined ? managed.keys.map(key => publicKey(key, now, projectedAccountId, this.quotaViewFor(managed.provider, key.id))) : [];
6339
6314
  views.push({
6340
6315
  provider: extra.id,
6341
6316
  displayName: extra.name,
@@ -6375,7 +6350,7 @@ export class KeysManagerService {
6375
6350
  if (seen.has(managed.provider))
6376
6351
  continue;
6377
6352
  const projectedAccountId = this.oauthOwnerFor(managed.provider);
6378
- const keys = managed.keys.map(key => publicKey(key, now, projectedAccountId));
6353
+ const keys = managed.keys.map(key => publicKey(key, now, projectedAccountId, this.quotaViewFor(managed.provider, key.id)));
6379
6354
  const binding = this.bindingState(managed, descriptor);
6380
6355
  views.push({
6381
6356
  provider: managed.provider,
@@ -6456,6 +6431,167 @@ export class KeysManagerService {
6456
6431
  this.refreshTransportAccountsIfIdle();
6457
6432
  return this.buildState();
6458
6433
  }
6434
+ /**
6435
+ * Remote: probe one provider's plan usage and answer the refreshed state.
6436
+ *
6437
+ * Pull-only (D2) and observation-only: a slow or failing vendor call can
6438
+ * change nothing but a row's `quota` field. Selection, cooldown, cursor,
6439
+ * sticky bindings and the durable document are untouched, and nothing is
6440
+ * written to disk.
6441
+ */
6442
+ async quotaRefresh(provider) {
6443
+ if (typeof provider !== 'string' || provider.length === 0)
6444
+ throw new TypeError('provider is required');
6445
+ // Own-property lookup: `store.provider` indexes a plain object, so a
6446
+ // prototype key would answer a function instead of a record.
6447
+ const record = Object.hasOwn(this.store.providers, provider) ? this.store.provider(provider) : undefined;
6448
+ if (record === undefined)
6449
+ return this.buildState();
6450
+ const cache = this.quotaCache(provider);
6451
+ // The cache classifies probe failures; allSettled is the second line of
6452
+ // defence so one rejected row can never reject the RPC.
6453
+ await Promise.allSettled(record.keys.map(key => this.refreshQuotaRow(provider, cache, key)));
6454
+ return this.buildState();
6455
+ }
6456
+ /** One provider's quota cache, created on first use. */
6457
+ quotaCache(provider) {
6458
+ const existing = this.quotaCaches.get(provider);
6459
+ if (existing !== undefined)
6460
+ return existing;
6461
+ const cache = new QuotaCache();
6462
+ this.quotaCaches.set(provider, cache);
6463
+ return cache;
6464
+ }
6465
+ /**
6466
+ * Refresh one row, resolving its credential first. TTL, backoff and
6467
+ * single-flight live in the cache, so two concurrent refreshes of the same
6468
+ * row share one probe.
6469
+ */
6470
+ async refreshQuotaRow(provider, cache, key) {
6471
+ const credential = await this.quotaCredential(key);
6472
+ await cache.get(provider, key.id, async () => {
6473
+ if (credential === undefined) {
6474
+ // An unreadable grant is an account problem, not "this plan has no
6475
+ // usage API": an OAuth row says `unauthorized` so the card can offer
6476
+ // a re-sign-in, an API-key row without a value says `absent`.
6477
+ return {
6478
+ status: key.kind === 'oauth' ? 'unauthorized' : 'absent',
6479
+ fetchedAt: 0,
6480
+ windows: [],
6481
+ reason: 'no readable credential',
6482
+ };
6483
+ }
6484
+ return resolveQuota(provider, {
6485
+ token: credential.token,
6486
+ ...(credential.accountId === undefined ? {} : { accountId: credential.accountId }),
6487
+ ...(this.quotaFetch === undefined ? {} : { fetch: this.quotaFetch }),
6488
+ });
6489
+ });
6490
+ }
6491
+ /** The credential one row's plan usage is read with, or undefined. */
6492
+ async quotaCredential(key) {
6493
+ if (key.kind === 'oauth') {
6494
+ const grantRef = key.oauth?.grantRef;
6495
+ const records = this.credentialRecords();
6496
+ if (grantRef === undefined || grantRef.length === 0 || records === undefined)
6497
+ return undefined;
6498
+ try {
6499
+ const record = await records.readRecord(grantRef);
6500
+ if (record === undefined || record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
6501
+ return undefined;
6502
+ const accountId = key.oauth?.accountId;
6503
+ return { token: record.payload.access, ...(accountId === undefined ? {} : { accountId }) };
6504
+ }
6505
+ catch {
6506
+ return undefined;
6507
+ }
6508
+ }
6509
+ const probe = await this.probeKey(key.ref);
6510
+ return probe.hit === undefined ? undefined : { token: probe.hit.value };
6511
+ }
6512
+ /** Project the cached quota of one row; a pure memory read, never a probe. */
6513
+ quotaViewFor(provider, keyId) {
6514
+ const snapshot = this.quotaCaches.get(provider)?.peek(provider, keyId);
6515
+ if (snapshot === undefined)
6516
+ return undefined;
6517
+ // Explicit projection: `reason` is a host-side diagnostic and must not
6518
+ // cross the RPC, and `windows` is copied so a caller cannot mutate cache.
6519
+ return {
6520
+ status: snapshot.status,
6521
+ fetchedAt: snapshot.fetchedAt,
6522
+ ...(snapshot.stale === true ? { stale: true } : {}),
6523
+ windows: snapshot.windows.map(window => ({
6524
+ id: window.id,
6525
+ usedFraction: window.usedFraction,
6526
+ resetsAt: window.resetsAt,
6527
+ })),
6528
+ };
6529
+ }
6530
+ /**
6531
+ * Build one provider view from a directory entry (live or the transports
6532
+ * package's static list, which unions the signed-out transport routes back
6533
+ * in). Extracted from `buildState` so both sources share one construction.
6534
+ */
6535
+ providerViewOf(entry, descriptor, active, now) {
6536
+ const namespace = this.namespace(descriptor, entry.settingsNs);
6537
+ const profile = namespace === undefined ? undefined : asProfile(getPath(namespace.value, entry.settingsPath));
6538
+ const managed = this.store.provider(entry.provider);
6539
+ const extra = EXTRA_PROVIDER_MAP.get(entry.provider);
6540
+ // A transport route names its own credential record and registers no
6541
+ // settings namespace, so the profile/capability read below can only
6542
+ // describe the route wrongly: it is neither a DSH route nor key-pool
6543
+ // capable, and it is never adoptable.
6544
+ const transport = entry.settingsNs === TRANSPORT_CREDENTIAL_SCOPE;
6545
+ const oauthFlow = this.oauthFlowAvailable(entry.provider);
6546
+ const signIn = signInCapable(entry.provider);
6547
+ const caps = capabilityOf(entry, profile, oauthFlow, signIn);
6548
+ const support = { supported: caps.keys, ...(caps.reason === undefined ? {} : { reason: caps.reason }) };
6549
+ const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
6550
+ const apiKeyEnv = profile !== undefined && typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv : null;
6551
+ const binding = managed === undefined ? undefined : this.bindingState(managed, descriptor);
6552
+ const bindingHealthy = binding === 'healthy' ? true : binding === 'mismatch' ? false : undefined;
6553
+ const projectedAccountId = managed === undefined ? null : this.oauthOwnerFor(managed.provider);
6554
+ const keys = managed !== undefined ? managed.keys.map(key => publicKey(key, now, projectedAccountId, this.quotaViewFor(managed.provider, key.id))) : [];
6555
+ const warning = binding === 'mismatch'
6556
+ ? 'The provider profile no longer points at Keys Manager. Re-adopt it after releasing it, or repair the provider in Models.'
6557
+ : undefined;
6558
+ const models = profile !== undefined ? normalizeModels(profile.models) : extra?.models ?? managed?.models ?? [];
6559
+ return {
6560
+ provider: entry.provider,
6561
+ displayName: extra?.name ?? entry.displayName ?? entry.provider,
6562
+ source: extra !== undefined ? 'extra' : 'dsh',
6563
+ origin: extra !== undefined || transport ? 'plugin' : entry.declared === true ? 'custom' : 'dsh',
6564
+ managed: managed !== undefined,
6565
+ createdProfile: managed?.createdProfile ?? false,
6566
+ configured: active.has(entry.provider) || profile !== undefined,
6567
+ active: active.has(entry.provider),
6568
+ supported: transport ? false : support.supported,
6569
+ ...(transport
6570
+ ? { reason: 'This route is served by a transport plugin; manage its account from this provider card.' }
6571
+ : support.reason === undefined ? {} : { reason: support.reason }),
6572
+ accountSupported: transport ? false : accountSupport.supported,
6573
+ ...(transport ? { transport: true } : {}),
6574
+ settingsNs: entry.settingsNs,
6575
+ settingsPath: [...entry.settingsPath],
6576
+ apiKeyEnv,
6577
+ brokerRef: managed?.brokerRef ?? null,
6578
+ ...(bindingHealthy === undefined ? {} : { bindingHealthy }),
6579
+ extra: extra !== undefined,
6580
+ extraId: extra?.id ?? managed?.extraId ?? null,
6581
+ api: profile?.api ?? extra?.api ?? managed?.api ?? null,
6582
+ baseURL: profile?.baseURL ?? extra?.baseURL ?? entry.defaultBaseURL ?? managed?.baseURL ?? null,
6583
+ env: [...(extra?.env ?? entry.nativeAuth?.env ?? [])],
6584
+ defaultBaseURL: entry.defaultBaseURL ?? extra?.baseURL ?? null,
6585
+ nativeAuth: entry.nativeAuth === undefined ? null : { env: [...entry.nativeAuth.env], oauth: entry.nativeAuth.oauth },
6586
+ models,
6587
+ keyCount: keys.length,
6588
+ healthyKeyCount: keys.filter(key => key.status === 'active').length,
6589
+ status: managed !== undefined ? statusOfProvider(managed.keys, now) : 'unmanaged',
6590
+ keys,
6591
+ ...(warning === undefined ? {} : { warning }),
6592
+ ...this.unattributedView(entry.provider),
6593
+ };
6594
+ }
6459
6595
  /** Find one directory entry by route id. */
6460
6596
  directoryEntry(provider) {
6461
6597
  return this.ctx.llm.listConfigurableProviders().find(entry => entry.provider === provider);