dsh-coding-subscription-oauth 0.6.3 → 0.6.4

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.
Files changed (116) hide show
  1. package/CHANGELOG.md +258 -250
  2. package/CONTRIBUTING.md +129 -129
  3. package/INSTALL.md +256 -255
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +303 -303
  7. package/README.es.md +304 -304
  8. package/README.fr.md +304 -304
  9. package/README.ja.md +304 -304
  10. package/README.ko.md +304 -304
  11. package/README.md +320 -320
  12. package/README.pt-BR.md +304 -304
  13. package/README.ru.md +304 -304
  14. package/README.zh-CN.md +318 -318
  15. package/compatibility/dsh-bom.json +30 -30
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -212
  18. package/docs/02-architecture.md +138 -138
  19. package/docs/02-architecture.zh-CN.md +138 -138
  20. package/lib/bin.js +1333 -569
  21. package/lib/bin.js.map +4 -4
  22. package/lib/client.js +1 -1
  23. package/lib/client.js.map +2 -2
  24. package/lib/index.js +689 -25492
  25. package/lib/index.js.map +4 -4
  26. package/lib/invariant.js.map +1 -1
  27. package/media/en/settings_accounts.png +0 -0
  28. package/media/en/settings_capabilities.png +0 -0
  29. package/media/en/settings_gateway.png +0 -0
  30. package/media/settings_accounts.png +0 -0
  31. package/media/settings_capabilities.png +0 -0
  32. package/media/settings_gateway.png +0 -0
  33. package/media/settings_overview.png +0 -0
  34. package/media/zh-CN/settings_accounts.png +0 -0
  35. package/media/zh-CN/settings_capabilities.png +0 -0
  36. package/media/zh-CN/settings_gateway.png +0 -0
  37. package/package.json +223 -223
  38. package/patches/dsh-agy@0.1.2.patch +25 -25
  39. package/scripts/release.mjs +186 -186
  40. package/scripts/smoke-deployed-routes.mjs +146 -146
  41. package/scripts/verify-deployed-catalog.mjs +87 -87
  42. package/src/adapter.ts +348 -348
  43. package/src/alias-adapter.ts +147 -147
  44. package/src/auth-routes.ts +921 -921
  45. package/src/auth.ts +67 -67
  46. package/src/bin.ts +350 -350
  47. package/src/capability-routes.ts +279 -279
  48. package/src/capability-runtime.ts +314 -314
  49. package/src/capability-settings.ts +671 -671
  50. package/src/capability-tools.ts +685 -685
  51. package/src/catalog.ts +271 -271
  52. package/src/client/GrokBuildSettings.tsx +771 -771
  53. package/src/client/api.ts +88 -88
  54. package/src/client/components/AboutTab.tsx +30 -30
  55. package/src/client/components/AccountsTab.tsx +241 -241
  56. package/src/client/components/Badge.tsx +33 -33
  57. package/src/client/components/CapabilitiesTab.tsx +265 -265
  58. package/src/client/components/CliPullPreview.tsx +116 -116
  59. package/src/client/components/CopyButton.tsx +57 -57
  60. package/src/client/components/GatewayTab.tsx +469 -469
  61. package/src/client/components/NoticeBanner.tsx +46 -46
  62. package/src/client/components/ProgressBar.tsx +53 -53
  63. package/src/client/components/ProviderCard.tsx +606 -606
  64. package/src/client/components/SettingsTabs.tsx +75 -75
  65. package/src/client/components/ToggleSwitch.tsx +71 -71
  66. package/src/client/constants.ts +230 -230
  67. package/src/client/display.ts +61 -61
  68. package/src/client/dshClientAdapter.ts +127 -127
  69. package/src/client/gatewaySnippets.ts +37 -37
  70. package/src/client/index.tsx +156 -156
  71. package/src/client/locales.ts +540 -540
  72. package/src/client/microStyles.ts +52 -52
  73. package/src/client/parsers.ts +398 -398
  74. package/src/client/styles.ts +325 -325
  75. package/src/client/types.ts +199 -199
  76. package/src/codex-http.ts +447 -447
  77. package/src/codex-images.ts +503 -503
  78. package/src/codex-model-capabilities.ts +320 -320
  79. package/src/codex-search.ts +245 -245
  80. package/src/codex-usage.ts +263 -263
  81. package/src/compatibility.ts +55 -55
  82. package/src/dsh-host-adapter.ts +173 -173
  83. package/src/gateway-anthropic-messages.ts +84 -84
  84. package/src/gateway-auth.ts +102 -102
  85. package/src/gateway-backend.ts +274 -274
  86. package/src/gateway-body.ts +49 -49
  87. package/src/gateway-config.ts +76 -76
  88. package/src/gateway-http.ts +104 -104
  89. package/src/gateway-openai-chat.ts +124 -124
  90. package/src/gateway-openai-responses.ts +53 -53
  91. package/src/gateway-parse.ts +224 -224
  92. package/src/gateway-protocol.ts +52 -52
  93. package/src/gateway-routes.ts +158 -158
  94. package/src/gateway.ts +258 -258
  95. package/src/grok-errors.ts +24 -24
  96. package/src/grok-imagine.ts +1627 -1627
  97. package/src/grok-import.ts +151 -151
  98. package/src/http-json.ts +82 -82
  99. package/src/ids.ts +59 -59
  100. package/src/imagine-routes.ts +463 -463
  101. package/src/index.ts +735 -735
  102. package/src/invariant.ts +17 -17
  103. package/src/kimi-errors.ts +26 -26
  104. package/src/media-store.ts +927 -927
  105. package/src/oauth-import-routes.ts +324 -324
  106. package/src/oauth-providers.ts +152 -152
  107. package/src/oauth-session.ts +183 -183
  108. package/src/oauth-sources.ts +1104 -1104
  109. package/src/oauth.ts +620 -620
  110. package/src/provider.ts +128 -128
  111. package/src/proxy.ts +11 -11
  112. package/src/redact.ts +72 -72
  113. package/src/session.ts +218 -218
  114. package/src/store.ts +217 -217
  115. package/src/web-origin.ts +296 -296
  116. package/src/web-routes.ts +38 -38
