dsh-keys-manager 0.2.8 → 0.2.10
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/lib/client/format.d.ts +17 -10
- package/lib/client/store.d.ts +8 -1
- package/lib/client/styles.d.ts +1 -1
- package/lib/client/types.d.ts +2 -1
- package/lib/client.js +120 -137
- package/lib/core.d.ts +31 -0
- package/lib/core.js +77 -0
- package/lib/core.js.map +1 -1
- package/lib/domain.d.ts +6 -2
- package/lib/index.d.ts +66 -4
- package/lib/index.js +347 -27
- package/lib/index.js.map +1 -1
- package/lib/quota/cache.d.ts +14 -0
- package/lib/quota/cache.js +61 -8
- package/lib/quota/cache.js.map +1 -1
- package/lib/quota/fetch.d.ts +7 -1
- package/lib/quota/fetch.js.map +1 -1
- package/lib/quota/model.d.ts +8 -4
- package/lib/quota/model.js +0 -12
- package/lib/quota/model.js.map +1 -1
- package/lib/quota/providers.d.ts +46 -0
- package/lib/quota/providers.js +242 -3
- package/lib/quota/providers.js.map +1 -1
- package/locale/en.json +3 -5
- package/locale/zh.json +3 -5
- package/package.json +2 -2
package/lib/domain.d.ts
CHANGED
|
@@ -125,8 +125,10 @@ export interface StateDocument {
|
|
|
125
125
|
}>;
|
|
126
126
|
}
|
|
127
127
|
/** One plan window projected into an account row. */
|
|
128
|
+
/** The plan windows a card can render; the one declaration every layer imports. */
|
|
129
|
+
export type QuotaWindowId = 'session' | 'week';
|
|
128
130
|
export interface QuotaWindowView {
|
|
129
|
-
id:
|
|
131
|
+
id: QuotaWindowId;
|
|
130
132
|
/** Share of the window already used, `0`..`1`. */
|
|
131
133
|
usedFraction: number;
|
|
132
134
|
/** Reset time as epoch milliseconds. */
|
|
@@ -137,7 +139,7 @@ export interface QuotaWindowView {
|
|
|
137
139
|
* it is deliberately absent from `KeyRecord` and `sanitizeState` (plan D1).
|
|
138
140
|
*/
|
|
139
141
|
export interface QuotaView {
|
|
140
|
-
status: 'ok' | 'absent' | 'unauthorized' | 'error';
|
|
142
|
+
status: 'ok' | 'absent' | 'unauthorized' | 'error' | 'natively-managed';
|
|
141
143
|
fetchedAt: number;
|
|
142
144
|
/** True when the windows are last-good data served behind a failed probe. */
|
|
143
145
|
stale?: boolean;
|
|
@@ -245,6 +247,8 @@ export interface TransportAccountView {
|
|
|
245
247
|
status: TransportAccountStatus;
|
|
246
248
|
/** Derived from {@link status}: true only while it is `'active'`. */
|
|
247
249
|
active: boolean;
|
|
250
|
+
/** Latest cached plan usage; absent until a quota refresh ran for this route. */
|
|
251
|
+
quota?: QuotaView;
|
|
248
252
|
}
|
|
249
253
|
/** One model row a transport route can advertise. */
|
|
250
254
|
export interface TransportCatalogModel {
|
package/lib/index.d.ts
CHANGED
|
@@ -779,6 +779,8 @@ export declare class KeysManagerService {
|
|
|
779
779
|
* `run` queue and no state flush.
|
|
780
780
|
*/
|
|
781
781
|
removeTransportAccount(route: string): Promise<StateView>;
|
|
782
|
+
/** Drop the cached usage snapshot for one transport scope. */
|
|
783
|
+
private dropTransportQuota;
|
|
782
784
|
/** The route's removal epoch; absent means never removed. */
|
|
783
785
|
private transportGenerationOf;
|
|
784
786
|
/**
|
|
@@ -1588,14 +1590,74 @@ export declare class KeysManagerService {
|
|
|
1588
1590
|
quotaRefresh(provider: string): Promise<StateView>;
|
|
1589
1591
|
/** One provider's quota cache, created on first use. */
|
|
1590
1592
|
private quotaCache;
|
|
1593
|
+
/** The listed transport row for a route id, refreshing the rows once if needed. */
|
|
1594
|
+
private transportRowOf;
|
|
1591
1595
|
/**
|
|
1592
|
-
* Refresh one
|
|
1593
|
-
*
|
|
1594
|
-
*
|
|
1596
|
+
* Refresh one transport route's usage.
|
|
1597
|
+
*
|
|
1598
|
+
* The grant is read-only: no rotation, no repair, no write-back. A record
|
|
1599
|
+
* that is missing or unparseable means "this account's usage is managed
|
|
1600
|
+
* natively" — never a sign-in prompt. The cache is keyed by the scope, so a
|
|
1601
|
+
* transport snapshot can never collide with a pool route's cache (D2).
|
|
1602
|
+
*/
|
|
1603
|
+
private refreshTransportQuota;
|
|
1604
|
+
/**
|
|
1605
|
+
* Refresh one row. The credential is resolved INSIDE the cache loader, so a
|
|
1606
|
+
* fresh entry (TTL hit or in-flight fellow) performs no credential read at
|
|
1607
|
+
* all (`I-000296`); TTL, backoff and single-flight live in the cache, so two
|
|
1608
|
+
* concurrent refreshes of the same row share one read and one probe.
|
|
1595
1609
|
*/
|
|
1596
1610
|
private refreshQuotaRow;
|
|
1597
|
-
/**
|
|
1611
|
+
/**
|
|
1612
|
+
* The credential one row's plan usage is read with.
|
|
1613
|
+
*
|
|
1614
|
+
* For an OAuth row the pool copy wins; when it is unreadable the projection
|
|
1615
|
+
* record (`llm-pi-ai/<provider>`) is consulted, because that grant — not the
|
|
1616
|
+
* pool row — is what actually serves the route. Reading is the only thing
|
|
1617
|
+
* this does: no write, no rebind, no `modifyRecord`.
|
|
1618
|
+
*/
|
|
1598
1619
|
private quotaCredential;
|
|
1620
|
+
/**
|
|
1621
|
+
* A readable pool grant for one row (`undefined` when no usable record
|
|
1622
|
+
* exists), or `transient` when the store itself kept failing.
|
|
1623
|
+
*
|
|
1624
|
+
* One retry covers a momentarily locked store (D2). A missing or invalid
|
|
1625
|
+
* record is a deterministic fact; a read that throws twice is not — the row
|
|
1626
|
+
* must report a transient failure, never an auth one.
|
|
1627
|
+
*/
|
|
1628
|
+
private readGrantCredential;
|
|
1629
|
+
/**
|
|
1630
|
+
* The provider's live projection as a quota credential.
|
|
1631
|
+
*
|
|
1632
|
+
* A record that exists but carries no readable grant (wrong kind, unrecognized
|
|
1633
|
+
* payload) is classified `natively-managed`, never `missing`: we cannot prove
|
|
1634
|
+
* no account serves the route, and claiming otherwise is exactly the false
|
|
1635
|
+
* "sign in again" this plan removes. A read that keeps THROWING is different —
|
|
1636
|
+
* it is retried once, then reported as `transient` (`error`), because a store
|
|
1637
|
+
* failure says nothing about the credential.
|
|
1638
|
+
*/
|
|
1639
|
+
private projectionQuotaCredential;
|
|
1640
|
+
/**
|
|
1641
|
+
* One row's cached quota windows for ranking (issue #22): a read-only peek,
|
|
1642
|
+
* never a probe. A row with no snapshot simply ranks as unknown.
|
|
1643
|
+
*/
|
|
1644
|
+
private quotaWindowsOf;
|
|
1645
|
+
/** The quota tier of one key (`0`/`1` are the sticky-safe tiers). */
|
|
1646
|
+
private quotaTierOf;
|
|
1647
|
+
/**
|
|
1648
|
+
* Whether a sticky binding may hold for this request (D3).
|
|
1649
|
+
*
|
|
1650
|
+
* The binding yields only to an actual quota signal: when no selectable key
|
|
1651
|
+
* of the route reports usable quota, every candidate ranks unknown (tier 2)
|
|
1652
|
+
* and the route must keep its pre-ranking sticky behaviour byte for byte.
|
|
1653
|
+
*/
|
|
1654
|
+
private stickyBindingHolds;
|
|
1655
|
+
/**
|
|
1656
|
+
* The next selectable key in quota order, skipping ids already tried and
|
|
1657
|
+
* advancing the cursor past whatever it picks — the same cursor contract
|
|
1658
|
+
* `pickRoundRobin` keeps for the unranked path.
|
|
1659
|
+
*/
|
|
1660
|
+
private pickRanked;
|
|
1599
1661
|
/** Project the cached quota of one row; a pure memory read, never a probe. */
|
|
1600
1662
|
private quotaViewFor;
|
|
1601
1663
|
/**
|
package/lib/index.js
CHANGED
|
@@ -17,7 +17,7 @@ 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
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';
|
|
20
|
+
import { KEY_LIMIT, TEST_SUCCESS_FINISH_KINDS, accountRef, applyFailureCooldown, bindingKey, classifyOAuthFailure, isSelectable, markKeySuccess, markKeyUsed, normalizeSettings, patchSettings, pickHealthyExcluding, pickRoundRobin, quotaRank, rankCandidates, shouldFailover, statusOfKey, statusOfProvider, validateKeyInput, validateKeyPatch, } from './core.js';
|
|
21
21
|
import { signInCapable, signInProvider } from './oauth/providers.js';
|
|
22
22
|
import { SignInCancelledError, runSignIn } from './oauth/signin.js';
|
|
23
23
|
import { EXTRA_PROVIDER_MAP, EXTRA_PROVIDERS } from './providers.js';
|
|
@@ -38,6 +38,8 @@ const ORIGINAL = Symbol.for('cordis.original');
|
|
|
38
38
|
* only writer allowed while `shutdownRequested` is up.
|
|
39
39
|
*/
|
|
40
40
|
const PRE_CLOSE_RESTORE = Symbol('keys-manager.pre-close restore');
|
|
41
|
+
/** Rows one quota refresh probes at once (`I-000296`). */
|
|
42
|
+
const QUOTA_PROBE_CONCURRENCY = 4;
|
|
41
43
|
const MAX_SWITCHES = 6;
|
|
42
44
|
const ATTEMPT_TTL_MS = 60 * 60 * 1000;
|
|
43
45
|
/** A retry pin only lives for this long; an expired pin is treated as absent. */
|
|
@@ -466,6 +468,42 @@ function missingHeaders(declared, stored) {
|
|
|
466
468
|
}
|
|
467
469
|
return missing;
|
|
468
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* Whether the credential a probe just used is already expired.
|
|
473
|
+
*
|
|
474
|
+
* The grant payload's expiry wins: it describes the token the vendor actually
|
|
475
|
+
* saw, while the row timestamp can lag behind a rotation. The row value is only
|
|
476
|
+
* a fallback for payloads without a usable expiry — never a "fresh" guess.
|
|
477
|
+
* A missing or unusable value counts as NOT expired (the conservative label).
|
|
478
|
+
*/
|
|
479
|
+
function credentialExpired(key, now, payloadExpiresAt) {
|
|
480
|
+
const payloadExpiry = usableExpiry(payloadExpiresAt);
|
|
481
|
+
if (payloadExpiry !== undefined)
|
|
482
|
+
return payloadExpiry <= now;
|
|
483
|
+
const rowExpiry = usableExpiry(key.oauth?.expiresAt);
|
|
484
|
+
return rowExpiry !== undefined && rowExpiry <= now;
|
|
485
|
+
}
|
|
486
|
+
/** Read a transport grant payload; `undefined` when it is not usable. */
|
|
487
|
+
function readTransportGrant(record) {
|
|
488
|
+
if (record?.kind !== 'grant')
|
|
489
|
+
return undefined;
|
|
490
|
+
const payload = record.payload;
|
|
491
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload))
|
|
492
|
+
return undefined;
|
|
493
|
+
const fields = payload;
|
|
494
|
+
if (typeof fields.access !== 'string' || fields.access.length === 0)
|
|
495
|
+
return undefined;
|
|
496
|
+
return {
|
|
497
|
+
access: fields.access,
|
|
498
|
+
...(typeof fields.expires === 'number' && Number.isFinite(fields.expires) ? { expires: fields.expires } : {}),
|
|
499
|
+
...(typeof fields.orgId === 'string' && fields.orgId.length > 0 ? { orgId: fields.orgId } : {}),
|
|
500
|
+
...(typeof fields.region === 'string' && fields.region.length > 0 ? { region: fields.region } : {}),
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
/** A payload/row expiry value this manager can reason about, or `undefined`. */
|
|
504
|
+
function usableExpiry(value) {
|
|
505
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
506
|
+
}
|
|
469
507
|
/** Public, secret-free key row. */
|
|
470
508
|
function publicKey(key, now, projectedAccountId, quota) {
|
|
471
509
|
return {
|
|
@@ -2304,6 +2342,9 @@ export class KeysManagerService {
|
|
|
2304
2342
|
}
|
|
2305
2343
|
if (outcome.status === 'authorized') {
|
|
2306
2344
|
this.finishLoginAttempt(attempt, 'ready');
|
|
2345
|
+
// A new grant is a new account: the cached usage belonged to the
|
|
2346
|
+
// previous credential, so the next read must probe again.
|
|
2347
|
+
this.dropTransportQuota(flow.key);
|
|
2307
2348
|
void this.refreshTransportAccounts();
|
|
2308
2349
|
return;
|
|
2309
2350
|
}
|
|
@@ -2366,9 +2407,17 @@ export class KeysManagerService {
|
|
|
2366
2407
|
await pending.settled;
|
|
2367
2408
|
}
|
|
2368
2409
|
await records.deleteRecord(flow.key);
|
|
2410
|
+
// The snapshot under this scope describes the account that just went away;
|
|
2411
|
+
// keeping it would show the previous account's numbers for one TTL.
|
|
2412
|
+
this.dropTransportQuota(flow.key);
|
|
2369
2413
|
await this.refreshTransportAccounts();
|
|
2370
2414
|
return this.buildState();
|
|
2371
2415
|
}
|
|
2416
|
+
/** Drop the cached usage snapshot for one transport scope. */
|
|
2417
|
+
dropTransportQuota(scope) {
|
|
2418
|
+
this.quotaCaches.get(scope)?.retain(scope, undefined);
|
|
2419
|
+
this.quotaCaches.delete(scope);
|
|
2420
|
+
}
|
|
2372
2421
|
/** The route's removal epoch; absent means never removed. */
|
|
2373
2422
|
transportGenerationOf(route) {
|
|
2374
2423
|
return this.transportRemovals.get(route) ?? 0;
|
|
@@ -6414,7 +6463,11 @@ export class KeysManagerService {
|
|
|
6414
6463
|
pausedKeyCount: allKeys.filter(key => key.status === 'paused').length,
|
|
6415
6464
|
bindingsCount: Object.keys(this.store.state.sessionBindings).length,
|
|
6416
6465
|
warnings,
|
|
6417
|
-
transportAccounts: this.transportRows.map(row =>
|
|
6466
|
+
transportAccounts: this.transportRows.map(row => {
|
|
6467
|
+
// Same projection the pool rows get; the cache key is the row's scope.
|
|
6468
|
+
const quota = this.quotaViewFor(row.scope, row.scope);
|
|
6469
|
+
return quota === undefined ? { ...row } : { ...row, quota };
|
|
6470
|
+
}),
|
|
6418
6471
|
};
|
|
6419
6472
|
}
|
|
6420
6473
|
/**
|
|
@@ -6445,12 +6498,35 @@ export class KeysManagerService {
|
|
|
6445
6498
|
// Own-property lookup: `store.provider` indexes a plain object, so a
|
|
6446
6499
|
// prototype key would answer a function instead of a record.
|
|
6447
6500
|
const record = Object.hasOwn(this.store.providers, provider) ? this.store.provider(provider) : undefined;
|
|
6448
|
-
if (record === undefined)
|
|
6501
|
+
if (record === undefined) {
|
|
6502
|
+
// Not a pi-ai pool route: a transport route (`llm-omp-transports/<id>`)
|
|
6503
|
+
// keeps its grant on the transports package's own scope, so the usage read
|
|
6504
|
+
// resolves that record instead of a pool row (D2).
|
|
6505
|
+
const transport = await this.transportRowOf(provider);
|
|
6506
|
+
if (transport !== undefined) {
|
|
6507
|
+
await this.refreshTransportQuota(provider, transport);
|
|
6508
|
+
return this.buildState();
|
|
6509
|
+
}
|
|
6510
|
+
// A released provider keeps no snapshots: nothing would ever read them
|
|
6511
|
+
// again, and a re-adoption must start from a clean slate.
|
|
6512
|
+
this.quotaCaches.get(provider)?.retain(provider, undefined);
|
|
6513
|
+
this.quotaCaches.delete(provider);
|
|
6449
6514
|
return this.buildState();
|
|
6515
|
+
}
|
|
6450
6516
|
const cache = this.quotaCache(provider);
|
|
6517
|
+
// Rows deleted since the last refresh must not linger in the cache either.
|
|
6518
|
+
cache.retain(provider, new Set(record.keys.map(key => key.id)));
|
|
6451
6519
|
// The cache classifies probe failures; allSettled is the second line of
|
|
6452
6520
|
// defence so one rejected row can never reject the RPC.
|
|
6453
|
-
|
|
6521
|
+
// At most QUOTA_PROBE_CONCURRENCY rows run at once (`I-000296`): a wide
|
|
6522
|
+
// pool must not open a dozen vendor connections in one gesture.
|
|
6523
|
+
const queue = [...record.keys];
|
|
6524
|
+
const workers = Array.from({ length: Math.min(QUOTA_PROBE_CONCURRENCY, queue.length) }, async () => {
|
|
6525
|
+
for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
|
|
6526
|
+
await this.refreshQuotaRow(provider, cache, next);
|
|
6527
|
+
}
|
|
6528
|
+
});
|
|
6529
|
+
await Promise.allSettled(workers);
|
|
6454
6530
|
return this.buildState();
|
|
6455
6531
|
}
|
|
6456
6532
|
/** One provider's quota cache, created on first use. */
|
|
@@ -6462,18 +6538,112 @@ export class KeysManagerService {
|
|
|
6462
6538
|
this.quotaCaches.set(provider, cache);
|
|
6463
6539
|
return cache;
|
|
6464
6540
|
}
|
|
6541
|
+
/** The listed transport row for a route id, refreshing the rows once if needed. */
|
|
6542
|
+
async transportRowOf(provider) {
|
|
6543
|
+
const listed = this.transportRows.find(row => row.id === provider);
|
|
6544
|
+
if (listed !== undefined)
|
|
6545
|
+
return listed;
|
|
6546
|
+
// The card may be opened before the first transport pass; one read pass is
|
|
6547
|
+
// cheap and keeps this path consistent with what the UI lists.
|
|
6548
|
+
await this.refreshTransportAccounts();
|
|
6549
|
+
return this.transportRows.find(row => row.id === provider);
|
|
6550
|
+
}
|
|
6465
6551
|
/**
|
|
6466
|
-
* Refresh one
|
|
6467
|
-
*
|
|
6468
|
-
*
|
|
6552
|
+
* Refresh one transport route's usage.
|
|
6553
|
+
*
|
|
6554
|
+
* The grant is read-only: no rotation, no repair, no write-back. A record
|
|
6555
|
+
* that is missing or unparseable means "this account's usage is managed
|
|
6556
|
+
* natively" — never a sign-in prompt. The cache is keyed by the scope, so a
|
|
6557
|
+
* transport snapshot can never collide with a pool route's cache (D2).
|
|
6558
|
+
*/
|
|
6559
|
+
async refreshTransportQuota(provider, row) {
|
|
6560
|
+
const cache = this.quotaCache(row.scope);
|
|
6561
|
+
await cache.get(row.scope, row.scope, async () => {
|
|
6562
|
+
const records = this.credentialRecords();
|
|
6563
|
+
if (records === undefined) {
|
|
6564
|
+
return {
|
|
6565
|
+
status: 'natively-managed',
|
|
6566
|
+
fetchedAt: 0,
|
|
6567
|
+
windows: [],
|
|
6568
|
+
reason: 'no credential store to read the transport grant',
|
|
6569
|
+
};
|
|
6570
|
+
}
|
|
6571
|
+
let record;
|
|
6572
|
+
try {
|
|
6573
|
+
record = await records.readRecord(row.scope);
|
|
6574
|
+
}
|
|
6575
|
+
catch {
|
|
6576
|
+
// A store that cannot be read is transient, exactly like the pool path.
|
|
6577
|
+
return {
|
|
6578
|
+
status: 'error',
|
|
6579
|
+
fetchedAt: 0,
|
|
6580
|
+
windows: [],
|
|
6581
|
+
reason: 'the transport grant could not be read',
|
|
6582
|
+
};
|
|
6583
|
+
}
|
|
6584
|
+
const grant = readTransportGrant(record);
|
|
6585
|
+
if (grant === undefined) {
|
|
6586
|
+
return {
|
|
6587
|
+
status: 'natively-managed',
|
|
6588
|
+
fetchedAt: 0,
|
|
6589
|
+
windows: [],
|
|
6590
|
+
reason: 'the transport grant is not readable by this plugin',
|
|
6591
|
+
};
|
|
6592
|
+
}
|
|
6593
|
+
const snapshot = await resolveQuota(provider, {
|
|
6594
|
+
token: grant.access,
|
|
6595
|
+
...(grant.orgId === undefined ? {} : { orgId: grant.orgId }),
|
|
6596
|
+
...(grant.region === undefined ? {} : { region: grant.region }),
|
|
6597
|
+
...(this.quotaFetch === undefined ? {} : { fetch: this.quotaFetch }),
|
|
6598
|
+
});
|
|
6599
|
+
// An expired stored token cannot be refreshed from here, so a refusal is
|
|
6600
|
+
// "a model request will fix this", not a sign-in prompt.
|
|
6601
|
+
const grantExpiry = usableExpiry(grant.expires);
|
|
6602
|
+
if (snapshot.status === 'unauthorized' && grantExpiry !== undefined && grantExpiry <= Date.now()) {
|
|
6603
|
+
return {
|
|
6604
|
+
status: 'natively-managed',
|
|
6605
|
+
fetchedAt: snapshot.fetchedAt,
|
|
6606
|
+
windows: [],
|
|
6607
|
+
reason: 'the stored transport credential expired and only a model request refreshes it',
|
|
6608
|
+
};
|
|
6609
|
+
}
|
|
6610
|
+
return snapshot;
|
|
6611
|
+
});
|
|
6612
|
+
}
|
|
6613
|
+
/**
|
|
6614
|
+
* Refresh one row. The credential is resolved INSIDE the cache loader, so a
|
|
6615
|
+
* fresh entry (TTL hit or in-flight fellow) performs no credential read at
|
|
6616
|
+
* all (`I-000296`); TTL, backoff and single-flight live in the cache, so two
|
|
6617
|
+
* concurrent refreshes of the same row share one read and one probe.
|
|
6469
6618
|
*/
|
|
6470
6619
|
async refreshQuotaRow(provider, cache, key) {
|
|
6471
|
-
const credential = await this.quotaCredential(key);
|
|
6472
6620
|
await cache.get(provider, key.id, async () => {
|
|
6473
|
-
|
|
6474
|
-
|
|
6475
|
-
//
|
|
6476
|
-
//
|
|
6621
|
+
const credential = await this.quotaCredential(provider, key);
|
|
6622
|
+
if (credential.kind === 'transient') {
|
|
6623
|
+
// A store that kept failing is "could not read usage now", never an
|
|
6624
|
+
// auth fact: `error` keeps the last-good numbers on display.
|
|
6625
|
+
return {
|
|
6626
|
+
status: 'error',
|
|
6627
|
+
fetchedAt: 0,
|
|
6628
|
+
windows: [],
|
|
6629
|
+
reason: 'the credential store could not be read',
|
|
6630
|
+
};
|
|
6631
|
+
}
|
|
6632
|
+
if (credential.kind === 'natively-managed') {
|
|
6633
|
+
// The route is served by a DSH-managed projection we cannot read. That
|
|
6634
|
+
// is not "your pool credential is invalid": the honest state keeps the
|
|
6635
|
+
// card from telling a user to sign in again right after they did.
|
|
6636
|
+
return {
|
|
6637
|
+
status: 'natively-managed',
|
|
6638
|
+
fetchedAt: 0,
|
|
6639
|
+
windows: [],
|
|
6640
|
+
reason: 'the route is served by a natively managed projection',
|
|
6641
|
+
};
|
|
6642
|
+
}
|
|
6643
|
+
if (credential.kind === 'missing') {
|
|
6644
|
+
// No projection serves this route and the row's own grant is
|
|
6645
|
+
// unreadable: an OAuth row says `unauthorized` so the card can offer a
|
|
6646
|
+
// re-sign-in, an API-key row without a value says `absent`.
|
|
6477
6647
|
return {
|
|
6478
6648
|
status: key.kind === 'oauth' ? 'unauthorized' : 'absent',
|
|
6479
6649
|
fetchedAt: 0,
|
|
@@ -6481,33 +6651,183 @@ export class KeysManagerService {
|
|
|
6481
6651
|
reason: 'no readable credential',
|
|
6482
6652
|
};
|
|
6483
6653
|
}
|
|
6484
|
-
|
|
6654
|
+
const snapshot = await resolveQuota(provider, {
|
|
6485
6655
|
token: credential.token,
|
|
6486
6656
|
...(credential.accountId === undefined ? {} : { accountId: credential.accountId }),
|
|
6487
6657
|
...(this.quotaFetch === undefined ? {} : { fetch: this.quotaFetch }),
|
|
6488
6658
|
});
|
|
6659
|
+
// A projection-sourced 401/403 cannot be fixed by re-signing-in the pool
|
|
6660
|
+
// row: the vendor refused the credential that serves the route, which is
|
|
6661
|
+
// the "natively managed, usage unavailable" fact.
|
|
6662
|
+
if (credential.source === 'projection' && snapshot.status === 'unauthorized') {
|
|
6663
|
+
return {
|
|
6664
|
+
status: 'natively-managed',
|
|
6665
|
+
fetchedAt: snapshot.fetchedAt,
|
|
6666
|
+
windows: [],
|
|
6667
|
+
reason: 'the serving projection credential was refused',
|
|
6668
|
+
};
|
|
6669
|
+
}
|
|
6670
|
+
// A pool-sourced 401 with a stored token that has already expired is a
|
|
6671
|
+
// refresh problem, not a sign-in prompt: re-signing-in this row cannot
|
|
6672
|
+
// help, and pi-ai only refreshes on model traffic (D1).
|
|
6673
|
+
if (credential.source === 'pool'
|
|
6674
|
+
&& snapshot.status === 'unauthorized'
|
|
6675
|
+
&& credentialExpired(key, Date.now(), credential.expiresAt)) {
|
|
6676
|
+
return {
|
|
6677
|
+
status: 'natively-managed',
|
|
6678
|
+
fetchedAt: snapshot.fetchedAt,
|
|
6679
|
+
windows: [],
|
|
6680
|
+
reason: 'the stored credential expired and only a model request refreshes it',
|
|
6681
|
+
};
|
|
6682
|
+
}
|
|
6683
|
+
return snapshot;
|
|
6489
6684
|
});
|
|
6490
6685
|
}
|
|
6491
|
-
/**
|
|
6492
|
-
|
|
6686
|
+
/**
|
|
6687
|
+
* The credential one row's plan usage is read with.
|
|
6688
|
+
*
|
|
6689
|
+
* For an OAuth row the pool copy wins; when it is unreadable the projection
|
|
6690
|
+
* record (`llm-pi-ai/<provider>`) is consulted, because that grant — not the
|
|
6691
|
+
* pool row — is what actually serves the route. Reading is the only thing
|
|
6692
|
+
* this does: no write, no rebind, no `modifyRecord`.
|
|
6693
|
+
*/
|
|
6694
|
+
async quotaCredential(provider, key) {
|
|
6493
6695
|
if (key.kind === 'oauth') {
|
|
6494
|
-
const
|
|
6495
|
-
|
|
6496
|
-
|
|
6497
|
-
|
|
6696
|
+
const own = await this.readGrantCredential(key.oauth?.grantRef, key.oauth?.accountId);
|
|
6697
|
+
if (own !== undefined && own.kind === 'credential')
|
|
6698
|
+
return own;
|
|
6699
|
+
// A store that kept throwing says nothing about this credential: report
|
|
6700
|
+
// the transient class instead of falling back to another account or
|
|
6701
|
+
// claiming the grant is unreadable.
|
|
6702
|
+
if (own !== undefined && own.kind === 'transient')
|
|
6703
|
+
return { kind: 'transient' };
|
|
6704
|
+
// Only a route this manager already classifies as foreign may borrow the
|
|
6705
|
+
// projection's credential; anything else keeps its own row's identity.
|
|
6706
|
+
if (!this.foreignProjections.has(provider))
|
|
6707
|
+
return { kind: 'missing' };
|
|
6708
|
+
return this.projectionQuotaCredential(provider);
|
|
6709
|
+
}
|
|
6710
|
+
const probe = await this.probeKey(key.ref);
|
|
6711
|
+
return probe.hit === undefined
|
|
6712
|
+
? { kind: 'missing' }
|
|
6713
|
+
: { kind: 'credential', source: 'pool', token: probe.hit.value };
|
|
6714
|
+
}
|
|
6715
|
+
/**
|
|
6716
|
+
* A readable pool grant for one row (`undefined` when no usable record
|
|
6717
|
+
* exists), or `transient` when the store itself kept failing.
|
|
6718
|
+
*
|
|
6719
|
+
* One retry covers a momentarily locked store (D2). A missing or invalid
|
|
6720
|
+
* record is a deterministic fact; a read that throws twice is not — the row
|
|
6721
|
+
* must report a transient failure, never an auth one.
|
|
6722
|
+
*/
|
|
6723
|
+
async readGrantCredential(grantRef, accountId) {
|
|
6724
|
+
const records = this.credentialRecords();
|
|
6725
|
+
if (grantRef === undefined || grantRef.length === 0 || records === undefined)
|
|
6726
|
+
return undefined;
|
|
6727
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
6498
6728
|
try {
|
|
6499
6729
|
const record = await records.readRecord(grantRef);
|
|
6500
6730
|
if (record === undefined || record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
|
|
6501
6731
|
return undefined;
|
|
6502
|
-
const
|
|
6503
|
-
return {
|
|
6732
|
+
const expires = usableExpiry(record.payload.expires);
|
|
6733
|
+
return {
|
|
6734
|
+
kind: 'credential',
|
|
6735
|
+
source: 'pool',
|
|
6736
|
+
token: record.payload.access,
|
|
6737
|
+
...(accountId === undefined ? {} : { accountId }),
|
|
6738
|
+
...(expires === undefined ? {} : { expiresAt: expires }),
|
|
6739
|
+
};
|
|
6504
6740
|
}
|
|
6505
6741
|
catch {
|
|
6506
|
-
|
|
6742
|
+
// Try once more; the second throw is reported as transient below.
|
|
6507
6743
|
}
|
|
6508
6744
|
}
|
|
6509
|
-
|
|
6510
|
-
|
|
6745
|
+
return { kind: 'transient' };
|
|
6746
|
+
}
|
|
6747
|
+
/**
|
|
6748
|
+
* The provider's live projection as a quota credential.
|
|
6749
|
+
*
|
|
6750
|
+
* A record that exists but carries no readable grant (wrong kind, unrecognized
|
|
6751
|
+
* payload) is classified `natively-managed`, never `missing`: we cannot prove
|
|
6752
|
+
* no account serves the route, and claiming otherwise is exactly the false
|
|
6753
|
+
* "sign in again" this plan removes. A read that keeps THROWING is different —
|
|
6754
|
+
* it is retried once, then reported as `transient` (`error`), because a store
|
|
6755
|
+
* failure says nothing about the credential.
|
|
6756
|
+
*/
|
|
6757
|
+
async projectionQuotaCredential(provider) {
|
|
6758
|
+
const records = this.credentialRecords();
|
|
6759
|
+
if (records === undefined)
|
|
6760
|
+
return { kind: 'missing' };
|
|
6761
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
6762
|
+
try {
|
|
6763
|
+
const record = await records.readRecord(`${OAUTH_GRANT_RECORD_SCOPE}/${provider}`);
|
|
6764
|
+
if (record === undefined)
|
|
6765
|
+
return { kind: 'missing' };
|
|
6766
|
+
if (record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
|
|
6767
|
+
return { kind: 'natively-managed' };
|
|
6768
|
+
const accountId = record.payload.accountId;
|
|
6769
|
+
const expires = usableExpiry(record.payload.expires);
|
|
6770
|
+
return {
|
|
6771
|
+
kind: 'credential',
|
|
6772
|
+
source: 'projection',
|
|
6773
|
+
token: record.payload.access,
|
|
6774
|
+
...(typeof accountId === 'string' && accountId.length > 0 ? { accountId } : {}),
|
|
6775
|
+
...(expires === undefined ? {} : { expiresAt: expires }),
|
|
6776
|
+
};
|
|
6777
|
+
}
|
|
6778
|
+
catch {
|
|
6779
|
+
// Same one-retry rule as the pool read.
|
|
6780
|
+
}
|
|
6781
|
+
}
|
|
6782
|
+
return { kind: 'transient' };
|
|
6783
|
+
}
|
|
6784
|
+
/**
|
|
6785
|
+
* One row's cached quota windows for ranking (issue #22): a read-only peek,
|
|
6786
|
+
* never a probe. A row with no snapshot simply ranks as unknown.
|
|
6787
|
+
*/
|
|
6788
|
+
quotaWindowsOf(provider, keyId) {
|
|
6789
|
+
const snapshot = this.quotaCaches.get(provider)?.peek(provider, keyId);
|
|
6790
|
+
// Ranking refuses anything the display path would not trust as live: a
|
|
6791
|
+
// non-`ok` state carries no quota fact, and a last-good snapshot kept
|
|
6792
|
+
// behind a failed probe must not outrank a fresh read for up to a day.
|
|
6793
|
+
if (snapshot === undefined || snapshot.status !== 'ok' || snapshot.stale === true)
|
|
6794
|
+
return undefined;
|
|
6795
|
+
return snapshot.windows;
|
|
6796
|
+
}
|
|
6797
|
+
/** The quota tier of one key (`0`/`1` are the sticky-safe tiers). */
|
|
6798
|
+
quotaTierOf(provider, keyId, now) {
|
|
6799
|
+
return quotaRank(this.quotaWindowsOf(provider, keyId), now).tier;
|
|
6800
|
+
}
|
|
6801
|
+
/**
|
|
6802
|
+
* Whether a sticky binding may hold for this request (D3).
|
|
6803
|
+
*
|
|
6804
|
+
* The binding yields only to an actual quota signal: when no selectable key
|
|
6805
|
+
* of the route reports usable quota, every candidate ranks unknown (tier 2)
|
|
6806
|
+
* and the route must keep its pre-ranking sticky behaviour byte for byte.
|
|
6807
|
+
*/
|
|
6808
|
+
stickyBindingHolds(providerId, provider, bound, now) {
|
|
6809
|
+
// (a) A binding that still has usable quota keeps the session.
|
|
6810
|
+
if (this.quotaTierOf(providerId, bound.id, now) <= 1)
|
|
6811
|
+
return true;
|
|
6812
|
+
// (b) The genuine no-quota-signal route: EVERY selectable key ranks
|
|
6813
|
+
// unknown (tier 2), so the pre-ranking sticky behaviour applies unchanged.
|
|
6814
|
+
// A tier-3 binding yields here as soon as any sibling reports real usage.
|
|
6815
|
+
return provider.keys.every(candidate => !isSelectable(candidate, now) || this.quotaTierOf(providerId, candidate.id, now) === 2);
|
|
6816
|
+
}
|
|
6817
|
+
/**
|
|
6818
|
+
* The next selectable key in quota order, skipping ids already tried and
|
|
6819
|
+
* advancing the cursor past whatever it picks — the same cursor contract
|
|
6820
|
+
* `pickRoundRobin` keeps for the unranked path.
|
|
6821
|
+
*/
|
|
6822
|
+
pickRanked(provider, now, tried) {
|
|
6823
|
+
const ranked = rankCandidates(provider, now, keyId => this.quotaWindowsOf(provider.provider, keyId));
|
|
6824
|
+
const chosen = ranked.find(candidate => tried?.has(candidate.id) !== true);
|
|
6825
|
+
if (chosen === undefined)
|
|
6826
|
+
return undefined;
|
|
6827
|
+
const index = provider.keys.findIndex(candidate => candidate.id === chosen.id);
|
|
6828
|
+
if (index >= 0)
|
|
6829
|
+
provider.cursor = (index + 1) % provider.keys.length;
|
|
6830
|
+
return chosen;
|
|
6511
6831
|
}
|
|
6512
6832
|
/** Project the cached quota of one row; a pure memory read, never a probe. */
|
|
6513
6833
|
quotaViewFor(provider, keyId) {
|
|
@@ -7956,12 +8276,12 @@ export class KeysManagerService {
|
|
|
7956
8276
|
const binding = this.store.binding(sessionId, providerId);
|
|
7957
8277
|
if (binding !== undefined) {
|
|
7958
8278
|
const bound = provider.keys.find(candidate => candidate.id === binding.keyId);
|
|
7959
|
-
if (isSelectable(bound, now))
|
|
8279
|
+
if (isSelectable(bound, now) && this.stickyBindingHolds(providerId, provider, bound, now))
|
|
7960
8280
|
key = bound;
|
|
7961
8281
|
}
|
|
7962
8282
|
}
|
|
7963
8283
|
if (key === undefined)
|
|
7964
|
-
key =
|
|
8284
|
+
key = this.pickRanked(provider, now);
|
|
7965
8285
|
const tryCandidate = async (candidate) => {
|
|
7966
8286
|
if (candidate === undefined)
|
|
7967
8287
|
return undefined;
|
|
@@ -7987,7 +8307,7 @@ export class KeysManagerService {
|
|
|
7987
8307
|
const selected = await tryCandidate(key);
|
|
7988
8308
|
if (selected !== undefined)
|
|
7989
8309
|
return selected;
|
|
7990
|
-
key =
|
|
8310
|
+
key = this.pickRanked(provider, now, tried);
|
|
7991
8311
|
}
|
|
7992
8312
|
// A previously missing key may have been restored in the credential store.
|
|
7993
8313
|
// Re-probe those candidates when no healthy key remains; a transient read
|