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
package/src/catalog.ts CHANGED
@@ -1,271 +1,271 @@
1
- /**
2
- * Account-specific Grok Build catalog: live GET /v1/models-v2 merged onto the
3
- * static baseline descriptors. Failures keep the last good list, then the
4
- * static baseline.
5
- * @module dsh-coding-subscription-oauth/catalog
6
- */
7
-
8
- import type { Api, Model, ThinkingLevelMap } from "@earendil-works/pi-ai";
9
- import { DEFAULT_GROK_BUILD_MODEL, GROK_BUILD_ROUTE } from "./ids.ts";
10
- import { GROK_BUILD_MODELS_URL, grokBuildBaselineModels, grokBuildFingerprintHeaders } from "./provider.ts";
11
- import { codingOAuthProxyUnreachableHint } from "./proxy.ts";
12
-
13
- const BODY_LIMIT_BYTES = 4 * 1024 * 1024;
14
- const BODY_LIMIT_ERROR = "Grok Build model listing exceeded the 4 MiB read ceiling";
15
- const PI_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
16
-
17
- export type CatalogSource = "live" | "cache" | "fallback";
18
-
19
- /** Vendor listing fields we keep after a live `/models-v2` fetch. */
20
- export interface LiveModelDescriptor {
21
- id: string;
22
- name?: string;
23
- contextWindow?: number;
24
- reasoning?: boolean;
25
- thinkingLevelMap?: ThinkingLevelMap;
26
- }
27
-
28
- function isRecord(value: unknown): value is Record<string, unknown> {
29
- return typeof value === "object" && value !== null && !Array.isArray(value);
30
- }
31
-
32
- function listingRows(body: unknown): unknown[] {
33
- return Array.isArray(body)
34
- ? body
35
- : isRecord(body) && Array.isArray(body["data"])
36
- ? body["data"]
37
- : isRecord(body) && Array.isArray(body["models"])
38
- ? body["models"]
39
- : [];
40
- }
41
-
42
- function isPiThinkingLevel(value: string): value is (typeof PI_THINKING_LEVELS)[number] {
43
- return (PI_THINKING_LEVELS as readonly string[]).includes(value);
44
- }
45
-
46
- /**
47
- * Translate Grok Build `reasoning_efforts` into a pi-ai map. Undeclared
48
- * extended levels (especially `xhigh`) must be pinned to null — pi-ai treats
49
- * an absent xhigh/max key as unsupported, and an absent low/medium/high key
50
- * as supported.
51
- */
52
- export function thinkingLevelMapFromLiveEfforts(efforts: unknown): ThinkingLevelMap | undefined {
53
- if (!Array.isArray(efforts)) return undefined;
54
- const offered: ThinkingLevelMap = { off: null };
55
- let sawOffered = false;
56
- for (const row of efforts) {
57
- if (!isRecord(row)) continue;
58
- const id = typeof row["id"] === "string" ? row["id"] : typeof row["value"] === "string" ? row["value"] : "";
59
- const value = typeof row["value"] === "string" && row["value"].length > 0 ? row["value"] : id;
60
- if (!isPiThinkingLevel(id) || id === "off" || value.length === 0) continue;
61
- offered[id] = value;
62
- sawOffered = true;
63
- }
64
- if (!sawOffered) return undefined;
65
- const map: ThinkingLevelMap = { off: null };
66
- for (const level of PI_THINKING_LEVELS) {
67
- if (level === "off") continue;
68
- map[level] = offered[level] ?? null;
69
- }
70
- return map;
71
- }
72
-
73
- function parseLiveRow(row: unknown): LiveModelDescriptor | undefined {
74
- if (typeof row === "string" && row.length > 0) return { id: row };
75
- if (!isRecord(row) || typeof row["id"] !== "string" || row["id"].length === 0) return undefined;
76
- const descriptor: LiveModelDescriptor = { id: row["id"] };
77
- if (typeof row["name"] === "string" && row["name"].length > 0) descriptor.name = row["name"];
78
- const contextWindow = row["context_window"] ?? row["contextWindow"];
79
- if (typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0) {
80
- descriptor.contextWindow = contextWindow;
81
- }
82
- if (row["supports_reasoning_effort"] === false) {
83
- descriptor.reasoning = false;
84
- } else {
85
- const thinkingLevelMap = thinkingLevelMapFromLiveEfforts(row["reasoning_efforts"]);
86
- if (thinkingLevelMap !== undefined) {
87
- descriptor.reasoning = true;
88
- descriptor.thinkingLevelMap = thinkingLevelMap;
89
- } else if (row["supports_reasoning_effort"] === true) {
90
- descriptor.reasoning = true;
91
- }
92
- }
93
- return descriptor;
94
- }
95
-
96
- /** Pull the live listing, including per-model reasoning levels when present. */
97
- export function extractLiveModels(body: unknown): LiveModelDescriptor[] {
98
- const seen = new Set<string>();
99
- const models: LiveModelDescriptor[] = [];
100
- for (const row of listingRows(body)) {
101
- const parsed = parseLiveRow(row);
102
- if (parsed === undefined || seen.has(parsed.id)) continue;
103
- seen.add(parsed.id);
104
- models.push(parsed);
105
- }
106
- return models;
107
- }
108
-
109
- /**
110
- * Pull model ids from a listing body. The `/v1/models-v2` response shape is
111
- * not a published contract, so accept the common envelopes: a bare array, an
112
- * OpenAI-style `{ data: [...] }`, or `{ models: [...] }`; rows may be plain
113
- * ids or objects with an `id` field.
114
- */
115
- export function extractModelIds(body: unknown): string[] {
116
- return extractLiveModels(body).map((model) => model.id);
117
- }
118
-
119
- function titleCaseId(id: string): string {
120
- return id
121
- .split(/[-_]/g)
122
- .map((part) => (part.length === 0 ? part : (part[0] ?? "").toUpperCase() + part.slice(1)))
123
- .join(" ");
124
- }
125
-
126
- function catalogModels(baseline: readonly Model<Api>[] = grokBuildBaselineModels()): readonly Model<Api>[] {
127
- return baseline;
128
- }
129
-
130
- function templateFor(id: string, catalog: readonly Model<Api>[]): Model<Api> {
131
- const exact = catalog.find((model) => model.id === id);
132
- if (exact !== undefined) return exact;
133
- const lower = id.toLowerCase();
134
- const fallback = catalog.find((model) => model.id === DEFAULT_GROK_BUILD_MODEL) ?? catalog[0];
135
- if (fallback === undefined) throw new Error("grok-build: baseline catalog is empty");
136
- if (lower.includes("composer") || lower.includes("fast")) {
137
- return catalog.find((model) => model.id === "grok-composer-2.5-fast") ?? fallback;
138
- }
139
- // grok-4.5 is the last generation without xhigh; later ids inherit 4.6.
140
- if (/(^|[-_])4\.5($|[-_])/u.test(lower)) {
141
- return catalog.find((model) => model.id === "grok-4.5") ?? fallback;
142
- }
143
- return catalog.find((model) => model.id === "grok-4.6") ?? fallback;
144
- }
145
-
146
- function applyLiveOverlay(model: Model<Api>, overlay: LiveModelDescriptor | undefined): Model<Api> {
147
- if (overlay === undefined) return model;
148
- return {
149
- ...model,
150
- id: overlay.id,
151
- ...(overlay.name === undefined ? {} : { name: overlay.name }),
152
- ...(overlay.contextWindow === undefined ? {} : { contextWindow: overlay.contextWindow }),
153
- ...(overlay.reasoning === undefined ? {} : { reasoning: overlay.reasoning }),
154
- ...(overlay.thinkingLevelMap === undefined ? {} : { thinkingLevelMap: overlay.thinkingLevelMap }),
155
- };
156
- }
157
-
158
- /** Turn a live id into a pi-ai model, inheriting baseline metadata when possible. */
159
- export function materializeLiveModel(
160
- id: string,
161
- catalog: readonly Model<Api>[] = catalogModels(),
162
- overlay?: LiveModelDescriptor,
163
- ): Model<Api> {
164
- const template = templateFor(id, catalog);
165
- const base = template.id === id ? template : { ...template, id, name: titleCaseId(id) };
166
- return applyLiveOverlay(base, overlay);
167
- }
168
-
169
- /**
170
- * If `liveIds` is missing or empty, serve the baseline catalog.
171
- * Otherwise serve only the live ids, each materialized against the baseline
172
- * and optionally overlaid with live `/models-v2` reasoning metadata.
173
- */
174
- export function mergeLiveCatalog(
175
- catalog: readonly Model<Api>[],
176
- liveIds: readonly string[] | undefined,
177
- liveModels: readonly LiveModelDescriptor[] = [],
178
- ): Model<Api>[] {
179
- if (liveIds === undefined || liveIds.length === 0) return [...catalog];
180
- const overlays = new Map(liveModels.map((model) => [model.id, model]));
181
- return liveIds.map((id) => materializeLiveModel(id, catalog, overlays.get(id)));
182
- }
183
-
184
- export function preferredGrokBuildModelFrom(models: readonly { id: string }[]): string {
185
- const ids = new Set(models.map((model) => model.id));
186
- if (ids.has(DEFAULT_GROK_BUILD_MODEL)) return DEFAULT_GROK_BUILD_MODEL;
187
- return models[0]?.id ?? DEFAULT_GROK_BUILD_MODEL;
188
- }
189
-
190
- async function readBoundedResponse(response: Response): Promise<Buffer> {
191
- const declared = response.headers.get("content-length");
192
- if (declared !== null && /^\d+$/u.test(declared) && Number(declared) > BODY_LIMIT_BYTES) {
193
- await response.body?.cancel().catch(() => undefined);
194
- throw new Error(BODY_LIMIT_ERROR);
195
- }
196
- if (response.body === null) return Buffer.alloc(0);
197
- const reader = response.body.getReader();
198
- const chunks: Buffer[] = [];
199
- let size = 0;
200
- try {
201
- while (true) {
202
- const { done, value } = await reader.read();
203
- if (done) break;
204
- size += value.byteLength;
205
- if (size > BODY_LIMIT_BYTES) {
206
- await reader.cancel().catch(() => undefined);
207
- throw new Error(BODY_LIMIT_ERROR);
208
- }
209
- chunks.push(Buffer.from(value));
210
- }
211
- } finally {
212
- reader.releaseLock();
213
- }
214
- return Buffer.concat(chunks, size);
215
- }
216
-
217
- /**
218
- * Fetch the account-visible models from `/v1/models-v2` with the CLI
219
- * fingerprint headers. Throws a secret-free error on failure.
220
- */
221
- export async function fetchLiveModels(accessToken: string, signal?: AbortSignal): Promise<LiveModelDescriptor[]> {
222
- let response: Response;
223
- try {
224
- response = await fetch(GROK_BUILD_MODELS_URL, {
225
- headers: {
226
- accept: "application/json",
227
- authorization: `Bearer ${accessToken}`,
228
- ...grokBuildFingerprintHeaders(),
229
- },
230
- ...(signal !== undefined ? { signal } : {}),
231
- });
232
- } catch {
233
- if (signal?.aborted) throw new Error("Live model listing was cancelled");
234
- throw new Error(
235
- `Grok Build model listing is unreachable (proxy required on some networks)${codingOAuthProxyUnreachableHint()}`,
236
- );
237
- }
238
- let raw: Buffer;
239
- try {
240
- raw = await readBoundedResponse(response);
241
- } catch (error) {
242
- if (signal?.aborted) throw new Error("Live model listing was cancelled");
243
- if (error instanceof Error && error.message === BODY_LIMIT_ERROR) throw error;
244
- throw new Error("Grok Build model listing response could not be read");
245
- }
246
- let body: unknown;
247
- try {
248
- body = JSON.parse(raw.toString("utf8"));
249
- } catch {
250
- throw new Error(`Grok Build model listing returned invalid JSON (HTTP ${response.status})`);
251
- }
252
- if (!response.ok) {
253
- const code = isRecord(body) && typeof body["error"] === "string" ? body["error"] : undefined;
254
- throw new Error(
255
- `Grok Build model listing failed (HTTP ${response.status})${code === undefined ? "" : `: ${code}`}`,
256
- );
257
- }
258
- const models = extractLiveModels(body);
259
- if (models.length === 0) throw new Error("Grok Build model listing contained no model ids");
260
- return models;
261
- }
262
-
263
- /** Fetch only the account-visible model ids from `/v1/models-v2`. */
264
- export async function fetchLiveModelIds(accessToken: string, signal?: AbortSignal): Promise<string[]> {
265
- return (await fetchLiveModels(accessToken, signal)).map((model) => model.id);
266
- }
267
-
268
- /** Re-exported so callers can normalise cached descriptors onto the route. */
269
- export function asRouteModel(model: Model<Api>): Model<Api> {
270
- return model.provider === GROK_BUILD_ROUTE ? model : { ...model, provider: GROK_BUILD_ROUTE };
271
- }
1
+ /**
2
+ * Account-specific Grok Build catalog: live GET /v1/models-v2 merged onto the
3
+ * static baseline descriptors. Failures keep the last good list, then the
4
+ * static baseline.
5
+ * @module dsh-coding-subscription-oauth/catalog
6
+ */
7
+
8
+ import type { Api, Model, ThinkingLevelMap } from "@earendil-works/pi-ai";
9
+ import { DEFAULT_GROK_BUILD_MODEL, GROK_BUILD_ROUTE } from "./ids.ts";
10
+ import { GROK_BUILD_MODELS_URL, grokBuildBaselineModels, grokBuildFingerprintHeaders } from "./provider.ts";
11
+ import { codingOAuthProxyUnreachableHint } from "./proxy.ts";
12
+
13
+ const BODY_LIMIT_BYTES = 4 * 1024 * 1024;
14
+ const BODY_LIMIT_ERROR = "Grok Build model listing exceeded the 4 MiB read ceiling";
15
+ const PI_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
16
+
17
+ export type CatalogSource = "live" | "cache" | "fallback";
18
+
19
+ /** Vendor listing fields we keep after a live `/models-v2` fetch. */
20
+ export interface LiveModelDescriptor {
21
+ id: string;
22
+ name?: string;
23
+ contextWindow?: number;
24
+ reasoning?: boolean;
25
+ thinkingLevelMap?: ThinkingLevelMap;
26
+ }
27
+
28
+ function isRecord(value: unknown): value is Record<string, unknown> {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
31
+
32
+ function listingRows(body: unknown): unknown[] {
33
+ return Array.isArray(body)
34
+ ? body
35
+ : isRecord(body) && Array.isArray(body["data"])
36
+ ? body["data"]
37
+ : isRecord(body) && Array.isArray(body["models"])
38
+ ? body["models"]
39
+ : [];
40
+ }
41
+
42
+ function isPiThinkingLevel(value: string): value is (typeof PI_THINKING_LEVELS)[number] {
43
+ return (PI_THINKING_LEVELS as readonly string[]).includes(value);
44
+ }
45
+
46
+ /**
47
+ * Translate Grok Build `reasoning_efforts` into a pi-ai map. Undeclared
48
+ * extended levels (especially `xhigh`) must be pinned to null — pi-ai treats
49
+ * an absent xhigh/max key as unsupported, and an absent low/medium/high key
50
+ * as supported.
51
+ */
52
+ export function thinkingLevelMapFromLiveEfforts(efforts: unknown): ThinkingLevelMap | undefined {
53
+ if (!Array.isArray(efforts)) return undefined;
54
+ const offered: ThinkingLevelMap = { off: null };
55
+ let sawOffered = false;
56
+ for (const row of efforts) {
57
+ if (!isRecord(row)) continue;
58
+ const id = typeof row["id"] === "string" ? row["id"] : typeof row["value"] === "string" ? row["value"] : "";
59
+ const value = typeof row["value"] === "string" && row["value"].length > 0 ? row["value"] : id;
60
+ if (!isPiThinkingLevel(id) || id === "off" || value.length === 0) continue;
61
+ offered[id] = value;
62
+ sawOffered = true;
63
+ }
64
+ if (!sawOffered) return undefined;
65
+ const map: ThinkingLevelMap = { off: null };
66
+ for (const level of PI_THINKING_LEVELS) {
67
+ if (level === "off") continue;
68
+ map[level] = offered[level] ?? null;
69
+ }
70
+ return map;
71
+ }
72
+
73
+ function parseLiveRow(row: unknown): LiveModelDescriptor | undefined {
74
+ if (typeof row === "string" && row.length > 0) return { id: row };
75
+ if (!isRecord(row) || typeof row["id"] !== "string" || row["id"].length === 0) return undefined;
76
+ const descriptor: LiveModelDescriptor = { id: row["id"] };
77
+ if (typeof row["name"] === "string" && row["name"].length > 0) descriptor.name = row["name"];
78
+ const contextWindow = row["context_window"] ?? row["contextWindow"];
79
+ if (typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0) {
80
+ descriptor.contextWindow = contextWindow;
81
+ }
82
+ if (row["supports_reasoning_effort"] === false) {
83
+ descriptor.reasoning = false;
84
+ } else {
85
+ const thinkingLevelMap = thinkingLevelMapFromLiveEfforts(row["reasoning_efforts"]);
86
+ if (thinkingLevelMap !== undefined) {
87
+ descriptor.reasoning = true;
88
+ descriptor.thinkingLevelMap = thinkingLevelMap;
89
+ } else if (row["supports_reasoning_effort"] === true) {
90
+ descriptor.reasoning = true;
91
+ }
92
+ }
93
+ return descriptor;
94
+ }
95
+
96
+ /** Pull the live listing, including per-model reasoning levels when present. */
97
+ export function extractLiveModels(body: unknown): LiveModelDescriptor[] {
98
+ const seen = new Set<string>();
99
+ const models: LiveModelDescriptor[] = [];
100
+ for (const row of listingRows(body)) {
101
+ const parsed = parseLiveRow(row);
102
+ if (parsed === undefined || seen.has(parsed.id)) continue;
103
+ seen.add(parsed.id);
104
+ models.push(parsed);
105
+ }
106
+ return models;
107
+ }
108
+
109
+ /**
110
+ * Pull model ids from a listing body. The `/v1/models-v2` response shape is
111
+ * not a published contract, so accept the common envelopes: a bare array, an
112
+ * OpenAI-style `{ data: [...] }`, or `{ models: [...] }`; rows may be plain
113
+ * ids or objects with an `id` field.
114
+ */
115
+ export function extractModelIds(body: unknown): string[] {
116
+ return extractLiveModels(body).map((model) => model.id);
117
+ }
118
+
119
+ function titleCaseId(id: string): string {
120
+ return id
121
+ .split(/[-_]/g)
122
+ .map((part) => (part.length === 0 ? part : (part[0] ?? "").toUpperCase() + part.slice(1)))
123
+ .join(" ");
124
+ }
125
+
126
+ function catalogModels(baseline: readonly Model<Api>[] = grokBuildBaselineModels()): readonly Model<Api>[] {
127
+ return baseline;
128
+ }
129
+
130
+ function templateFor(id: string, catalog: readonly Model<Api>[]): Model<Api> {
131
+ const exact = catalog.find((model) => model.id === id);
132
+ if (exact !== undefined) return exact;
133
+ const lower = id.toLowerCase();
134
+ const fallback = catalog.find((model) => model.id === DEFAULT_GROK_BUILD_MODEL) ?? catalog[0];
135
+ if (fallback === undefined) throw new Error("grok-build: baseline catalog is empty");
136
+ if (lower.includes("composer") || lower.includes("fast")) {
137
+ return catalog.find((model) => model.id === "grok-composer-2.5-fast") ?? fallback;
138
+ }
139
+ // grok-4.5 is the last generation without xhigh; later ids inherit 4.6.
140
+ if (/(^|[-_])4\.5($|[-_])/u.test(lower)) {
141
+ return catalog.find((model) => model.id === "grok-4.5") ?? fallback;
142
+ }
143
+ return catalog.find((model) => model.id === "grok-4.6") ?? fallback;
144
+ }
145
+
146
+ function applyLiveOverlay(model: Model<Api>, overlay: LiveModelDescriptor | undefined): Model<Api> {
147
+ if (overlay === undefined) return model;
148
+ return {
149
+ ...model,
150
+ id: overlay.id,
151
+ ...(overlay.name === undefined ? {} : { name: overlay.name }),
152
+ ...(overlay.contextWindow === undefined ? {} : { contextWindow: overlay.contextWindow }),
153
+ ...(overlay.reasoning === undefined ? {} : { reasoning: overlay.reasoning }),
154
+ ...(overlay.thinkingLevelMap === undefined ? {} : { thinkingLevelMap: overlay.thinkingLevelMap }),
155
+ };
156
+ }
157
+
158
+ /** Turn a live id into a pi-ai model, inheriting baseline metadata when possible. */
159
+ export function materializeLiveModel(
160
+ id: string,
161
+ catalog: readonly Model<Api>[] = catalogModels(),
162
+ overlay?: LiveModelDescriptor,
163
+ ): Model<Api> {
164
+ const template = templateFor(id, catalog);
165
+ const base = template.id === id ? template : { ...template, id, name: titleCaseId(id) };
166
+ return applyLiveOverlay(base, overlay);
167
+ }
168
+
169
+ /**
170
+ * If `liveIds` is missing or empty, serve the baseline catalog.
171
+ * Otherwise serve only the live ids, each materialized against the baseline
172
+ * and optionally overlaid with live `/models-v2` reasoning metadata.
173
+ */
174
+ export function mergeLiveCatalog(
175
+ catalog: readonly Model<Api>[],
176
+ liveIds: readonly string[] | undefined,
177
+ liveModels: readonly LiveModelDescriptor[] = [],
178
+ ): Model<Api>[] {
179
+ if (liveIds === undefined || liveIds.length === 0) return [...catalog];
180
+ const overlays = new Map(liveModels.map((model) => [model.id, model]));
181
+ return liveIds.map((id) => materializeLiveModel(id, catalog, overlays.get(id)));
182
+ }
183
+
184
+ export function preferredGrokBuildModelFrom(models: readonly { id: string }[]): string {
185
+ const ids = new Set(models.map((model) => model.id));
186
+ if (ids.has(DEFAULT_GROK_BUILD_MODEL)) return DEFAULT_GROK_BUILD_MODEL;
187
+ return models[0]?.id ?? DEFAULT_GROK_BUILD_MODEL;
188
+ }
189
+
190
+ async function readBoundedResponse(response: Response): Promise<Buffer> {
191
+ const declared = response.headers.get("content-length");
192
+ if (declared !== null && /^\d+$/u.test(declared) && Number(declared) > BODY_LIMIT_BYTES) {
193
+ await response.body?.cancel().catch(() => undefined);
194
+ throw new Error(BODY_LIMIT_ERROR);
195
+ }
196
+ if (response.body === null) return Buffer.alloc(0);
197
+ const reader = response.body.getReader();
198
+ const chunks: Buffer[] = [];
199
+ let size = 0;
200
+ try {
201
+ while (true) {
202
+ const { done, value } = await reader.read();
203
+ if (done) break;
204
+ size += value.byteLength;
205
+ if (size > BODY_LIMIT_BYTES) {
206
+ await reader.cancel().catch(() => undefined);
207
+ throw new Error(BODY_LIMIT_ERROR);
208
+ }
209
+ chunks.push(Buffer.from(value));
210
+ }
211
+ } finally {
212
+ reader.releaseLock();
213
+ }
214
+ return Buffer.concat(chunks, size);
215
+ }
216
+
217
+ /**
218
+ * Fetch the account-visible models from `/v1/models-v2` with the CLI
219
+ * fingerprint headers. Throws a secret-free error on failure.
220
+ */
221
+ export async function fetchLiveModels(accessToken: string, signal?: AbortSignal): Promise<LiveModelDescriptor[]> {
222
+ let response: Response;
223
+ try {
224
+ response = await fetch(GROK_BUILD_MODELS_URL, {
225
+ headers: {
226
+ accept: "application/json",
227
+ authorization: `Bearer ${accessToken}`,
228
+ ...grokBuildFingerprintHeaders(),
229
+ },
230
+ ...(signal !== undefined ? { signal } : {}),
231
+ });
232
+ } catch {
233
+ if (signal?.aborted) throw new Error("Live model listing was cancelled");
234
+ throw new Error(
235
+ `Grok Build model listing is unreachable (proxy required on some networks)${codingOAuthProxyUnreachableHint()}`,
236
+ );
237
+ }
238
+ let raw: Buffer;
239
+ try {
240
+ raw = await readBoundedResponse(response);
241
+ } catch (error) {
242
+ if (signal?.aborted) throw new Error("Live model listing was cancelled");
243
+ if (error instanceof Error && error.message === BODY_LIMIT_ERROR) throw error;
244
+ throw new Error("Grok Build model listing response could not be read");
245
+ }
246
+ let body: unknown;
247
+ try {
248
+ body = JSON.parse(raw.toString("utf8"));
249
+ } catch {
250
+ throw new Error(`Grok Build model listing returned invalid JSON (HTTP ${response.status})`);
251
+ }
252
+ if (!response.ok) {
253
+ const code = isRecord(body) && typeof body["error"] === "string" ? body["error"] : undefined;
254
+ throw new Error(
255
+ `Grok Build model listing failed (HTTP ${response.status})${code === undefined ? "" : `: ${code}`}`,
256
+ );
257
+ }
258
+ const models = extractLiveModels(body);
259
+ if (models.length === 0) throw new Error("Grok Build model listing contained no model ids");
260
+ return models;
261
+ }
262
+
263
+ /** Fetch only the account-visible model ids from `/v1/models-v2`. */
264
+ export async function fetchLiveModelIds(accessToken: string, signal?: AbortSignal): Promise<string[]> {
265
+ return (await fetchLiveModels(accessToken, signal)).map((model) => model.id);
266
+ }
267
+
268
+ /** Re-exported so callers can normalise cached descriptors onto the route. */
269
+ export function asRouteModel(model: Model<Api>): Model<Api> {
270
+ return model.provider === GROK_BUILD_ROUTE ? model : { ...model, provider: GROK_BUILD_ROUTE };
271
+ }