dsh-coding-subscription-oauth 0.6.2 → 0.6.3

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 (121) hide show
  1. package/CHANGELOG.md +222 -206
  2. package/CONTRIBUTING.md +129 -120
  3. package/INSTALL.md +218 -218
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +289 -289
  7. package/README.es.md +290 -290
  8. package/README.fr.md +290 -290
  9. package/README.ja.md +290 -290
  10. package/README.ko.md +290 -290
  11. package/README.md +304 -304
  12. package/README.pt-BR.md +290 -290
  13. package/README.ru.md +290 -290
  14. package/README.zh-CN.md +302 -302
  15. package/compatibility/dsh-bom.json +0 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -195
  18. package/docs/02-architecture.md +130 -130
  19. package/docs/02-architecture.zh-CN.md +130 -130
  20. package/lib/bin.js.map +1 -1
  21. package/lib/capability-settings.d.ts +8 -2
  22. package/lib/capability-settings.d.ts.map +1 -1
  23. package/lib/capability-tools.d.ts +7 -2
  24. package/lib/capability-tools.d.ts.map +1 -1
  25. package/lib/client.js +3 -3
  26. package/lib/client.js.map +2 -2
  27. package/lib/codex-images.d.ts +8 -0
  28. package/lib/codex-images.d.ts.map +1 -1
  29. package/lib/index.js +32 -7
  30. package/lib/index.js.map +2 -2
  31. package/lib/invariant.js.map +1 -1
  32. package/media/en/settings_accounts.png +0 -0
  33. package/media/en/settings_capabilities.png +0 -0
  34. package/media/en/settings_gateway.png +0 -0
  35. package/media/settings_accounts.png +0 -0
  36. package/media/settings_capabilities.png +0 -0
  37. package/media/settings_gateway.png +0 -0
  38. package/media/settings_overview.png +0 -0
  39. package/media/zh-CN/settings_accounts.png +0 -0
  40. package/media/zh-CN/settings_capabilities.png +0 -0
  41. package/media/zh-CN/settings_gateway.png +0 -0
  42. package/package.json +148 -148
  43. package/patches/dsh-agy@0.1.2.patch +25 -25
  44. package/scripts/release.mjs +186 -186
  45. package/scripts/smoke-deployed-routes.mjs +146 -146
  46. package/scripts/verify-deployed-catalog.mjs +87 -87
  47. package/src/adapter.ts +273 -273
  48. package/src/alias-adapter.ts +130 -130
  49. package/src/auth-routes.ts +921 -921
  50. package/src/auth.ts +67 -67
  51. package/src/bin.ts +350 -350
  52. package/src/capability-routes.ts +279 -279
  53. package/src/capability-runtime.ts +314 -313
  54. package/src/capability-settings.ts +671 -658
  55. package/src/capability-tools.ts +685 -666
  56. package/src/catalog.ts +271 -271
  57. package/src/client/GrokBuildSettings.tsx +771 -770
  58. package/src/client/api.ts +88 -88
  59. package/src/client/components/AboutTab.tsx +30 -30
  60. package/src/client/components/AccountsTab.tsx +241 -241
  61. package/src/client/components/Badge.tsx +33 -33
  62. package/src/client/components/CapabilitiesTab.tsx +265 -265
  63. package/src/client/components/CliPullPreview.tsx +116 -116
  64. package/src/client/components/CopyButton.tsx +57 -57
  65. package/src/client/components/GatewayTab.tsx +469 -469
  66. package/src/client/components/NoticeBanner.tsx +46 -46
  67. package/src/client/components/ProgressBar.tsx +53 -53
  68. package/src/client/components/ProviderCard.tsx +606 -606
  69. package/src/client/components/SettingsTabs.tsx +75 -75
  70. package/src/client/components/ToggleSwitch.tsx +71 -71
  71. package/src/client/constants.ts +230 -224
  72. package/src/client/display.ts +61 -61
  73. package/src/client/dshClientAdapter.ts +127 -127
  74. package/src/client/gatewaySnippets.ts +37 -37
  75. package/src/client/index.tsx +156 -156
  76. package/src/client/locales.ts +540 -535
  77. package/src/client/microStyles.ts +52 -52
  78. package/src/client/parsers.ts +398 -396
  79. package/src/client/styles.ts +325 -325
  80. package/src/client/types.ts +199 -197
  81. package/src/codex-http.ts +447 -447
  82. package/src/codex-images.ts +503 -485
  83. package/src/codex-model-capabilities.ts +320 -320
  84. package/src/codex-search.ts +245 -245
  85. package/src/codex-usage.ts +263 -263
  86. package/src/compatibility.ts +41 -41
  87. package/src/dsh-host-adapter.ts +173 -173
  88. package/src/gateway-anthropic-messages.ts +84 -84
  89. package/src/gateway-auth.ts +102 -102
  90. package/src/gateway-backend.ts +274 -274
  91. package/src/gateway-body.ts +49 -49
  92. package/src/gateway-config.ts +76 -76
  93. package/src/gateway-http.ts +104 -104
  94. package/src/gateway-openai-chat.ts +124 -124
  95. package/src/gateway-openai-responses.ts +53 -53
  96. package/src/gateway-parse.ts +224 -224
  97. package/src/gateway-protocol.ts +52 -52
  98. package/src/gateway-routes.ts +158 -158
  99. package/src/gateway.ts +258 -258
  100. package/src/grok-errors.ts +24 -24
  101. package/src/grok-imagine.ts +1627 -1627
  102. package/src/grok-import.ts +151 -151
  103. package/src/http-json.ts +82 -82
  104. package/src/ids.ts +59 -59
  105. package/src/imagine-routes.ts +463 -463
  106. package/src/index.ts +709 -709
  107. package/src/invariant.ts +17 -17
  108. package/src/kimi-errors.ts +26 -26
  109. package/src/media-store.ts +927 -927
  110. package/src/oauth-import-routes.ts +324 -324
  111. package/src/oauth-providers.ts +152 -152
  112. package/src/oauth-session.ts +183 -183
  113. package/src/oauth-sources.ts +1104 -1104
  114. package/src/oauth.ts +620 -620
  115. package/src/provider.ts +128 -128
  116. package/src/proxy.ts +11 -11
  117. package/src/redact.ts +72 -72
  118. package/src/session.ts +218 -218
  119. package/src/store.ts +217 -217
  120. package/src/web-origin.ts +296 -296
  121. 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,33 +1,33 @@
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",
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
31
  "@deepseek-ai/dsh-atomic-write": "0.1.1-rc.2",
32
32
  "@deepseek-ai/dsh-attachment": "0.1.1-rc.2",
33
33
  "@deepseek-ai/dsh-client-locale": "0.1.1-rc.2",
@@ -42,14 +42,14 @@ export const DSH_EXACT_BOM = Object.freeze({
42
42
  "@deepseek-ai/dsh-llm": "0.1.1-rc.2",
43
43
  "@deepseek-ai/dsh-llm-pi-ai": "0.1.1-rc.2",
44
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
- }
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
+ }