dsh-keys-manager 0.2.4 → 0.2.6

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
@@ -16,7 +16,10 @@
16
16
  import { AsyncLocalStorage } from 'node:async_hooks';
17
17
  import { createHash, randomBytes } from 'node:crypto';
18
18
  import { CURSOR_ROUTE, cursorCatalogModels } from 'dsh-llm-omp-transports';
19
+ import * as transportModule from 'dsh-llm-omp-transports';
19
20
  import { KEY_LIMIT, TEST_SUCCESS_FINISH_KINDS, accountRef, applyFailureCooldown, bindingKey, classifyOAuthFailure, isSelectable, markKeySuccess, markKeyUsed, normalizeSettings, patchSettings, pickHealthyExcluding, pickRoundRobin, shouldFailover, statusOfKey, statusOfProvider, validateKeyInput, validateKeyPatch, } from './core.js';
21
+ import { signInCapable, signInProvider } from './oauth/providers.js';
22
+ import { SignInCancelledError, runSignIn } from './oauth/signin.js';
20
23
  import { EXTRA_PROVIDER_MAP, EXTRA_PROVIDERS } from './providers.js';
21
24
  import { KeysManagerStore, ensureStateFile, statePath } from './store.js';
22
25
  export const name = 'keys-manager';
@@ -177,7 +180,9 @@ function promptView(prompt) {
177
180
  && typeof entry.id === 'string'
178
181
  && typeof entry.label === 'string')
179
182
  : undefined;
