dsh-keys-manager 0.2.4 → 0.2.5

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,34 @@ 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';
526
569
  /**
527
570
  * The catalog a transport route advertises to its model picker.
528
571
  *
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.
572
+ * A route without a catalog projection reports no models rather than borrowing
573
+ * another route's. The catalog is the transport package's own data, not this
574
+ * plugin's: `devin` is delivered by a sibling track in the same iteration, so
575
+ * the installed transport build may predate its export. The function is
576
+ * therefore probed on the module namespace instead of imported by name — an
577
+ * absent export yields an empty catalog instead of breaking this plugin's
578
+ * import graph. An empty list is indistinguishable from the legitimate
579
+ * all-models state, so `onMissing` reports it instead of the picker rendering
580
+ * a silent `[]`.
531
581
  */
532
- function transportCatalogOf(route) {
533
- return route === CURSOR_ROUTE ? cursorCatalogModels() : [];
582
+ function transportCatalogOf(route, onMissing) {
583
+ if (route === CURSOR_ROUTE)
584
+ return cursorCatalogModels();
585
+ if (route !== DEVIN_ROUTE) {
586
+ onMissing?.(route);
587
+ return [];
588
+ }
589
+ const probe = transportModule.devinCatalogModels;
590
+ if (typeof probe !== 'function') {
591
+ onMissing?.(route);
592
+ return [];
593
+ }
594
+ return probe();
534
595
  }
535
596
  /** Env names that are a single API-key credential, not an OAuth/federation token. */
536
597
  function isKeyishEnv(name) {
@@ -573,17 +634,20 @@ const NO_OAUTH_FLOW_REASON = 'This provider has no OAuth sign-in flow registered
573
634
  *
574
635
  * `oauthFlow` is the live answer from {@link KeysManagerService.oauthFlowAvailable}
575
636
  * — C6-2 requires an actually-beginable flow, not the catalog flag alone.
637
+ * `signIn` is the second source of the account verdict: this plugin's own
638
+ * in-process sign-in clients (`src/oauth/providers.ts`), which run inside the
639
+ * attempt surface instead of a seam flow.
576
640
  */
577
- function capabilityOf(entry, profile, oauthFlow) {
641
+ function capabilityOf(entry, profile, oauthFlow, signIn = false) {
578
642
  if (entry.error !== undefined)
579
643
  return { keys: false, accounts: false, reason: entry.error };
580
- const accounts = entry.nativeAuth?.oauth === true && oauthFlow;
644
+ const accounts = signIn || (entry.nativeAuth?.oauth === true && oauthFlow);
581
645
  const unsupportedReason = UNSUPPORTED_KEY_POOL_PROVIDERS[entry.provider];
582
646
  if (unsupportedReason !== undefined) {
583
647
  // The table's reason describes the key verdict; when the only possible
584
648
  // capability (accounts) is unavailable too, the flow gap is the truthful
585
649
  // explanation a user needs.
586
- const reason = entry.nativeAuth?.oauth === true && !oauthFlow ? NO_OAUTH_FLOW_REASON : unsupportedReason;
650
+ const reason = !accounts && entry.nativeAuth?.oauth === true && !oauthFlow ? NO_OAUTH_FLOW_REASON : unsupportedReason;
587
651
  return { keys: false, accounts, reason };
588
652
  }
589
653
  if (entry.provider === 'deepseek-official')
@@ -597,8 +661,8 @@ function capabilityOf(entry, profile, oauthFlow) {
597
661
  // key credential at all.
598
662
  if (auth.env.some(isKeyishEnv))
599
663
  return { keys: true, accounts };
600
- if (auth.oauth) {
601
- return oauthFlow
664
+ if (auth.oauth || signIn) {
665
+ return accounts
602
666
  ? { keys: false, accounts: true, reason: 'This provider signs in with an OAuth account; no API key is used' }
603
667
  : { keys: false, accounts: false, reason: NO_OAUTH_FLOW_REASON };
604
668
  }
@@ -617,12 +681,17 @@ function capabilityOf(entry, profile, oauthFlow) {
617
681
  * may mount after this plugin, so availability is never cached at
618
682
  * construction. While the flow list is empty (seam not mounted yet) support
619
683
  * is false; the next state build re-evaluates once flows are enumerable.
684
+ *
685
+ * `signIn` answers before that gate: an in-process client needs no seam flow,
686
+ * so it stays available even while the flow list is empty.
620
687
  */
621
- function accountSupportOf(entry, oauthFlow) {
688
+ function accountSupportOf(entry, oauthFlow, signIn = false) {
622
689
  if (entry === undefined)
623
690
  return { supported: false, reason: 'This provider route is not registered' };
624
691
  if (entry.error !== undefined)
625
692
  return { supported: false, reason: entry.error };
693
+ if (signIn)
694
+ return { supported: true };
626
695
  if (entry.nativeAuth?.oauth !== true)
627
696
  return { supported: false, reason: 'This provider offers no OAuth account sign-in' };
628
697
  if (!oauthFlow)
@@ -668,7 +737,15 @@ export class KeysManagerService {
668
737
  attemptSequence = 0;
669
738
  switches = new Map();
670
739
  warnings = [];
740
+ /** Transport routes already reported as having no shipped catalog. */
741
+ catalogReports = new Set();
671
742
  settings;
743
+ /**
744
+ * Test/embedding seam for the in-process sign-in drivers (the same pattern
745
+ * `isolationWaitMs` uses). Production leaves it undefined, so `runSignIn`
746
+ * loads the build artifact lazily on the first attempt.
747
+ */
748
+ signInAdapter;
672
749
  rawCredentials;
673
750
  credentialOriginals = new WeakMap();
674
751
  credentialWrappers = new WeakMap();
@@ -1818,11 +1895,20 @@ export class KeysManagerService {
1818
1895
  if (typeof provider !== 'string' || provider.length === 0)
1819
1896
  throw new TypeError('provider is required');
1820
1897
  const flow = this.oauthFlowFor(provider);
1821
- if (flow === undefined)
1898
+ // Two sign-in sources: a flow on the Harness authorization seam (pi-ai
1899
+ // projections), and this plugin's own in-process clients (`src/oauth/`).
1900
+ // A provider may have both; the seam stays authoritative when it does,
1901
+ // because its harvest owns the grant projection.
1902
+ const signIn = signInProvider(provider);
1903
+ if (flow === undefined && signIn === undefined)
1822
1904
  throw new Error(`Provider "${provider}" offers no OAuth sign-in flow`);
1823
1905
  const providerRecord = this.store.provider(provider);
1824
- if (providerRecord === undefined)
1906
+ // A sign-in-only *extra* route does not exist in the pool yet: its first
1907
+ // successful sign-in creates the route and its first row (design §4.4).
1908
+ const createsRoute = flow === undefined && signIn !== undefined && EXTRA_PROVIDER_MAP.has(provider);
1909
+ if (providerRecord === undefined && !createsRoute) {
1825
1910
  throw new Error(`Provider "${provider}" is not managed; adopt it before signing in`);
1911
+ }
1826
1912
  // Validate the re-authentication target up front (round-3 finding 6):
1827
1913
  // the harvest binds the new grant to this row, so it must already name
1828
1914
  // a live OAuth account of this provider. It runs BEFORE the pending
@@ -1831,12 +1917,22 @@ export class KeysManagerService {
1831
1917
  // foreign id is refused even while another sign-in is pending.
1832
1918
  let cleanTarget;
1833
1919
  if (typeof targetAccountId === 'string' && targetAccountId.length > 0) {
1834
- const target = providerRecord.keys.find(candidate => candidate.id === targetAccountId);
1920
+ const target = providerRecord?.keys.find(candidate => candidate.id === targetAccountId);
1835
1921
  if (target === undefined)
1836
1922
  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;
1923
+ if (flow !== undefined) {
1924
+ if (target.kind !== 'oauth' || target.oauth === null)
1925
+ throw new Error(`Key "${targetAccountId}" is not an OAuth account`);
1926
+ cleanTarget = targetAccountId;
1927
+ }
1928
+ else if (target.kind === 'api-key' && target.importedFrom?.startsWith('signin:') === true) {
1929
+ // Only a row this sign-in path owns may be re-authenticated in place;
1930
+ // a hand-entered key is never silently replaced.
1931
+ cleanTarget = targetAccountId;
1932
+ }
1933
+ else {
1934
+ throw new Error(`Key "${targetAccountId}" is not a sign-in credential`);
1935
+ }
1840
1936
  }
1841
1937
  if (this.loginsInFlight.has(provider)) {
1842
1938
  // F3 (I-000082): a pending attempt IS the flow — reopening the dialog
@@ -1872,18 +1968,25 @@ export class KeysManagerService {
1872
1968
  notices: [],
1873
1969
  createdAt: now,
1874
1970
  updatedAt: now,
1971
+ inProcess: flow === undefined,
1875
1972
  controller: new AbortController(),
1876
1973
  };
1877
1974
  this.loginAttempts.set(attempt.id, attempt);
1878
1975
  this.capLoginAttempts();
1879
1976
  this.loginsInFlight.set(provider, attempt.id);
1977
+ const interaction = this.attemptInteraction(attempt);
1978
+ if (flow === undefined) {
1979
+ // In-process sign-in: no seam flow, no grant record. The driver mints a
1980
+ // static credential and {@link commitSignIn} writes the pool row.
1981
+ void this.driveSignIn(attempt, provider, interaction);
1982
+ return attemptView(attempt);
1983
+ }
1880
1984
  const records = this.credentialRecords();
1881
1985
  if (records === undefined) {
1882
1986
  this.loginAttempts.delete(attempt.id);
1883
1987
  this.loginsInFlight.delete(provider);
1884
1988
  throw new Error('The credential store does not support records; OAuth sign-in is unavailable');
1885
1989
  }
1886
- const interaction = this.attemptInteraction(attempt);
1887
1990
  const beginPromise = this.ctx.authorization.begin({
1888
1991
  key: flow.key,
1889
1992
  method: flow.method,
@@ -1905,6 +2008,104 @@ export class KeysManagerService {
1905
2008
  });
1906
2009
  return attemptView(attempt);
1907
2010
  }
2011
+ /**
2012
+ * Run one in-process sign-in and commit the static credential it mints.
2013
+ *
2014
+ * The driver runs outside the mutation queue (design §4.4): it performs
2015
+ * provider I/O and parks on prompts, so holding the queue would block every
2016
+ * other remote call for minutes. The commit itself re-enters through the
2017
+ * public transactional methods, exactly like a remote caller would.
2018
+ */
2019
+ async driveSignIn(attempt, provider, interaction) {
2020
+ try {
2021
+ const credential = await runSignIn(provider, {
2022
+ interaction,
2023
+ signal: attempt.controller.signal,
2024
+ ...(this.signInAdapter === undefined ? {} : { adapter: this.signInAdapter }),
2025
+ });
2026
+ await this.commitSignIn(attempt, provider, credential);
2027
+ }
2028
+ catch (error) {
2029
+ // A terminal transition that already happened (cancel, TTL prune) owns
2030
+ // the attempt; nothing above may overwrite it.
2031
+ if (attempt.settledAt !== undefined)
2032
+ return;
2033
+ if (error instanceof SignInCancelledError || attempt.controller.signal.aborted) {
2034
+ this.finishLoginAttempt(attempt, 'cancelled');
2035
+ return;
2036
+ }
2037
+ this.failLoginAttempt(attempt, error);
2038
+ }
2039
+ }
2040
+ /**
2041
+ * Turn a minted static credential into pool state.
2042
+ *
2043
+ * Three shapes, one rule — the credential is a *static* secret, so it is an
2044
+ * ordinary `kind: 'api-key'` row with `importedFrom: 'signin:<driver>'`, never
2045
+ * a grant:
2046
+ *
2047
+ * 1. `targetAccountId` → replace that row's literal in place (same id, same
2048
+ * ref, same list position).
2049
+ * 2. an unmanaged *extra* route → create the route and its first row
2050
+ * (`kilo`, whose card is an extra profile).
2051
+ * 3. a managed route → append a row (`zai`, a shipped DSH route).
2052
+ *
2053
+ * The secret passes the same `validateKeyInput` guard `addKey` uses, so an
2054
+ * over-long provider token fails as the existing named error.
2055
+ */
2056
+ async commitSignIn(attempt, provider, credential) {
2057
+ // A cancel that landed while the flow was finishing must not write a row.
2058
+ if (attempt.settledAt !== undefined)
2059
+ return;
2060
+ const signIn = signInProvider(provider);
2061
+ if (signIn === undefined)
2062
+ throw new Error(`Provider "${provider}" offers no in-process sign-in`);
2063
+ const input = validateKeyInput(attempt.alias ?? signIn.label, credential.access);
2064
+ const importedFrom = `signin:${signIn.driver}`;
2065
+ const target = attempt.targetAccountId;
2066
+ if (target !== undefined) {
2067
+ await this.replaceSignInCredential(provider, target, input.value);
2068
+ attempt.accountId = target;
2069
+ }
2070
+ else if (this.store.provider(provider) === undefined) {
2071
+ await this.addExtraProvider(provider, input.alias, input.value, importedFrom);
2072
+ const created = this.store.provider(provider);
2073
+ // `findLast`: a repeat sign-in on a managed route appends a second row
2074
+ // with the same provenance, and the attempt must name the row it wrote.
2075
+ attempt.accountId = created?.keys.findLast(key => key.importedFrom === importedFrom)?.id;
2076
+ }
2077
+ else {
2078
+ await this.addKey(provider, input.alias, input.value, importedFrom);
2079
+ const managed = this.store.provider(provider);
2080
+ attempt.accountId = managed?.keys.findLast(key => key.importedFrom === importedFrom)?.id;
2081
+ }
2082
+ this.finishLoginAttempt(attempt, 'ready');
2083
+ }
2084
+ /**
2085
+ * Replace a sign-in row's literal in place on re-authentication.
2086
+ *
2087
+ * Mirrors the recovery half of the grant harvest: the row keeps its id, ref
2088
+ * and position, the missing flag a demotion set goes, and a cooldown the OLD
2089
+ * credential earned ends with the new one. No row is added and no record is
2090
+ * created — the literal is the whole credential.
2091
+ */
2092
+ async replaceSignInCredential(provider, keyId, value) {
2093
+ await this.run(async () => {
2094
+ const record = this.store.provider(provider);
2095
+ if (record === undefined)
2096
+ throw new Error(`Provider "${provider}" is not managed`);
2097
+ const key = record.keys.find(candidate => candidate.id === keyId);
2098
+ if (key === undefined)
2099
+ throw new Error(`Account "${keyId}" not found on ${provider}`);
2100
+ if (key.kind !== 'api-key')
2101
+ throw new Error(`Key "${keyId}" is not a sign-in credential`);
2102
+ await this.setOriginal(key.ref, value);
2103
+ key.valueMissing = false;
2104
+ key.cooldownUntil = 0;
2105
+ this.cooldownGenerations.delete(key.id);
2106
+ this.store.touch();
2107
+ });
2108
+ }
1908
2109
  /** Resolve the attempt's parked prompt with the human's answer. */
1909
2110
  async answerAccountPrompt(attemptId, value) {
1910
2111
  const attempt = this.loginAttempts.get(attemptId);
@@ -1920,6 +2121,22 @@ export class KeysManagerService {
1920
2121
  this.dropPrompt(attempt);
1921
2122
  resolve(value);
1922
2123
  }
2124
+ /**
2125
+ * Remote: cancel one interactive attempt.
2126
+ *
2127
+ * The seam path learns about cancellation from `authorization`; an
2128
+ * in-process sign-in has no seam handle, so the login dialog's Cancel calls
2129
+ * this. Idempotent: a settled attempt is left alone.
2130
+ */
2131
+ cancelAccountLogin(attemptId) {
2132
+ const attempt = this.loginAttempts.get(attemptId);
2133
+ if (attempt === undefined)
2134
+ throw new Error('Unknown sign-in attempt');
2135
+ if (!attempt.inProcess) {
2136
+ throw new Error('The authorization seam owns this sign-in; cancel it from the surface that started it');
2137
+ }
2138
+ this.finishLoginAttempt(attempt, 'cancelled');
2139
+ }
1923
2140
  /** One attempt's serializable view, or undefined when unknown. */
1924
2141
  getAccountAttempt(attemptId) {
1925
2142
  const attempt = this.loginAttempts.get(attemptId);
@@ -2027,6 +2244,8 @@ export class KeysManagerService {
2027
2244
  notices: [],
2028
2245
  createdAt: now,
2029
2246
  updatedAt: now,
2247
+ // A transport attempt is seam-driven; `cancelAccountLogin` must not touch it.
2248
+ inProcess: false,
2030
2249
  controller: new AbortController(),
2031
2250
  };
2032
2251
  this.loginAttempts.set(attempt.id, attempt);
@@ -2121,6 +2340,23 @@ export class KeysManagerService {
2121
2340
  transportGenerationOf(route) {
2122
2341
  return this.transportRemovals.get(route) ?? 0;
2123
2342
  }
2343
+ /**
2344
+ * Explain a registered transport flow that has no catalog.
2345
+ *
2346
+ * An empty list is also the legitimate all-models state, so the only honest
2347
+ * way to tell a stale transport build apart is to say so. The message rides
2348
+ * every read whose accessor is missing — a once-only gate would leave a
2349
+ * remounted or reloaded picker unexplained — while `catalogReports` keeps
2350
+ * the state warning to one push per route.
2351
+ */
2352
+ reportMissingCatalog(route) {
2353
+ 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`;
2354
+ if (!this.catalogReports.has(route)) {
2355
+ this.catalogReports.add(route);
2356
+ this.pushWarning(message);
2357
+ }
2358
+ return message;
2359
+ }
2124
2360
  /**
2125
2361
  * Remote: read one transport route's catalog and configured allow-list.
2126
2362
  *
@@ -2133,12 +2369,14 @@ export class KeysManagerService {
2133
2369
  async transportModels(route) {
2134
2370
  this.assertTransportRoute(route);
2135
2371
  const configured = this.transportModelIds(route);
2136
- const catalog = transportCatalogOf(route);
2372
+ let warning;
2373
+ const catalog = transportCatalogOf(route, missing => { warning = this.reportMissingCatalog(missing); });
2137
2374
  // A settings profile can outlive a catalog id; the picker renders the
2138
2375
  // catalog, so an unknown id would count toward {n} of {total} while
2139
2376
  // matching no checkbox and failing every save.
2140
2377
  const known = new Set(catalog.map(row => row.id));
2141
- return { catalog, models: configured.filter(id => known.has(id)) };
2378
+ const models = configured.filter(id => known.has(id));
2379
+ return warning === undefined ? { catalog, models } : { catalog, models, warning };
2142
2380
  }
2143
2381
  /**
2144
2382
  * Remote: replace one transport route's model allow-list.
@@ -2151,7 +2389,7 @@ export class KeysManagerService {
2151
2389
  if (!Array.isArray(models) || models.some(id => typeof id !== 'string')) {
2152
2390
  throw new TypeError('models must be a list of model ids');
2153
2391
  }
2154
- const catalog = transportCatalogOf(route);
2392
+ const catalog = transportCatalogOf(route, missing => this.reportMissingCatalog(missing));
2155
2393
  if (catalog.length === 0)
2156
2394
  throw new Error(`Provider "${route}" offers no model list`);
2157
2395
  const known = new Map(catalog.map(row => [row.id, row.name]));
@@ -4548,6 +4786,11 @@ export class KeysManagerService {
4548
4786
  if (!await this.awaitProjectionOwnership(provider)) {
4549
4787
  return { ok: false, latencyMs: 0, error: 'Account ownership is still loading; try again in a moment' };
4550
4788
  }
4789
+ // An adoption that predates profile materialization has nothing to test
4790
+ // against, and no UI action would give it a profile. Rebuild it (and bind
4791
+ // a key-pool route) before the route read; a route this call cannot repair
4792
+ // keeps the explicit "no settings profile" refusal below.
4793
+ await this.ensureCatalogProfile(record);
4551
4794
  const route = this.testRouteProfile(record);
4552
4795
  if ('error' in route)
4553
4796
  return { ok: false, latencyMs: 0, error: route.error };
@@ -6024,9 +6267,10 @@ export class KeysManagerService {
6024
6267
  // capable, and it is never adoptable.
6025
6268
  const transport = entry.settingsNs === TRANSPORT_CREDENTIAL_SCOPE;
6026
6269
  const oauthFlow = this.oauthFlowAvailable(entry.provider);
6027
- const caps = capabilityOf(entry, profile, oauthFlow);
6270
+ const signIn = signInCapable(entry.provider);
6271
+ const caps = capabilityOf(entry, profile, oauthFlow, signIn);
6028
6272
  const support = { supported: caps.keys, ...(caps.reason === undefined ? {} : { reason: caps.reason }) };
6029
- const accountSupport = accountSupportOf(entry, oauthFlow);
6273
+ const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
6030
6274
  const apiKeyEnv = profile !== undefined && typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv : null;
6031
6275
  const binding = managed === undefined ? undefined : this.bindingState(managed, descriptor);
6032
6276
  const bindingHealthy = binding === 'healthy' ? true : binding === 'mismatch' ? false : undefined;
@@ -6090,8 +6334,9 @@ export class KeysManagerService {
6090
6334
  configured: managed !== undefined,
6091
6335
  active: false,
6092
6336
  supported: true,
6093
- // Extra providers are key-pool routes; they offer no OAuth flow.
6094
- accountSupported: false,
6337
+ // Extra providers are key-pool routes; `kilo` additionally has an
6338
+ // in-process sign-in, which needs no seam flow.
6339
+ accountSupported: signInCapable(extra.id),
6095
6340
  settingsNs: 'llm-pi-ai',
6096
6341
  settingsPath: ['providers', extra.id],
6097
6342
  apiKeyEnv: managed?.brokerRef ?? null,
@@ -6130,7 +6375,7 @@ export class KeysManagerService {
6130
6375
  configured: false,
6131
6376
  active: false,
6132
6377
  supported: true,
6133
- accountSupported: false,
6378
+ accountSupported: signInCapable(managed.provider),
6134
6379
  settingsNs: managed.settingsNs,
6135
6380
  settingsPath: [...managed.settingsPath],
6136
6381
  apiKeyEnv: managed.brokerRef,
@@ -6565,6 +6810,94 @@ export class KeysManagerService {
6565
6810
  }
6566
6811
  return undefined;
6567
6812
  }
6813
+ /**
6814
+ * The installed catalog's models for one route, normalized for a profile
6815
+ * write, or `undefined` when the seam cannot answer. A `provider`-only
6816
+ * discovery request reads pi-ai's bundled catalog instead of the endpoint,
6817
+ * so materializing a profile for an unconfigured route uses no network and
6818
+ * no credential.
6819
+ */
6820
+ async catalogModelsFor(settingsNs, provider) {
6821
+ try {
6822
+ return discoveredModels(await this.ctx.llm.discoverModels(settingsNs, { provider }, AbortSignal.timeout(5_000)));
6823
+ }
6824
+ catch (error) {
6825
+ this.warn(`the installed catalog could not describe ${provider}: ${error instanceof Error ? error.message : String(error)}`);
6826
+ return undefined;
6827
+ }
6828
+ }
6829
+ /**
6830
+ * Write the installed catalog's models into a route's missing profile, or
6831
+ * into one that exists without models. The written profile names no
6832
+ * credential reference and no endpoint: pi-ai falls back to the catalog for
6833
+ * both, and a broker reference here would shadow a stored OAuth grant.
6834
+ *
6835
+ * A profile created while the catalog call was outstanding belongs to the
6836
+ * user, so the write re-reads it and only fills models a working profile
6837
+ * still lacks. `created` distinguishes the node this call created from a
6838
+ * user profile it filled, because rollback may only remove the former.
6839
+ */
6840
+ async materializeCatalogProfile(settingsNs, settingsPath, provider) {
6841
+ const models = await this.catalogModelsFor(settingsNs, provider);
6842
+ if (models === undefined || models.length === 0)
6843
+ return undefined;
6844
+ const live = this.profileAt(settingsNs, settingsPath);
6845
+ if (live !== undefined) {
6846
+ // A profile with models is the user's answer; never replace it.
6847
+ if (normalizeModels(live.models).length > 0)
6848
+ return undefined;
6849
+ try {
6850
+ const written = await this.mutateSettings(settingsNs, [{ op: 'set', path: [...settingsPath, 'models'], value: models }], () => {
6851
+ const current = this.profileAt(settingsNs, settingsPath);
6852
+ return current !== undefined && normalizeModels(current.models).length === 0;
6853
+ });
6854
+ return written ? { models, created: false } : undefined;
6855
+ }
6856
+ catch (error) {
6857
+ this.warn(`the ${provider} profile could not be completed: ${error instanceof Error ? error.message : String(error)}`);
6858
+ return undefined;
6859
+ }
6860
+ }
6861
+ try {
6862
+ const written = await this.mutateSettings(settingsNs, [{ op: 'set', path: [...settingsPath], value: { models } }], () => this.profileAt(settingsNs, settingsPath) === undefined);
6863
+ return written ? { models, created: true } : undefined;
6864
+ }
6865
+ catch (error) {
6866
+ this.warn(`the ${provider} profile could not be created: ${error instanceof Error ? error.message : String(error)}`);
6867
+ return undefined;
6868
+ }
6869
+ }
6870
+ /**
6871
+ * Repair the profile a row test needs on an already-managed route: a route
6872
+ * adopted before profiles were materialized has none, and a key-pool profile
6873
+ * carried over from Models may lack models.
6874
+ *
6875
+ * Rules: a profile carrying models is never touched; one missing them is
6876
+ * filled; a missing profile is rebuilt only when the record gives no sign of
6877
+ * ever having had one. A pre-fix adoption records neither `hadProfile` nor
6878
+ * `createdProfile`, so a profile the user deletes there cannot be told apart
6879
+ * from a route that never had one — it is rebuilt, and the row test is the
6880
+ * only caller.
6881
+ */
6882
+ async ensureCatalogProfile(record) {
6883
+ if (record.extraId !== null || record.adapter !== 'pi-ai')
6884
+ return;
6885
+ const live = this.profileAt(record.settingsNs, record.settingsPath);
6886
+ if (live !== undefined && normalizeModels(live.models).length > 0)
6887
+ return;
6888
+ if (live === undefined && (record.hadProfile || record.createdProfile))
6889
+ return;
6890
+ const materialized = await this.materializeCatalogProfile(record.settingsNs, record.settingsPath, record.provider);
6891
+ if (materialized === undefined)
6892
+ return;
6893
+ record.models = materialized.models;
6894
+ if (materialized.created)
6895
+ record.createdProfile = true;
6896
+ // A key-pool route needs the binding a materialized profile does not carry;
6897
+ // an OAuth-served route stays unbound (the authority decides).
6898
+ await this.syncBrokerBinding(record.provider);
6899
+ this.store.touch();
6900
+ }
6568
6901
  /** Remote: take over one existing provider route. */
6569
6902
  adoptProvider(provider) {
6570
6903
  return this.run(async () => {
@@ -6595,8 +6928,9 @@ export class KeysManagerService {
6595
6928
  // route adopts as before; the key-pool table alone no longer blocks
6596
6929
  // an adoptable account route.
6597
6930
  const oauthFlow = this.oauthFlowAvailable(entry.provider);
6598
- const caps = capabilityOf(entry, profile, oauthFlow);
6599
- const accountSupport = accountSupportOf(entry, oauthFlow);
6931
+ const signIn = signInCapable(entry.provider);
6932
+ const caps = capabilityOf(entry, profile, oauthFlow, signIn);
6933
+ const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
6600
6934
  if (!caps.keys && !accountSupport.supported) {
6601
6935
  throw new Error(caps.reason ?? accountSupport.reason ?? 'This provider cannot be managed');
6602
6936
  }
@@ -6612,25 +6946,50 @@ export class KeysManagerService {
6612
6946
  // managed state or imported credential exists.
6613
6947
  if (!descriptor.writable)
6614
6948
  throw new Error('The active profile is read-only');
6949
+ const piAiRoute = !(entry.settingsNs.includes('deepseek') || provider === 'deepseek-official');
6615
6950
  const hit = await this.findImport(entry, profile);
6616
6951
  let imported;
6617
6952
  if (hit !== undefined)
6618
6953
  imported = await this.createKeyRecord(provider, 'Imported', hit.value, hit.ref);
6954
+ // A pi-ai catalog route has no profile until something configures it, and
6955
+ // the connection test (as well as the Models page) resolves this route's
6956
+ // models from that profile. Materialize it from the installed catalog so
6957
+ // adopting in Keys Manager does not leave a route nothing can test. A
6958
+ // hand-declared route is refused above and keeps its "configure in
6959
+ // Models first" rule; the DeepSeek adapter keeps this path untouched.
6960
+ // The import runs first: a failed credential read would otherwise leave
6961
+ // this profile behind with no managed record to roll it back.
6962
+ let materialized;
6963
+ if (piAiRoute && profile === undefined) {
6964
+ materialized = await this.materializeCatalogProfile(entry.settingsNs, entry.settingsPath, provider);
6965
+ // A profile that appeared while the catalog call was outstanding is
6966
+ // the user's, and adoption proceeds against it without a warning.
6967
+ if (materialized === undefined && this.profileAt(entry.settingsNs, entry.settingsPath) === undefined) {
6968
+ this.pushWarning(`The ${provider} route was adopted without a Models profile; configure a model for it before testing the connection.`);
6969
+ }
6970
+ }
6971
+ // A user profile that appeared after the snapshot above is the record's
6972
+ // source of truth. The node this adoption created is not: it carries no
6973
+ // pre-adoption settings, and `originalApiKeyEnv` stays what adoption found
6974
+ // so the takeover never replaces a reference the user saved meanwhile.
6975
+ const adoptedProfile = profile !== undefined || materialized?.created === true
6976
+ ? profile
6977
+ : this.profileAt(entry.settingsNs, entry.settingsPath);
6619
6978
  const record = {
6620
6979
  provider,
6621
6980
  displayName: extra?.name ?? entry.displayName ?? provider,
6622
6981
  source: extra !== undefined ? 'extra' : 'dsh',
6623
6982
  settingsNs: entry.settingsNs,
6624
6983
  settingsPath: [...entry.settingsPath],
6625
- adapter: entry.settingsNs.includes('deepseek') || provider === 'deepseek-official' ? 'deepseek' : 'pi-ai',
6984
+ adapter: piAiRoute ? 'pi-ai' : 'deepseek',
6626
6985
  brokerRef,
6627
6986
  originalApiKeyEnv,
6628
- createdProfile: false,
6629
- hadProfile: profile !== undefined,
6987
+ createdProfile: materialized?.created === true,
6988
+ hadProfile: adoptedProfile !== undefined,
6630
6989
  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 ?? [],
6990
+ api: adoptedProfile?.api ?? extra?.api ?? null,
6991
+ baseURL: adoptedProfile?.baseURL ?? extra?.baseURL ?? entry.defaultBaseURL ?? null,
6992
+ models: materialized?.models ?? (adoptedProfile !== undefined ? normalizeModels(adoptedProfile.models) : extra?.models ?? []),
6634
6993
  adoptedAt: Date.now(),
6635
6994
  cursor: 0,
6636
6995
  keys: imported !== undefined ? [imported] : [],
@@ -6755,8 +7114,10 @@ export class KeysManagerService {
6755
7114
  * Undo an adoption whose initial binding write was refused (PR review
6756
7115
  * round 2): drop the managed record and its broker entry, delete the
6757
7116
  * 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.
7117
+ * reference that landed despite the refusal. The source credential is never
7118
+ * touched, and a profile this adoption materialized is removed whole only
7119
+ * while it still holds exactly that materialized node: a user save landing
7120
+ * between the write and the rollback owns the profile, so it keeps it.
6760
7121
  */
6761
7122
  async rollbackAdoption(record, imported) {
6762
7123
  const provider = record.provider;
@@ -6770,6 +7131,21 @@ export class KeysManagerService {
6770
7131
  this.warn(`adoption rollback could not delete the imported credential ${imported.ref} for ${provider}: ${error instanceof Error ? error.message : String(error)}`);
6771
7132
  }
6772
7133
  }
7134
+ if (record.createdProfile) {
7135
+ const live = this.profileAt(record.settingsNs, record.settingsPath);
7136
+ if (live !== undefined && isMaterializedProfile(live, record.models)) {
7137
+ try {
7138
+ await this.mutateSettings(record.settingsNs, [{ op: 'unset', path: record.settingsPath }]);
7139
+ }
7140
+ catch (error) {
7141
+ this.warn(`adoption rollback could not remove the ${provider} profile it created: ${error instanceof Error ? error.message : String(error)}`);
7142
+ }
7143
+ this.store.touch();
7144
+ return;
7145
+ }
7146
+ // A user took the node over while the adoption was settling, so it falls
7147
+ // through to the apiKeyEnv-only compensation below: never delete theirs.
7148
+ }
6773
7149
  const descriptor = this.describeSettings();
6774
7150
  const namespace = this.namespace(descriptor, record.settingsNs);
6775
7151
  const profile = asProfile(namespace === undefined ? undefined : getPath(namespace.value, record.settingsPath));
@@ -6805,17 +7181,7 @@ export class KeysManagerService {
6805
7181
  catch (error) {
6806
7182
  failure = error instanceof Error ? error.message : String(error);
6807
7183
  }
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
- }
7184
+ const models = discoveredModels(discovered);
6819
7185
  if (models.length > 0)
6820
7186
  return { models, failure };
6821
7187
  return { models: normalizeModels(extra.models), failure };
@@ -6828,7 +7194,9 @@ export class KeysManagerService {
6828
7194
  * the key that serves it in the same mutation, so the write below is the
6829
7195
  * route's first binding rather than a takeover of a value the user owns.
6830
7196
  */
6831
- addExtraProvider(extraId, alias, value) {
7197
+ addExtraProvider(extraId, alias, value,
7198
+ /** Provenance for the first row; `signin:<driver>` for an in-process sign-in. */
7199
+ importedFrom = null) {
6832
7200
  return this.run(async () => {
6833
7201
  if (typeof extraId !== 'string' || extraId.length === 0)
6834
7202
  throw new Error('extraId is required');
@@ -6847,7 +7215,7 @@ export class KeysManagerService {
6847
7215
  // add-key flow restores them and the repair keeps one implementation.
6848
7216
  // Hand it the value resolved above: the entry refusal stays the single
6849
7217
  // decision for this surface, and the environment is read once per add.
6850
- await this.addKeyLocked(extraId, input.alias, input.value, headers);
7218
+ await this.addKeyLocked(extraId, input.alias, input.value, headers, importedFrom);
6851
7219
  this.store.touch();
6852
7220
  return this.buildState();
6853
7221
  }
@@ -6877,7 +7245,7 @@ export class KeysManagerService {
6877
7245
  cursor: 0,
6878
7246
  keys: [],
6879
7247
  };
6880
- const key = await this.createKeyRecord(extraId, input.alias, input.value);
7248
+ const key = await this.createKeyRecord(extraId, input.alias, input.value, importedFrom);
6881
7249
  const ops = [{ op: 'set', path: ['providers', extraId, 'apiKeyEnv'], value: record.brokerRef }];
6882
7250
  // Fill the declared headers the stored profile does not carry; a value
6883
7251
  // the profile already sets for the same header is never overwritten.
@@ -6912,9 +7280,20 @@ export class KeysManagerService {
6912
7280
  this.store.touch();
6913
7281
  return this.buildState();
6914
7282
  }
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');
7283
+ // A sign-in already proved the credential, so its commit seeds the catalog
7284
+ // instead of probing the endpoint: discovery may hold this serialized
7285
+ // mutation for its whole 20 s timeout before the row appears (F3).
7286
+ const found = importedFrom === null
7287
+ ? await this.discoverModels(extra, input.value)
7288
+ : { models: normalizeModels(extra.models) };
7289
+ const { models, failure } = found;
7290
+ // The sign-in branch never probed the endpoint, so it cannot report a
7291
+ // discovery result.
7292
+ if (models.length === 0) {
7293
+ throw new Error(importedFrom === null
7294
+ ? 'No models were discovered and the seed catalog is empty'
7295
+ : 'The plugin catalog is empty for this provider');
7296
+ }
6918
7297
  if (failure !== undefined)
6919
7298
  this.pushWarning(`Model discovery failed; installed ${models.length} seed models instead: ${failure}`);
6920
7299
  const brokerRef = brokerRefFor(extraId);
@@ -6926,7 +7305,7 @@ export class KeysManagerService {
6926
7305
  ...(headers === undefined ? {} : { headers }),
6927
7306
  models,
6928
7307
  };
6929
- const key = await this.createKeyRecord(extraId, input.alias, input.value);
7308
+ const key = await this.createKeyRecord(extraId, input.alias, input.value, importedFrom);
6930
7309
  try {
6931
7310
  // The profile and its binding are created together (see the method
6932
7311
  // comment); no user value exists to take over here.
@@ -7026,7 +7405,7 @@ export class KeysManagerService {
7026
7405
  this.pushWarning(`Restored the missing ${Object.keys(missing).join(', ')} header on the managed profile.`);
7027
7406
  }
7028
7407
  /** Add one key; caller already owns the mutation queue. */
7029
- async addKeyLocked(provider, alias, value, declaredHeaders) {
7408
+ async addKeyLocked(provider, alias, value, declaredHeaders, importedFrom = null) {
7030
7409
  const record = this.store.provider(provider);
7031
7410
  if (record === undefined)
7032
7411
  throw new Error(`Provider "${provider}" is not managed`);
@@ -7043,7 +7422,7 @@ export class KeysManagerService {
7043
7422
  const input = validateKeyInput(alias, value);
7044
7423
  if (record.keys.length >= KEY_LIMIT)
7045
7424
  throw new Error(`A provider may have at most ${KEY_LIMIT} keys`);
7046
- const key = await this.createKeyRecord(provider, input.alias, input.value);
7425
+ const key = await this.createKeyRecord(provider, input.alias, input.value, importedFrom);
7047
7426
  record.keys.push(key);
7048
7427
  // After the key add: a refused key (capability or capacity) must leave the
7049
7428
  // settings document untouched, so the repair never runs ahead of it.
@@ -7056,9 +7435,9 @@ export class KeysManagerService {
7056
7435
  await this.syncBrokerBinding(provider, record.extraId === null ? {} : { write: false });
7057
7436
  }
7058
7437
  /** Remote: add one key to a managed provider. */
7059
- addKey(provider, alias, value) {
7438
+ addKey(provider, alias, value, importedFrom = null) {
7060
7439
  return this.run(async () => {
7061
- await this.addKeyLocked(provider, alias, value);
7440
+ await this.addKeyLocked(provider, alias, value, undefined, importedFrom);
7062
7441
  this.store.touch();
7063
7442
  return this.buildState();
7064
7443
  });