dsh-keys-manager 0.2.6 → 0.2.9
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 +52 -0
- package/README.md +219 -269
- package/README.zh-CN.md +142 -136
- package/lib/client/format.d.ts +27 -3
- package/lib/client/styles.d.ts +1 -1
- package/lib/client/types.d.ts +10 -2
- package/lib/client.js +155 -7
- package/lib/domain.d.ts +30 -5
- package/lib/index.d.ts +66 -5
- package/lib/index.js +295 -78
- package/lib/index.js.map +1 -1
- package/lib/quota/cache.d.ts +61 -0
- package/lib/quota/cache.js +88 -0
- package/lib/quota/cache.js.map +1 -0
- package/lib/quota/fetch.d.ts +33 -0
- package/lib/quota/fetch.js +36 -0
- package/lib/quota/fetch.js.map +1 -0
- package/lib/quota/model.d.ts +60 -0
- package/lib/quota/model.js +62 -0
- package/lib/quota/model.js.map +1 -0
- package/lib/quota/providers.d.ts +89 -0
- package/lib/quota/providers.js +533 -0
- package/lib/quota/providers.js.map +1 -0
- package/locale/en.json +7 -1
- package/locale/zh.json +7 -1
- package/package.json +15 -15
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory quota cache: TTL with jitter, single-flight per account, failure
|
|
3
|
+
* backoff, and last-good retention.
|
|
4
|
+
*
|
|
5
|
+
* The Host owns one instance. Nothing is persisted and nothing is polled: a
|
|
6
|
+
* read either serves a snapshot or performs at most one in-flight vendor call
|
|
7
|
+
* per (provider, key). Failures are cached too, so a rate-limited endpoint is
|
|
8
|
+
* not hammered on every card render; a last-good snapshot stays visible
|
|
9
|
+
* (flagged `stale`) for up to 24 h before the failure state replaces it.
|
|
10
|
+
* Quota state here never feeds selection, cooldown or failure escalation.
|
|
11
|
+
*
|
|
12
|
+
* @module dsh-keys-manager/quota/cache
|
|
13
|
+
*/
|
|
14
|
+
import type { QuotaSnapshot } from './model.js';
|
|
15
|
+
/** A snapshot as served to the UI: `stale` marks last-good data behind a failure. */
|
|
16
|
+
export interface QuotaSnapshotView extends QuotaSnapshot {
|
|
17
|
+
stale?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Cache policy overrides; every field has a production default. */
|
|
20
|
+
export interface QuotaCacheOptions {
|
|
21
|
+
/** Base freshness window; defaults to 300 s. */
|
|
22
|
+
ttlMs?: number;
|
|
23
|
+
/** Symmetric jitter as a fraction of `ttlMs`; defaults to 0.25 (±25%). */
|
|
24
|
+
jitterRatio?: number;
|
|
25
|
+
/** Retry delay after `error`/`absent`; defaults to 10 s. */
|
|
26
|
+
failureBackoffMs?: number;
|
|
27
|
+
/** Retry delay after `unauthorized`; defaults to 60 s. */
|
|
28
|
+
unauthorizedBackoffMs?: number;
|
|
29
|
+
/** How long a last-good snapshot may outlive a failure; defaults to 24 h. */
|
|
30
|
+
staleMs?: number;
|
|
31
|
+
/** Injected clock for tests. */
|
|
32
|
+
now?: () => number;
|
|
33
|
+
/** Injected randomness for jitter tests; `[0, 1]`. */
|
|
34
|
+
random?: () => number;
|
|
35
|
+
}
|
|
36
|
+
/** Shared cache across all provider cards; safe for concurrent reads. */
|
|
37
|
+
export declare class QuotaCache {
|
|
38
|
+
private readonly entries;
|
|
39
|
+
private readonly inFlight;
|
|
40
|
+
private readonly ttlMs;
|
|
41
|
+
private readonly jitterRatio;
|
|
42
|
+
private readonly failureBackoffMs;
|
|
43
|
+
private readonly unauthorizedBackoffMs;
|
|
44
|
+
private readonly staleMs;
|
|
45
|
+
private readonly now;
|
|
46
|
+
private readonly random;
|
|
47
|
+
constructor(options?: QuotaCacheOptions);
|
|
48
|
+
/**
|
|
49
|
+
* Serve one account's snapshot, loading it at most once per freshness or
|
|
50
|
+
* backoff window. Concurrent reads of the same account share one load.
|
|
51
|
+
*/
|
|
52
|
+
get(provider: string, keyId: string, load: () => Promise<QuotaSnapshot>): Promise<QuotaSnapshotView>;
|
|
53
|
+
private load;
|
|
54
|
+
/**
|
|
55
|
+
* The snapshot currently held for one account, without loading. The normal
|
|
56
|
+
* state path uses this so a card render can never reach a vendor (D2).
|
|
57
|
+
*/
|
|
58
|
+
peek(provider: string, keyId: string): QuotaSnapshotView | undefined;
|
|
59
|
+
private retryDelay;
|
|
60
|
+
private settle;
|
|
61
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
const DEFAULT_POLICY = {
|
|
2
|
+
ttlMs: 300_000,
|
|
3
|
+
jitterRatio: 0.25,
|
|
4
|
+
failureBackoffMs: 10_000,
|
|
5
|
+
unauthorizedBackoffMs: 60_000,
|
|
6
|
+
staleMs: 24 * 60 * 60 * 1000,
|
|
7
|
+
};
|
|
8
|
+
/** Shared cache across all provider cards; safe for concurrent reads. */
|
|
9
|
+
export class QuotaCache {
|
|
10
|
+
entries = new Map();
|
|
11
|
+
inFlight = new Map();
|
|
12
|
+
ttlMs;
|
|
13
|
+
jitterRatio;
|
|
14
|
+
failureBackoffMs;
|
|
15
|
+
unauthorizedBackoffMs;
|
|
16
|
+
staleMs;
|
|
17
|
+
now;
|
|
18
|
+
random;
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_POLICY.ttlMs;
|
|
21
|
+
this.jitterRatio = options.jitterRatio ?? DEFAULT_POLICY.jitterRatio;
|
|
22
|
+
this.failureBackoffMs = options.failureBackoffMs ?? DEFAULT_POLICY.failureBackoffMs;
|
|
23
|
+
this.unauthorizedBackoffMs = options.unauthorizedBackoffMs ?? DEFAULT_POLICY.unauthorizedBackoffMs;
|
|
24
|
+
this.staleMs = options.staleMs ?? DEFAULT_POLICY.staleMs;
|
|
25
|
+
this.now = options.now ?? Date.now;
|
|
26
|
+
this.random = options.random ?? Math.random;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Serve one account's snapshot, loading it at most once per freshness or
|
|
30
|
+
* backoff window. Concurrent reads of the same account share one load.
|
|
31
|
+
*/
|
|
32
|
+
get(provider, keyId, load) {
|
|
33
|
+
const key = `${provider}\u0000${keyId}`;
|
|
34
|
+
const now = this.now();
|
|
35
|
+
const entry = this.entries.get(key);
|
|
36
|
+
if (entry !== undefined && now < entry.nextAttemptAt)
|
|
37
|
+
return Promise.resolve(entry.snapshot);
|
|
38
|
+
const pending = this.inFlight.get(key);
|
|
39
|
+
if (pending !== undefined)
|
|
40
|
+
return pending;
|
|
41
|
+
const promise = this.load(key, now, load).finally(() => this.inFlight.delete(key));
|
|
42
|
+
this.inFlight.set(key, promise);
|
|
43
|
+
return promise;
|
|
44
|
+
}
|
|
45
|
+
async load(key, now, load) {
|
|
46
|
+
const result = await this.settle(load, now);
|
|
47
|
+
const previous = this.entries.get(key);
|
|
48
|
+
// The cache owns the clock, so probe time and test time cannot diverge.
|
|
49
|
+
const stamped = { ...result, fetchedAt: now };
|
|
50
|
+
const lastGood = stamped.status === 'ok' ? stamped : previous?.lastGood;
|
|
51
|
+
const keepLastGood = stamped.status !== 'ok' && lastGood !== undefined && now - lastGood.fetchedAt <= this.staleMs;
|
|
52
|
+
const served = keepLastGood && lastGood !== undefined ? { ...lastGood, stale: true } : { ...stamped, stale: false };
|
|
53
|
+
this.entries.set(key, {
|
|
54
|
+
snapshot: served,
|
|
55
|
+
nextAttemptAt: now + this.retryDelay(stamped.status),
|
|
56
|
+
lastGood,
|
|
57
|
+
});
|
|
58
|
+
return served;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The snapshot currently held for one account, without loading. The normal
|
|
62
|
+
* state path uses this so a card render can never reach a vendor (D2).
|
|
63
|
+
*/
|
|
64
|
+
peek(provider, keyId) {
|
|
65
|
+
return this.entries.get(`${provider}\u0000${keyId}`)?.snapshot;
|
|
66
|
+
}
|
|
67
|
+
retryDelay(status) {
|
|
68
|
+
if (status === 'ok') {
|
|
69
|
+
const jitter = this.jitterRatio * (2 * this.random() - 1);
|
|
70
|
+
return this.ttlMs * (1 + jitter);
|
|
71
|
+
}
|
|
72
|
+
return status === 'unauthorized' ? this.unauthorizedBackoffMs : this.failureBackoffMs;
|
|
73
|
+
}
|
|
74
|
+
async settle(load, now) {
|
|
75
|
+
try {
|
|
76
|
+
return await load();
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
status: 'error',
|
|
81
|
+
fetchedAt: now,
|
|
82
|
+
windows: [],
|
|
83
|
+
reason: error instanceof Error ? error.message : 'quota probe failed',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../src/quota/cache.ts"],"names":[],"mappings":"AAsCA,MAAM,cAAc,GAAG;IACrB,KAAK,EAAE,OAAO;IACd,WAAW,EAAE,IAAI;IACjB,gBAAgB,EAAE,MAAM;IACxB,qBAAqB,EAAE,MAAM;IAC7B,OAAO,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;CACpB,CAAA;AASV,yEAAyE;AACzE,MAAM,OAAO,UAAU;IACJ,OAAO,GAAG,IAAI,GAAG,EAAsB,CAAA;IACvC,QAAQ,GAAG,IAAI,GAAG,EAAsC,CAAA;IACxD,KAAK,CAAQ;IACb,WAAW,CAAQ;IACnB,gBAAgB,CAAQ;IACxB,qBAAqB,CAAQ;IAC7B,OAAO,CAAQ;IACf,GAAG,CAAc;IACjB,MAAM,CAAc;IAErC,YAAY,UAA6B,EAAE;QACzC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,cAAc,CAAC,KAAK,CAAA;QAClD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,cAAc,CAAC,WAAW,CAAA;QACpE,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,IAAI,cAAc,CAAC,gBAAgB,CAAA;QACnF,IAAI,CAAC,qBAAqB,GAAG,OAAO,CAAC,qBAAqB,IAAI,cAAc,CAAC,qBAAqB,C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,CAAC,GAAG,MAAM,CAAC,CAAA;QAClC,CAAC;QACD,OAAO,MAAM,KAAK,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAA;IACvF,CAAC;IAEO,KAAK,CAAC,MAAM,CAAC,IAAkC,EAAE,GAAW;QAClE,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO;gBACL,MAAM,EAAE,OAAO;gBACf,SAAS,EAAE,GAAG;gBACd,OAAO,EAAE,EAAE;gBACX,MAAM,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB;aACtE,CAAA;QACH,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One HTTP read against a vendor usage endpoint, classified into quota status.
|
|
3
|
+
*
|
|
4
|
+
* Both probes share this function so 401/403, 404, timeout and parse failures
|
|
5
|
+
* mean the same thing everywhere: `unauthorized`, `absent`, `error`. It never
|
|
6
|
+
* throws — every failure mode becomes a `QuotaRead` — and the caller's abort
|
|
7
|
+
* signal is combined with a hard timeout so a hung vendor cannot hold a card
|
|
8
|
+
* render open.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-keys-manager/quota/fetch
|
|
11
|
+
*/
|
|
12
|
+
import type { QuotaStatus } from './model.js';
|
|
13
|
+
/** Injected for tests; the platform `fetch` in production. */
|
|
14
|
+
export type QuotaFetch = typeof fetch;
|
|
15
|
+
/** A parsed 2xx body, or the classified reason the read produced nothing. */
|
|
16
|
+
export type QuotaRead = {
|
|
17
|
+
ok: true;
|
|
18
|
+
body: Record<string, unknown>;
|
|
19
|
+
} | {
|
|
20
|
+
ok: false;
|
|
21
|
+
status: Exclude<QuotaStatus, 'ok'>;
|
|
22
|
+
reason: string;
|
|
23
|
+
};
|
|
24
|
+
/** Per-call overrides; all optional so probes stay one-liners. */
|
|
25
|
+
export interface QuotaReadOptions {
|
|
26
|
+
fetch?: QuotaFetch;
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
}
|
|
30
|
+
/** Hard cap on one vendor read. */
|
|
31
|
+
export declare const DEFAULT_TIMEOUT_MS = 10000;
|
|
32
|
+
/** GET `url` and classify the response into a quota read. */
|
|
33
|
+
export declare function readQuotaJson(url: string, headers: Record<string, string>, options?: QuotaReadOptions): Promise<QuotaRead>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Hard cap on one vendor read. */
|
|
2
|
+
export const DEFAULT_TIMEOUT_MS = 10_000;
|
|
3
|
+
/** GET `url` and classify the response into a quota read. */
|
|
4
|
+
export async function readQuotaJson(url, headers, options = {}) {
|
|
5
|
+
const { fetch: fetchImpl = globalThis.fetch, signal, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
|
|
6
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
7
|
+
const combined = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
|
|
8
|
+
try {
|
|
9
|
+
const response = await fetchImpl(url, { headers, signal: combined });
|
|
10
|
+
if (response.status === 401 || response.status === 403) {
|
|
11
|
+
return { ok: false, status: 'unauthorized', reason: `http ${response.status}` };
|
|
12
|
+
}
|
|
13
|
+
if (response.status === 404)
|
|
14
|
+
return { ok: false, status: 'absent', reason: 'http 404' };
|
|
15
|
+
if (response.status < 200 || response.status >= 300) {
|
|
16
|
+
return { ok: false, status: 'error', reason: `http ${response.status}` };
|
|
17
|
+
}
|
|
18
|
+
const body = await response.json();
|
|
19
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
20
|
+
return { ok: false, status: 'error', reason: 'non-object body' };
|
|
21
|
+
}
|
|
22
|
+
return { ok: true, body: body };
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (signal?.aborted === true)
|
|
26
|
+
return { ok: false, status: 'error', reason: 'aborted' };
|
|
27
|
+
if (timeout.aborted)
|
|
28
|
+
return { ok: false, status: 'error', reason: 'timeout' };
|
|
29
|
+
return {
|
|
30
|
+
ok: false,
|
|
31
|
+
status: 'error',
|
|
32
|
+
reason: error instanceof Error ? error.message : 'network error',
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=fetch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/quota/fetch.ts"],"names":[],"mappings":"AA4BA,mCAAmC;AACnC,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAA;AAExC,6DAA6D;AAC7D,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,GAAW,EACX,OAA+B,EAC/B,UAA4B,EAAE;IAE9B,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,GAAG,kBAAkB,EAAE,GAAG,OAAO,CAAA;IAC/F,MAAM,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IAC9C,MAAM,QAAQ,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;IACpF,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAA;QACpE,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvD,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,QAAQ,QAAQ,CAAC,MAAM,EAAE,EAA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AACH,CAAC"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quota-domain types and the pure unit normalizers every probe shares.
|
|
3
|
+
*
|
|
4
|
+
* Vendors disagree on nearly every unit: Claude reports *used* utilization
|
|
5
|
+
* and an ISO reset stamp, Codex reports used percent with epoch seconds or a
|
|
6
|
+
* relative delay under aliased keys. Normalizing here keeps the probes thin
|
|
7
|
+
* and keeps "used" vs "remaining" invertible in one tested place. Nothing in
|
|
8
|
+
* this module touches the network, the clock, the filesystem, or key
|
|
9
|
+
* selection state.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-keys-manager/quota/model
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Outcome class of one quota read. Only `ok` carries usable windows; probes
|
|
15
|
+
* produce the first four, while `natively-managed` is host-only: the route is
|
|
16
|
+
* served by a DSH-managed projection whose credential this process cannot read.
|
|
17
|
+
*/
|
|
18
|
+
export type QuotaStatus = 'ok' | 'absent' | 'unauthorized' | 'error' | 'natively-managed';
|
|
19
|
+
/** The plan windows the UI can render; a provider may expose either or both. */
|
|
20
|
+
export type QuotaWindowId = 'session' | 'week';
|
|
21
|
+
/** One usage window of a managed account's plan. */
|
|
22
|
+
export interface QuotaWindow {
|
|
23
|
+
id: QuotaWindowId;
|
|
24
|
+
/** Share of the window already consumed, `0`..`1`. */
|
|
25
|
+
usedFraction: number;
|
|
26
|
+
/** Reset time as epoch milliseconds. */
|
|
27
|
+
resetsAt: number;
|
|
28
|
+
}
|
|
29
|
+
/** Normalized, cacheable result of one probe. */
|
|
30
|
+
export interface QuotaSnapshot {
|
|
31
|
+
status: QuotaStatus;
|
|
32
|
+
/** Epoch milliseconds when the probe ran. */
|
|
33
|
+
fetchedAt: number;
|
|
34
|
+
windows: QuotaWindow[];
|
|
35
|
+
/** Diagnostic detail for non-`ok` states; never rendered verbatim. */
|
|
36
|
+
reason?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Used percentage (`0`..`100`, may exceed) → used fraction. A negative count
|
|
40
|
+
* is not "0% used" — it is a vendor payload we cannot interpret, so it yields
|
|
41
|
+
* `undefined` and the caller drops the window instead of printing a fake bar.
|
|
42
|
+
* The upper clamp stays: over-100% still means exhausted.
|
|
43
|
+
*/
|
|
44
|
+
export declare function fractionFromUsed(usedPercent: number): number | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Remaining percentage (`0`..`100`) → used fraction. Remaining above 100% is
|
|
47
|
+
* equally uninterpretable and yields `undefined`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function fractionFromRemaining(remainingPercent: number): number | undefined;
|
|
50
|
+
/** Epoch seconds → epoch milliseconds. */
|
|
51
|
+
export declare function resetFromSeconds(seconds: number): number | undefined;
|
|
52
|
+
/** Epoch milliseconds → epoch milliseconds (validated). */
|
|
53
|
+
export declare function resetFromMs(ms: number): number | undefined;
|
|
54
|
+
/** ISO-8601 string → epoch milliseconds; an unparseable string is `undefined`. */
|
|
55
|
+
export declare function resetFromIso(iso: string): number | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Lenient reset-time normalizer: epoch seconds, epoch milliseconds or an ISO
|
|
58
|
+
* string, whichever alias the vendor returned.
|
|
59
|
+
*/
|
|
60
|
+
export declare function resetFrom(value: unknown): number | undefined;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quota-domain types and the pure unit normalizers every probe shares.
|
|
3
|
+
*
|
|
4
|
+
* Vendors disagree on nearly every unit: Claude reports *used* utilization
|
|
5
|
+
* and an ISO reset stamp, Codex reports used percent with epoch seconds or a
|
|
6
|
+
* relative delay under aliased keys. Normalizing here keeps the probes thin
|
|
7
|
+
* and keeps "used" vs "remaining" invertible in one tested place. Nothing in
|
|
8
|
+
* this module touches the network, the clock, the filesystem, or key
|
|
9
|
+
* selection state.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-keys-manager/quota/model
|
|
12
|
+
*/
|
|
13
|
+
function clampFraction(value) {
|
|
14
|
+
return Math.min(1, Math.max(0, value));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Used percentage (`0`..`100`, may exceed) → used fraction. A negative count
|
|
18
|
+
* is not "0% used" — it is a vendor payload we cannot interpret, so it yields
|
|
19
|
+
* `undefined` and the caller drops the window instead of printing a fake bar.
|
|
20
|
+
* The upper clamp stays: over-100% still means exhausted.
|
|
21
|
+
*/
|
|
22
|
+
export function fractionFromUsed(usedPercent) {
|
|
23
|
+
if (!Number.isFinite(usedPercent) || usedPercent < 0)
|
|
24
|
+
return undefined;
|
|
25
|
+
return clampFraction(usedPercent / 100);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Remaining percentage (`0`..`100`) → used fraction. Remaining above 100% is
|
|
29
|
+
* equally uninterpretable and yields `undefined`.
|
|
30
|
+
*/
|
|
31
|
+
export function fractionFromRemaining(remainingPercent) {
|
|
32
|
+
if (!Number.isFinite(remainingPercent) || remainingPercent < 0 || remainingPercent > 100)
|
|
33
|
+
return undefined;
|
|
34
|
+
return clampFraction(1 - remainingPercent / 100);
|
|
35
|
+
}
|
|
36
|
+
/** Epoch seconds → epoch milliseconds. */
|
|
37
|
+
export function resetFromSeconds(seconds) {
|
|
38
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined;
|
|
39
|
+
}
|
|
40
|
+
/** Epoch milliseconds → epoch milliseconds (validated). */
|
|
41
|
+
export function resetFromMs(ms) {
|
|
42
|
+
return Number.isFinite(ms) && ms > 0 ? ms : undefined;
|
|
43
|
+
}
|
|
44
|
+
/** ISO-8601 string → epoch milliseconds; an unparseable string is `undefined`. */
|
|
45
|
+
export function resetFromIso(iso) {
|
|
46
|
+
const parsed = Date.parse(iso);
|
|
47
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Lenient reset-time normalizer: epoch seconds, epoch milliseconds or an ISO
|
|
51
|
+
* string, whichever alias the vendor returned.
|
|
52
|
+
*/
|
|
53
|
+
export function resetFrom(value) {
|
|
54
|
+
if (typeof value === 'number') {
|
|
55
|
+
// Epoch milliseconds passed 1e12 in 2001; anything below that is seconds.
|
|
56
|
+
return Math.abs(value) < 1e12 ? resetFromSeconds(value) : resetFromMs(value);
|
|
57
|
+
}
|
|
58
|
+
if (typeof value === 'string' && value.length > 0)
|
|
59
|
+
return resetFromIso(value);
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=model.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/quota/model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AA+BH,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAA;AACxC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,WAAmB;IAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,WAAW,GAAG,CAAC;QAAE,OAAO,SAAS,CAAA;IACtE,OAAO,aAAa,CAAC,WAAW,GAAG,GAAG,CAAC,CAAA;AACzC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,gBAAwB;IAC5D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC,IAAI,gBAAgB,GAAG,CAAC,IAAI,gBAAgB,GAAG,GAAG;QAAE,OAAO,SAAS,CAAA;IAC1G,OAAO,aAAa,CAAC,CAAC,GAAG,gBAAgB,GAAG,GAAG,CAAC,CAAA;AAClD,CAAC;AAED,0CAA0C;AAC1C,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC9C,OAAO,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;AAC7E,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,WAAW,CAAC,EAAU;IACpC,OAAO,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;AACvD,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;AACrD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,0EAA0E;QAC1E,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;IAC9E,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAA;IAC7E,OAAO,SAAS,CAAA;AAClB,CAAC"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { QuotaFetch } from './fetch.js';
|
|
2
|
+
import type { QuotaSnapshot } from './model.js';
|
|
3
|
+
/** Everything a probe needs; the credential stays out of the cache. */
|
|
4
|
+
export interface QuotaProbeInput {
|
|
5
|
+
token: string;
|
|
6
|
+
accountId?: string;
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
/** Injected for tests; the platform `fetch` in production. */
|
|
9
|
+
fetch?: QuotaFetch;
|
|
10
|
+
}
|
|
11
|
+
/** One provider's usage read, normalized to a snapshot. Never throws. */
|
|
12
|
+
export type QuotaProbe = (input: QuotaProbeInput) => Promise<QuotaSnapshot>;
|
|
13
|
+
/** Claude OAuth plan usage: `five_hour` is the session, `seven_day` the week. */
|
|
14
|
+
export declare const claudeQuotaProbe: QuotaProbe;
|
|
15
|
+
/** Codex / ChatGPT plan usage: primary and secondary windows, classified by duration. */
|
|
16
|
+
export declare const codexQuotaProbe: QuotaProbe;
|
|
17
|
+
/**
|
|
18
|
+
* Z.AI / Zhipu GLM coding-plan quota. The key is sent verbatim, with no
|
|
19
|
+
* `Bearer` prefix, and `percentage` is USED percent. `unit` 3 = hours,
|
|
20
|
+
* 4 = days, 5 = months, 6 = weeks; `TIME_LIMIT` buckets only map when their
|
|
21
|
+
* unit says hours or weeks (the monthly MCP-call quota stays unmapped).
|
|
22
|
+
*/
|
|
23
|
+
export declare const zaiQuotaProbe: QuotaProbe;
|
|
24
|
+
/**
|
|
25
|
+
* Kimi Code quota: the aggregate `usage` object is the weekly window, each
|
|
26
|
+
* `limits[]` row is classified by its `window.duration` + `time_unit`.
|
|
27
|
+
* Numbers arrive as strings.
|
|
28
|
+
*/
|
|
29
|
+
export declare const kimiQuotaProbe: QuotaProbe;
|
|
30
|
+
/**
|
|
31
|
+
* MiniMax coding-plan quota. The vendor answers HTTP 200 even for a rejected
|
|
32
|
+
* credential, so `base_resp.status_code` is the real success signal. Plan-wide
|
|
33
|
+
* buckets repeat the same two windows, so the most-binding row wins.
|
|
34
|
+
*/
|
|
35
|
+
export declare const minimaxQuotaProbe: QuotaProbe;
|
|
36
|
+
/**
|
|
37
|
+
* OpenCode Go quota. `percent` is USED percent, `resetsAt` an ISO stamp, and
|
|
38
|
+
* `status: 'rate-limited'` outranks the percent. The monthly window anchors on
|
|
39
|
+
* the subscription anniversary, so it is deliberately not mapped to `week`.
|
|
40
|
+
*/
|
|
41
|
+
export declare const opencodeGoQuotaProbe: QuotaProbe;
|
|
42
|
+
/**
|
|
43
|
+
* Command Code plan windows. The CLI's account route reports a credit balance
|
|
44
|
+
* plus `windowLimits.{fiveHour,weekly}` of `{ used, cap, resetAt }`; a
|
|
45
|
+
* pay-as-you-go account carries only the balance, which has no window at all
|
|
46
|
+
* and therefore no usage the card can render — that case is `error`, never a
|
|
47
|
+
* fabricated 0%.
|
|
48
|
+
*
|
|
49
|
+
* shortcut: the org pool needs `/alpha/whoami` first to learn `orgId`; this
|
|
50
|
+
* probe reads the personal balance only and adds the org query when a managed
|
|
51
|
+
* org account must show its own pool.
|
|
52
|
+
*/
|
|
53
|
+
export declare const commandcodeQuotaProbe: QuotaProbe;
|
|
54
|
+
/**
|
|
55
|
+
* SuperGrok (xAI OAuth) weekly credits through the Grok CLI billing proxy.
|
|
56
|
+
* The payload is `{ config: { currentPeriod: { start, end, type } ,
|
|
57
|
+
* creditUsagePercent, isUnifiedBillingUser } }`; a fresh weekly period omits
|
|
58
|
+
* the percent, which means 0 % used while that period is still open.
|
|
59
|
+
*
|
|
60
|
+
* Only an explicit WEEK period maps: this UI has `session` and `week` windows,
|
|
61
|
+
* and a monthly included quota is neither. A unified-billing account needs a
|
|
62
|
+
* second (default) billing payload to say which counter gates requests — this
|
|
63
|
+
* probe reads the credits payload alone, so unified is `error` rather than a
|
|
64
|
+
* week that may not apply.
|
|
65
|
+
*/
|
|
66
|
+
export declare const xaiQuotaProbe: QuotaProbe;
|
|
67
|
+
/**
|
|
68
|
+
* ClinePass limits, read with the stored Cline API key exactly as Cline's own
|
|
69
|
+
* client reads them (magpie `internal/provider/cline_usage.go`): the endpoint
|
|
70
|
+
* answers a key as it answers an account. `limits[]` carries `type`
|
|
71
|
+
* (`five_hour` / `weekly` / `monthly`), `percentUsed` (USED percent) and an
|
|
72
|
+
* ISO `resetsAt`.
|
|
73
|
+
*
|
|
74
|
+
* The monthly limit has no window in this UI (only `session` and `week`), so
|
|
75
|
+
* it is dropped; an account whose only limit is monthly reads `error`. A 404
|
|
76
|
+
* is Cline's "no ClinePass on this account" and stays `absent`.
|
|
77
|
+
*
|
|
78
|
+
* shortcut: the credit balance needs `/users/me` and then
|
|
79
|
+
* `/users/{id}/balance` (two more calls) and is not a window; add it only if a
|
|
80
|
+
* card must show the remaining dollars.
|
|
81
|
+
*/
|
|
82
|
+
export declare const clineQuotaProbe: QuotaProbe;
|
|
83
|
+
/** The probe for a route id, or `undefined` when the provider exposes no usage API. */
|
|
84
|
+
export declare function quotaProbe(provider: string): QuotaProbe | undefined;
|
|
85
|
+
/**
|
|
86
|
+
* Probe one route id, degrading an unknown route to `absent` and a probe that
|
|
87
|
+
* somehow throws to `error`, so callers never handle an exception.
|
|
88
|
+
*/
|
|
89
|
+
export declare function resolveQuota(provider: string, input: QuotaProbeInput): Promise<QuotaSnapshot>;
|