dsh-subscriptions 0.1.0
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/LICENSE +21 -0
- package/README.md +129 -0
- package/cordis.patch.yml +12 -0
- package/lib/auth/claude-code-creds.d.ts +23 -0
- package/lib/auth/claude-code-creds.js +172 -0
- package/lib/auth/device-flow.d.ts +55 -0
- package/lib/auth/device-flow.js +177 -0
- package/lib/auth/jwt.d.ts +10 -0
- package/lib/auth/jwt.js +25 -0
- package/lib/auth/oauth-flow.d.ts +91 -0
- package/lib/auth/oauth-flow.js +227 -0
- package/lib/auth/pkce.d.ts +31 -0
- package/lib/auth/pkce.js +35 -0
- package/lib/auth/rpc.d.ts +209 -0
- package/lib/auth/rpc.js +386 -0
- package/lib/auth/store.d.ts +196 -0
- package/lib/auth/store.js +468 -0
- package/lib/client/CursorCard.d.ts +9 -0
- package/lib/client/CursorCard.js +113 -0
- package/lib/client/ExternalUsageCards.d.ts +9 -0
- package/lib/client/ExternalUsageCards.js +72 -0
- package/lib/client/ImageGallery.d.ts +54 -0
- package/lib/client/ImageGallery.js +112 -0
- package/lib/client/ImageGenerateToolview.d.ts +48 -0
- package/lib/client/ImageGenerateToolview.js +133 -0
- package/lib/client/ProviderAccountManager.d.ts +13 -0
- package/lib/client/ProviderAccountManager.js +147 -0
- package/lib/client/ProviderModelEditor.d.ts +39 -0
- package/lib/client/ProviderModelEditor.js +107 -0
- package/lib/client/SpeedSelect.d.ts +71 -0
- package/lib/client/SpeedSelect.js +177 -0
- package/lib/client/SubscriptionUsageBadge.d.ts +116 -0
- package/lib/client/SubscriptionUsageBadge.js +543 -0
- package/lib/client/SubscriptionsSection.d.ts +140 -0
- package/lib/client/SubscriptionsSection.js +544 -0
- package/lib/client/UsageBadgeDisplaySetting.d.ts +7 -0
- package/lib/client/UsageBadgeDisplaySetting.js +36 -0
- package/lib/client/VideoGenerateToolview.d.ts +42 -0
- package/lib/client/VideoGenerateToolview.js +175 -0
- package/lib/client/account-preferences.d.ts +24 -0
- package/lib/client/account-preferences.js +21 -0
- package/lib/client/fast-command.d.ts +2 -0
- package/lib/client/fast-command.js +4 -0
- package/lib/client/host-contract.d.ts +90 -0
- package/lib/client/host-contract.js +101 -0
- package/lib/client/host-icons.d.ts +24 -0
- package/lib/client/host-icons.js +21 -0
- package/lib/client/index.d.ts +27 -0
- package/lib/client/index.js +136 -0
- package/lib/client/locales.d.ts +297 -0
- package/lib/client/locales.js +295 -0
- package/lib/client/subscription-card-styles.d.ts +3 -0
- package/lib/client/subscription-card-styles.js +53 -0
- package/lib/client/subscriptions-rpc.d.ts +14 -0
- package/lib/client/subscriptions-rpc.js +34 -0
- package/lib/client/usage-badge-preferences.d.ts +11 -0
- package/lib/client/usage-badge-preferences.js +41 -0
- package/lib/client.js +4472 -0
- package/lib/client.js.map +1 -0
- package/lib/compat.d.ts +36 -0
- package/lib/compat.js +20 -0
- package/lib/http.d.ts +6 -0
- package/lib/http.js +15 -0
- package/lib/index.d.ts +80 -0
- package/lib/index.js +14018 -0
- package/lib/model-defaults.d.ts +23 -0
- package/lib/model-defaults.js +237 -0
- package/lib/provider-settings.d.ts +39 -0
- package/lib/provider-settings.js +151 -0
- package/lib/providers/account-preferences.d.ts +41 -0
- package/lib/providers/account-preferences.js +153 -0
- package/lib/providers/accounts.d.ts +112 -0
- package/lib/providers/accounts.js +142 -0
- package/lib/providers/antigravity-oauth-client.d.ts +7 -0
- package/lib/providers/antigravity-oauth-client.js +7 -0
- package/lib/providers/antigravity.d.ts +110 -0
- package/lib/providers/antigravity.js +516 -0
- package/lib/providers/catalog-store.d.ts +48 -0
- package/lib/providers/catalog-store.js +243 -0
- package/lib/providers/claude-cli-version.d.ts +15 -0
- package/lib/providers/claude-cli-version.js +24 -0
- package/lib/providers/claude.d.ts +181 -0
- package/lib/providers/claude.js +680 -0
- package/lib/providers/codex-client-version.d.ts +8 -0
- package/lib/providers/codex-client-version.js +17 -0
- package/lib/providers/codex-search.d.ts +29 -0
- package/lib/providers/codex-search.js +198 -0
- package/lib/providers/codex.d.ts +229 -0
- package/lib/providers/codex.js +821 -0
- package/lib/providers/common.d.ts +389 -0
- package/lib/providers/common.js +656 -0
- package/lib/providers/copilot.d.ts +344 -0
- package/lib/providers/copilot.js +888 -0
- package/lib/providers/cursor-adapter.d.ts +15 -0
- package/lib/providers/cursor-adapter.js +39 -0
- package/lib/providers/cursor-auth.d.ts +43 -0
- package/lib/providers/cursor-auth.js +169 -0
- package/lib/providers/cursor-model-settings.d.ts +15 -0
- package/lib/providers/cursor-model-settings.js +51 -0
- package/lib/providers/cursor-usage.d.ts +9 -0
- package/lib/providers/cursor-usage.js +112 -0
- package/lib/providers/external-usage-controller.d.ts +19 -0
- package/lib/providers/external-usage-controller.js +32 -0
- package/lib/providers/external-usage.d.ts +8 -0
- package/lib/providers/external-usage.js +82 -0
- package/lib/providers/grok.d.ts +205 -0
- package/lib/providers/grok.js +713 -0
- package/lib/providers/image-pool.d.ts +30 -0
- package/lib/providers/image-pool.js +89 -0
- package/lib/providers/npm-cli-version.d.ts +56 -0
- package/lib/providers/npm-cli-version.js +98 -0
- package/lib/providers/pool-family.d.ts +56 -0
- package/lib/providers/pool-family.js +45 -0
- package/lib/providers/pool-health.d.ts +74 -0
- package/lib/providers/pool-health.js +150 -0
- package/lib/providers/pool-usage.d.ts +86 -0
- package/lib/providers/pool-usage.js +223 -0
- package/lib/providers/pool.d.ts +108 -0
- package/lib/providers/pool.js +368 -0
- package/lib/providers/rate-limit.d.ts +192 -0
- package/lib/providers/rate-limit.js +338 -0
- package/lib/tools/image-generate.d.ts +128 -0
- package/lib/tools/image-generate.js +438 -0
- package/lib/tools/registration.d.ts +15 -0
- package/lib/tools/registration.js +24 -0
- package/lib/tools/video-generate.d.ts +89 -0
- package/lib/tools/video-generate.js +257 -0
- package/lib/tools/x-search.d.ts +58 -0
- package/lib/tools/x-search.js +197 -0
- package/lib/translate/anthropic.d.ts +161 -0
- package/lib/translate/anthropic.js +515 -0
- package/lib/translate/antigravity-schema.d.ts +4 -0
- package/lib/translate/antigravity-schema.js +145 -0
- package/lib/translate/antigravity-thinking.d.ts +5 -0
- package/lib/translate/antigravity-thinking.js +44 -0
- package/lib/translate/antigravity.d.ts +114 -0
- package/lib/translate/antigravity.js +366 -0
- package/lib/translate/chat-completions.d.ts +120 -0
- package/lib/translate/chat-completions.js +382 -0
- package/lib/translate/resolved.d.ts +80 -0
- package/lib/translate/resolved.js +118 -0
- package/lib/translate/responses.d.ts +179 -0
- package/lib/translate/responses.js +408 -0
- package/lib/translate/sse.d.ts +21 -0
- package/lib/translate/sse.js +56 -0
- package/package.json +114 -0
- package/vendor/cursor/LICENSE +21 -0
- package/vendor/cursor/index.d.ts +18 -0
- package/vendor/cursor/index.js +3574 -0
- package/vendor/cursor/proto.js +254 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quota tracking for pool members: polls the providers' usage endpoints
|
|
3
|
+
* (the same normalized `ProviderUsage` shape the Settings page consumes) and
|
|
4
|
+
* turns the windows into a scheduling score.
|
|
5
|
+
*
|
|
6
|
+
* The score is a REQUIRED BURN RATE: the fraction of the window that must be
|
|
7
|
+
* consumed per millisecond for the quota to be exactly used up at reset time
|
|
8
|
+
* (`remaining / timeUntilReset`). Subscription quota does not roll over, so a
|
|
9
|
+
* window about to reset with plenty left is the most urgent to spend — the
|
|
10
|
+
* `quota_aware` strategy therefore prefers the highest-urgency member, which
|
|
11
|
+
* over time converges on every window hitting zero right at its reset.
|
|
12
|
+
*/
|
|
13
|
+
import type { ProviderUsage } from './common.js';
|
|
14
|
+
import type { ProviderId } from '../auth/store.js';
|
|
15
|
+
import type { ConcretePoolMember } from './pool-family.js';
|
|
16
|
+
/** A member is taken out of rotation once any window crosses this fill level. */
|
|
17
|
+
export declare const QUOTA_FULL_PERCENT = 95;
|
|
18
|
+
/** How long a usage snapshot is trusted before a background refresh. */
|
|
19
|
+
export declare const USAGE_TTL_MS: number;
|
|
20
|
+
/** The scheduling view of one member's quota. */
|
|
21
|
+
export interface MemberQuota {
|
|
22
|
+
/** False when a window is effectively full or the login is gone. */
|
|
23
|
+
available: boolean;
|
|
24
|
+
/** Required burn rate (fraction of window per ms); 0 when unknown. */
|
|
25
|
+
urgency: number;
|
|
26
|
+
/** Epoch ms of the snapshot this was computed from; 0 when none. */
|
|
27
|
+
fetchedAt: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Per-ACCOUNT usage snapshots with in-flight dedupe and
|
|
31
|
+
* stale-while-revalidate refresh. Providers without a usage endpoint
|
|
32
|
+
* (copilot) resolve no fetcher and score a constant zero urgency — which
|
|
33
|
+
* naturally ranks them behind every measured member. Fetchers are resolved
|
|
34
|
+
* lazily per (provider, account) so accounts added after startup join
|
|
35
|
+
* tracking on their first score.
|
|
36
|
+
*/
|
|
37
|
+
export declare class PoolUsageTracker {
|
|
38
|
+
private readonly fetcherFor;
|
|
39
|
+
private readonly ttlMs;
|
|
40
|
+
private readonly entries;
|
|
41
|
+
private readonly inflight;
|
|
42
|
+
constructor(fetcherFor: (provider: ProviderId, account: string) => (() => Promise<ProviderUsage>) | undefined, ttlMs?: number);
|
|
43
|
+
/**
|
|
44
|
+
* The quota view of one member. A cold cache awaits the first fetch; a
|
|
45
|
+
* stale one answers immediately while the refresh serves the NEXT call
|
|
46
|
+
* (member selection must never block on the network mid-conversation). A
|
|
47
|
+
* failure still cooling down degrades immediately with no network call.
|
|
48
|
+
*
|
|
49
|
+
* Deliberately does NOT fall back to `lastSnapshot` the way
|
|
50
|
+
* {@link snapshotFor} does: scoring routing decisions off data that is
|
|
51
|
+
* known to be stale-and-unrefreshable risks steering traffic by a urgency
|
|
52
|
+
* number the endpoint itself is no longer vouching for, whereas
|
|
53
|
+
* `snapshotFor`'s stale-display concern (the Settings page, the composer
|
|
54
|
+
* badge) has no such downside — showing an old percentage beats showing
|
|
55
|
+
* nothing.
|
|
56
|
+
* @param member - the pool member to score (account resolved).
|
|
57
|
+
* @returns availability plus the urgency score.
|
|
58
|
+
*/
|
|
59
|
+
quotaFor(member: ConcretePoolMember): Promise<MemberQuota>;
|
|
60
|
+
/**
|
|
61
|
+
* Same cache as {@link quotaFor}, for direct display (the Settings page):
|
|
62
|
+
* the raw snapshot, or the original fetch error, instead of a routing
|
|
63
|
+
* score.
|
|
64
|
+
* @param provider - the account's provider.
|
|
65
|
+
* @param account - the account key.
|
|
66
|
+
* @param force - bypass a fresh cached SNAPSHOT for an honest re-check (the
|
|
67
|
+
* manual Refresh button). A live failure cooldown is never bypassed —
|
|
68
|
+
* retrying through it is exactly what turns a 429 into a permanent
|
|
69
|
+
* lockout, so even a forced call still answers from the negative cache.
|
|
70
|
+
* @returns `{ supported: false }` when the provider has no usage fetcher.
|
|
71
|
+
*/
|
|
72
|
+
snapshotFor(provider: ProviderId, account: string, force?: boolean): Promise<ProviderUsage>;
|
|
73
|
+
/** Drop cached snapshots: one account, or a whole provider when `account` is omitted. */
|
|
74
|
+
invalidate(provider: ProviderId, account?: string): void;
|
|
75
|
+
/**
|
|
76
|
+
* Run (or join) the single in-flight fetch for one account key, caching
|
|
77
|
+
* either outcome. A missing/invalid credential is deliberately NOT
|
|
78
|
+
* negative-cached: it costs no network round trip (the session lookup
|
|
79
|
+
* fails before the request goes out) and re-checking live means the
|
|
80
|
+
* member rejoins routing the instant its login is fixed, rather than
|
|
81
|
+
* waiting out a stale cooldown.
|
|
82
|
+
*/
|
|
83
|
+
private refresh;
|
|
84
|
+
/** Score one member against a snapshot's windows. */
|
|
85
|
+
private score;
|
|
86
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quota tracking for pool members: polls the providers' usage endpoints
|
|
3
|
+
* (the same normalized `ProviderUsage` shape the Settings page consumes) and
|
|
4
|
+
* turns the windows into a scheduling score.
|
|
5
|
+
*
|
|
6
|
+
* The score is a REQUIRED BURN RATE: the fraction of the window that must be
|
|
7
|
+
* consumed per millisecond for the quota to be exactly used up at reset time
|
|
8
|
+
* (`remaining / timeUntilReset`). Subscription quota does not roll over, so a
|
|
9
|
+
* window about to reset with plenty left is the most urgent to spend — the
|
|
10
|
+
* `quota_aware` strategy therefore prefers the highest-urgency member, which
|
|
11
|
+
* over time converges on every window hitting zero right at its reset.
|
|
12
|
+
*/
|
|
13
|
+
import { isMissingOrInvalidCredential, OAuthEndpointError } from './common.js';
|
|
14
|
+
/** A member is taken out of rotation once any window crosses this fill level. */
|
|
15
|
+
export const QUOTA_FULL_PERCENT = 95;
|
|
16
|
+
/** How long a usage snapshot is trusted before a background refresh. */
|
|
17
|
+
export const USAGE_TTL_MS = 5 * 60_000;
|
|
18
|
+
/** Assumed window length when the provider discloses no `resetsAt`. */
|
|
19
|
+
const FALLBACK_HORIZON_MS = {
|
|
20
|
+
session: 5 * 60 * 60_000,
|
|
21
|
+
weekly: 7 * 24 * 60 * 60_000,
|
|
22
|
+
other: 30 * 24 * 60 * 60_000,
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Per-ACCOUNT usage snapshots with in-flight dedupe and
|
|
26
|
+
* stale-while-revalidate refresh. Providers without a usage endpoint
|
|
27
|
+
* (copilot) resolve no fetcher and score a constant zero urgency — which
|
|
28
|
+
* naturally ranks them behind every measured member. Fetchers are resolved
|
|
29
|
+
* lazily per (provider, account) so accounts added after startup join
|
|
30
|
+
* tracking on their first score.
|
|
31
|
+
*/
|
|
32
|
+
export class PoolUsageTracker {
|
|
33
|
+
fetcherFor;
|
|
34
|
+
ttlMs;
|
|
35
|
+
entries = new Map();
|
|
36
|
+
inflight = new Map();
|
|
37
|
+
constructor(fetcherFor, ttlMs = USAGE_TTL_MS) {
|
|
38
|
+
this.fetcherFor = fetcherFor;
|
|
39
|
+
this.ttlMs = ttlMs;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The quota view of one member. A cold cache awaits the first fetch; a
|
|
43
|
+
* stale one answers immediately while the refresh serves the NEXT call
|
|
44
|
+
* (member selection must never block on the network mid-conversation). A
|
|
45
|
+
* failure still cooling down degrades immediately with no network call.
|
|
46
|
+
*
|
|
47
|
+
* Deliberately does NOT fall back to `lastSnapshot` the way
|
|
48
|
+
* {@link snapshotFor} does: scoring routing decisions off data that is
|
|
49
|
+
* known to be stale-and-unrefreshable risks steering traffic by a urgency
|
|
50
|
+
* number the endpoint itself is no longer vouching for, whereas
|
|
51
|
+
* `snapshotFor`'s stale-display concern (the Settings page, the composer
|
|
52
|
+
* badge) has no such downside — showing an old percentage beats showing
|
|
53
|
+
* nothing.
|
|
54
|
+
* @param member - the pool member to score (account resolved).
|
|
55
|
+
* @returns availability plus the urgency score.
|
|
56
|
+
*/
|
|
57
|
+
async quotaFor(member) {
|
|
58
|
+
const key = `${member.provider}/${member.account}`;
|
|
59
|
+
const fetcher = this.fetcherFor(member.provider, member.account);
|
|
60
|
+
if (fetcher === undefined)
|
|
61
|
+
return { available: true, urgency: 0, fetchedAt: 0 };
|
|
62
|
+
const entry = this.entries.get(key);
|
|
63
|
+
if (entry !== undefined) {
|
|
64
|
+
const fresh = Date.now() - entry.at < (entry.cooldownMs ?? this.ttlMs);
|
|
65
|
+
if (entry.snapshot !== undefined) {
|
|
66
|
+
if (!fresh)
|
|
67
|
+
void this.refresh(key, fetcher).catch(() => undefined);
|
|
68
|
+
return this.score(member, entry);
|
|
69
|
+
}
|
|
70
|
+
if (fresh)
|
|
71
|
+
return degradedQuota(entry.error);
|
|
72
|
+
// The cooldown expired: fall through to a fresh, blocking attempt.
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const snapshot = await this.refresh(key, fetcher);
|
|
76
|
+
return this.score(member, { snapshot, at: Date.now() });
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
return degradedQuota(error);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Same cache as {@link quotaFor}, for direct display (the Settings page):
|
|
84
|
+
* the raw snapshot, or the original fetch error, instead of a routing
|
|
85
|
+
* score.
|
|
86
|
+
* @param provider - the account's provider.
|
|
87
|
+
* @param account - the account key.
|
|
88
|
+
* @param force - bypass a fresh cached SNAPSHOT for an honest re-check (the
|
|
89
|
+
* manual Refresh button). A live failure cooldown is never bypassed —
|
|
90
|
+
* retrying through it is exactly what turns a 429 into a permanent
|
|
91
|
+
* lockout, so even a forced call still answers from the negative cache.
|
|
92
|
+
* @returns `{ supported: false }` when the provider has no usage fetcher.
|
|
93
|
+
*/
|
|
94
|
+
async snapshotFor(provider, account, force = false) {
|
|
95
|
+
const fetcher = this.fetcherFor(provider, account);
|
|
96
|
+
if (fetcher === undefined)
|
|
97
|
+
return { supported: false };
|
|
98
|
+
const key = `${provider}/${account}`;
|
|
99
|
+
const entry = this.entries.get(key);
|
|
100
|
+
if (entry !== undefined && Date.now() - entry.at < (entry.cooldownMs ?? this.ttlMs)) {
|
|
101
|
+
if (entry.snapshot !== undefined) {
|
|
102
|
+
if (!force)
|
|
103
|
+
return entry.snapshot;
|
|
104
|
+
}
|
|
105
|
+
else if (entry.lastSnapshot !== undefined) {
|
|
106
|
+
// A stale-but-real snapshot beats surfacing the cooldown error to
|
|
107
|
+
// every display surface — this is what was previously showing, so
|
|
108
|
+
// keep showing it (even through a forced refresh: retrying past the
|
|
109
|
+
// cooldown is exactly the retry storm `cooldownMs` exists to avoid).
|
|
110
|
+
return entry.lastSnapshot;
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
throw entry.error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
return await this.refresh(key, fetcher);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
// Same fallback as the already-cooling-down branch above, for the
|
|
121
|
+
// fetch that just failed on THIS call: `refresh` recorded whatever
|
|
122
|
+
// snapshot was on record before it ran onto the new failure entry.
|
|
123
|
+
const failed = this.entries.get(key);
|
|
124
|
+
if (failed?.snapshot === undefined && failed?.lastSnapshot !== undefined)
|
|
125
|
+
return failed.lastSnapshot;
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** Drop cached snapshots: one account, or a whole provider when `account` is omitted. */
|
|
130
|
+
invalidate(provider, account) {
|
|
131
|
+
if (account !== undefined) {
|
|
132
|
+
this.entries.delete(`${provider}/${account}`);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
for (const key of [...this.entries.keys()]) {
|
|
136
|
+
if (key.startsWith(`${provider}/`))
|
|
137
|
+
this.entries.delete(key);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Run (or join) the single in-flight fetch for one account key, caching
|
|
142
|
+
* either outcome. A missing/invalid credential is deliberately NOT
|
|
143
|
+
* negative-cached: it costs no network round trip (the session lookup
|
|
144
|
+
* fails before the request goes out) and re-checking live means the
|
|
145
|
+
* member rejoins routing the instant its login is fixed, rather than
|
|
146
|
+
* waiting out a stale cooldown.
|
|
147
|
+
*/
|
|
148
|
+
refresh(key, fetcher) {
|
|
149
|
+
let pending = this.inflight.get(key);
|
|
150
|
+
if (pending === undefined) {
|
|
151
|
+
// Captured before the fetch starts: whichever real snapshot is on
|
|
152
|
+
// record right now is what a failure below should fall back to. A
|
|
153
|
+
// failure entry's own `lastSnapshot` counts too — otherwise the stale
|
|
154
|
+
// snapshot would survive exactly one cooldown and vanish on the next
|
|
155
|
+
// consecutive failure, even though nothing newer ever replaced it.
|
|
156
|
+
const prior = this.entries.get(key);
|
|
157
|
+
const lastSnapshot = prior?.snapshot ?? prior?.lastSnapshot;
|
|
158
|
+
pending = fetcher().then((snapshot) => {
|
|
159
|
+
this.entries.set(key, { snapshot, at: Date.now() });
|
|
160
|
+
return snapshot;
|
|
161
|
+
}, (error) => {
|
|
162
|
+
if (!isMissingOrInvalidCredential(error)) {
|
|
163
|
+
this.entries.set(key, {
|
|
164
|
+
error,
|
|
165
|
+
at: Date.now(),
|
|
166
|
+
cooldownMs: cooldownFor(error, this.ttlMs),
|
|
167
|
+
...lastSnapshot === undefined ? {} : { lastSnapshot },
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
throw error;
|
|
171
|
+
}).finally(() => {
|
|
172
|
+
this.inflight.delete(key);
|
|
173
|
+
});
|
|
174
|
+
this.inflight.set(key, pending);
|
|
175
|
+
}
|
|
176
|
+
return pending;
|
|
177
|
+
}
|
|
178
|
+
/** Score one member against a snapshot's windows. */
|
|
179
|
+
score(member, entry) {
|
|
180
|
+
const windows = (entry.snapshot.windows ?? []).filter(window => windowApplies(window, member.model));
|
|
181
|
+
let available = true;
|
|
182
|
+
let urgency = 0;
|
|
183
|
+
for (const window of windows) {
|
|
184
|
+
if (window.usedPercent >= QUOTA_FULL_PERCENT)
|
|
185
|
+
available = false;
|
|
186
|
+
urgency = Math.max(urgency, windowUrgency(window));
|
|
187
|
+
}
|
|
188
|
+
return { available, urgency, fetchedAt: entry.at };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The routing view of a fetch failure. Logged out: the member cannot serve
|
|
193
|
+
* at all. Any other failure (network, endpoint rate limit) must not block
|
|
194
|
+
* routing — the member stays available with a zero score, degrading the
|
|
195
|
+
* strategy to plain priority order for it.
|
|
196
|
+
*/
|
|
197
|
+
function degradedQuota(error) {
|
|
198
|
+
return isMissingOrInvalidCredential(error)
|
|
199
|
+
? { available: false, urgency: 0, fetchedAt: 0 }
|
|
200
|
+
: { available: true, urgency: 0, fetchedAt: 0 };
|
|
201
|
+
}
|
|
202
|
+
/** How long to hold a failure in the negative cache: the endpoint's own `retry-after`, or the default TTL. */
|
|
203
|
+
function cooldownFor(error, defaultTtlMs) {
|
|
204
|
+
return error instanceof OAuthEndpointError && error.retryAfterMs !== undefined ? error.retryAfterMs : defaultTtlMs;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Whether a window constrains this model: unscoped windows always do; a
|
|
208
|
+
* model-scoped window (Claude's Opus/Sonnet lanes) applies when its scope
|
|
209
|
+
* names the model family.
|
|
210
|
+
*/
|
|
211
|
+
function windowApplies(window, model) {
|
|
212
|
+
if (window.scope === undefined)
|
|
213
|
+
return true;
|
|
214
|
+
return model.toLowerCase().includes(window.scope.toLowerCase());
|
|
215
|
+
}
|
|
216
|
+
/** The required burn rate of one window (fraction per ms). */
|
|
217
|
+
function windowUrgency(window, now = Date.now()) {
|
|
218
|
+
const remaining = Math.max(0, 1 - window.usedPercent / 100);
|
|
219
|
+
const horizon = window.resetsAt !== undefined
|
|
220
|
+
? Math.max(window.resetsAt - now, 1)
|
|
221
|
+
: FALLBACK_HORIZON_MS[window.kind];
|
|
222
|
+
return remaining / horizon;
|
|
223
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pool adapter: same-subscription account routing, plus optional
|
|
3
|
+
* configured tier extras. The picker is the union of every account's
|
|
4
|
+
* catalog. A model listed by several accounts failovers; a model listed by
|
|
5
|
+
* one account is pinned to it. Tiers are extra picker rows. Member
|
|
6
|
+
* selection is sticky per session (so prompt caches survive) and optionally
|
|
7
|
+
* quota-aware; failures fail over to the next member as long as no stream
|
|
8
|
+
* chunk has been emitted.
|
|
9
|
+
*/
|
|
10
|
+
import { LlmAdapter } from '@deepseek-ai/dsh-llm';
|
|
11
|
+
import type { GenerateOptions, LlmModelInfo, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm';
|
|
12
|
+
import type { ProviderId } from '../auth/store.js';
|
|
13
|
+
import type { AccountAwareAdapter } from './accounts.js';
|
|
14
|
+
import type { PoolDefinition, PoolMemberRef } from './pool-family.js';
|
|
15
|
+
import { PoolHealthRegistry } from './pool-health.js';
|
|
16
|
+
import type { PoolUsageTracker } from './pool-usage.js';
|
|
17
|
+
/** Member-selection strategy: plain priority failover or quota-aware scheduling. */
|
|
18
|
+
export type PoolStrategy = 'priority' | 'quota_aware';
|
|
19
|
+
export interface PoolAdapterOptions {
|
|
20
|
+
/** The live subscription adapters, by provider route. */
|
|
21
|
+
adapters: Partial<Record<ProviderId, AccountAwareAdapter>>;
|
|
22
|
+
health: PoolHealthRegistry;
|
|
23
|
+
usage: PoolUsageTracker;
|
|
24
|
+
strategy: PoolStrategy;
|
|
25
|
+
/** A challenger must out-urgency the sticky member by this factor to take over. */
|
|
26
|
+
switchMargin: number;
|
|
27
|
+
/** The default account of one provider (for config members omitting `account`). */
|
|
28
|
+
defaultAccount: (provider: ProviderId) => Promise<string | undefined>;
|
|
29
|
+
/** Resolve legacy account aliases before pool deduplication and cache identity. */
|
|
30
|
+
resolveAccount?: (provider: ProviderId, account: string) => Promise<string>;
|
|
31
|
+
/** Account pools (auto-aggregated plus config overrides), resolved lazily. */
|
|
32
|
+
families: () => Promise<Map<string, PoolDefinition>>;
|
|
33
|
+
/** User-configured extra picker entries (heterogeneous fallbacks), by pool id. */
|
|
34
|
+
tiers: Record<string, PoolMemberRef[]>;
|
|
35
|
+
onWarn: (message: string) => void;
|
|
36
|
+
}
|
|
37
|
+
export declare class PoolAdapter extends LlmAdapter {
|
|
38
|
+
private readonly options;
|
|
39
|
+
/** sessionId|poolId → member key of the last member that served a chunk. */
|
|
40
|
+
private readonly sticky;
|
|
41
|
+
/** Messages already warned about — configuration diagnostics repeat every request otherwise. */
|
|
42
|
+
private readonly warned;
|
|
43
|
+
/**
|
|
44
|
+
* Short-lived pools snapshot. `owns()` runs on every resolveModel — the
|
|
45
|
+
* model picker issues one per entry — and pool assembly touches every
|
|
46
|
+
* provider's catalog and account store, so recompute at most this often.
|
|
47
|
+
* Auth changes bump {@link generation} so a stale snapshot cannot land.
|
|
48
|
+
*/
|
|
49
|
+
private poolsCache;
|
|
50
|
+
private poolsInflight;
|
|
51
|
+
private generation;
|
|
52
|
+
constructor(options: PoolAdapterOptions);
|
|
53
|
+
/** Drop the pools snapshot so the next read reflects the current accounts. */
|
|
54
|
+
invalidate(): void;
|
|
55
|
+
/** Warn once per distinct message (pools() runs on every request). */
|
|
56
|
+
private warnOnce;
|
|
57
|
+
/** Drop members whose adapter is not registered (copy — caller state is shared). */
|
|
58
|
+
private usable;
|
|
59
|
+
/** Account pools (auto-aggregated plus config overrides) with usable members. */
|
|
60
|
+
private familyPools;
|
|
61
|
+
/** All pools (account pools merged with extra tiers) with usable members. */
|
|
62
|
+
private pools;
|
|
63
|
+
/** Recompute the pools snapshot (account pools merged with extra tiers). */
|
|
64
|
+
private assemblePools;
|
|
65
|
+
/**
|
|
66
|
+
* Extra picker rows one provider lists (configured tiers). Account pools
|
|
67
|
+
* reuse the catalog entry of the same wire id, so they are not listed
|
|
68
|
+
* again — the picker stays one row per model in ChatGPT / Claude / ….
|
|
69
|
+
*/
|
|
70
|
+
modelsForProvider(provider: ProviderId): Promise<LlmModelInfo[]>;
|
|
71
|
+
/**
|
|
72
|
+
* Whether `model` on `provider`'s route is served here (several accounts
|
|
73
|
+
* fail over, one account is pinned, or a configured tier).
|
|
74
|
+
*/
|
|
75
|
+
owns(provider: ProviderId, model: string): Promise<boolean>;
|
|
76
|
+
/**
|
|
77
|
+
* Resolve every member's account (config members may omit it to mean "the
|
|
78
|
+
* default account") and drop members with no resolvable login. Duplicates
|
|
79
|
+
* collapse — an explicitly pinned account and the default may coincide.
|
|
80
|
+
*/
|
|
81
|
+
private concrete;
|
|
82
|
+
/**
|
|
83
|
+
* Resolve a pool model to the conservative INTERSECTION of its members'
|
|
84
|
+
* capabilities: the smallest context window and output cap, the reasoning
|
|
85
|
+
* efforts every member supports, and the modalities all of them accept —
|
|
86
|
+
* so a request valid for the pool stays valid after a failover. Capability
|
|
87
|
+
* metadata is account-specific, so every distinct member is resolved.
|
|
88
|
+
*/
|
|
89
|
+
resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
|
|
90
|
+
stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
|
|
91
|
+
/**
|
|
92
|
+
* Order the candidates for one request. Health filters both strategies;
|
|
93
|
+
* `quota_aware` then ranks by urgency (members without telemetry, e.g.
|
|
94
|
+
* copilot, score zero and sink to the bottom of their class), while
|
|
95
|
+
* quota-exhausted members stay as a last-resort tail in pool order. The
|
|
96
|
+
* sticky member keeps its lead unless a challenger out-scores it by
|
|
97
|
+
* `switchMargin`.
|
|
98
|
+
*/
|
|
99
|
+
private select;
|
|
100
|
+
/** Pin the serving member to the session (with bounded memory). */
|
|
101
|
+
private remember;
|
|
102
|
+
/**
|
|
103
|
+
* The error for an exhausted pool, carrying the earliest recovery hint of
|
|
104
|
+
* THIS pool's members (the health registry is shared across pools, so the
|
|
105
|
+
* hint is scoped to the keys this pool can actually recover through).
|
|
106
|
+
*/
|
|
107
|
+
private exhausted;
|
|
108
|
+
}
|