@@ -1,263 +1,263 @@
1
- /**
2
- * Optional ChatGPT Codex quota reader (`GET /backend-api/wham/usage`).
3
- * Normalizes unknown/malformed optional fields instead of failing the card.
4
- *
5
- * Cache semantics:
6
- * - A successful `read()` stores the projection until `ttlMs` elapses.
7
- * - Concurrent non-force `read()` calls share one in-flight GET.
8
- * - `read({ force: true })` always issues a new GET and never joins an
9
- * existing in-flight read (forced or not). A later completion of the
10
- * abandoned in-flight GET cannot overwrite the forced result.
11
- * - `clear()` drops the stored projection and detaches any in-flight GET so
12
- * its later completion cannot repopulate the cache.
13
- *
14
- * @module dsh-coding-subscription-oauth/codex-usage
15
- */
16
-
17
- import { LlmError } from "@deepseek-ai/dsh-llm";
18
- import {
19
- type CodexAuthSession,
20
- type CodexFetch,
21
- type CodexHttpClient,
22
- createCodexHttpClient,
23
- isRecord,
24
- optionalNonEmptyString,
25
- } from "./codex-http.ts";
26
-
27
- /** Official ChatGPT rate-limit usage endpoint used by the Codex client. */
28
- export const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
29
-
30
- export interface CodexRateLimitWindow {
31
- readonly usedPercent: number;
32
- readonly remainingPercent: number;
33
- readonly windowSeconds: number;
34
- readonly resetsAt?: number;
35
- }
36
-
37
- export interface CodexRateLimit {
38
- readonly id: string;
39
- readonly name?: string;
40
- readonly windows: readonly CodexRateLimitWindow[];
41
- }
42
-
43
- export interface CodexCredits {
44
- readonly unlimited: boolean;
45
- readonly balance?: string;
46
- }
47
-
48
- export interface CodexIndividualLimit {
49
- readonly limit: string;
50
- readonly used: string;
51
- readonly remaining?: string;
52
- readonly remainingPercent: number;
53
- readonly resetsAt?: number;
54
- }
55
-
56
- export interface CodexUsage {
57
- readonly rateLimits: readonly CodexRateLimit[];
58
- readonly credits?: CodexCredits;
59
- readonly individualLimit?: CodexIndividualLimit;
60
- readonly spendControlReached?: boolean;
61
- readonly resetCredits?: { readonly availableCount: number };
62
- readonly fetchedAt: number;
63
- }
64
-
65
- export interface CodexUsageReaderOptions {
66
- readonly auth: CodexAuthSession;
67
- readonly http?: CodexHttpClient;
68
- readonly fetchImpl?: CodexFetch;
69
- readonly originator?: string;
70
- readonly userAgent?: string;
71
- readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
72
- readonly now?: () => number;
73
- readonly ttlMs?: number;
74
- }
75
-
76
- export interface CodexUsageReader {
77
- read(options?: { force?: boolean; signal?: AbortSignal }): Promise<CodexUsage>;
78
- clear(): void;
79
- }
80
-
81
- const DEFAULT_TTL_MS = 60_000;
82
-
83
- function finitePercent(value: unknown): number | undefined {
84
- return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100 ? value : undefined;
85
- }
86
-
87
- function positiveInt(value: unknown): number | undefined {
88
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
89
- }
90
-
91
- function epochSeconds(value: unknown): number | undefined {
92
- if (value === undefined || value === null || value === 0) return undefined;
93
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
94
- }
95
-
96
- function decimalAmount(value: unknown): string | undefined {
97
- return typeof value === "string" && value.length > 0 && value.length <= 64 && /^-?\d+(?:\.\d+)?$/u.test(value)
98
- ? value
99
- : undefined;
100
- }
101
-
102
- function parseWindow(value: unknown): CodexRateLimitWindow | undefined {
103
- if (!isRecord(value)) return undefined;
104
- const usedPercent = finitePercent(value["used_percent"]);
105
- const windowSeconds = positiveInt(value["limit_window_seconds"]);
106
- if (usedPercent === undefined || windowSeconds === undefined) return undefined;
107
- const resetsAt = epochSeconds(value["reset_at"]);
108
- return {
109
- usedPercent,
110
- remainingPercent: 100 - usedPercent,
111
- windowSeconds,
112
- ...(resetsAt === undefined ? {} : { resetsAt }),
113
- };
114
- }
115
-
116
- function parseLimit(id: string, name: string | undefined, value: unknown): CodexRateLimit | undefined {
117
- if (!isRecord(value)) return undefined;
118
- const windows = [parseWindow(value["primary_window"]), parseWindow(value["secondary_window"])].filter(
119
- (window): window is CodexRateLimitWindow => window !== undefined,
120
- );
121
- if (windows.length === 0) return undefined;
122
- return { id, ...(name === undefined ? {} : { name }), windows };
123
- }
124
-
125
- function parseCredits(value: unknown): CodexCredits | undefined {
126
- if (!isRecord(value) || value["has_credits"] !== true || typeof value["unlimited"] !== "boolean") return undefined;
127
- const balance = decimalAmount(value["balance"]);
128
- return {
129
- unlimited: value["unlimited"],
130
- ...(balance === undefined ? {} : { balance }),
131
- };
132
- }
133
-
134
- function parseIndividualLimit(value: unknown): CodexIndividualLimit | undefined {
135
- if (!isRecord(value)) return undefined;
136
- const individual = value["individual_limit"];
137
- if (!isRecord(individual)) return undefined;
138
- const remainingPercent = finitePercent(individual["remaining_percent"]);
139
- const limit = decimalAmount(individual["limit"]);
140
- const used = decimalAmount(individual["used"]);
141
- if (remainingPercent === undefined || limit === undefined || used === undefined) return undefined;
142
- const remaining = decimalAmount(individual["remaining"]);
143
- const resetsAt = epochSeconds(individual["reset_at"]);
144
- return {
145
- limit,
146
- used,
147
- remainingPercent,
148
- ...(remaining === undefined ? {} : { remaining }),
149
- ...(resetsAt === undefined ? {} : { resetsAt }),
150
- };
151
- }
152
-
153
- function copyUsage(usage: CodexUsage): CodexUsage {
154
- return { ...usage, rateLimits: [...usage.rateLimits] };
155
- }
156
-
157
- /**
158
- * Reduce an opaque `wham/usage` payload to a secret-free quota projection.
159
- * Unknown extra fields are ignored; malformed optional buckets are skipped.
160
- */
161
- export function normalizeCodexUsage(value: unknown, fetchedAt = Date.now()): CodexUsage {
162
- if (!isRecord(value)) {
163
- throw new LlmError("Codex returned a malformed usage response", "SERVER");
164
- }
165
- const rateLimits: CodexRateLimit[] = [];
166
- const seen = new Set<string>();
167
- const add = (limit: CodexRateLimit | undefined): void => {
168
- if (limit === undefined || seen.has(limit.id)) return;
169
- seen.add(limit.id);
170
- rateLimits.push(limit);
171
- };
172
- add(parseLimit("codex", "Codex", value["rate_limit"]));
173
- const additional = value["additional_rate_limits"];
174
- if (Array.isArray(additional)) {
175
- for (const entry of additional) {
176
- if (!isRecord(entry)) continue;
177
- const id = optionalNonEmptyString(entry["metered_feature"]);
178
- if (id === undefined) continue;
179
- const name = optionalNonEmptyString(entry["limit_name"]);
180
- add(parseLimit(id, name, entry["rate_limit"]));
181
- }
182
- }
183
- add(parseLimit("code_review", "Code review", value["code_review_rate_limit"]));
184
- const credits = parseCredits(value["credits"]);
185
- const individualLimit = parseIndividualLimit(value["spend_control"]);
186
- const spendControlReached =
187
- isRecord(value["spend_control"]) && typeof value["spend_control"]["reached"] === "boolean"
188
- ? value["spend_control"]["reached"]
189
- : undefined;
190
- const resetRaw = value["rate_limit_reset_credits"];
191
- const resetCount = isRecord(resetRaw) ? resetRaw["available_count"] : undefined;
192
- const resetCredits =
193
- typeof resetCount === "number" && Number.isSafeInteger(resetCount) && resetCount >= 0
194
- ? { availableCount: resetCount }
195
- : undefined;
196
- return {
197
- rateLimits,
198
- fetchedAt,
199
- ...(credits === undefined ? {} : { credits }),
200
- ...(individualLimit === undefined ? {} : { individualLimit }),
201
- ...(spendControlReached === undefined ? {} : { spendControlReached }),
202
- ...(resetCredits === undefined ? {} : { resetCredits }),
203
- };
204
- }
205
-
206
- /**
207
- * Cached, injectable usage reader. Failures do not invent quota numbers.
208
- *
209
- * See the module doc for `force` / `clear` cache semantics.
210
- */
211
- export function createCodexUsageReader(options: CodexUsageReaderOptions): CodexUsageReader {
212
- const http =
213
- options.http ??
214
- createCodexHttpClient({
215
- auth: options.auth,
216
- ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
217
- ...(options.originator === undefined ? {} : { originator: options.originator }),
218
- ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
219
- ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
220
- ...(options.now === undefined ? {} : { now: options.now }),
221
- });
222
- const now = options.now ?? Date.now;
223
- const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
224
- let cached: CodexUsage | undefined;
225
- let inFlight: Promise<CodexUsage> | undefined;
226
- let epoch = 0;
227
-
228
- const load = async (signal?: AbortSignal): Promise<CodexUsage> => {
229
- const payload = await http.requestJson({
230
- url: CODEX_USAGE_URL,
231
- method: "GET",
232
- headers: { "cache-control": "no-store" },
233
- ...(signal === undefined ? {} : { signal }),
234
- });
235
- return normalizeCodexUsage(payload, now());
236
- };
237
-
238
- return {
239
- read({ force = false, signal } = {}) {
240
- if (!force && cached !== undefined && now() - cached.fetchedAt < ttlMs) {
241
- return Promise.resolve(copyUsage(cached));
242
- }
243
- if (!force && inFlight !== undefined) return inFlight;
244
- if (force) epoch += 1;
245
- const started = epoch;
246
- const current = load(signal)
247
- .then((value) => {
248
- if (started === epoch) cached = value;
249
- return value;
250
- })
251
- .finally(() => {
252
- if (inFlight === current) inFlight = undefined;
253
- });
254
- inFlight = current;
255
- return current;
256
- },
257
- clear() {
258
- epoch += 1;
259
- cached = undefined;
260
- inFlight = undefined;
261
- },
262
- };
263
- }
1
+ /**
2
+ * Optional ChatGPT Codex quota reader (`GET /backend-api/wham/usage`).
3
+ * Normalizes unknown/malformed optional fields instead of failing the card.
4
+ *
5
+ * Cache semantics:
6
+ * - A successful `read()` stores the projection until `ttlMs` elapses.
7
+ * - Concurrent non-force `read()` calls share one in-flight GET.
8
+ * - `read({ force: true })` always issues a new GET and never joins an
9
+ * existing in-flight read (forced or not). A later completion of the
10
+ * abandoned in-flight GET cannot overwrite the forced result.
11
+ * - `clear()` drops the stored projection and detaches any in-flight GET so
12
+ * its later completion cannot repopulate the cache.
13
+ *
14
+ * @module dsh-coding-subscription-oauth/codex-usage
15
+ */
16
+
17
+ import { LlmError } from "@deepseek-ai/dsh-llm";
18
+ import {
19
+ type CodexAuthSession,
20
+ type CodexFetch,
21
+ type CodexHttpClient,
22
+ createCodexHttpClient,
23
+ isRecord,
24
+ optionalNonEmptyString,
25
+ } from "./codex-http.ts";
26
+
27
+ /** Official ChatGPT rate-limit usage endpoint used by the Codex client. */
28
+ export const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
29
+
30
+ export interface CodexRateLimitWindow {
31
+ readonly usedPercent: number;
32
+ readonly remainingPercent: number;
33
+ readonly windowSeconds: number;
34
+ readonly resetsAt?: number;
35
+ }
36
+
37
+ export interface CodexRateLimit {
38
+ readonly id: string;
39
+ readonly name?: string;
40
+ readonly windows: readonly CodexRateLimitWindow[];
41
+ }
42
+
43
+ export interface CodexCredits {
44
+ readonly unlimited: boolean;
45
+ readonly balance?: string;
46
+ }
47
+
48
+ export interface CodexIndividualLimit {
49
+ readonly limit: string;
50
+ readonly used: string;
51
+ readonly remaining?: string;
52
+ readonly remainingPercent: number;
53
+ readonly resetsAt?: number;
54
+ }
55
+
56
+ export interface CodexUsage {
57
+ readonly rateLimits: readonly CodexRateLimit[];
58
+ readonly credits?: CodexCredits;
59
+ readonly individualLimit?: CodexIndividualLimit;
60
+ readonly spendControlReached?: boolean;
61
+ readonly resetCredits?: { readonly availableCount: number };
62
+ readonly fetchedAt: number;
63
+ }
64
+
65
+ export interface CodexUsageReaderOptions {
66
+ readonly auth: CodexAuthSession;
67
+ readonly http?: CodexHttpClient;
68
+ readonly fetchImpl?: CodexFetch;
69
+ readonly originator?: string;
70
+ readonly userAgent?: string;
71
+ readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
72
+ readonly now?: () => number;
73
+ readonly ttlMs?: number;
74
+ }
75
+
76
+ export interface CodexUsageReader {
77
+ read(options?: { force?: boolean; signal?: AbortSignal }): Promise<CodexUsage>;
78
+ clear(): void;
79
+ }
80
+
81
+ const DEFAULT_TTL_MS = 60_000;
82
+
83
+ function finitePercent(value: unknown): number | undefined {
84
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100 ? value : undefined;
85
+ }
86
+
87
+ function positiveInt(value: unknown): number | undefined {
88
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
89
+ }
90
+
91
+ function epochSeconds(value: unknown): number | undefined {
92
+ if (value === undefined || value === null || value === 0) return undefined;
93
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
94
+ }
95
+
96
+ function decimalAmount(value: unknown): string | undefined {
97
+ return typeof value === "string" && value.length > 0 && value.length <= 64 && /^-?\d+(?:\.\d+)?$/u.test(value)
98
+ ? value
99
+ : undefined;
100
+ }
101
+
102
+ function parseWindow(value: unknown): CodexRateLimitWindow | undefined {
103
+ if (!isRecord(value)) return undefined;
104
+ const usedPercent = finitePercent(value["used_percent"]);
105
+ const windowSeconds = positiveInt(value["limit_window_seconds"]);
106
+ if (usedPercent === undefined || windowSeconds === undefined) return undefined;
107
+ const resetsAt = epochSeconds(value["reset_at"]);
108
+ return {
109
+ usedPercent,
110
+ remainingPercent: 100 - usedPercent,
111
+ windowSeconds,
112
+ ...(resetsAt === undefined ? {} : { resetsAt }),
113
+ };
114
+ }
115
+
116
+ function parseLimit(id: string, name: string | undefined, value: unknown): CodexRateLimit | undefined {
117
+ if (!isRecord(value)) return undefined;
118
+ const windows = [parseWindow(value["primary_window"]), parseWindow(value["secondary_window"])].filter(
119
+ (window): window is CodexRateLimitWindow => window !== undefined,
120
+ );
121
+ if (windows.length === 0) return undefined;
122
+ return { id, ...(name === undefined ? {} : { name }), windows };
123
+ }
124
+
125
+ function parseCredits(value: unknown): CodexCredits | undefined {
126
+ if (!isRecord(value) || value["has_credits"] !== true || typeof value["unlimited"] !== "boolean") return undefined;
127
+ const balance = decimalAmount(value["balance"]);
128
+ return {
129
+ unlimited: value["unlimited"],
130
+ ...(balance === undefined ? {} : { balance }),
131
+ };
132
+ }
133
+
134
+ function parseIndividualLimit(value: unknown): CodexIndividualLimit | undefined {
135
+ if (!isRecord(value)) return undefined;
136
+ const individual = value["individual_limit"];
137
+ if (!isRecord(individual)) return undefined;
138
+ const remainingPercent = finitePercent(individual["remaining_percent"]);
139
+ const limit = decimalAmount(individual["limit"]);
140
+ const used = decimalAmount(individual["used"]);
141
+ if (remainingPercent === undefined || limit === undefined || used === undefined) return undefined;
142
+ const remaining = decimalAmount(individual["remaining"]);
143
+ const resetsAt = epochSeconds(individual["reset_at"]);
144
+ return {
145
+ limit,
146
+ used,
147
+ remainingPercent,
148
+ ...(remaining === undefined ? {} : { remaining }),
149
+ ...(resetsAt === undefined ? {} : { resetsAt }),
150
+ };
151
+ }
152
+
153
+ function copyUsage(usage: CodexUsage): CodexUsage {
154
+ return { ...usage, rateLimits: [...usage.rateLimits] };
155
+ }
156
+
157
+ /**
158
+ * Reduce an opaque `wham/usage` payload to a secret-free quota projection.
159
+ * Unknown extra fields are ignored; malformed optional buckets are skipped.
160
+ */
161
+ export function normalizeCodexUsage(value: unknown, fetchedAt = Date.now()): CodexUsage {
162
+ if (!isRecord(value)) {
163
+ throw new LlmError("Codex returned a malformed usage response", "SERVER");
164
+ }
165
+ const rateLimits: CodexRateLimit[] = [];
166
+ const seen = new Set<string>();
167
+ const add = (limit: CodexRateLimit | undefined): void => {
168
+ if (limit === undefined || seen.has(limit.id)) return;
169
+ seen.add(limit.id);
170
+ rateLimits.push(limit);
171
+ };
172
+ add(parseLimit("codex", "Codex", value["rate_limit"]));
173
+ const additional = value["additional_rate_limits"];
174
+ if (Array.isArray(additional)) {
175
+ for (const entry of additional) {
176
+ if (!isRecord(entry)) continue;
177
+ const id = optionalNonEmptyString(entry["metered_feature"]);
178
+ if (id === undefined) continue;
179
+ const name = optionalNonEmptyString(entry["limit_name"]);
180
+ add(parseLimit(id, name, entry["rate_limit"]));
181
+ }
182
+ }
183
+ add(parseLimit("code_review", "Code review", value["code_review_rate_limit"]));
184
+ const credits = parseCredits(value["credits"]);
185
+ const individualLimit = parseIndividualLimit(value["spend_control"]);
186
+ const spendControlReached =
187
+ isRecord(value["spend_control"]) && typeof value["spend_control"]["reached"] === "boolean"
188
+ ? value["spend_control"]["reached"]
189
+ : undefined;
190
+ const resetRaw = value["rate_limit_reset_credits"];
191
+ const resetCount = isRecord(resetRaw) ? resetRaw["available_count"] : undefined;
192
+ const resetCredits =
193
+ typeof resetCount === "number" && Number.isSafeInteger(resetCount) && resetCount >= 0
194
+ ? { availableCount: resetCount }
195
+ : undefined;
196
+ return {
197
+ rateLimits,
198
+ fetchedAt,
199
+ ...(credits === undefined ? {} : { credits }),
200
+ ...(individualLimit === undefined ? {} : { individualLimit }),
201
+ ...(spendControlReached === undefined ? {} : { spendControlReached }),
202
+ ...(resetCredits === undefined ? {} : { resetCredits }),
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Cached, injectable usage reader. Failures do not invent quota numbers.
208
+ *
209
+ * See the module doc for `force` / `clear` cache semantics.
210
+ */
211
+ export function createCodexUsageReader(options: CodexUsageReaderOptions): CodexUsageReader {
212
+ const http =
213
+ options.http ??
214
+ createCodexHttpClient({
215
+ auth: options.auth,
216
+ ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
217
+ ...(options.originator === undefined ? {} : { originator: options.originator }),
218
+ ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
219
+ ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
220
+ ...(options.now === undefined ? {} : { now: options.now }),
221
+ });
222
+ const now = options.now ?? Date.now;
223
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
224
+ let cached: CodexUsage | undefined;
225
+ let inFlight: Promise<CodexUsage> | undefined;
226
+ let epoch = 0;
227
+
228
+ const load = async (signal?: AbortSignal): Promise<CodexUsage> => {
229
+ const payload = await http.requestJson({
230
+ url: CODEX_USAGE_URL,
231
+ method: "GET",
232
+ headers: { "cache-control": "no-store" },
233
+ ...(signal === undefined ? {} : { signal }),
234
+ });
235
+ return normalizeCodexUsage(payload, now());
236
+ };
237
+
238
+ return {
239
+ read({ force = false, signal } = {}) {
240
+ if (!force && cached !== undefined && now() - cached.fetchedAt < ttlMs) {
241
+ return Promise.resolve(copyUsage(cached));
242
+ }
243
+ if (!force && inFlight !== undefined) return inFlight;
244
+ if (force) epoch += 1;
245
+ const started = epoch;
246
+ const current = load(signal)
247
+ .then((value) => {
248
+ if (started === epoch) cached = value;
249
+ return value;
250
+ })
251
+ .finally(() => {
252
+ if (inFlight === current) inFlight = undefined;
253
+ });
254
+ inFlight = current;
255
+ return current;
256
+ },
257
+ clear() {
258
+ epoch += 1;
259
+ cached = undefined;
260
+ inFlight = undefined;
261
+ },
262
+ };
263
+ }
@@ -1,55 +1,55 @@
1
- /** Stable compatibility contracts for standalone and future co-installation. */
2
-
3
- import type { DshHostCapability, OwnerAccessMode } from "dsh-coding-oauth-core";
4
-
5
- export interface DshCompatibilityDiagnostic {
6
- readonly id: string;
7
- readonly component: "host" | "client" | "owner-request" | "runtime";
8
- readonly level: "info" | "warning" | "error";
9
- readonly message: string;
10
- readonly expected?: string;
11
- readonly actual?: string;
12
- }
13
-
14
- export interface CodingOAuthParticipantDiagnosticSource {
15
- readonly participantId: "coding-subscription-oauth";
16
- diagnostics(): readonly DshCompatibilityDiagnostic[];
17
- }
18
-
19
- export interface DshCompatibility {
20
- readonly coreAbi: string;
21
- readonly dshVersion: string | null;
22
- readonly status: "healthy" | "degraded" | "incompatible";
23
- readonly uiOwner: "hub" | "standalone" | null;
24
- readonly accessMode: OwnerAccessMode;
25
- readonly capabilities: Readonly<Record<string, DshHostCapability>>;
26
- readonly diagnostics: readonly string[];
27
- }
28
-
29
- export const DSH_EXACT_BOM = Object.freeze({
30
- "@deepseek-ai/cordis": "4.0.1",
31
- "@deepseek-ai/dsh-atomic-write": "0.1.1-rc.2",
32
- "@deepseek-ai/dsh-attachment": "0.1.1-rc.2",
33
- "@deepseek-ai/dsh-client-locale": "0.1.1-rc.2",
34
- "@deepseek-ai/dsh-client-runtime": "0.1.1-rc.2",
35
- "@deepseek-ai/dsh-client-ui-settings": "0.1.1-rc.2",
36
- "@deepseek-ai/dsh-client-ui-slots": "0.1.1-rc.2",
37
- "@deepseek-ai/dsh-client-web": "0.1.1-rc.2",
38
- "@deepseek-ai/dsh-credentials": "0.1.1-rc.2",
39
- "@deepseek-ai/dsh-home-paths": "0.1.1-rc.2",
40
- "@deepseek-ai/dsh-host-webserver": "0.1.1-rc.2",
41
- "@deepseek-ai/dsh-invariants": "0.1.1-rc.2",
42
- "@deepseek-ai/dsh-llm": "0.1.1-rc.2",
43
- "@deepseek-ai/dsh-llm-pi-ai": "0.1.1-rc.2",
44
- "@deepseek-ai/dsh-tools": "0.1.1-rc.2",
45
- "@deepseek-ai/schemastery": "3.18.1",
46
- "@earendil-works/pi-ai": "0.84.2",
47
- react: "18.3.1",
48
- "react-dom": "18.3.1",
49
- } as const);
50
-
51
- export function incompatibleDiagnostics(
52
- diagnostics: readonly DshCompatibilityDiagnostic[],
53
- ): DshCompatibilityDiagnostic[] {
54
- return diagnostics.filter((diagnostic) => diagnostic.level === "error");
55
- }
1
+ /** Stable compatibility contracts for standalone and future co-installation. */
2
+
3
+ import type { DshHostCapability, OwnerAccessMode } from "dsh-coding-oauth-core";
4
+
5
+ export interface DshCompatibilityDiagnostic {
6
+ readonly id: string;
7
+ readonly component: "host" | "client" | "owner-request" | "runtime";
8
+ readonly level: "info" | "warning" | "error";
9
+ readonly message: string;
10
+ readonly expected?: string;
11
+ readonly actual?: string;
12
+ }
13
+
14
+ export interface CodingOAuthParticipantDiagnosticSource {
15
+ readonly participantId: "coding-subscription-oauth";
16
+ diagnostics(): readonly DshCompatibilityDiagnostic[];
17
+ }
18
+
19
+ export interface DshCompatibility {
20
+ readonly coreAbi: string;
21
+ readonly dshVersion: string | null;
22
+ readonly status: "healthy" | "degraded" | "incompatible";
23
+ readonly uiOwner: "hub" | "standalone" | null;
24
+ readonly accessMode: OwnerAccessMode;
25
+ readonly capabilities: Readonly<Record<string, DshHostCapability>>;
26
+ readonly diagnostics: readonly string[];
27
+ }
28
+
29
+ export const DSH_EXACT_BOM = Object.freeze({
30
+ "@deepseek-ai/cordis": "4.0.1",
31
+ "@deepseek-ai/dsh-atomic-write": "0.1.1-rc.2",
32
+ "@deepseek-ai/dsh-attachment": "0.1.1-rc.2",
33
+ "@deepseek-ai/dsh-client-locale": "0.1.1-rc.2",
34
+ "@deepseek-ai/dsh-client-runtime": "0.1.1-rc.2",
35
+ "@deepseek-ai/dsh-client-ui-settings": "0.1.1-rc.2",
36
+ "@deepseek-ai/dsh-client-ui-slots": "0.1.1-rc.2",
37
+ "@deepseek-ai/dsh-client-web": "0.1.1-rc.2",
38
+ "@deepseek-ai/dsh-credentials": "0.1.1-rc.2",
39
+ "@deepseek-ai/dsh-home-paths": "0.1.1-rc.2",
40
+ "@deepseek-ai/dsh-host-webserver": "0.1.1-rc.2",
41
+ "@deepseek-ai/dsh-invariants": "0.1.1-rc.2",
42
+ "@deepseek-ai/dsh-llm": "0.1.1-rc.2",
43
+ "@deepseek-ai/dsh-llm-pi-ai": "0.1.1-rc.2",
44
+ "@deepseek-ai/dsh-tools": "0.1.1-rc.2",
45
+ "@deepseek-ai/schemastery": "3.18.1",
46
+ "@earendil-works/pi-ai": "0.84.2",
47
+ react: "18.3.1",
48
+ "react-dom": "18.3.1",
49
+ } as const);
50
+
51
+ export function incompatibleDiagnostics(
52
+ diagnostics: readonly DshCompatibilityDiagnostic[],
53
+ ): DshCompatibilityDiagnostic[] {
54
+ return diagnostics.filter((diagnostic) => diagnostic.level === "error");
55
+ }