180
- const kind = prompt.kind === 'secret' || prompt.kind === 'select' ? prompt.kind : 'text';
183
+ const kind = prompt.kind === 'secret' || prompt.kind === 'select' || prompt.kind === 'manual-code'
184
+ ? prompt.kind
185
+ : 'text';
181
186
  return {
182
187
  kind,
183
188
  message: prompt.message,
@@ -242,6 +247,7 @@ const INVOCATIONS = [
242
247
  // duplicating the account.
243
248
  endpoint('beginAccountLogin', ['provider', 'alias', 'targetAccountId']),
244
249
  endpoint('answerAccountPrompt', ['attemptId', 'value']),
250
+ endpoint('cancelAccountLogin', ['attemptId']),
245
251
  endpoint('accountAttempt', ['attemptId']),
246
252
  endpoint('listAccountAttempts'),
247
253
  endpoint('activateAccount', ['provider', 'accountId']),
@@ -275,6 +281,15 @@ function getPath(value, path) {
275
281
  function asProfile(value) {
276
282
  return value !== null && typeof value === 'object' ? value : undefined;
277
283
  }
284
+ /**
285
+ * Whether a live profile still holds exactly the node a materialized adoption
286
+ * wrote: `models` and nothing else. Any additional field, or a different model
287
+ * list, means a user took the node over.
288
+ */
289
+ function isMaterializedProfile(profile, models) {
290
+ const keys = Object.keys(profile);
291
+ return keys.length === 1 && keys[0] === 'models' && JSON.stringify(profile.models) === JSON.stringify(models);
292
+ }
278
293
  /** Stable broker credential reference for one provider route. */
279
294
  function brokerRefFor(provider) {
280
295
  const stem = provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 34);
@@ -344,6 +359,24 @@ function discoveredModel(model) {
344
359
  inputModalities: model.inputModalities,
345
360
  });
346
361
  }
362
+ /**
363
+ * Normalize one discovery answer for a profile write: unusable and duplicate
364
+ * rows dropped, capped at the same limit discovery itself applies.
365
+ */
366
+ function discoveredModels(discovered) {
367
+ const models = [];
368
+ const seen = new Set();
369
+ for (const model of discovered) {
370
+ const normalized = discoveredModel(model);
371
+ if (normalized === undefined || seen.has(normalized.id))
372
+ continue;
373
+ seen.add(normalized.id);
374
+ models.push(normalized);
375
+ if (models.length >= 60)
376
+ break;
377
+ }
378
+ return models;
379
+ }
347
380
  /** Credential-bearing header names the carrier must never persist as plain settings. */
348
381
  const CREDENTIAL_HEADER_NAMES = new Set(['authorization', 'proxy-authorization', 'cookie', 'api-key', 'apikey', 'x-api-key']);
349
382
  /** Carrier headers are non-secret metadata; a credential-bearing name is refused. */
@@ -475,11 +508,14 @@ function transportGrantOf(record) {
475
508
  const source = payload;
476
509
  if (typeof source.access !== 'string' || source.access.length === 0)
477
510
  return undefined;
478
- if (typeof source.expires !== 'number' || !Number.isFinite(source.expires))
511
+ // No `expires` is the documented static-bearer shape (devin's adapter serves
512
+ // it), so only a PRESENT but unreadable value is a corrupt record.
513
+ if (source.expires !== undefined && (typeof source.expires !== 'number' || !Number.isFinite(source.expires))) {
479
514
  return undefined;
515
+ }
480
516
  return {
481
517
  access: source.access,
482
- expires: source.expires,
518
+ ...(source.expires === undefined ? {} : { expires: source.expires }),
483
519
  ...(typeof source.refresh === 'string' && source.refresh.length > 0 ? { refresh: source.refresh } : {}),
484
520
  ...(typeof source.email === 'string' && source.email.length > 0 ? { email: source.email } : {}),
485
521
  ...(typeof source.accountId === 'string' && source.accountId.length > 0 ? { accountId: source.accountId } : {}),
@@ -495,14 +531,19 @@ function transportGrantOf(record) {
495
531
  * exists while signed out, so the UI can offer the sign-in that writes it.
496
532
  */
497
533
  function transportAccountOf(flow, record, now) {
534
+ const route = flow.key.slice(TRANSPORT_CREDENTIAL_SCOPE.length + 1);
498
535
  const grant = transportGrantOf(record);
499
- const status = grant !== undefined
500
- ? grant.expires > now
501
- ? 'active'
502
- : grant.refresh === undefined ? 'needs-reauth' : 'expired'
503
- : record === undefined ? 'signed-out' : 'needs-reauth';
536
+ const status = grant === undefined
537
+ ? record === undefined ? 'signed-out' : 'needs-reauth'
538
+ : grant.expires === undefined
539
+ // Only the devin resolver serves an expiry-less record; cursor's needs a
540
+ // dated grant and throws on one, so there the row is not usable.
541
+ ? route === DEVIN_ROUTE ? 'active' : 'needs-reauth'
542
+ : grant.expires > now
543
+ ? 'active'
544
+ : grant.refresh === undefined ? 'needs-reauth' : 'expired';
504
545
  return {
505
- id: flow.key.slice(TRANSPORT_CREDENTIAL_SCOPE.length + 1),
546
+ id: route,
506
547
  scope: flow.key,
507
548
  displayName: flow.label,
508
549
  ...(grant?.email === undefined ? {} : { email: grant.email }),
@@ -523,14 +564,46 @@ function transportAccountOf(flow, record, now) {
523
564
  function transportMethodOf(flow) {
524
565
  return flow.methods[0]?.id;
525
566
  }
567
+ /** The `devin` transport route id (its catalog ships with the same package). */
568
+ const DEVIN_ROUTE = 'devin';
569
+ /**
570
+ * The catalog accessor each transport route ships in the transports package.
571
+ *
572
+ * 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.
576
+ */
577
+ const TRANSPORT_CATALOG_EXPORTS = Object.freeze({
578
+ [DEVIN_ROUTE]: 'devinCatalogModels',
579
+ 'google-gemini-cli': 'googleGeminiCliCatalogModels',
580
+ 'google-antigravity': 'googleAntigravityCatalogModels',
581
+ 'factory-droid': 'factoryDroidCatalogModels',
582
+ });
526
583
  /**
527
584
  * The catalog a transport route advertises to its model picker.
528
585
  *
529
- * Only the Cursor route ships a catalog projection today; a route without one
530
- * reports no models rather than borrowing another route's catalog.
586
+ * A route without a catalog projection reports no models rather than borrowing
587
+ * another route's. The catalog is the transport package's own data, not this
588
+ * plugin's, and the installed build may predate these exports. Each accessor is
589
+ * therefore probed on the module namespace instead of imported by name — an
590
+ * absent export yields an empty catalog instead of breaking this plugin's
591
+ * import graph. An empty list is indistinguishable from the legitimate
592
+ * all-models state, so `onMissing` reports it instead of the picker rendering a
593
+ * silent `[]`.
531
594
  */
532
- function transportCatalogOf(route) {
533
- return route === CURSOR_ROUTE ? cursorCatalogModels() : [];
595
+ function transportCatalogOf(route, onMissing) {
596
+ if (route === CURSOR_ROUTE)
597
+ return cursorCatalogModels();
598
+ // Own keys only: a prototype-colliding id ("toString") must take the
599
+ // missing-catalog path, not read an inherited value as an export name.
600
+ const exportName = Object.hasOwn(TRANSPORT_CATALOG_EXPORTS, route) ? TRANSPORT_CATALOG_EXPORTS[route] : undefined;
601
+ const probe = exportName === undefined ? undefined : transportModule[exportName];
602
+ if (typeof probe !== 'function') {
603
+ onMissing?.(route);
604
+ return [];
605
+ }
606
+ return probe();
534
607
  }
535
608
  /** Env names that are a single API-key credential, not an OAuth/federation token. */
536
609
  function isKeyishEnv(name) {
@@ -573,17 +646,20 @@ const NO_OAUTH_FLOW_REASON = 'This provider has no OAuth sign-in flow registered
573
646
  *
574
647
  * `oauthFlow` is the live answer from {@link KeysManagerService.oauthFlowAvailable}
575
648
  * — C6-2 requires an actually-beginable flow, not the catalog flag alone.
649
+ * `signIn` is the second source of the account verdict: this plugin's own
650
+ * in-process sign-in clients (`src/oauth/providers.ts`), which run inside the
651
+ * attempt surface instead of a seam flow.
576
652
  */
577
- function capabilityOf(entry, profile, oauthFlow) {
653
+ function capabilityOf(entry, profile, oauthFlow, signIn = false) {
578
654
  if (entry.error !== undefined)
579
655
  return { keys: false, accounts: false, reason: entry.error };
580
- const accounts = entry.nativeAuth?.oauth === true && oauthFlow;
656
+ const accounts = signIn || (entry.nativeAuth?.oauth === true && oauthFlow);
581
657
  const unsupportedReason = UNSUPPORTED_KEY_POOL_PROVIDERS[entry.provider];
582
658
  if (unsupportedReason !== undefined) {
583
659
  // The table's reason describes the key verdict; when the only possible
584
660
  // capability (accounts) is unavailable too, the flow gap is the truthful
585
661
  // explanation a user needs.
586
- const reason = entry.nativeAuth?.oauth === true && !oauthFlow ? NO_OAUTH_FLOW_REASON : unsupportedReason;
662
+ const reason = !accounts && entry.nativeAuth?.oauth === true && !oauthFlow ? NO_OAUTH_FLOW_REASON : unsupportedReason;
587
663
  return { keys: false, accounts, reason };
588
664
  }
589
665
  if (entry.provider === 'deepseek-official')
@@ -597,8 +673,8 @@ function capabilityOf(entry, profile, oauthFlow) {
597
673
  // key credential at all.
598
674
  if (auth.env.some(isKeyishEnv))
599
675
  return { keys: true, accounts };
600
- if (auth.oauth) {
601
- return oauthFlow
676
+ if (auth.oauth || signIn) {
677
+ return accounts
602
678
  ? { keys: false, accounts: true, reason: 'This provider signs in with an OAuth account; no API key is used' }
603
679
  : { keys: false, accounts: false, reason: NO_OAUTH_FLOW_REASON };
604
680
  }
@@ -617,12 +693,17 @@ function capabilityOf(entry, profile, oauthFlow) {
617
693
  * may mount after this plugin, so availability is never cached at
618
694
  * construction. While the flow list is empty (seam not mounted yet) support
619
695
  * is false; the next state build re-evaluates once flows are enumerable.
696
+ *
697
+ * `signIn` answers before that gate: an in-process client needs no seam flow,
698
+ * so it stays available even while the flow list is empty.
620
699
  */
621
- function accountSupportOf(entry, oauthFlow) {
700
+ function accountSupportOf(entry, oauthFlow, signIn = false) {
622
701
  if (entry === undefined)
623
702
  return { supported: false, reason: 'This provider route is not registered' };
624
703
  if (entry.error !== undefined)
625
704
  return { supported: false, reason: entry.error };
705
+ if (signIn)
706
+ return { supported: true };
626
707
  if (entry.nativeAuth?.oauth !== true)
627
708
  return { supported: false, reason: 'This provider offers no OAuth account sign-in' };
628
709
  if (!oauthFlow)
@@ -668,7 +749,15 @@ export class KeysManagerService {
668
749
  attemptSequence = 0;
669
750
  switches = new Map();
670
751
  warnings = [];
752
+ /** Transport routes already reported as having no shipped catalog. */
753
+ catalogReports = new Set();
671
754
  settings;
755
+ /**
756
+ * Test/embedding seam for the in-process sign-in drivers (the same pattern
757
+ * `isolationWaitMs` uses). Production leaves it undefined, so `runSignIn`
758
+ * loads the build artifact lazily on the first attempt.
759
+ */
760
+ signInAdapter;
672
761
  rawCredentials;
673
762
  credentialOriginals = new WeakMap();
674
763
  credentialWrappers = new WeakMap();
@@ -1818,11 +1907,20 @@ export class KeysManagerService {
1818
1907
  if (typeof provider !== 'string' || provider.length === 0)
1819
1908
  throw new TypeError('provider is required');
1820
1909
  const flow = this.oauthFlowFor(provider);
1821
- if (flow === undefined)
1910
+ // Two sign-in sources: a flow on the Harness authorization seam (pi-ai
1911
+ // projections), and this plugin's own in-process clients (`src/oauth/`).
1912
+ // A provider may have both; the seam stays authoritative when it does,
1913
+ // because its harvest owns the grant projection.
1914
+ const signIn = signInProvider(provider);
1915
+ if (flow === undefined && signIn === undefined)
1822
1916
  throw new Error(`Provider "${provider}" offers no OAuth sign-in flow`);
1823
1917
  const providerRecord = this.store.provider(provider);
1824
- if (providerRecord === undefined)
1918
+ // A sign-in-only *extra* route does not exist in the pool yet: its first
1919
+ // successful sign-in creates the route and its first row (design §4.4).
1920
+ const createsRoute = flow === undefined && signIn !== undefined && EXTRA_PROVIDER_MAP.has(provider);
1921
+ if (providerRecord === undefined && !createsRoute) {
1825
1922
  throw new Error(`Provider "${provider}" is not managed; adopt it before signing in`);
1923
+ }
1826
1924
  // Validate the re-authentication target up front (round-3 finding 6):
1827
1925
  // the harvest binds the new grant to this row, so it must already name
1828
1926
  // a live OAuth account of this provider. It runs BEFORE the pending
@@ -1831,12 +1929,22 @@ export class KeysManagerService {
1831
1929
  // foreign id is refused even while another sign-in is pending.
1832
1930
  let cleanTarget;
1833
1931
  if (typeof targetAccountId === 'string' && targetAccountId.length > 0) {
1834
- const target = providerRecord.keys.find(candidate => candidate.id === targetAccountId);
1932
+ const target = providerRecord?.keys.find(candidate => candidate.id === targetAccountId);
1835
1933
  if (target === undefined)
1836
1934
  throw new Error(`Account "${targetAccountId}" not found on ${provider}`);
1837
- if (target.kind !== 'oauth' || target.oauth === null)
1838
- throw new Error(`Key "${targetAccountId}" is not an OAuth account`);
1839
- cleanTarget = targetAccountId;
1935
+ if (flow !== undefined) {
1936
+ if (target.kind !== 'oauth' || target.oauth === null)
1937
+ throw new Error(`Key "${targetAccountId}" is not an OAuth account`);
1938
+ cleanTarget = targetAccountId;
1939
+ }
1940
+ else if (target.kind === 'api-key' && target.importedFrom?.startsWith('signin:') === true) {
1941
+ // Only a row this sign-in path owns may be re-authenticated in place;
1942
+ // a hand-entered key is never silently replaced.
1943
+ cleanTarget = targetAccountId;
1944
+ }
1945
+ else {
1946
+ throw new Error(`Key "${targetAccountId}" is not a sign-in credential`);
1947
+ }
1840
1948
  }
1841
1949
  if (this.loginsInFlight.has(provider)) {
1842
1950
  // F3 (I-000082): a pending attempt IS the flow — reopening the dialog
@@ -1872,18 +1980,25 @@ export class KeysManagerService {
1872
1980
  notices: [],
1873
1981
  createdAt: now,
1874
1982
  updatedAt: now,
1983
+ inProcess: flow === undefined,
1875
1984
  controller: new AbortController(),
1876
1985
  };
1877
1986
  this.loginAttempts.set(attempt.id, attempt);
1878
1987
  this.capLoginAttempts();
1879
1988
  this.loginsInFlight.set(provider, attempt.id);
1989
+ const interaction = this.attemptInteraction(attempt);
1990
+ if (flow === undefined) {
1991
+ // In-process sign-in: no seam flow, no grant record. The driver mints a
1992
+ // static credential and {@link commitSignIn} writes the pool row.
1993
+ void this.driveSignIn(attempt, provider, interaction);
1994
+ return attemptView(attempt);
1995
+ }
1880
1996
  const records = this.credentialRecords();
1881
1997
  if (records === undefined) {
1882
1998
  this.loginAttempts.delete(attempt.id);
1883
1999
  this.loginsInFlight.delete(provider);
1884
2000
  throw new Error('The credential store does not support records; OAuth sign-in is unavailable');
1885
2001
  }
1886
- const interaction = this.attemptInteraction(attempt);
1887
2002
  const beginPromise = this.ctx.authorization.begin({
1888
2003
  key: flow.key,
1889
2004
  method: flow.method,
@@ -1905,6 +2020,104 @@ export class KeysManagerService {
1905
2020
  });
1906
2021
  return attemptView(attempt);
1907
2022
  }
2023
+ /**
2024
+ * Run one in-process sign-in and commit the static credential it mints.
2025
+ *
2026
+ * The driver runs outside the mutation queue (design §4.4): it performs
2027
+ * provider I/O and parks on prompts, so holding the queue would block every
2028
+ * other remote call for minutes. The commit itself re-enters through the
2029
+ * public transactional methods, exactly like a remote caller would.
2030
+ */
2031
+ async driveSignIn(attempt, provider, interaction) {
2032
+ try {
2033
+ const credential = await runSignIn(provider, {
2034
+ interaction,
2035
+ signal: attempt.controller.signal,
2036
+ ...(this.signInAdapter === undefined ? {} : { adapter: this.signInAdapter }),
2037
+ });
2038
+ await this.commitSignIn(attempt, provider, credential);
2039
+ }
2040
+ catch (error) {
2041
+ // A terminal transition that already happened (cancel, TTL prune) owns
2042
+ // the attempt; nothing above may overwrite it.
2043
+ if (attempt.settledAt !== undefined)
2044
+ return;
2045
+ if (error instanceof SignInCancelledError || attempt.controller.signal.aborted) {
2046
+ this.finishLoginAttempt(attempt, 'cancelled');
2047
+ return;
2048
+ }
2049
+ this.failLoginAttempt(attempt, error);
2050
+ }
2051
+ }
2052
+ /**
2053
+ * Turn a minted static credential into pool state.
2054
+ *
2055
+ * Three shapes, one rule — the credential is a *static* secret, so it is an
2056
+ * ordinary `kind: 'api-key'` row with `importedFrom: 'signin:<driver>'`, never
2057
+ * a grant:
2058
+ *
2059
+ * 1. `targetAccountId` → replace that row's literal in place (same id, same
2060
+ * ref, same list position).
2061
+ * 2. an unmanaged *extra* route → create the route and its first row
2062
+ * (`kilo`, whose card is an extra profile).
2063
+ * 3. a managed route → append a row (`zai`, a shipped DSH route).
2064
+ *
2065
+ * The secret passes the same `validateKeyInput` guard `addKey` uses, so an
2066
+ * over-long provider token fails as the existing named error.
2067
+ */
2068
+ async commitSignIn(attempt, provider, credential) {
2069
+ // A cancel that landed while the flow was finishing must not write a row.
2070
+ if (attempt.settledAt !== undefined)
2071
+ return;
2072
+ const signIn = signInProvider(provider);
2073
+ if (signIn === undefined)
2074
+ throw new Error(`Provider "${provider}" offers no in-process sign-in`);
2075
+ const input = validateKeyInput(attempt.alias ?? signIn.label, credential.access);
2076
+ const importedFrom = `signin:${signIn.driver}`;
2077
+ const target = attempt.targetAccountId;
2078
+ if (target !== undefined) {
2079
+ await this.replaceSignInCredential(provider, target, input.value);
2080
+ attempt.accountId = target;
2081
+ }
2082
+ else if (this.store.provider(provider) === undefined) {
2083
+ await this.addExtraProvider(provider, input.alias, input.value, importedFrom);
2084
+ const created = this.store.provider(provider);
2085
+ // `findLast`: a repeat sign-in on a managed route appends a second row
2086
+ // with the same provenance, and the attempt must name the row it wrote.
2087
+ attempt.accountId = created?.keys.findLast(key => key.importedFrom === importedFrom)?.id;
2088
+ }
2089
+ else {
2090
+ await this.addKey(provider, input.alias, input.value, importedFrom);
2091
+ const managed = this.store.provider(provider);
2092
+ attempt.accountId = managed?.keys.findLast(key => key.importedFrom === importedFrom)?.id;
2093
+ }
2094
+ this.finishLoginAttempt(attempt, 'ready');
2095
+ }
2096
+ /**
2097
+ * Replace a sign-in row's literal in place on re-authentication.
2098
+ *
2099
+ * Mirrors the recovery half of the grant harvest: the row keeps its id, ref
2100
+ * and position, the missing flag a demotion set goes, and a cooldown the OLD
2101
+ * credential earned ends with the new one. No row is added and no record is
2102
+ * created — the literal is the whole credential.
2103
+ */
2104
+ async replaceSignInCredential(provider, keyId, value) {
2105
+ await this.run(async () => {
2106
+ const record = this.store.provider(provider);
2107
+ if (record === undefined)
2108
+ throw new Error(`Provider "${provider}" is not managed`);
2109
+ const key = record.keys.find(candidate => candidate.id === keyId);
2110
+ if (key === undefined)
2111
+ throw new Error(`Account "${keyId}" not found on ${provider}`);
2112
+ if (key.kind !== 'api-key')
2113
+ throw new Error(`Key "${keyId}" is not a sign-in credential`);
2114
+ await this.setOriginal(key.ref, value);
2115
+ key.valueMissing = false;
2116
+ key.cooldownUntil = 0;
2117
+ this.cooldownGenerations.delete(key.id);
2118
+ this.store.touch();
2119
+ });
2120
+ }
1908
2121
  /** Resolve the attempt's parked prompt with the human's answer. */
1909
2122
  async answerAccountPrompt(attemptId, value) {
1910
2123
  const attempt = this.loginAttempts.get(attemptId);
@@ -1920,6 +2133,22 @@ export class KeysManagerService {
1920
2133
  this.dropPrompt(attempt);
1921
2134
  resolve(value);
1922
2135
  }
2136
+ /**
2137
+ * Remote: cancel one interactive attempt.
2138
+ *
2139
+ * The seam path learns about cancellation from `authorization`; an
2140
+ * in-process sign-in has no seam handle, so the login dialog's Cancel calls
2141
+ * this. Idempotent: a settled attempt is left alone.
2142
+ */
2143
+ cancelAccountLogin(attemptId) {
2144
+ const attempt = this.loginAttempts.get(attemptId);
2145
+ if (attempt === undefined)
2146
+ throw new Error('Unknown sign-in attempt');
2147
+ if (!attempt.inProcess) {
2148
+ throw new Error('The authorization seam owns this sign-in; cancel it from the surface that started it');
2149
+ }
2150
+ this.finishLoginAttempt(attempt, 'cancelled');
2151
+ }
1923
2152
  /** One attempt's serializable view, or undefined when unknown. */
1924
2153
  getAccountAttempt(attemptId) {
1925
2154
  const attempt = this.loginAttempts.get(attemptId);
@@ -2027,6 +2256,8 @@ export class KeysManagerService {
2027
2256
  notices: [],
2028
2257
  createdAt: now,
2029
2258
  updatedAt: now,
2259
+ // A transport attempt is seam-driven; `cancelAccountLogin` must not touch it.
2260
+ inProcess: false,
2030
2261
  controller: new AbortController(),
2031
2262
  };
2032
2263
  this.loginAttempts.set(attempt.id, attempt);
@@ -2121,6 +2352,23 @@ export class KeysManagerService {
2121
2352
  transportGenerationOf(route) {
2122
2353
  return this.transportRemovals.get(route) ?? 0;
2123
2354
  }
2355
+ /**
2356
+ * Explain a registered transport flow that has no catalog.
2357
+ *
2358
+ * 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.
2363
+ */
2364
+ 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;
2371
+ }
2124
2372
  /**
2125
2373
  * Remote: read one transport route's catalog and configured allow-list.
2126
2374
  *
@@ -2133,12 +2381,14 @@ export class KeysManagerService {
2133
2381
  async transportModels(route) {
2134
2382
  this.assertTransportRoute(route);
2135
2383
  const configured = this.transportModelIds(route);
2136
- const catalog = transportCatalogOf(route);
2384
+ let warning;
2385
+ const catalog = transportCatalogOf(route, missing => { warning = this.reportMissingCatalog(missing); });
2137
2386
  // A settings profile can outlive a catalog id; the picker renders the
2138
2387
  // catalog, so an unknown id would count toward {n} of {total} while
2139
2388
  // matching no checkbox and failing every save.
2140
2389
  const known = new Set(catalog.map(row => row.id));
2141
- return { catalog, models: configured.filter(id => known.has(id)) };
2390
+ const models = configured.filter(id => known.has(id));
2391
+ return warning === undefined ? { catalog, models } : { catalog, models, warning };
2142
2392
  }
2143
2393
  /**
2144
2394
  * Remote: replace one transport route's model allow-list.
@@ -2151,7 +2401,7 @@ export class KeysManagerService {
2151
2401
  if (!Array.isArray(models) || models.some(id => typeof id !== 'string')) {
2152
2402
  throw new TypeError('models must be a list of model ids');
2153
2403
  }
2154
- const catalog = transportCatalogOf(route);
2404
+ const catalog = transportCatalogOf(route, missing => this.reportMissingCatalog(missing));
2155
2405
  if (catalog.length === 0)
2156
2406
  throw new Error(`Provider "${route}" offers no model list`);
2157
2407
  const known = new Map(catalog.map(row => [row.id, row.name]));
@@ -4548,6 +4798,11 @@ export class KeysManagerService {
4548
4798
  if (!await this.awaitProjectionOwnership(provider)) {
4549
4799
  return { ok: false, latencyMs: 0, error: 'Account ownership is still loading; try again in a moment' };
4550
4800
  }
4801
+ // An adoption that predates profile materialization has nothing to test
4802
+ // against, and no UI action would give it a profile. Rebuild it (and bind
4803
+ // a key-pool route) before the route read; a route this call cannot repair
4804
+ // keeps the explicit "no settings profile" refusal below.
4805
+ await this.ensureCatalogProfile(record);
4551
4806
  const route = this.testRouteProfile(record);
4552
4807
  if ('error' in route)
4553
4808
  return { ok: false, latencyMs: 0, error: route.error };
@@ -6024,9 +6279,10 @@ export class KeysManagerService {
6024
6279
  // capable, and it is never adoptable.
6025
6280
  const transport = entry.settingsNs === TRANSPORT_CREDENTIAL_SCOPE;
6026
6281
  const oauthFlow = this.oauthFlowAvailable(entry.provider);
6027
- const caps = capabilityOf(entry, profile, oauthFlow);
6282
+ const signIn = signInCapable(entry.provider);
6283
+ const caps = capabilityOf(entry, profile, oauthFlow, signIn);
6028
6284
  const support = { supported: caps.keys, ...(caps.reason === undefined ? {} : { reason: caps.reason }) };
6029
- const accountSupport = accountSupportOf(entry, oauthFlow);
6285
+ const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
6030
6286
  const apiKeyEnv = profile !== undefined && typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv : null;
6031
6287
  const binding = managed === undefined ? undefined : this.bindingState(managed, descriptor);
6032
6288
  const bindingHealthy = binding === 'healthy' ? true : binding === 'mismatch' ? false : undefined;
@@ -6090,8 +6346,9 @@ export class KeysManagerService {
6090
6346
  configured: managed !== undefined,
6091
6347
  active: false,
6092
6348
  supported: true,
6093
- // Extra providers are key-pool routes; they offer no OAuth flow.
6094
- accountSupported: false,
6349
+ // Extra providers are key-pool routes; `kilo` additionally has an
6350
+ // in-process sign-in, which needs no seam flow.
6351
+ accountSupported: signInCapable(extra.id),
6095
6352
  settingsNs: 'llm-pi-ai',
6096
6353
  settingsPath: ['providers', extra.id],
6097
6354
  apiKeyEnv: managed?.brokerRef ?? null,
@@ -6130,7 +6387,7 @@ export class KeysManagerService {
6130
6387
  configured: false,
6131
6388
  active: false,
6132
6389
  supported: true,
6133
- accountSupported: false,
6390
+ accountSupported: signInCapable(managed.provider),
6134
6391
  settingsNs: managed.settingsNs,
6135
6392
  settingsPath: [...managed.settingsPath],
6136
6393
  apiKeyEnv: managed.brokerRef,
@@ -6565,6 +6822,94 @@ export class KeysManagerService {
6565
6822
  }
6566
6823
  return undefined;
6567
6824
  }
6825
+ /**
6826
+ * The installed catalog's models for one route, normalized for a profile
6827
+ * write, or `undefined` when the seam cannot answer. A `provider`-only
6828
+ * discovery request reads pi-ai's bundled catalog instead of the endpoint,
6829
+ * so materializing a profile for an unconfigured route uses no network and
6830
+ * no credential.
6831
+ */
6832
+ async catalogModelsFor(settingsNs, provider) {
6833
+ try {
6834
+ return discoveredModels(await this.ctx.llm.discoverModels(settingsNs, { provider }, AbortSignal.timeout(5_000)));
6835
+ }
6836
+ catch (error) {
6837
+ this.warn(`the installed catalog could not describe ${provider}: ${error instanceof Error ? error.message : String(error)}`);
6838
+ return undefined;
6839
+ }
6840
+ }
6841
+ /**
6842
+ * Write the installed catalog's models into a route's missing profile, or
6843
+ * into one that exists without models. The written profile names no
6844
+ * credential reference and no endpoint: pi-ai falls back to the catalog for
6845
+ * both, and a broker reference here would shadow a stored OAuth grant.
6846
+ *
6847
+ * A profile created while the catalog call was outstanding belongs to the
6848
+ * user, so the write re-reads it and only fills models a working profile
6849
+ * still lacks. `created` distinguishes the node this call created from a
6850
+ * user profile it filled, because rollback may only remove the former.
6851
+ */
6852
+ async materializeCatalogProfile(settingsNs, settingsPath, provider) {
6853
+ const models = await this.catalogModelsFor(settingsNs, provider);
6854
+ if (models === undefined || models.length === 0)
6855
+ return undefined;
6856
+ const live = this.profileAt(settingsNs, settingsPath);
6857
+ if (live !== undefined) {
6858
+ // A profile with models is the user's answer; never replace it.
6859
+ if (normalizeModels(live.models).length > 0)
6860
+ return undefined;
6861
+ try {
6862
+ const written = await this.mutateSettings(settingsNs, [{ op: 'set', path: [...settingsPath, 'models'], value: models }], () => {
6863
+ const current = this.profileAt(settingsNs, settingsPath);
6864
+ return current !== undefined && normalizeModels(current.models).length === 0;
6865
+ });
6866
+ return written ? { models, created: false } : undefined;
6867
+ }
6868
+ catch (error) {
6869
+ this.warn(`the ${provider} profile could not be completed: ${error instanceof Error ? error.message : String(error)}`);
6870
+ return undefined;
6871
+ }
6872
+ }
6873
+ try {
6874
+ const written = await this.mutateSettings(settingsNs, [{ op: 'set', path: [...settingsPath], value: { models } }], () => this.profileAt(settingsNs, settingsPath) === undefined);
6875
+ return written ? { models, created: true } : undefined;
6876
+ }
6877
+ catch (error) {
6878
+ this.warn(`the ${provider} profile could not be created: ${error instanceof Error ? error.message : String(error)}`);
6879
+ return undefined;
6880
+ }
6881
+ }
6882
+ /**
6883
+ * Repair the profile a row test needs on an already-managed route: a route
6884
+ * adopted before profiles were materialized has none, and a key-pool profile
6885
+ * carried over from Models may lack models.
6886
+ *
6887
+ * Rules: a profile carrying models is never touched; one missing them is
6888
+ * filled; a missing profile is rebuilt only when the record gives no sign of
6889
+ * ever having had one. A pre-fix adoption records neither `hadProfile` nor
6890
+ * `createdProfile`, so a profile the user deletes there cannot be told apart
6891
+ * from a route that never had one — it is rebuilt, and the row test is the
6892
+ * only caller.
6893
+ */
6894
+ async ensureCatalogProfile(record) {
6895
+ if (record.extraId !== null || record.adapter !== 'pi-ai')
6896
+ return;
6897
+ const live = this.profileAt(record.settingsNs, record.settingsPath);
6898
+ if (live !== undefined && normalizeModels(live.models).length > 0)
6899
+ return;
6900
+ if (live === undefined && (record.hadProfile || record.createdProfile))
6901
+ return;
6902
+ const materialized = await this.materializeCatalogProfile(record.settingsNs, record.settingsPath, record.provider);
6903
+ if (materialized === undefined)
6904
+ return;
6905
+ record.models = materialized.models;
6906
+ if (materialized.created)
6907
+ record.createdProfile = true;
6908
+ // A key-pool route needs the binding a materialized profile does not carry;
6909
+ // an OAuth-served route stays unbound (the authority decides).
6910
+ await this.syncBrokerBinding(record.provider);
6911
+ this.store.touch();
6912
+ }
6568
6913
  /** Remote: take over one existing provider route. */
6569
6914
  adoptProvider(provider) {
6570
6915
  return this.run(async () => {
@@ -6595,8 +6940,9 @@ export class KeysManagerService {
6595
6940
  // route adopts as before; the key-pool table alone no longer blocks
6596
6941
  // an adoptable account route.
6597
6942
  const oauthFlow = this.oauthFlowAvailable(entry.provider);
6598
- const caps = capabilityOf(entry, profile, oauthFlow);
6599
- const accountSupport = accountSupportOf(entry, oauthFlow);
6943
+ const signIn = signInCapable(entry.provider);
6944
+ const caps = capabilityOf(entry, profile, oauthFlow, signIn);
6945
+ const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
6600
6946
  if (!caps.keys && !accountSupport.supported) {
6601
6947
  throw new Error(caps.reason ?? accountSupport.reason ?? 'This provider cannot be managed');
6602
6948
  }
@@ -6612,25 +6958,50 @@ export class KeysManagerService {
6612
6958
  // managed state or imported credential exists.
6613
6959
  if (!descriptor.writable)
6614
6960
  throw new Error('The active profile is read-only');
6961
+ const piAiRoute = !(entry.settingsNs.includes('deepseek') || provider === 'deepseek-official');
6615
6962
  const hit = await this.findImport(entry, profile);
6616
6963
  let imported;
6617
6964
  if (hit !== undefined)
6618
6965
  imported = await this.createKeyRecord(provider, 'Imported', hit.value, hit.ref);
6966
+ // A pi-ai catalog route has no profile until something configures it, and
6967
+ // the connection test (as well as the Models page) resolves this route's
6968
+ // models from that profile. Materialize it from the installed catalog so
6969
+ // adopting in Keys Manager does not leave a route nothing can test. A
6970
+ // hand-declared route is refused above and keeps its "configure in
6971
+ // Models first" rule; the DeepSeek adapter keeps this path untouched.
6972
+ // The import runs first: a failed credential read would otherwise leave
6973
+ // this profile behind with no managed record to roll it back.
6974
+ let materialized;
6975
+ if (piAiRoute && profile === undefined) {
6976
+ materialized = await this.materializeCatalogProfile(entry.settingsNs, entry.settingsPath, provider);
6977
+ // A profile that appeared while the catalog call was outstanding is
6978
+ // the user's, and adoption proceeds against it without a warning.
6979
+ if (materialized === undefined && this.profileAt(entry.settingsNs, entry.settingsPath) === undefined) {
6980
+ this.pushWarning(`The ${provider} route was adopted without a Models profile; configure a model for it before testing the connection.`);
6981
+ }
6982
+ }
6983
+ // A user profile that appeared after the snapshot above is the record's
6984
+ // source of truth. The node this adoption created is not: it carries no
6985
+ // pre-adoption settings, and `originalApiKeyEnv` stays what adoption found
6986
+ // so the takeover never replaces a reference the user saved meanwhile.
6987
+ const adoptedProfile = profile !== undefined || materialized?.created === true
6988
+ ? profile
6989
+ : this.profileAt(entry.settingsNs, entry.settingsPath);
6619
6990
  const record = {
6620
6991
  provider,
6621
6992
  displayName: extra?.name ?? entry.displayName ?? provider,
6622
6993
  source: extra !== undefined ? 'extra' : 'dsh',
6623
6994
  settingsNs: entry.settingsNs,
6624
6995
  settingsPath: [...entry.settingsPath],
6625
- adapter: entry.settingsNs.includes('deepseek') || provider === 'deepseek-official' ? 'deepseek' : 'pi-ai',
6996
+ adapter: piAiRoute ? 'pi-ai' : 'deepseek',
6626
6997
  brokerRef,
6627
6998
  originalApiKeyEnv,
6628
- createdProfile: false,
6629
- hadProfile: profile !== undefined,
6999
+ createdProfile: materialized?.created === true,
7000
+ hadProfile: adoptedProfile !== undefined,
6630
7001
  extraId: extra?.id ?? null,
6631
- api: profile?.api ?? extra?.api ?? null,
6632
- baseURL: profile?.baseURL ?? extra?.baseURL ?? entry.defaultBaseURL ?? null,
6633
- models: profile !== undefined ? normalizeModels(profile.models) : extra?.models ?? [],
7002
+ api: adoptedProfile?.api ?? extra?.api ?? null,
7003
+ baseURL: adoptedProfile?.baseURL ?? extra?.baseURL ?? entry.defaultBaseURL ?? null,
7004
+ models: materialized?.models ?? (adoptedProfile !== undefined ? normalizeModels(adoptedProfile.models) : extra?.models ?? []),
6634
7005
  adoptedAt: Date.now(),
6635
7006
  cursor: 0,
6636
7007
  keys: imported !== undefined ? [imported] : [],
@@ -6755,8 +7126,10 @@ export class KeysManagerService {
6755
7126
  * Undo an adoption whose initial binding write was refused (PR review
6756
7127
  * round 2): drop the managed record and its broker entry, delete the
6757
7128
  * plugin-scope copy this call created, and put back a pre-adoption
6758
- * reference that landed despite the refusal. The source credential and the
6759
- * profile's other fields are never touched — adoption only read them.
7129
+ * reference that landed despite the refusal. The source credential is never
7130
+ * touched, and a profile this adoption materialized is removed whole only
7131
+ * while it still holds exactly that materialized node: a user save landing
7132
+ * between the write and the rollback owns the profile, so it keeps it.
6760
7133
  */
6761
7134
  async rollbackAdoption(record, imported) {
6762
7135
  const provider = record.provider;
@@ -6770,6 +7143,21 @@ export class KeysManagerService {
6770
7143
  this.warn(`adoption rollback could not delete the imported credential ${imported.ref} for ${provider}: ${error instanceof Error ? error.message : String(error)}`);
6771
7144
  }
6772
7145
  }
7146
+ if (record.createdProfile) {
7147
+ const live = this.profileAt(record.settingsNs, record.settingsPath);
7148
+ if (live !== undefined && isMaterializedProfile(live, record.models)) {
7149
+ try {
7150
+ await this.mutateSettings(record.settingsNs, [{ op: 'unset', path: record.settingsPath }]);
7151
+ }
7152
+ catch (error) {
7153
+ this.warn(`adoption rollback could not remove the ${provider} profile it created: ${error instanceof Error ? error.message : String(error)}`);
7154
+ }
7155
+ this.store.touch();
7156
+ return;
7157
+ }
7158
+ // A user took the node over while the adoption was settling, so it falls
7159
+ // through to the apiKeyEnv-only compensation below: never delete theirs.
7160
+ }
6773
7161
  const descriptor = this.describeSettings();
6774
7162
  const namespace = this.namespace(descriptor, record.settingsNs);
6775
7163
  const profile = asProfile(namespace === undefined ? undefined : getPath(namespace.value, record.settingsPath));
@@ -6805,17 +7193,7 @@ export class KeysManagerService {
6805
7193
  catch (error) {
6806
7194
  failure = error instanceof Error ? error.message : String(error);
6807
7195
  }
6808
- const models = [];
6809
- const seen = new Set();
6810
- for (const model of discovered) {
6811
- const normalized = discoveredModel(model);
6812
- if (normalized === undefined || seen.has(normalized.id))
6813
- continue;
6814
- seen.add(normalized.id);
6815
- models.push(normalized);
6816
- if (models.length >= 60)
6817
- break;
6818
- }
7196
+ const models = discoveredModels(discovered);
6819
7197
  if (models.length > 0)
6820
7198
  return { models, failure };
6821
7199
  return { models: normalizeModels(extra.models), failure };
@@ -6828,7 +7206,9 @@ export class KeysManagerService {
6828
7206
  * the key that serves it in the same mutation, so the write below is the
6829
7207
  * route's first binding rather than a takeover of a value the user owns.
6830
7208
  */
6831
- addExtraProvider(extraId, alias, value) {
7209
+ addExtraProvider(extraId, alias, value,
7210
+ /** Provenance for the first row; `signin:<driver>` for an in-process sign-in. */
7211
+ importedFrom = null) {
6832
7212
  return this.run(async () => {
6833
7213
  if (typeof extraId !== 'string' || extraId.length === 0)
6834
7214
  throw new Error('extraId is required');
@@ -6847,7 +7227,7 @@ export class KeysManagerService {
6847
7227
  // add-key flow restores them and the repair keeps one implementation.
6848
7228
  // Hand it the value resolved above: the entry refusal stays the single
6849
7229
  // decision for this surface, and the environment is read once per add.
6850
- await this.addKeyLocked(extraId, input.alias, input.value, headers);
7230
+ await this.addKeyLocked(extraId, input.alias, input.value, headers, importedFrom);
6851
7231
  this.store.touch();
6852
7232
  return this.buildState();
6853
7233
  }
@@ -6877,7 +7257,7 @@ export class KeysManagerService {
6877
7257
  cursor: 0,
6878
7258
  keys: [],
6879
7259
  };
6880
- const key = await this.createKeyRecord(extraId, input.alias, input.value);
7260
+ const key = await this.createKeyRecord(extraId, input.alias, input.value, importedFrom);
6881
7261
  const ops = [{ op: 'set', path: ['providers', extraId, 'apiKeyEnv'], value: record.brokerRef }];
6882
7262
  // Fill the declared headers the stored profile does not carry; a value
6883
7263
  // the profile already sets for the same header is never overwritten.
@@ -6912,9 +7292,20 @@ export class KeysManagerService {
6912
7292
  this.store.touch();
6913
7293
  return this.buildState();
6914
7294
  }
6915
- const { models, failure } = await this.discoverModels(extra, input.value);
6916
- if (models.length === 0)
6917
- throw new Error('No models were discovered and the seed catalog is empty');
7295
+ // A sign-in already proved the credential, so its commit seeds the catalog
7296
+ // instead of probing the endpoint: discovery may hold this serialized
7297
+ // mutation for its whole 20 s timeout before the row appears (F3).
7298
+ const found = importedFrom === null
7299
+ ? await this.discoverModels(extra, input.value)
7300
+ : { models: normalizeModels(extra.models) };
7301
+ const { models, failure } = found;
7302
+ // The sign-in branch never probed the endpoint, so it cannot report a
7303
+ // discovery result.
7304
+ if (models.length === 0) {
7305
+ throw new Error(importedFrom === null
7306
+ ? 'No models were discovered and the seed catalog is empty'
7307
+ : 'The plugin catalog is empty for this provider');
7308
+ }
6918
7309
  if (failure !== undefined)
6919
7310
  this.pushWarning(`Model discovery failed; installed ${models.length} seed models instead: ${failure}`);
6920
7311
  const brokerRef = brokerRefFor(extraId);
@@ -6926,7 +7317,7 @@ export class KeysManagerService {
6926
7317
  ...(headers === undefined ? {} : { headers }),
6927
7318
  models,
6928
7319
  };
6929
- const key = await this.createKeyRecord(extraId, input.alias, input.value);
7320
+ const key = await this.createKeyRecord(extraId, input.alias, input.value, importedFrom);
6930
7321
  try {
6931
7322
  // The profile and its binding are created together (see the method
6932
7323
  // comment); no user value exists to take over here.
@@ -7026,7 +7417,7 @@ export class KeysManagerService {
7026
7417
  this.pushWarning(`Restored the missing ${Object.keys(missing).join(', ')} header on the managed profile.`);
7027
7418
  }
7028
7419
  /** Add one key; caller already owns the mutation queue. */
7029
- async addKeyLocked(provider, alias, value, declaredHeaders) {
7420
+ async addKeyLocked(provider, alias, value, declaredHeaders, importedFrom = null) {
7030
7421
  const record = this.store.provider(provider);
7031
7422
  if (record === undefined)
7032
7423
  throw new Error(`Provider "${provider}" is not managed`);
@@ -7043,7 +7434,7 @@ export class KeysManagerService {
7043
7434
  const input = validateKeyInput(alias, value);
7044
7435
  if (record.keys.length >= KEY_LIMIT)
7045
7436
  throw new Error(`A provider may have at most ${KEY_LIMIT} keys`);
7046
- const key = await this.createKeyRecord(provider, input.alias, input.value);
7437
+ const key = await this.createKeyRecord(provider, input.alias, input.value, importedFrom);
7047
7438
  record.keys.push(key);
7048
7439
  // After the key add: a refused key (capability or capacity) must leave the
7049
7440
  // settings document untouched, so the repair never runs ahead of it.
@@ -7056,9 +7447,9 @@ export class KeysManagerService {
7056
7447
  await this.syncBrokerBinding(provider, record.extraId === null ? {} : { write: false });
7057
7448
  }
7058
7449
  /** Remote: add one key to a managed provider. */
7059
- addKey(provider, alias, value) {
7450
+ addKey(provider, alias, value, importedFrom = null) {
7060
7451
  return this.run(async () => {
7061
- await this.addKeyLocked(provider, alias, value);
7452
+ await this.addKeyLocked(provider, alias, value, undefined, importedFrom);
7062
7453
  this.store.touch();
7063
7454
  return this.buildState();
7064
7455
  });