dsh-coding-subscription-oauth 0.5.8 → 0.6.2

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 (148) hide show
  1. package/CHANGELOG.md +217 -188
  2. package/CONTRIBUTING.md +120 -120
  3. package/INSTALL.md +241 -209
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +298 -294
  7. package/README.es.md +299 -295
  8. package/README.fr.md +299 -295
  9. package/README.ja.md +299 -295
  10. package/README.ko.md +299 -295
  11. package/README.md +313 -307
  12. package/README.pt-BR.md +299 -295
  13. package/README.ru.md +299 -295
  14. package/README.zh-CN.md +311 -305
  15. package/compatibility/dsh-bom.json +30 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +195 -195
  18. package/docs/02-architecture.md +134 -129
  19. package/docs/02-architecture.zh-CN.md +134 -129
  20. package/lib/adapter.d.ts.map +1 -1
  21. package/lib/alias-adapter.d.ts +3 -1
  22. package/lib/alias-adapter.d.ts.map +1 -1
  23. package/lib/auth-routes.d.ts +8 -15
  24. package/lib/auth-routes.d.ts.map +1 -1
  25. package/lib/bin.js +746 -1402
  26. package/lib/bin.js.map +4 -4
  27. package/lib/capability-routes.d.ts +3 -3
  28. package/lib/capability-routes.d.ts.map +1 -1
  29. package/lib/capability-settings.d.ts +5 -4
  30. package/lib/capability-settings.d.ts.map +1 -1
  31. package/lib/client.js +27 -8
  32. package/lib/client.js.map +4 -4
  33. package/lib/compatibility.d.ts +46 -0
  34. package/lib/compatibility.d.ts.map +1 -0
  35. package/lib/dsh-host-adapter.d.ts +18 -0
  36. package/lib/dsh-host-adapter.d.ts.map +1 -0
  37. package/lib/gateway-auth.d.ts +1 -2
  38. package/lib/gateway-auth.d.ts.map +1 -1
  39. package/lib/gateway-routes.d.ts +3 -4
  40. package/lib/gateway-routes.d.ts.map +1 -1
  41. package/lib/gateway.d.ts +4 -0
  42. package/lib/gateway.d.ts.map +1 -1
  43. package/lib/ids.d.ts +3 -32
  44. package/lib/ids.d.ts.map +1 -1
  45. package/lib/imagine-routes.d.ts +2 -0
  46. package/lib/imagine-routes.d.ts.map +1 -1
  47. package/lib/index.d.ts +19 -4
  48. package/lib/index.d.ts.map +1 -1
  49. package/lib/index.js +26627 -1047
  50. package/lib/index.js.map +4 -4
  51. package/lib/invariant.js.map +1 -1
  52. package/lib/oauth-import-routes.d.ts +3 -4
  53. package/lib/oauth-import-routes.d.ts.map +1 -1
  54. package/lib/proxy.d.ts +3 -16
  55. package/lib/proxy.d.ts.map +1 -1
  56. package/lib/web-origin.d.ts +28 -4
  57. package/lib/web-origin.d.ts.map +1 -1
  58. package/lib/web-routes.d.ts.map +1 -1
  59. package/media/en/settings_accounts.png +0 -0
  60. package/media/en/settings_capabilities.png +0 -0
  61. package/media/en/settings_gateway.png +0 -0
  62. package/media/settings_accounts.png +0 -0
  63. package/media/settings_capabilities.png +0 -0
  64. package/media/settings_gateway.png +0 -0
  65. package/media/settings_overview.png +0 -0
  66. package/media/zh-CN/settings_accounts.png +0 -0
  67. package/media/zh-CN/settings_capabilities.png +0 -0
  68. package/media/zh-CN/settings_gateway.png +0 -0
  69. package/package.json +211 -174
  70. package/patches/dsh-agy@0.1.2.patch +25 -25
  71. package/scripts/release.mjs +186 -170
  72. package/scripts/smoke-deployed-routes.mjs +146 -146
  73. package/scripts/verify-deployed-catalog.mjs +87 -87
  74. package/src/adapter.ts +329 -268
  75. package/src/alias-adapter.ts +141 -147
  76. package/src/auth-routes.ts +921 -871
  77. package/src/auth.ts +67 -67
  78. package/src/bin.ts +350 -350
  79. package/src/capability-routes.ts +279 -275
  80. package/src/capability-runtime.ts +313 -313
  81. package/src/capability-settings.ts +658 -657
  82. package/src/capability-tools.ts +666 -666
  83. package/src/catalog.ts +271 -271
  84. package/src/client/GrokBuildSettings.tsx +770 -718
  85. package/src/client/api.ts +88 -88
  86. package/src/client/components/AboutTab.tsx +30 -30
  87. package/src/client/components/AccountsTab.tsx +241 -224
  88. package/src/client/components/Badge.tsx +33 -33
  89. package/src/client/components/CapabilitiesTab.tsx +265 -227
  90. package/src/client/components/CliPullPreview.tsx +116 -107
  91. package/src/client/components/CopyButton.tsx +57 -57
  92. package/src/client/components/GatewayTab.tsx +469 -409
  93. package/src/client/components/NoticeBanner.tsx +46 -46
  94. package/src/client/components/ProgressBar.tsx +53 -53
  95. package/src/client/components/ProviderCard.tsx +606 -502
  96. package/src/client/components/SettingsTabs.tsx +75 -75
  97. package/src/client/components/ToggleSwitch.tsx +71 -62
  98. package/src/client/constants.ts +224 -206
  99. package/src/client/display.ts +61 -61
  100. package/src/client/dshClientAdapter.ts +127 -0
  101. package/src/client/gatewaySnippets.ts +37 -36
  102. package/src/client/index.tsx +156 -37
  103. package/src/client/locales.ts +535 -491
  104. package/src/client/microStyles.ts +52 -33
  105. package/src/client/parsers.ts +396 -386
  106. package/src/client/styles.ts +325 -307
  107. package/src/client/types.ts +197 -185
  108. package/src/codex-http.ts +447 -447
  109. package/src/codex-images.ts +485 -485
  110. package/src/codex-model-capabilities.ts +320 -320
  111. package/src/codex-search.ts +245 -245
  112. package/src/codex-usage.ts +263 -263
  113. package/src/compatibility.ts +55 -0
  114. package/src/dsh-host-adapter.ts +173 -0
  115. package/src/gateway-anthropic-messages.ts +84 -84
  116. package/src/gateway-auth.ts +102 -100
  117. package/src/gateway-backend.ts +274 -274
  118. package/src/gateway-body.ts +49 -49
  119. package/src/gateway-config.ts +76 -76
  120. package/src/gateway-http.ts +104 -104
  121. package/src/gateway-openai-chat.ts +124 -124
  122. package/src/gateway-openai-responses.ts +53 -53
  123. package/src/gateway-parse.ts +224 -224
  124. package/src/gateway-protocol.ts +52 -52
  125. package/src/gateway-routes.ts +158 -152
  126. package/src/gateway.ts +258 -242
  127. package/src/grok-errors.ts +24 -24
  128. package/src/grok-imagine.ts +1627 -1627
  129. package/src/grok-import.ts +151 -151
  130. package/src/http-json.ts +82 -82
  131. package/src/ids.ts +59 -45
  132. package/src/imagine-routes.ts +463 -461
  133. package/src/index.ts +729 -592
  134. package/src/invariant.ts +17 -17
  135. package/src/kimi-errors.ts +26 -26
  136. package/src/media-store.ts +927 -927
  137. package/src/oauth-import-routes.ts +324 -314
  138. package/src/oauth-providers.ts +152 -152
  139. package/src/oauth-session.ts +183 -183
  140. package/src/oauth-sources.ts +1104 -1104
  141. package/src/oauth.ts +620 -620
  142. package/src/provider.ts +128 -128
  143. package/src/proxy.ts +11 -99
  144. package/src/redact.ts +72 -72
  145. package/src/session.ts +218 -218
  146. package/src/store.ts +217 -217
  147. package/src/web-origin.ts +296 -60
  148. package/src/web-routes.ts +38 -75
@@ -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
+ }
@@ -0,0 +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
+ }