dsh-keys-manager 0.2.3 → 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/CHANGELOG.md +31 -0
- package/README.md +49 -4
- package/README.zh-CN.md +24 -4
- package/lib/client/format.d.ts +11 -1
- package/lib/client/styles.d.ts +1 -1
- package/lib/client/types.d.ts +16 -2
- package/lib/client.js +293 -33
- package/lib/core.d.ts +7 -8
- package/lib/core.js +7 -0
- package/lib/core.js.map +1 -1
- package/lib/domain.d.ts +29 -1
- package/lib/host-types.d.ts +12 -3
- package/lib/index.d.ts +165 -6
- package/lib/index.js +750 -119
- package/lib/index.js.map +1 -1
- package/lib/oauth/adapter.d.ts +59 -0
- package/lib/oauth/adapter.js +47 -0
- package/lib/oauth/adapter.js.map +1 -0
- package/lib/oauth/providers.d.ts +31 -0
- package/lib/oauth/providers.js +34 -0
- package/lib/oauth/providers.js.map +1 -0
- package/lib/oauth/signin.d.ts +58 -0
- package/lib/oauth/signin.js +112 -0
- package/lib/oauth/signin.js.map +1 -0
- package/lib/omp-oauth/oauth.mjs +1785 -0
- package/locale/en.json +11 -1
- package/locale/zh.json +11 -1
- package/package.json +9 -4
- package/scripts/verify-dist.mjs +18 -1
package/lib/index.js
CHANGED
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
17
17
|
import { createHash, randomBytes } from 'node:crypto';
|
|
18
|
-
import {
|
|
18
|
+
import { CURSOR_ROUTE, cursorCatalogModels } from 'dsh-llm-omp-transports';
|
|
19
|
+
import * as transportModule from 'dsh-llm-omp-transports';
|
|
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';
|
|
19
23
|
import { EXTRA_PROVIDER_MAP, EXTRA_PROVIDERS } from './providers.js';
|
|
20
24
|
import { KeysManagerStore, ensureStateFile, statePath } from './store.js';
|
|
21
25
|
export const name = 'keys-manager';
|
|
@@ -176,7 +180,9 @@ function promptView(prompt) {
|
|
|
176
180
|
&& typeof entry.id === 'string'
|
|
177
181
|
&& typeof entry.label === 'string')
|
|
178
182
|
: undefined;
|
|
179
|
-
const kind = prompt.kind === 'secret' || prompt.kind === 'select'
|
|
183
|
+
const kind = prompt.kind === 'secret' || prompt.kind === 'select' || prompt.kind === 'manual-code'
|
|
184
|
+
? prompt.kind
|
|
185
|
+
: 'text';
|
|
180
186
|
return {
|
|
181
187
|
kind,
|
|
182
188
|
message: prompt.message,
|
|
@@ -241,6 +247,7 @@ const INVOCATIONS = [
|
|
|
241
247
|
// duplicating the account.
|
|
242
248
|
endpoint('beginAccountLogin', ['provider', 'alias', 'targetAccountId']),
|
|
243
249
|
endpoint('answerAccountPrompt', ['attemptId', 'value']),
|
|
250
|
+
endpoint('cancelAccountLogin', ['attemptId']),
|
|
244
251
|
endpoint('accountAttempt', ['attemptId']),
|
|
245
252
|
endpoint('listAccountAttempts'),
|
|
246
253
|
endpoint('activateAccount', ['provider', 'accountId']),
|
|
@@ -255,6 +262,11 @@ const INVOCATIONS = [
|
|
|
255
262
|
endpoint('beginTransportLogin', ['provider']),
|
|
256
263
|
endpoint('activateTransportAccount', ['provider']),
|
|
257
264
|
endpoint('removeTransportAccount', ['provider']),
|
|
265
|
+
// The transport card's model picker: the catalog lives in the transports
|
|
266
|
+
// package (listModels answers only the allow-list), and the selection is
|
|
267
|
+
// written to the route's own settings path.
|
|
268
|
+
endpoint('transportModels', ['provider']),
|
|
269
|
+
endpoint('saveTransportModels', ['provider', 'models']),
|
|
258
270
|
];
|
|
259
271
|
/** Read a nested value by path. */
|
|
260
272
|
function getPath(value, path) {
|
|
@@ -269,6 +281,15 @@ function getPath(value, path) {
|
|
|
269
281
|
function asProfile(value) {
|
|
270
282
|
return value !== null && typeof value === 'object' ? value : undefined;
|
|
271
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
|
+
}
|
|
272
293
|
/** Stable broker credential reference for one provider route. */
|
|
273
294
|
function brokerRefFor(provider) {
|
|
274
295
|
const stem = provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 34);
|
|
@@ -338,6 +359,24 @@ function discoveredModel(model) {
|
|
|
338
359
|
inputModalities: model.inputModalities,
|
|
339
360
|
});
|
|
340
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
|
+
}
|
|
341
380
|
/** Credential-bearing header names the carrier must never persist as plain settings. */
|
|
342
381
|
const CREDENTIAL_HEADER_NAMES = new Set(['authorization', 'proxy-authorization', 'cookie', 'api-key', 'apikey', 'x-api-key']);
|
|
343
382
|
/** Carrier headers are non-secret metadata; a credential-bearing name is refused. */
|
|
@@ -469,11 +508,14 @@ function transportGrantOf(record) {
|
|
|
469
508
|
const source = payload;
|
|
470
509
|
if (typeof source.access !== 'string' || source.access.length === 0)
|
|
471
510
|
return undefined;
|
|
472
|
-
|
|
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))) {
|
|
473
514
|
return undefined;
|
|
515
|
+
}
|
|
474
516
|
return {
|
|
475
517
|
access: source.access,
|
|
476
|
-
expires: source.expires,
|
|
518
|
+
...(source.expires === undefined ? {} : { expires: source.expires }),
|
|
477
519
|
...(typeof source.refresh === 'string' && source.refresh.length > 0 ? { refresh: source.refresh } : {}),
|
|
478
520
|
...(typeof source.email === 'string' && source.email.length > 0 ? { email: source.email } : {}),
|
|
479
521
|
...(typeof source.accountId === 'string' && source.accountId.length > 0 ? { accountId: source.accountId } : {}),
|
|
@@ -489,14 +531,19 @@ function transportGrantOf(record) {
|
|
|
489
531
|
* exists while signed out, so the UI can offer the sign-in that writes it.
|
|
490
532
|
*/
|
|
491
533
|
function transportAccountOf(flow, record, now) {
|
|
534
|
+
const route = flow.key.slice(TRANSPORT_CREDENTIAL_SCOPE.length + 1);
|
|
492
535
|
const grant = transportGrantOf(record);
|
|
493
|
-
const status = grant
|
|
494
|
-
?
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
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';
|
|
498
545
|
return {
|
|
499
|
-
id:
|
|
546
|
+
id: route,
|
|
500
547
|
scope: flow.key,
|
|
501
548
|
displayName: flow.label,
|
|
502
549
|
...(grant?.email === undefined ? {} : { email: grant.email }),
|
|
@@ -517,6 +564,35 @@ function transportAccountOf(flow, record, now) {
|
|
|
517
564
|
function transportMethodOf(flow) {
|
|
518
565
|
return flow.methods[0]?.id;
|
|
519
566
|
}
|
|
567
|
+
/** The `devin` transport route id (its catalog ships with the same package). */
|
|
568
|
+
const DEVIN_ROUTE = 'devin';
|
|
569
|
+
/**
|
|
570
|
+
* The catalog a transport route advertises to its model picker.
|
|
571
|
+
*
|
|
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 `[]`.
|
|
581
|
+
*/
|
|
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();
|
|
595
|
+
}
|
|
520
596
|
/** Env names that are a single API-key credential, not an OAuth/federation token. */
|
|
521
597
|
function isKeyishEnv(name) {
|
|
522
598
|
if (!/(?:API_KEY|_TOKEN)$/.test(name))
|
|
@@ -558,17 +634,20 @@ const NO_OAUTH_FLOW_REASON = 'This provider has no OAuth sign-in flow registered
|
|
|
558
634
|
*
|
|
559
635
|
* `oauthFlow` is the live answer from {@link KeysManagerService.oauthFlowAvailable}
|
|
560
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.
|
|
561
640
|
*/
|
|
562
|
-
function capabilityOf(entry, profile, oauthFlow) {
|
|
641
|
+
function capabilityOf(entry, profile, oauthFlow, signIn = false) {
|
|
563
642
|
if (entry.error !== undefined)
|
|
564
643
|
return { keys: false, accounts: false, reason: entry.error };
|
|
565
|
-
const accounts = entry.nativeAuth?.oauth === true && oauthFlow;
|
|
644
|
+
const accounts = signIn || (entry.nativeAuth?.oauth === true && oauthFlow);
|
|
566
645
|
const unsupportedReason = UNSUPPORTED_KEY_POOL_PROVIDERS[entry.provider];
|
|
567
646
|
if (unsupportedReason !== undefined) {
|
|
568
647
|
// The table's reason describes the key verdict; when the only possible
|
|
569
648
|
// capability (accounts) is unavailable too, the flow gap is the truthful
|
|
570
649
|
// explanation a user needs.
|
|
571
|
-
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;
|
|
572
651
|
return { keys: false, accounts, reason };
|
|
573
652
|
}
|
|
574
653
|
if (entry.provider === 'deepseek-official')
|
|
@@ -582,8 +661,8 @@ function capabilityOf(entry, profile, oauthFlow) {
|
|
|
582
661
|
// key credential at all.
|
|
583
662
|
if (auth.env.some(isKeyishEnv))
|
|
584
663
|
return { keys: true, accounts };
|
|
585
|
-
if (auth.oauth) {
|
|
586
|
-
return
|
|
664
|
+
if (auth.oauth || signIn) {
|
|
665
|
+
return accounts
|
|
587
666
|
? { keys: false, accounts: true, reason: 'This provider signs in with an OAuth account; no API key is used' }
|
|
588
667
|
: { keys: false, accounts: false, reason: NO_OAUTH_FLOW_REASON };
|
|
589
668
|
}
|
|
@@ -602,12 +681,17 @@ function capabilityOf(entry, profile, oauthFlow) {
|
|
|
602
681
|
* may mount after this plugin, so availability is never cached at
|
|
603
682
|
* construction. While the flow list is empty (seam not mounted yet) support
|
|
604
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.
|
|
605
687
|
*/
|
|
606
|
-
function accountSupportOf(entry, oauthFlow) {
|
|
688
|
+
function accountSupportOf(entry, oauthFlow, signIn = false) {
|
|
607
689
|
if (entry === undefined)
|
|
608
690
|
return { supported: false, reason: 'This provider route is not registered' };
|
|
609
691
|
if (entry.error !== undefined)
|
|
610
692
|
return { supported: false, reason: entry.error };
|
|
693
|
+
if (signIn)
|
|
694
|
+
return { supported: true };
|
|
611
695
|
if (entry.nativeAuth?.oauth !== true)
|
|
612
696
|
return { supported: false, reason: 'This provider offers no OAuth account sign-in' };
|
|
613
697
|
if (!oauthFlow)
|
|
@@ -653,7 +737,15 @@ export class KeysManagerService {
|
|
|
653
737
|
attemptSequence = 0;
|
|
654
738
|
switches = new Map();
|
|
655
739
|
warnings = [];
|
|
740
|
+
/** Transport routes already reported as having no shipped catalog. */
|
|
741
|
+
catalogReports = new Set();
|
|
656
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;
|
|
657
749
|
rawCredentials;
|
|
658
750
|
credentialOriginals = new WeakMap();
|
|
659
751
|
credentialWrappers = new WeakMap();
|
|
@@ -1068,9 +1160,10 @@ export class KeysManagerService {
|
|
|
1068
1160
|
// serves the route ahead of any broker reference exactly like an
|
|
1069
1161
|
// unowned grant, so it is classified as foreign below (PR review
|
|
1070
1162
|
// rounds 4 and 13).
|
|
1071
|
-
const
|
|
1072
|
-
?
|
|
1163
|
+
const projection = record.kind === 'grant' && isOAuthGrantPayload(record.payload)
|
|
1164
|
+
? record.payload
|
|
1073
1165
|
: undefined;
|
|
1166
|
+
const owner = projection === undefined ? undefined : matchOwningAccount(provider, accounts, projection);
|
|
1074
1167
|
// A newer activation/login claimed the owner while this read was in
|
|
1075
1168
|
// flight: the stale read is discarded, never written over it. A
|
|
1076
1169
|
// remount replaced the whole store: its classification is gone too.
|
|
@@ -1802,11 +1895,20 @@ export class KeysManagerService {
|
|
|
1802
1895
|
if (typeof provider !== 'string' || provider.length === 0)
|
|
1803
1896
|
throw new TypeError('provider is required');
|
|
1804
1897
|
const flow = this.oauthFlowFor(provider);
|
|
1805
|
-
|
|
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)
|
|
1806
1904
|
throw new Error(`Provider "${provider}" offers no OAuth sign-in flow`);
|
|
1807
1905
|
const providerRecord = this.store.provider(provider);
|
|
1808
|
-
|
|
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) {
|
|
1809
1910
|
throw new Error(`Provider "${provider}" is not managed; adopt it before signing in`);
|
|
1911
|
+
}
|
|
1810
1912
|
// Validate the re-authentication target up front (round-3 finding 6):
|
|
1811
1913
|
// the harvest binds the new grant to this row, so it must already name
|
|
1812
1914
|
// a live OAuth account of this provider. It runs BEFORE the pending
|
|
@@ -1815,12 +1917,22 @@ export class KeysManagerService {
|
|
|
1815
1917
|
// foreign id is refused even while another sign-in is pending.
|
|
1816
1918
|
let cleanTarget;
|
|
1817
1919
|
if (typeof targetAccountId === 'string' && targetAccountId.length > 0) {
|
|
1818
|
-
const target = providerRecord
|
|
1920
|
+
const target = providerRecord?.keys.find(candidate => candidate.id === targetAccountId);
|
|
1819
1921
|
if (target === undefined)
|
|
1820
1922
|
throw new Error(`Account "${targetAccountId}" not found on ${provider}`);
|
|
1821
|
-
if (
|
|
1822
|
-
|
|
1823
|
-
|
|
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
|
+
}
|
|
1824
1936
|
}
|
|
1825
1937
|
if (this.loginsInFlight.has(provider)) {
|
|
1826
1938
|
// F3 (I-000082): a pending attempt IS the flow — reopening the dialog
|
|
@@ -1856,18 +1968,25 @@ export class KeysManagerService {
|
|
|
1856
1968
|
notices: [],
|
|
1857
1969
|
createdAt: now,
|
|
1858
1970
|
updatedAt: now,
|
|
1971
|
+
inProcess: flow === undefined,
|
|
1859
1972
|
controller: new AbortController(),
|
|
1860
1973
|
};
|
|
1861
1974
|
this.loginAttempts.set(attempt.id, attempt);
|
|
1862
1975
|
this.capLoginAttempts();
|
|
1863
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
|
+
}
|
|
1864
1984
|
const records = this.credentialRecords();
|
|
1865
1985
|
if (records === undefined) {
|
|
1866
1986
|
this.loginAttempts.delete(attempt.id);
|
|
1867
1987
|
this.loginsInFlight.delete(provider);
|
|
1868
1988
|
throw new Error('The credential store does not support records; OAuth sign-in is unavailable');
|
|
1869
1989
|
}
|
|
1870
|
-
const interaction = this.attemptInteraction(attempt);
|
|
1871
1990
|
const beginPromise = this.ctx.authorization.begin({
|
|
1872
1991
|
key: flow.key,
|
|
1873
1992
|
method: flow.method,
|
|
@@ -1889,6 +2008,104 @@ export class KeysManagerService {
|
|
|
1889
2008
|
});
|
|
1890
2009
|
return attemptView(attempt);
|
|
1891
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
|
+
}
|
|
1892
2109
|
/** Resolve the attempt's parked prompt with the human's answer. */
|
|
1893
2110
|
async answerAccountPrompt(attemptId, value) {
|
|
1894
2111
|
const attempt = this.loginAttempts.get(attemptId);
|
|
@@ -1904,6 +2121,22 @@ export class KeysManagerService {
|
|
|
1904
2121
|
this.dropPrompt(attempt);
|
|
1905
2122
|
resolve(value);
|
|
1906
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
|
+
}
|
|
1907
2140
|
/** One attempt's serializable view, or undefined when unknown. */
|
|
1908
2141
|
getAccountAttempt(attemptId) {
|
|
1909
2142
|
const attempt = this.loginAttempts.get(attemptId);
|
|
@@ -2011,6 +2244,8 @@ export class KeysManagerService {
|
|
|
2011
2244
|
notices: [],
|
|
2012
2245
|
createdAt: now,
|
|
2013
2246
|
updatedAt: now,
|
|
2247
|
+
// A transport attempt is seam-driven; `cancelAccountLogin` must not touch it.
|
|
2248
|
+
inProcess: false,
|
|
2014
2249
|
controller: new AbortController(),
|
|
2015
2250
|
};
|
|
2016
2251
|
this.loginAttempts.set(attempt.id, attempt);
|
|
@@ -2105,6 +2340,104 @@ export class KeysManagerService {
|
|
|
2105
2340
|
transportGenerationOf(route) {
|
|
2106
2341
|
return this.transportRemovals.get(route) ?? 0;
|
|
2107
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
|
+
}
|
|
2360
|
+
/**
|
|
2361
|
+
* Remote: read one transport route's catalog and configured allow-list.
|
|
2362
|
+
*
|
|
2363
|
+
* @remarks
|
|
2364
|
+
* The catalog comes from the transports package, because the route's
|
|
2365
|
+
* `listModels` answers only the allow-list. An empty allow-list means "all
|
|
2366
|
+
* models", so an unreadable settings store must not answer `[]` — a save
|
|
2367
|
+
* would then clear a narrowed selection — and it rejects instead.
|
|
2368
|
+
*/
|
|
2369
|
+
async transportModels(route) {
|
|
2370
|
+
this.assertTransportRoute(route);
|
|
2371
|
+
const configured = this.transportModelIds(route);
|
|
2372
|
+
let warning;
|
|
2373
|
+
const catalog = transportCatalogOf(route, missing => { warning = this.reportMissingCatalog(missing); });
|
|
2374
|
+
// A settings profile can outlive a catalog id; the picker renders the
|
|
2375
|
+
// catalog, so an unknown id would count toward {n} of {total} while
|
|
2376
|
+
// matching no checkbox and failing every save.
|
|
2377
|
+
const known = new Set(catalog.map(row => row.id));
|
|
2378
|
+
const models = configured.filter(id => known.has(id));
|
|
2379
|
+
return warning === undefined ? { catalog, models } : { catalog, models, warning };
|
|
2380
|
+
}
|
|
2381
|
+
/**
|
|
2382
|
+
* Remote: replace one transport route's model allow-list.
|
|
2383
|
+
*
|
|
2384
|
+
* Writes only the route's own `providers.<route>.models` path through the
|
|
2385
|
+
* live settings revision; an empty list restores the full catalog.
|
|
2386
|
+
*/
|
|
2387
|
+
async saveTransportModels(route, models) {
|
|
2388
|
+
this.assertTransportRoute(route);
|
|
2389
|
+
if (!Array.isArray(models) || models.some(id => typeof id !== 'string')) {
|
|
2390
|
+
throw new TypeError('models must be a list of model ids');
|
|
2391
|
+
}
|
|
2392
|
+
const catalog = transportCatalogOf(route, missing => this.reportMissingCatalog(missing));
|
|
2393
|
+
if (catalog.length === 0)
|
|
2394
|
+
throw new Error(`Provider "${route}" offers no model list`);
|
|
2395
|
+
const known = new Map(catalog.map(row => [row.id, row.name]));
|
|
2396
|
+
const selected = [...new Set(models)];
|
|
2397
|
+
const unknown = selected.find(id => !known.has(id));
|
|
2398
|
+
if (unknown !== undefined)
|
|
2399
|
+
throw new Error(`Provider "${route}" has no model "${unknown}"`);
|
|
2400
|
+
await this.mutateSettings(TRANSPORT_CREDENTIAL_SCOPE, [
|
|
2401
|
+
{
|
|
2402
|
+
op: 'set',
|
|
2403
|
+
path: ['providers', route, 'models'],
|
|
2404
|
+
value: selected.map(id => ({ id, name: known.get(id) })),
|
|
2405
|
+
},
|
|
2406
|
+
]);
|
|
2407
|
+
return this.transportModels(route);
|
|
2408
|
+
}
|
|
2409
|
+
/** Refuse a route the transports package does not register. */
|
|
2410
|
+
assertTransportRoute(route) {
|
|
2411
|
+
if (typeof route !== 'string' || route.length === 0)
|
|
2412
|
+
throw new TypeError('provider is required');
|
|
2413
|
+
if (this.transportFlowFor(route) === undefined)
|
|
2414
|
+
throw new Error(`Provider "${route}" offers no transport account`);
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* One transport route's configured model ids, read from the live settings.
|
|
2418
|
+
*
|
|
2419
|
+
* @remarks
|
|
2420
|
+
* Rejects when the descriptor is unreadable or this plugin's namespace is
|
|
2421
|
+
* not mounted: a registered route always owns that namespace, so answering
|
|
2422
|
+
* "no models configured" would report the all-models state for a store the
|
|
2423
|
+
* host simply could not read.
|
|
2424
|
+
*/
|
|
2425
|
+
transportModelIds(route) {
|
|
2426
|
+
const descriptor = this.describeSettings();
|
|
2427
|
+
if (!descriptor.readable)
|
|
2428
|
+
throw new Error('Cannot read settings: the settings store is unavailable');
|
|
2429
|
+
const namespace = this.namespace(descriptor, TRANSPORT_CREDENTIAL_SCOPE);
|
|
2430
|
+
if (namespace === undefined) {
|
|
2431
|
+
throw new Error(`Settings namespace "${TRANSPORT_CREDENTIAL_SCOPE}" is not mounted`);
|
|
2432
|
+
}
|
|
2433
|
+
const value = getPath(namespace.value, ['providers', route, 'models']);
|
|
2434
|
+
if (!Array.isArray(value))
|
|
2435
|
+
return [];
|
|
2436
|
+
return value.flatMap(row => {
|
|
2437
|
+
const id = row !== null && typeof row === 'object' ? row.id : undefined;
|
|
2438
|
+
return typeof id === 'string' ? [id] : [];
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2108
2441
|
/**
|
|
2109
2442
|
* Drop a grant a withdrawn sign-in wrote after its account was removed.
|
|
2110
2443
|
*
|
|
@@ -2636,11 +2969,20 @@ export class KeysManagerService {
|
|
|
2636
2969
|
return;
|
|
2637
2970
|
}
|
|
2638
2971
|
if (harvest.wroteRef) {
|
|
2639
|
-
|
|
2640
|
-
|
|
2972
|
+
// A live row still names this ref: a same-ref re-authentication writes
|
|
2973
|
+
// over the record its own pre-existing row depends on, and this
|
|
2974
|
+
// compensation must not leave that row dangling (same guard as the
|
|
2975
|
+
// rotation cleanup, R5-MF1).
|
|
2976
|
+
if (this.grantRefServed(attempt.provider, harvest.grantRef)) {
|
|
2977
|
+
this.warn(`harvest compensation kept ${harvest.grantRef} for ${attempt.provider}: an account row still references it`);
|
|
2641
2978
|
}
|
|
2642
|
-
|
|
2643
|
-
|
|
2979
|
+
else {
|
|
2980
|
+
try {
|
|
2981
|
+
await records.deleteRecord(harvest.grantRef);
|
|
2982
|
+
}
|
|
2983
|
+
catch (error) {
|
|
2984
|
+
this.warn(`harvest compensation could not delete ${harvest.grantRef}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2985
|
+
}
|
|
2644
2986
|
}
|
|
2645
2987
|
}
|
|
2646
2988
|
await this.revertHarvestProjection(attempt, harvest);
|
|
@@ -3392,9 +3734,16 @@ export class KeysManagerService {
|
|
|
3392
3734
|
// changes. A same-ref rotation that lands while the activation waits in
|
|
3393
3735
|
// the queue is the uncovered case.
|
|
3394
3736
|
const source = await records.readRecord(prepared.grantRef);
|
|
3395
|
-
|
|
3737
|
+
const sourceMatches = source !== undefined
|
|
3738
|
+
&& source.kind === 'grant'
|
|
3739
|
+
&& JSON.stringify(source.payload) === prepared.written;
|
|
3740
|
+
// The preparation can carry a payload its own repair write did not
|
|
3741
|
+
// persist: the ownership-verified projection is then the live credential,
|
|
3742
|
+
// and an absent or unusable ref is that state — not a concurrent writer.
|
|
3743
|
+
const sourceAbsentOrUnusable = source === undefined
|
|
3396
3744
|
|| source.kind !== 'grant'
|
|
3397
|
-
||
|
|
3745
|
+
|| !isOAuthGrantPayload(source.payload);
|
|
3746
|
+
if (!sourceMatches && !(prepared.recoveredFromProjection && sourceAbsentOrUnusable)) {
|
|
3398
3747
|
throw new Error(`The grant payload for "${accountId}" on ${provider} could not be projected; activate the account again`);
|
|
3399
3748
|
}
|
|
3400
3749
|
}
|
|
@@ -3562,19 +3911,123 @@ export class KeysManagerService {
|
|
|
3562
3911
|
throw error;
|
|
3563
3912
|
}
|
|
3564
3913
|
}
|
|
3914
|
+
/**
|
|
3915
|
+
* The row's own grant payload, recovered from the live projection when the
|
|
3916
|
+
* plugin-scope record is gone. The projection IS the route's credential, so a
|
|
3917
|
+
* matching payload is written back (compare-at-absent) and used immediately.
|
|
3918
|
+
*
|
|
3919
|
+
* `recoveredFromProjection` marks a payload the ownership-verified projection
|
|
3920
|
+
* supplied when the repair write did not persist it: the ref stays absent or
|
|
3921
|
+
* unusable, so a caller that re-reads it must treat the payload as the live
|
|
3922
|
+
* credential instead of a concurrent writer's record. That case also returns
|
|
3923
|
+
* the projection record it validated: a caller that compares before writing
|
|
3924
|
+
* must use this snapshot as its baseline, or the compare would accept a
|
|
3925
|
+
* rotation that landed after the payload was read. It never marks a
|
|
3926
|
+
* projection whose row has been detached or repointed since the snapshot —
|
|
3927
|
+
* that recovery is refused, because the projection then belongs to a
|
|
3928
|
+
* generation this row no longer names. For the same reason a repair the
|
|
3929
|
+
* updater declined (row gone, retiring, or repointed) resolves `undefined`:
|
|
3930
|
+
* the callers' own "missing or unusable" failure is the truthful answer, not
|
|
3931
|
+
* the payload of a generation this row has left behind.
|
|
3932
|
+
*/
|
|
3933
|
+
async recoverGrantPayload(provider, row, records) {
|
|
3934
|
+
const grantRef = row.oauth.grantRef;
|
|
3935
|
+
const stored = await records.readRecord(grantRef);
|
|
3936
|
+
if (stored !== undefined && stored.kind === 'grant' && isOAuthGrantPayload(stored.payload)) {
|
|
3937
|
+
return { payload: stored.payload, recoveredFromProjection: false };
|
|
3938
|
+
}
|
|
3939
|
+
const projectionKey = `${OAUTH_GRANT_RECORD_SCOPE}/${provider}`;
|
|
3940
|
+
// The seam can hand back its own live record and this repair awaits before
|
|
3941
|
+
// it writes: snapshot it once so the ownership check, the write and the
|
|
3942
|
+
// returned baseline all see the payload that was verified, even if the
|
|
3943
|
+
// source is updated in place meanwhile.
|
|
3944
|
+
const projection = structuredClone(await records.readRecord(projectionKey));
|
|
3945
|
+
if (projection === undefined || projection.kind !== 'grant' || !isOAuthGrantPayload(projection.payload))
|
|
3946
|
+
return undefined;
|
|
3947
|
+
// Only a projection this row owns is adopted; recovering a foreign grant
|
|
3948
|
+
// would attach another account's credential to this row.
|
|
3949
|
+
const oauthRows = this.store.provider(provider)?.keys.filter(candidate => candidate.kind === 'oauth' && candidate.oauth !== null) ?? [];
|
|
3950
|
+
if (matchOwningAccount(provider, oauthRows, projection.payload)?.id !== row.id)
|
|
3951
|
+
return undefined;
|
|
3952
|
+
// `row` is a snapshot taken before the reads: a removal or a re-sign-in can
|
|
3953
|
+
// have detached or repointed it since, and the repair must not land on a
|
|
3954
|
+
// ref this row no longer names.
|
|
3955
|
+
if (oauthRows.find(candidate => candidate.id === row.id)?.oauth?.grantRef !== grantRef) {
|
|
3956
|
+
// The row no longer names this ref, so the projection that matched it
|
|
3957
|
+
// belongs to a previous generation: refusing leaves the caller's own
|
|
3958
|
+
// "missing or unusable" failure in place instead of reviving it.
|
|
3959
|
+
return undefined;
|
|
3960
|
+
}
|
|
3961
|
+
// A declined updater is NOT "the ref is occupied by an unusable record":
|
|
3962
|
+
// it means nothing was written for this row, so the projection read above
|
|
3963
|
+
// is a previous generation's payload and must not be served.
|
|
3964
|
+
let declined = false;
|
|
3965
|
+
try {
|
|
3966
|
+
// Compare-at-absent: an occupied ref returns `current`, which the seam
|
|
3967
|
+
// keeps, so a concurrent login's or rotation's record wins the ref.
|
|
3968
|
+
const liveNow = await records.modifyRecord(grantRef, current => {
|
|
3969
|
+
if (current !== undefined)
|
|
3970
|
+
return Promise.resolve(current);
|
|
3971
|
+
// Runs under the seam's per-key lock, so this is the state the write
|
|
3972
|
+
// commits against: a removal that deleted the ref and marked (or
|
|
3973
|
+
// spliced) the row since the checks above must not be undone by
|
|
3974
|
+
// re-creating the credential it deleted.
|
|
3975
|
+
const liveRow = this.store.provider(provider)?.keys.find(candidate => candidate.id === row.id);
|
|
3976
|
+
if (liveRow === undefined
|
|
3977
|
+
|| this.retiringAccounts.has(liveRow)
|
|
3978
|
+
|| liveRow.kind !== 'oauth'
|
|
3979
|
+
|| liveRow.oauth === null
|
|
3980
|
+
|| liveRow.oauth.grantRef !== grantRef) {
|
|
3981
|
+
declined = true;
|
|
3982
|
+
return Promise.resolve(undefined);
|
|
3983
|
+
}
|
|
3984
|
+
return Promise.resolve({ kind: 'grant', payload: structuredClone(projection.payload) });
|
|
3985
|
+
});
|
|
3986
|
+
// No post-write compensation (PR #37 I-000233): it would prove what THIS
|
|
3987
|
+
// call wrote, not that the record it deleted was still ours — a same-ref
|
|
3988
|
+
// sign-in can commit a fresh record before attaching its row, and the
|
|
3989
|
+
// seam has no compare-and-delete (`deleteRecord(key)` takes no expected
|
|
3990
|
+
// payload). It is redundant: the removal path owns the ref it retires.
|
|
3991
|
+
// `removeOAuthGrant` marks the row in `retiringAccounts` BEFORE its first
|
|
3992
|
+
// awaited delete, and this updater revalidates synchronously under the
|
|
3993
|
+
// seam's per-key lock, so a removal that started first makes the update
|
|
3994
|
+
// decline, and one that starts after this write deletes
|
|
3995
|
+
// `row.oauth.grantRef` — the very ref this updater just proved the row
|
|
3996
|
+
// names — itself.
|
|
3997
|
+
if (declined)
|
|
3998
|
+
return undefined;
|
|
3999
|
+
// The ref may have been taken while this read was parked: the record's
|
|
4000
|
+
// payload is the credential the caller must borrow now, not the
|
|
4001
|
+
// projection this repair declined to write over it.
|
|
4002
|
+
if (liveNow !== undefined && liveNow.kind === 'grant' && isOAuthGrantPayload(liveNow.payload)) {
|
|
4003
|
+
return { payload: liveNow.payload, recoveredFromProjection: false };
|
|
4004
|
+
}
|
|
4005
|
+
}
|
|
4006
|
+
catch (error) {
|
|
4007
|
+
// Best-effort repair: the projection still served this read.
|
|
4008
|
+
this.warn(`could not restore ${grantRef} for ${provider}: ${error instanceof Error ? error.message : String(error)}`);
|
|
4009
|
+
}
|
|
4010
|
+
return { payload: projection.payload, recoveredFromProjection: true, projection };
|
|
4011
|
+
}
|
|
3565
4012
|
/**
|
|
3566
4013
|
* The slow half of an activation, outside the queue: read the row's grant
|
|
3567
|
-
* generation
|
|
4014
|
+
* generation (recovered from the live projection when its record is gone),
|
|
4015
|
+
* validate it, and capture the projection the route serves now.
|
|
3568
4016
|
*/
|
|
3569
4017
|
async prepareActivation(provider, row, records) {
|
|
3570
4018
|
const grantRef = row.oauth.grantRef;
|
|
3571
|
-
const
|
|
3572
|
-
if (
|
|
4019
|
+
const recovered = await this.recoverGrantPayload(provider, row, records);
|
|
4020
|
+
if (recovered === undefined) {
|
|
3573
4021
|
throw new Error(`The grant payload at ${grantRef} is missing or unusable; sign in to this account again`);
|
|
3574
4022
|
}
|
|
3575
4023
|
const projectionKey = `${OAUTH_GRANT_RECORD_SCOPE}/${provider}`;
|
|
3576
|
-
|
|
3577
|
-
|
|
4024
|
+
// A projection-only recovery already read and ownership-verified the route.
|
|
4025
|
+
// Re-reading it here would open a gap: a same-ref rotation landing in it
|
|
4026
|
+
// leaves the payload from the first read and a baseline from the second, so
|
|
4027
|
+
// the compare would pass and write the older credential. The record the
|
|
4028
|
+
// payload came from is the only truthful baseline for it.
|
|
4029
|
+
const live = recovered.projection ?? await records.readRecord(projectionKey);
|
|
4030
|
+
const payload = structuredClone(recovered.payload);
|
|
3578
4031
|
// F5: the restored record decides its owner, so the classification is
|
|
3579
4032
|
// derived from the baseline payload through the shared matcher — the same
|
|
3580
4033
|
// rule the reconciler applies — rather than from an owner id captured
|
|
@@ -3587,6 +4040,7 @@ export class KeysManagerService {
|
|
|
3587
4040
|
grantRef,
|
|
3588
4041
|
payload,
|
|
3589
4042
|
written: JSON.stringify(payload),
|
|
4043
|
+
recoveredFromProjection: recovered.recoveredFromProjection,
|
|
3590
4044
|
baseline: live === undefined ? { state: 'absent' } : { state: 'present', record: structuredClone(live) },
|
|
3591
4045
|
// Captured with the baseline, before the turn claims the route: the
|
|
3592
4046
|
// compensation has to put back the classification that matches the
|
|
@@ -4332,6 +4786,11 @@ export class KeysManagerService {
|
|
|
4332
4786
|
if (!await this.awaitProjectionOwnership(provider)) {
|
|
4333
4787
|
return { ok: false, latencyMs: 0, error: 'Account ownership is still loading; try again in a moment' };
|
|
4334
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);
|
|
4335
4794
|
const route = this.testRouteProfile(record);
|
|
4336
4795
|
if ('error' in route)
|
|
4337
4796
|
return { ok: false, latencyMs: 0, error: route.error };
|
|
@@ -4452,11 +4911,68 @@ export class KeysManagerService {
|
|
|
4452
4911
|
test: true,
|
|
4453
4912
|
});
|
|
4454
4913
|
}
|
|
4914
|
+
/**
|
|
4915
|
+
* Whether this test may still borrow the route, or the result it must report
|
|
4916
|
+
* instead: the window is live, shutdown has not begun, and the row still
|
|
4917
|
+
* exists, is not retiring, and still names the `grantRef` the test captured.
|
|
4918
|
+
*
|
|
4919
|
+
* Read before the borrow and again after every await that precedes it. The
|
|
4920
|
+
* grant recovery is one: it outlives the isolation deadline on a slow seam,
|
|
4921
|
+
* and a window the watchdog already released no longer compensates its late
|
|
4922
|
+
* borrow (that branch is guarded by `abandonedWindows.get(provider) === window`).
|
|
4923
|
+
*/
|
|
4924
|
+
borrowBarrier(window, provider, row, grantRef) {
|
|
4925
|
+
if (window.cleaned) {
|
|
4926
|
+
// QC fix wave 2: the watchdog abandoned this window while an await was in
|
|
4927
|
+
// flight. Starting (or resuming) the borrow now would land it after the
|
|
4928
|
+
// cleanup that already ran, so the test stops here.
|
|
4929
|
+
return this.abandonedTestResult();
|
|
4930
|
+
}
|
|
4931
|
+
if (this.shutdownRequested) {
|
|
4932
|
+
// PR review round 30: shutdown abandons the chain parked here, so the
|
|
4933
|
+
// borrow write must not land after `close()`. Round 34: the marker
|
|
4934
|
+
// is up from shutdown's entry, so the pre-close restoration is covered
|
|
4935
|
+
// too — it does not borrow, and this test must not either.
|
|
4936
|
+
return this.shutdownEntryResult();
|
|
4937
|
+
}
|
|
4938
|
+
// PR review round 12: the reads and the recovery above are awaits, so a
|
|
4939
|
+
// removal can have deleted the provider or this row while they were in
|
|
4940
|
+
// flight (a test that registered and one that did not are covered: the
|
|
4941
|
+
// marker refuses the latter, this re-check the former). Never write the
|
|
4942
|
+
// borrow — and never re-project the removed account's grant — on that state.
|
|
4943
|
+
// PR review round 15: the existence check alone still holds while a removal
|
|
4944
|
+
// is deleting credentials (the row is spliced only after its grant delete),
|
|
4945
|
+
// so the row's retirement mark is part of the assertion. The provider-wide
|
|
4946
|
+
// marker is deliberately not read here: a removal that began while this
|
|
4947
|
+
// test is registered waits for it in {@link settleTestBeforeRemoval} and is
|
|
4948
|
+
// the designed handshake, while the row mark is only set by a removal that
|
|
4949
|
+
// already passed that check.
|
|
4950
|
+
const live = this.store.provider(provider);
|
|
4951
|
+
const removing = this.retiringAccounts.has(row);
|
|
4952
|
+
const liveRow = live?.keys.find(candidate => candidate.id === row.id);
|
|
4953
|
+
if (removing || liveRow === undefined) {
|
|
4954
|
+
return removing
|
|
4955
|
+
? { ok: false, latencyMs: 0, error: `Provider "${provider}" is being removed; the test did not borrow its credential` }
|
|
4956
|
+
: { ok: false, latencyMs: 0, error: `Key "${row.id}" was removed from ${provider} before its test could borrow it` };
|
|
4957
|
+
}
|
|
4958
|
+
// PR #37 review (I-000234): a re-sign-in repoints the row instead of
|
|
4959
|
+
// removing it. The recovery read then belongs to the generation the row no
|
|
4960
|
+
// longer names, so borrowing it would test the previous credential and
|
|
4961
|
+
// report the outcome against this row.
|
|
4962
|
+
if (liveRow.oauth === null || liveRow.oauth.grantRef !== grantRef) {
|
|
4963
|
+
return { ok: false, latencyMs: 0, error: `Key "${row.id}" was repointed on ${provider} before its test could borrow it` };
|
|
4964
|
+
}
|
|
4965
|
+
return undefined;
|
|
4966
|
+
}
|
|
4455
4967
|
/** One request with the row's grant temporarily projected as the route's credential. */
|
|
4456
4968
|
async runOAuthRowTest(provider, row, model, window) {
|
|
4457
4969
|
const grant = row.oauth;
|
|
4458
4970
|
if (grant === null)
|
|
4459
4971
|
return { ok: false, latencyMs: 0, error: `Key "${row.id}" is not an OAuth account` };
|
|
4972
|
+
// Captured here, not read from the row later: a re-sign-in repoints the
|
|
4973
|
+
// row's generation in place, so the live object would answer with the NEW
|
|
4974
|
+
// ref and the borrow would look current.
|
|
4975
|
+
const grantRef = grant.grantRef;
|
|
4460
4976
|
const records = this.credentialRecords();
|
|
4461
4977
|
if (records === undefined)
|
|
4462
4978
|
return { ok: false, latencyMs: 0, error: 'The credential store does not support records' };
|
|
@@ -4466,23 +4982,6 @@ export class KeysManagerService {
|
|
|
4466
4982
|
// grant chain, so a rotation echo cannot observe or overwrite the
|
|
4467
4983
|
// temporary projection between them.
|
|
4468
4984
|
await this.scheduleGrantReconciliation(provider, async () => {
|
|
4469
|
-
const stored = await records.readRecord(grant.grantRef);
|
|
4470
|
-
if (window.cleaned) {
|
|
4471
|
-
// QC fix wave 2: the watchdog abandoned this window while the read was
|
|
4472
|
-
// in flight. Starting (or resuming) the borrow now would land it after
|
|
4473
|
-
// the cleanup that already ran, so the test stops here.
|
|
4474
|
-
result = this.abandonedTestResult();
|
|
4475
|
-
return;
|
|
4476
|
-
}
|
|
4477
|
-
if (stored === undefined || stored.kind !== 'grant' || !isOAuthGrantPayload(stored.payload)) {
|
|
4478
|
-
result = {
|
|
4479
|
-
ok: false,
|
|
4480
|
-
latencyMs: 0,
|
|
4481
|
-
error: `The grant payload at ${grant.grantRef} is missing or unusable; sign in to this account again`,
|
|
4482
|
-
};
|
|
4483
|
-
return;
|
|
4484
|
-
}
|
|
4485
|
-
const borrowed = structuredClone(stored.payload);
|
|
4486
4985
|
const captured = await records.readRecord(projectionKey);
|
|
4487
4986
|
// PR review round 14: the snapshot and its comparison key are frozen
|
|
4488
4987
|
// here. The seam hands back a live record, so a writer mutating that
|
|
@@ -4490,36 +4989,30 @@ export class KeysManagerService {
|
|
|
4490
4989
|
// the updater's `current` and make the borrow look unchanged.
|
|
4491
4990
|
const previous = captured === undefined ? undefined : structuredClone(captured);
|
|
4492
4991
|
const previousKey = previous === undefined ? undefined : JSON.stringify(previous);
|
|
4493
|
-
|
|
4494
|
-
|
|
4992
|
+
const blocked = this.borrowBarrier(window, provider, row, grantRef);
|
|
4993
|
+
if (blocked !== undefined) {
|
|
4994
|
+
result = blocked;
|
|
4495
4995
|
return;
|
|
4496
4996
|
}
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4997
|
+
// The recovery writes a grant record, so it runs only once this test is
|
|
4998
|
+
// known to borrow: an abandoned or retiring test must not restore one.
|
|
4999
|
+
const recovered = await this.recoverGrantPayload(provider, row, records);
|
|
5000
|
+
if (recovered === undefined) {
|
|
5001
|
+
result = {
|
|
5002
|
+
ok: false,
|
|
5003
|
+
latencyMs: 0,
|
|
5004
|
+
error: `The grant payload at ${grantRef} is missing or unusable; sign in to this account again`,
|
|
5005
|
+
};
|
|
4503
5006
|
return;
|
|
4504
5007
|
}
|
|
4505
|
-
|
|
4506
|
-
//
|
|
4507
|
-
//
|
|
4508
|
-
//
|
|
4509
|
-
//
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
// The provider-wide marker is deliberately not read here: a removal that
|
|
4514
|
-
// began while this test is registered waits for it in
|
|
4515
|
-
// {@link settleTestBeforeRemoval} and is the designed handshake, while
|
|
4516
|
-
// the row mark is only set by a removal that already passed that check.
|
|
4517
|
-
const live = this.store.provider(provider);
|
|
4518
|
-
const removing = this.retiringAccounts.has(row);
|
|
4519
|
-
if (removing || live === undefined || !live.keys.some(candidate => candidate.id === row.id)) {
|
|
4520
|
-
result = removing
|
|
4521
|
-
? { ok: false, latencyMs: 0, error: `Provider "${provider}" is being removed; the test did not borrow its credential` }
|
|
4522
|
-
: { ok: false, latencyMs: 0, error: `Key "${row.id}" was removed from ${provider} before its test could borrow it` };
|
|
5008
|
+
const borrowed = structuredClone(recovered.payload);
|
|
5009
|
+
// PR #37 review (must-fix): the recovery is an untimed seam round trip
|
|
5010
|
+
// and can outlive the isolation deadline, after which the window's
|
|
5011
|
+
// cleanup has already run and released the window. Registering facts or
|
|
5012
|
+
// borrowing now would land them with no owner: re-run the barrier first.
|
|
5013
|
+
const lateBlocked = this.borrowBarrier(window, provider, row, grantRef);
|
|
5014
|
+
if (lateBlocked !== undefined) {
|
|
5015
|
+
result = lateBlocked;
|
|
4523
5016
|
return;
|
|
4524
5017
|
}
|
|
4525
5018
|
// QC fix wave 2: record the borrow before the write, so an abandoned
|
|
@@ -5217,11 +5710,13 @@ export class KeysManagerService {
|
|
|
5217
5710
|
return { ok: false, error: failure?.message ?? failure?.code ?? 'The provider reported a failure' };
|
|
5218
5711
|
}
|
|
5219
5712
|
// PR review SF3 + round 8: only a real completion is a pass. The ping
|
|
5220
|
-
// asks for one token, so `
|
|
5713
|
+
// asks for one token, so `max-tokens` is the expected completion; a
|
|
5221
5714
|
// finish chunk with NO reason, `aborted`, or any kind this broker
|
|
5222
5715
|
// does not know means the provider did not answer, so reporting a
|
|
5223
|
-
// pass would claim a credential it never served.
|
|
5224
|
-
|
|
5716
|
+
// pass would claim a credential it never served. The accepted kinds
|
|
5717
|
+
// are the installed `@deepseek-ai/dsh-llm` union (`FinishReasonMap`),
|
|
5718
|
+
// shared with the tests so the two cannot drift again.
|
|
5719
|
+
if (kind !== undefined && TEST_SUCCESS_FINISH_KINDS.includes(kind)) {
|
|
5225
5720
|
// PR review round 42: a successful ping only proves the route
|
|
5226
5721
|
// answered. An api-key row test must also prove the pinned literal
|
|
5227
5722
|
// was the credential that served it — a takeover during the stream
|
|
@@ -5772,9 +6267,10 @@ export class KeysManagerService {
|
|
|
5772
6267
|
// capable, and it is never adoptable.
|
|
5773
6268
|
const transport = entry.settingsNs === TRANSPORT_CREDENTIAL_SCOPE;
|
|
5774
6269
|
const oauthFlow = this.oauthFlowAvailable(entry.provider);
|
|
5775
|
-
const
|
|
6270
|
+
const signIn = signInCapable(entry.provider);
|
|
6271
|
+
const caps = capabilityOf(entry, profile, oauthFlow, signIn);
|
|
5776
6272
|
const support = { supported: caps.keys, ...(caps.reason === undefined ? {} : { reason: caps.reason }) };
|
|
5777
|
-
const accountSupport = accountSupportOf(entry, oauthFlow);
|
|
6273
|
+
const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
|
|
5778
6274
|
const apiKeyEnv = profile !== undefined && typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv : null;
|
|
5779
6275
|
const binding = managed === undefined ? undefined : this.bindingState(managed, descriptor);
|
|
5780
6276
|
const bindingHealthy = binding === 'healthy' ? true : binding === 'mismatch' ? false : undefined;
|
|
@@ -5838,8 +6334,9 @@ export class KeysManagerService {
|
|
|
5838
6334
|
configured: managed !== undefined,
|
|
5839
6335
|
active: false,
|
|
5840
6336
|
supported: true,
|
|
5841
|
-
// Extra providers are key-pool routes;
|
|
5842
|
-
|
|
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),
|
|
5843
6340
|
settingsNs: 'llm-pi-ai',
|
|
5844
6341
|
settingsPath: ['providers', extra.id],
|
|
5845
6342
|
apiKeyEnv: managed?.brokerRef ?? null,
|
|
@@ -5878,7 +6375,7 @@ export class KeysManagerService {
|
|
|
5878
6375
|
configured: false,
|
|
5879
6376
|
active: false,
|
|
5880
6377
|
supported: true,
|
|
5881
|
-
accountSupported:
|
|
6378
|
+
accountSupported: signInCapable(managed.provider),
|
|
5882
6379
|
settingsNs: managed.settingsNs,
|
|
5883
6380
|
settingsPath: [...managed.settingsPath],
|
|
5884
6381
|
apiKeyEnv: managed.brokerRef,
|
|
@@ -6313,6 +6810,94 @@ export class KeysManagerService {
|
|
|
6313
6810
|
}
|
|
6314
6811
|
return undefined;
|
|
6315
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
|
+
}
|
|
6316
6901
|
/** Remote: take over one existing provider route. */
|
|
6317
6902
|
adoptProvider(provider) {
|
|
6318
6903
|
return this.run(async () => {
|
|
@@ -6343,8 +6928,9 @@ export class KeysManagerService {
|
|
|
6343
6928
|
// route adopts as before; the key-pool table alone no longer blocks
|
|
6344
6929
|
// an adoptable account route.
|
|
6345
6930
|
const oauthFlow = this.oauthFlowAvailable(entry.provider);
|
|
6346
|
-
const
|
|
6347
|
-
const
|
|
6931
|
+
const signIn = signInCapable(entry.provider);
|
|
6932
|
+
const caps = capabilityOf(entry, profile, oauthFlow, signIn);
|
|
6933
|
+
const accountSupport = accountSupportOf(entry, oauthFlow, signIn);
|
|
6348
6934
|
if (!caps.keys && !accountSupport.supported) {
|
|
6349
6935
|
throw new Error(caps.reason ?? accountSupport.reason ?? 'This provider cannot be managed');
|
|
6350
6936
|
}
|
|
@@ -6360,25 +6946,50 @@ export class KeysManagerService {
|
|
|
6360
6946
|
// managed state or imported credential exists.
|
|
6361
6947
|
if (!descriptor.writable)
|
|
6362
6948
|
throw new Error('The active profile is read-only');
|
|
6949
|
+
const piAiRoute = !(entry.settingsNs.includes('deepseek') || provider === 'deepseek-official');
|
|
6363
6950
|
const hit = await this.findImport(entry, profile);
|
|
6364
6951
|
let imported;
|
|
6365
6952
|
if (hit !== undefined)
|
|
6366
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);
|
|
6367
6978
|
const record = {
|
|
6368
6979
|
provider,
|
|
6369
6980
|
displayName: extra?.name ?? entry.displayName ?? provider,
|
|
6370
6981
|
source: extra !== undefined ? 'extra' : 'dsh',
|
|
6371
6982
|
settingsNs: entry.settingsNs,
|
|
6372
6983
|
settingsPath: [...entry.settingsPath],
|
|
6373
|
-
adapter:
|
|
6984
|
+
adapter: piAiRoute ? 'pi-ai' : 'deepseek',
|
|
6374
6985
|
brokerRef,
|
|
6375
6986
|
originalApiKeyEnv,
|
|
6376
|
-
createdProfile:
|
|
6377
|
-
hadProfile:
|
|
6987
|
+
createdProfile: materialized?.created === true,
|
|
6988
|
+
hadProfile: adoptedProfile !== undefined,
|
|
6378
6989
|
extraId: extra?.id ?? null,
|
|
6379
|
-
api:
|
|
6380
|
-
baseURL:
|
|
6381
|
-
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 ?? []),
|
|
6382
6993
|
adoptedAt: Date.now(),
|
|
6383
6994
|
cursor: 0,
|
|
6384
6995
|
keys: imported !== undefined ? [imported] : [],
|
|
@@ -6503,8 +7114,10 @@ export class KeysManagerService {
|
|
|
6503
7114
|
* Undo an adoption whose initial binding write was refused (PR review
|
|
6504
7115
|
* round 2): drop the managed record and its broker entry, delete the
|
|
6505
7116
|
* plugin-scope copy this call created, and put back a pre-adoption
|
|
6506
|
-
* reference that landed despite the refusal. The source credential
|
|
6507
|
-
*
|
|
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.
|
|
6508
7121
|
*/
|
|
6509
7122
|
async rollbackAdoption(record, imported) {
|
|
6510
7123
|
const provider = record.provider;
|
|
@@ -6518,6 +7131,21 @@ export class KeysManagerService {
|
|
|
6518
7131
|
this.warn(`adoption rollback could not delete the imported credential ${imported.ref} for ${provider}: ${error instanceof Error ? error.message : String(error)}`);
|
|
6519
7132
|
}
|
|
6520
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
|
+
}
|
|
6521
7149
|
const descriptor = this.describeSettings();
|
|
6522
7150
|
const namespace = this.namespace(descriptor, record.settingsNs);
|
|
6523
7151
|
const profile = asProfile(namespace === undefined ? undefined : getPath(namespace.value, record.settingsPath));
|
|
@@ -6553,17 +7181,7 @@ export class KeysManagerService {
|
|
|
6553
7181
|
catch (error) {
|
|
6554
7182
|
failure = error instanceof Error ? error.message : String(error);
|
|
6555
7183
|
}
|
|
6556
|
-
const models =
|
|
6557
|
-
const seen = new Set();
|
|
6558
|
-
for (const model of discovered) {
|
|
6559
|
-
const normalized = discoveredModel(model);
|
|
6560
|
-
if (normalized === undefined || seen.has(normalized.id))
|
|
6561
|
-
continue;
|
|
6562
|
-
seen.add(normalized.id);
|
|
6563
|
-
models.push(normalized);
|
|
6564
|
-
if (models.length >= 60)
|
|
6565
|
-
break;
|
|
6566
|
-
}
|
|
7184
|
+
const models = discoveredModels(discovered);
|
|
6567
7185
|
if (models.length > 0)
|
|
6568
7186
|
return { models, failure };
|
|
6569
7187
|
return { models: normalizeModels(extra.models), failure };
|
|
@@ -6576,7 +7194,9 @@ export class KeysManagerService {
|
|
|
6576
7194
|
* the key that serves it in the same mutation, so the write below is the
|
|
6577
7195
|
* route's first binding rather than a takeover of a value the user owns.
|
|
6578
7196
|
*/
|
|
6579
|
-
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) {
|
|
6580
7200
|
return this.run(async () => {
|
|
6581
7201
|
if (typeof extraId !== 'string' || extraId.length === 0)
|
|
6582
7202
|
throw new Error('extraId is required');
|
|
@@ -6595,7 +7215,7 @@ export class KeysManagerService {
|
|
|
6595
7215
|
// add-key flow restores them and the repair keeps one implementation.
|
|
6596
7216
|
// Hand it the value resolved above: the entry refusal stays the single
|
|
6597
7217
|
// decision for this surface, and the environment is read once per add.
|
|
6598
|
-
await this.addKeyLocked(extraId, input.alias, input.value, headers);
|
|
7218
|
+
await this.addKeyLocked(extraId, input.alias, input.value, headers, importedFrom);
|
|
6599
7219
|
this.store.touch();
|
|
6600
7220
|
return this.buildState();
|
|
6601
7221
|
}
|
|
@@ -6625,7 +7245,7 @@ export class KeysManagerService {
|
|
|
6625
7245
|
cursor: 0,
|
|
6626
7246
|
keys: [],
|
|
6627
7247
|
};
|
|
6628
|
-
const key = await this.createKeyRecord(extraId, input.alias, input.value);
|
|
7248
|
+
const key = await this.createKeyRecord(extraId, input.alias, input.value, importedFrom);
|
|
6629
7249
|
const ops = [{ op: 'set', path: ['providers', extraId, 'apiKeyEnv'], value: record.brokerRef }];
|
|
6630
7250
|
// Fill the declared headers the stored profile does not carry; a value
|
|
6631
7251
|
// the profile already sets for the same header is never overwritten.
|
|
@@ -6660,9 +7280,20 @@ export class KeysManagerService {
|
|
|
6660
7280
|
this.store.touch();
|
|
6661
7281
|
return this.buildState();
|
|
6662
7282
|
}
|
|
6663
|
-
|
|
6664
|
-
|
|
6665
|
-
|
|
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
|
+
}
|
|
6666
7297
|
if (failure !== undefined)
|
|
6667
7298
|
this.pushWarning(`Model discovery failed; installed ${models.length} seed models instead: ${failure}`);
|
|
6668
7299
|
const brokerRef = brokerRefFor(extraId);
|
|
@@ -6674,7 +7305,7 @@ export class KeysManagerService {
|
|
|
6674
7305
|
...(headers === undefined ? {} : { headers }),
|
|
6675
7306
|
models,
|
|
6676
7307
|
};
|
|
6677
|
-
const key = await this.createKeyRecord(extraId, input.alias, input.value);
|
|
7308
|
+
const key = await this.createKeyRecord(extraId, input.alias, input.value, importedFrom);
|
|
6678
7309
|
try {
|
|
6679
7310
|
// The profile and its binding are created together (see the method
|
|
6680
7311
|
// comment); no user value exists to take over here.
|
|
@@ -6774,7 +7405,7 @@ export class KeysManagerService {
|
|
|
6774
7405
|
this.pushWarning(`Restored the missing ${Object.keys(missing).join(', ')} header on the managed profile.`);
|
|
6775
7406
|
}
|
|
6776
7407
|
/** Add one key; caller already owns the mutation queue. */
|
|
6777
|
-
async addKeyLocked(provider, alias, value, declaredHeaders) {
|
|
7408
|
+
async addKeyLocked(provider, alias, value, declaredHeaders, importedFrom = null) {
|
|
6778
7409
|
const record = this.store.provider(provider);
|
|
6779
7410
|
if (record === undefined)
|
|
6780
7411
|
throw new Error(`Provider "${provider}" is not managed`);
|
|
@@ -6791,7 +7422,7 @@ export class KeysManagerService {
|
|
|
6791
7422
|
const input = validateKeyInput(alias, value);
|
|
6792
7423
|
if (record.keys.length >= KEY_LIMIT)
|
|
6793
7424
|
throw new Error(`A provider may have at most ${KEY_LIMIT} keys`);
|
|
6794
|
-
const key = await this.createKeyRecord(provider, input.alias, input.value);
|
|
7425
|
+
const key = await this.createKeyRecord(provider, input.alias, input.value, importedFrom);
|
|
6795
7426
|
record.keys.push(key);
|
|
6796
7427
|
// After the key add: a refused key (capability or capacity) must leave the
|
|
6797
7428
|
// settings document untouched, so the repair never runs ahead of it.
|
|
@@ -6804,9 +7435,9 @@ export class KeysManagerService {
|
|
|
6804
7435
|
await this.syncBrokerBinding(provider, record.extraId === null ? {} : { write: false });
|
|
6805
7436
|
}
|
|
6806
7437
|
/** Remote: add one key to a managed provider. */
|
|
6807
|
-
addKey(provider, alias, value) {
|
|
7438
|
+
addKey(provider, alias, value, importedFrom = null) {
|
|
6808
7439
|
return this.run(async () => {
|
|
6809
|
-
await this.addKeyLocked(provider, alias, value);
|
|
7440
|
+
await this.addKeyLocked(provider, alias, value, undefined, importedFrom);
|
|
6810
7441
|
this.store.touch();
|
|
6811
7442
|
return this.buildState();
|
|
6812
7443
|
});
|