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
package/src/index.ts CHANGED
@@ -1,598 +1,735 @@
1
- /**
2
- * Optional xAI Grok Build bundle with OAuth, account model catalog,
3
- * and an account section inside dsh Settings.
4
- * @module dsh-coding-subscription-oauth
5
- */
6
-
7
- import { dirname, join } from "node:path";
8
- import type { Context } from "@deepseek-ai/cordis";
9
- import type { AttachmentStore } from "@deepseek-ai/dsh-attachment";
10
- import type { CredentialInfo, CredentialProvider, CredentialRef } from "@deepseek-ai/dsh-credentials";
11
- import type {} from "@deepseek-ai/dsh-host-webserver";
12
- import { assertUsableApiKey, type RetryPolicyConfig, RetryPolicySchema } from "@deepseek-ai/dsh-llm";
13
- import z from "@deepseek-ai/schemastery";
14
- import type { Credential, OAuthCredential } from "@earendil-works/pi-ai";
15
- import { createCodingOAuthAdapter } from "./adapter.ts";
16
- import { registerCodingOAuthRoutes } from "./auth-routes.ts";
17
- import { registerCapabilityRoutes } from "./capability-routes.ts";
18
- import {
19
- bindCapabilitySearch,
20
- bindCapabilityTools,
21
- bindCodexFastRoute,
22
- CapabilityRuntimeState,
23
- type CapabilitySearchRegistry,
24
- type CapabilityToolRegistry,
25
- } from "./capability-runtime.ts";
26
- import {
27
- type CapabilitySettingsPatch,
28
- CapabilitySettingsSchema,
29
- type CapabilitySettingsService,
30
- createCapabilitySettingsController,
31
- resolveCapabilitySettings,
32
- } from "./capability-settings.ts";
33
- import {
34
- CODEX_IMAGE_EDIT_TOOL,
35
- CODEX_IMAGE_GENERATE_TOOL,
36
- createCapabilityTools,
37
- type ResolveCodexImageRoute,
38
- resolveCodexImageRouteFromLlm,
39
- } from "./capability-tools.ts";
40
- import { codexAuthFromSession } from "./codex-http.ts";
41
- import { createCodexModelCapabilities } from "./codex-model-capabilities.ts";
42
- import { createCodexSearchProvider } from "./codex-search.ts";
43
- import { createCodexUsageReader } from "./codex-usage.ts";
44
- import { createCodingOAuthGatewayController } from "./gateway.ts";
45
- import { type GatewayConfig, GatewayConfigSchema } from "./gateway-config.ts";
46
- import { registerGatewayRoutes } from "./gateway-routes.ts";
47
- import {
48
- createGrokImagineClient,
49
- GROK_IMAGINE_IMAGE_TOOL,
50
- GROK_IMAGINE_VIDEO_STATUS_TOOL,
51
- GROK_IMAGINE_VIDEO_TOOL,
52
- GrokImagineError,
53
- type ImagineOperation,
54
- } from "./grok-imagine.ts";
55
- import {
56
- CLAUDE_PI_PROVIDER,
57
- CODEX_PI_PROVIDER,
58
- CODING_OAUTH_ROUTES,
59
- KIMI_PI_PROVIDER,
60
- XAI_PI_PROVIDER,
61
- } from "./ids.ts";
62
- import { registerImagineRoutes } from "./imagine-routes.ts";
63
- import { MediaStore } from "./media-store.ts";
64
- import {
65
- type OAuthImportDestinationStore,
66
- type OAuthImportDestinations,
67
- registerOAuthImportRoutes,
68
- } from "./oauth-import-routes.ts";
69
- import { OAUTH_PROVIDER_DEFINITIONS } from "./oauth-providers.ts";
70
- import { OAuthProviderSession } from "./oauth-session.ts";
71
- import type { OAuthSourceCredential } from "./oauth-sources.ts";
72
- import { ensureCodingOAuthProxy } from "./proxy.ts";
73
- import { GrokBuildSession } from "./session.ts";
74
- import { GrokBuildCredentialStore, type OAuthCredentialFileStore } from "./store.ts";
75
-
76
- export { createCodingOAuthAdapter, createGrokBuildAdapter, preferredGrokBuildModel } from "./adapter.ts";
77
- export type { AliasLlmRoutePolicy } from "./alias-adapter.ts";
78
- export { AliasLlmAdapter } from "./alias-adapter.ts";
79
- export type { GrokBuildAuthStatus } from "./auth.ts";
80
- export {
81
- grokBuildAuthStatus,
82
- importGrokBuildFromGrok,
83
- importGrokBuildSession,
84
- loginGrokBuild,
85
- loginGrokBuildSession,
86
- logoutGrokBuild,
87
- } from "./auth.ts";
88
- export type {
89
- CodingOAuthWebStatus,
90
- GrokBuildLoginMethod,
91
- GrokBuildWebAuthStatus,
92
- LoginChallenge,
93
- SubscriptionLoginChallenge,
94
- SubscriptionWebAuthStatus,
95
- } from "./auth-routes.ts";
96
- export {
97
- CODING_OAUTH_LOGIN_CANCEL_PATH,
98
- CODING_OAUTH_LOGIN_CODE_PATH,
99
- CODING_OAUTH_LOGIN_PATH,
100
- CODING_OAUTH_LOGOUT_PATH,
101
- CODING_OAUTH_MODELS_PATH,
102
- CODING_OAUTH_STATUS_PATH,
103
- GROK_BUILD_AUTH_IMPORT_PATH,
104
- GROK_BUILD_AUTH_LOGIN_CANCEL_PATH,
105
- GROK_BUILD_AUTH_LOGIN_CODE_PATH,
106
- GROK_BUILD_AUTH_LOGIN_PATH,
107
- GROK_BUILD_AUTH_LOGOUT_PATH,
108
- GROK_BUILD_AUTH_MODELS_PATH,
109
- GROK_BUILD_AUTH_STATUS_PATH,
110
- GrokBuildWebAuth,
111
- registerCodingOAuthRoutes,
112
- registerGrokBuildAuthRoutes,
113
- SubscriptionWebAuth,
114
- } from "./auth-routes.ts";
115
- export type { CatalogSource, LiveModelDescriptor } from "./catalog.ts";
116
- export {
117
- extractLiveModels,
118
- extractModelIds,
119
- fetchLiveModelIds,
120
- fetchLiveModels,
121
- materializeLiveModel,
122
- mergeLiveCatalog,
123
- preferredGrokBuildModelFrom,
124
- thinkingLevelMapFromLiveEfforts,
125
- } from "./catalog.ts";
126
- export type { GrokImportProbe } from "./grok-import.ts";
127
- export { grokAuthPath, importGrokAuth, parseGrokAuthDocument, probeGrokAuth } from "./grok-import.ts";
128
- export type { CodingOAuthProviderSlug, CodingOAuthRoute } from "./ids.ts";
129
- export {
130
- ANTIGRAVITY_ROUTE,
131
- CLAUDE_CODE_OAUTH_AUTH_FILENAME,
132
- CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
133
- CLAUDE_CODE_OAUTH_ROUTE,
134
- CLAUDE_PI_PROVIDER,
135
- CODEX_OAUTH_AUTH_FILENAME,
136
- CODEX_OAUTH_MODELS_CACHE_FILENAME,
137
- CODEX_OAUTH_ROUTE,
138
- CODEX_PI_PROVIDER,
139
- CODING_OAUTH_ROUTES,
140
- DEFAULT_GROK_BUILD_MODEL,
141
- GROK_BUILD_AUTH_FILENAME,
142
- GROK_BUILD_MODELS_CACHE_FILENAME,
143
- GROK_BUILD_ROUTE,
144
- GROK_BUILD_STREAM_IDLE_TIMEOUT_MS,
145
- KIMI_CODE_OAUTH_AUTH_FILENAME,
146
- KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
147
- KIMI_CODE_OAUTH_ROUTE,
148
- KIMI_PI_PROVIDER,
149
- XAI_PI_PROVIDER,
150
- } from "./ids.ts";
151
- export type { GrokBuildOAuthErrorCode, GrokBuildOAuthParams, PkceLoginCallbacks } from "./oauth.ts";
152
- export {
153
- buildAuthorizeUrl,
154
- discoverOAuthEndpoints,
155
- extractCode,
156
- GROK_BUILD_OAUTH_CLIENT_ID,
157
- GROK_BUILD_OAUTH_DEFAULT_PORT,
158
- GROK_BUILD_OAUTH_ISSUER,
159
- GROK_BUILD_OAUTH_SCOPE,
160
- GrokBuildOAuthError,
161
- generatePkce,
162
- loginGrokBuildPkce,
163
- refreshGrokBuildToken,
164
- resolveOAuthParams,
165
- } from "./oauth.ts";
166
- export type { OAuthProviderDefinition, SubscriptionLoginMethod, SubscriptionProviderSlug } from "./oauth-providers.ts";
167
- export {
168
- CLAUDE_CODE_OAUTH_PROVIDER,
169
- CODEX_OAUTH_PROVIDER,
170
- KIMI_CODE_OAUTH_PROVIDER,
171
- OAUTH_PROVIDER_DEFINITIONS,
172
- oauthProviderDefinition,
173
- } from "./oauth-providers.ts";
174
- export type { OAuthProviderStatus } from "./oauth-session.ts";
175
- export { OAuthProviderSession, oauthModelsCachePath } from "./oauth-session.ts";
176
- export {
177
- GROK_BUILD_BASE_URL,
178
- GROK_BUILD_MODELS_URL,
179
- GROK_CLIENT_VERSION,
180
- grokBuildBaselineModels,
181
- grokBuildFingerprintHeaders,
182
- grokBuildProvider,
183
- grokBuildReasoningMap,
184
- } from "./provider.ts";
185
- export type { CodingOAuthProxyOptions } from "./proxy.ts";
186
- export {
187
- codingOAuthProxyInEffect,
188
- codingOAuthProxyUnreachableHint,
189
- ensureCodingOAuthProxy,
190
- ensureGrokBuildProxy,
191
- grokBuildProxyInEffect,
192
- } from "./proxy.ts";
193
- export { redactProxyUrl, safeMessage } from "./redact.ts";
194
- export { GrokBuildSession } from "./session.ts";
195
- export {
196
- GrokBuildCredentialStore,
197
- grokBuildAuthPath,
198
- OAuthCredentialFileStore,
199
- oauthCredentialPath,
200
- } from "./store.ts";
201
-
202
- /** Stable Cordis plugin name. */
203
- export const name = "llm-grok-build-oauth";
204
-
205
- /** Separate API-key credential used only by official xAI Imagine REST calls. */
206
- export const XAI_API_KEY_CREDENTIAL = "XAI_API_KEY";
207
- /** Validate locally because `credentialRef()` is a value export of the optional credentials peer. */
208
- const XAI_API_KEY_REF = fixedCredentialRef(XAI_API_KEY_CREDENTIAL);
209
-
210
- function fixedCredentialRef(value: string): CredentialRef {
211
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(value)) {
212
- throw new TypeError(`invalid credential reference ${JSON.stringify(value)}`);
213
- }
214
- return value as CredentialRef;
215
- }
216
-
217
- /** Owner-private artifact directory below the resolved DSH home. */
218
- export const IMAGINE_MEDIA_STORE_DIRNAME = ".dsh-coding-subscription-oauth-media";
219
-
220
- /** LLM registry required before the subscription route can register. */
221
- export const inject = ["llm"];
222
-
223
- /** Plugin configuration; every field is optional. */
224
- export interface Config {
225
- /** HTTP(S) proxy URL for the audited coding-subscription host allowlist. */
226
- proxy?: string;
227
- /** Kimi China traffic stays direct unless explicitly opted into the proxy. */
228
- proxyKimi?: boolean;
229
- /**
230
- * Optional provider retry policy override for the four OAuth routes. When
231
- * omitted, the plugin retries transient failures (rate limit, server,
232
- * timeout, transport, empty response) plus AUTH — the latter is safe because
233
- * the stored credential is invalidated on every AUTH finish, so the retried
234
- * step refreshes before reuse. Quota exhaustion is never retried.
235
- */
236
- retryPolicy?: RetryPolicyConfig;
237
- /** Secret-free composition/YAML defaults below live user settings. */
238
- capabilities?: CapabilitySettingsPatch;
239
- /** Opt-in isolated local OpenAI-compatible gateway. Default off. */
240
- gateway?: Partial<GatewayConfig>;
241
- }
242
-
243
- export const Config: z<Config> = z.object({
244
- proxy: z.string(),
245
- proxyKimi: z.boolean().default(false),
246
- retryPolicy: RetryPolicySchema,
247
- capabilities: CapabilitySettingsSchema,
248
- gateway: GatewayConfigSchema,
249
- });
250
-
251
- const CODEX_TOOL_NAMES = new Set<string>([CODEX_IMAGE_GENERATE_TOOL, CODEX_IMAGE_EDIT_TOOL]);
252
- const IMAGINE_TOOL_NAMES = new Set<string>([
253
- GROK_IMAGINE_IMAGE_TOOL,
254
- GROK_IMAGINE_VIDEO_TOOL,
255
- GROK_IMAGINE_VIDEO_STATUS_TOOL,
256
- ]);
257
-
258
- function requireSubscription(
259
- subscriptions: readonly OAuthProviderSession[],
260
- nativeProviderId: string,
261
- ): OAuthProviderSession {
262
- const session = subscriptions.find((candidate) => candidate.definition.nativeProviderId === nativeProviderId);
263
- if (session === undefined) throw new Error(`missing built-in OAuth provider ${nativeProviderId}`);
264
- return session;
265
- }
266
-
267
- function asSourceCredential(credential: Credential | undefined): OAuthSourceCredential | undefined {
268
- if (credential === undefined) return undefined;
269
- if (credential.type !== "oauth") throw new Error("OAuth import destination contains a non-OAuth credential");
270
- const accountId =
271
- typeof credential.accountId === "string" && credential.accountId.length > 0 ? credential.accountId : undefined;
272
- return {
273
- type: "oauth",
274
- access: credential.access,
275
- refresh: credential.refresh,
276
- expires: credential.expires,
277
- ...(accountId === undefined ? {} : { accountId }),
278
- };
279
- }
280
-
281
- function asStoredCredential(credential: OAuthSourceCredential): OAuthCredential {
282
- return {
283
- type: "oauth",
284
- access: credential.access,
285
- refresh: credential.refresh,
286
- expires: credential.expires,
287
- ...(credential.accountId === undefined ? {} : { accountId: credential.accountId }),
288
- };
289
- }
290
-
291
- function oauthImportStore(store: OAuthCredentialFileStore): OAuthImportDestinationStore {
292
- return {
293
- filename: store.filename,
294
- async modify(providerId, fn) {
295
- const result = await store.modify(providerId, async (current) => {
296
- const next = await fn(asSourceCredential(current));
297
- return next === undefined ? current : asStoredCredential(next);
298
- });
299
- return asSourceCredential(result);
300
- },
301
- };
302
- }
303
-
304
- function oauthImportDestinations(
305
- grok: GrokBuildSession,
306
- subscriptions: readonly OAuthProviderSession[],
307
- ): OAuthImportDestinations {
308
- const codex = requireSubscription(subscriptions, CODEX_PI_PROVIDER);
309
- const kimi = requireSubscription(subscriptions, KIMI_PI_PROVIDER);
310
- const claude = requireSubscription(subscriptions, CLAUDE_PI_PROVIDER);
311
- return {
312
- grok: { providerId: XAI_PI_PROVIDER, store: oauthImportStore(grok.store) },
313
- codex: { providerId: codex.definition.nativeProviderId, store: oauthImportStore(codex.store) },
314
- kimi: { providerId: kimi.definition.nativeProviderId, store: oauthImportStore(kimi.store) },
315
- claude: { providerId: claude.definition.nativeProviderId, store: oauthImportStore(claude.store) },
316
- };
317
- }
318
-
319
- async function describeImagineCredential(credentials: CredentialProvider | undefined): Promise<CredentialInfo> {
320
- if (credentials === undefined) return { configured: false, writable: false };
321
- return credentials.describe(XAI_API_KEY_REF);
322
- }
323
-
324
- async function resolveImagineApiKey(credentials: CredentialProvider, operation: ImagineOperation): Promise<string> {
325
- const resolved = await credentials.resolve(XAI_API_KEY_REF);
326
- if (resolved === undefined) {
327
- throw new GrokImagineError(
328
- "MISSING_CREDENTIAL",
329
- `${XAI_API_KEY_CREDENTIAL} is not configured for ${operation}. Grok Imagine does not use OAuth.`,
330
- );
331
- }
332
- return assertUsableApiKey(resolved.value, "dsh-coding-subscription-oauth", XAI_API_KEY_CREDENTIAL);
333
- }
334
-
335
- function unavailableImagineClient(): {
336
- generateImage(): Promise<never>;
337
- startVideo(): Promise<never>;
338
- videoStatus(): Promise<never>;
339
- } {
340
- const unavailable = async (): Promise<never> => {
341
- throw new GrokImagineError("MISSING_CREDENTIAL", "Grok Imagine services are not composed");
342
- };
343
- return { generateImage: unavailable, startVideo: unavailable, videoStatus: unavailable };
344
- }
345
-
346
- /**
347
- * Register the `grok-build` LLM route with a provider-native OAuth store.
348
- * @param ctx - plugin context carrying the LLM registry plus optional web server.
349
- */
350
- export function apply(ctx: Context, config: Config): void {
351
- ensureCodingOAuthProxy(config.proxy, config.proxyKimi === undefined ? {} : { proxyKimi: config.proxyKimi });
352
- const logger = ctx.logger(name);
353
- const baseCapabilities = resolveCapabilitySettings(config.capabilities);
354
- const runtime = new CapabilityRuntimeState(baseCapabilities, () => {
355
- logger.warn("an optional capability listener failed");
1
+ /**
2
+ * Optional xAI Grok Build bundle with OAuth, account model catalog,
3
+ * and an account section inside dsh Settings.
4
+ * @module dsh-coding-subscription-oauth
5
+ */
6
+
7
+ import { dirname, join } from "node:path";
8
+ import type { Context, Fiber } from "@deepseek-ai/cordis";
9
+ import type { AttachmentStore } from "@deepseek-ai/dsh-attachment";
10
+ import type { CredentialInfo, CredentialProvider, CredentialRef } from "@deepseek-ai/dsh-credentials";
11
+ import type {} from "@deepseek-ai/dsh-host-webserver";
12
+ import { assertUsableApiKey, type RetryPolicyConfig, RetryPolicySchema } from "@deepseek-ai/dsh-llm";
13
+ import z from "@deepseek-ai/schemastery";
14
+ import type { Credential, OAuthCredential } from "@earendil-works/pi-ai";
15
+ import { acquireCodingOAuthRuntime, CODING_OAUTH_CORE_ABI, type CodingOAuthRuntime } from "dsh-coding-oauth-core";
16
+ import { createCodingOAuthAdapter } from "./adapter.ts";
17
+ import { registerCodingOAuthRoutes } from "./auth-routes.ts";
18
+ import { registerCapabilityRoutes } from "./capability-routes.ts";
19
+ import {
20
+ bindCapabilitySearch,
21
+ bindCapabilityTools,
22
+ bindCodexFastRoute,
23
+ CapabilityRuntimeState,
24
+ type CapabilitySearchRegistry,
25
+ type CapabilityToolRegistry,
26
+ } from "./capability-runtime.ts";
27
+ import {
28
+ type CapabilitySettingsPatch,
29
+ CapabilitySettingsSchema,
30
+ type CapabilitySettingsService,
31
+ createCapabilitySettingsController,
32
+ resolveCapabilitySettings,
33
+ } from "./capability-settings.ts";
34
+ import {
35
+ CODEX_IMAGE_EDIT_TOOL,
36
+ CODEX_IMAGE_GENERATE_TOOL,
37
+ createCapabilityTools,
38
+ type ResolveCodexImageRoute,
39
+ resolveCodexImageRouteFromLlm,
40
+ } from "./capability-tools.ts";
41
+ import { codexAuthFromSession } from "./codex-http.ts";
42
+ import { createCodexModelCapabilities } from "./codex-model-capabilities.ts";
43
+ import { createCodexSearchProvider } from "./codex-search.ts";
44
+ import { createCodexUsageReader } from "./codex-usage.ts";
45
+ import { createDshHostAdapter } from "./dsh-host-adapter.ts";
46
+ import { createCodingOAuthGatewayController } from "./gateway.ts";
47
+ import { type GatewayConfig, GatewayConfigSchema } from "./gateway-config.ts";
48
+ import { registerGatewayRoutes } from "./gateway-routes.ts";
49
+ import {
50
+ createGrokImagineClient,
51
+ GROK_IMAGINE_IMAGE_TOOL,
52
+ GROK_IMAGINE_VIDEO_STATUS_TOOL,
53
+ GROK_IMAGINE_VIDEO_TOOL,
54
+ GrokImagineError,
55
+ type ImagineOperation,
56
+ } from "./grok-imagine.ts";
57
+ import {
58
+ CLAUDE_PI_PROVIDER,
59
+ CODEX_PI_PROVIDER,
60
+ CODING_OAUTH_ROUTES,
61
+ IMAGINE_MEDIA_STORE_DIRNAME,
62
+ KIMI_PI_PROVIDER,
63
+ XAI_PI_PROVIDER,
64
+ } from "./ids.ts";
65
+ import { registerImagineRoutes } from "./imagine-routes.ts";
66
+ import { MediaStore } from "./media-store.ts";
67
+ import {
68
+ type OAuthImportDestinationStore,
69
+ type OAuthImportDestinations,
70
+ registerOAuthImportRoutes,
71
+ } from "./oauth-import-routes.ts";
72
+ import { OAUTH_PROVIDER_DEFINITIONS } from "./oauth-providers.ts";
73
+ import { OAuthProviderSession } from "./oauth-session.ts";
74
+ import type { OAuthSourceCredential } from "./oauth-sources.ts";
75
+ import { acquireCodingOAuthProxy } from "./proxy.ts";
76
+ import { GrokBuildSession } from "./session.ts";
77
+ import { GrokBuildCredentialStore, type OAuthCredentialFileStore } from "./store.ts";
78
+ import { createOwnerRequestPolicy, safeguardOwnerRequestPolicy } from "./web-origin.ts";
79
+
80
+ export type {
81
+ CodingOAuthParticipant,
82
+ CodingOAuthRuntime,
83
+ DshHostCapabilities,
84
+ OwnerRequestPolicy as CoreOwnerRequestPolicy,
85
+ } from "dsh-coding-oauth-core";
86
+ export {
87
+ acquireCodingOAuthRuntime,
88
+ CODING_OAUTH_CORE_ABI,
89
+ } from "dsh-coding-oauth-core";
90
+ export { createCodingOAuthAdapter, createGrokBuildAdapter, preferredGrokBuildModel } from "./adapter.ts";
91
+ export type { AliasLlmRoutePolicy } from "./alias-adapter.ts";
92
+ export { AliasLlmAdapter } from "./alias-adapter.ts";
93
+ export type { GrokBuildAuthStatus } from "./auth.ts";
94
+ export {
95
+ grokBuildAuthStatus,
96
+ importGrokBuildFromGrok,
97
+ importGrokBuildSession,
98
+ loginGrokBuild,
99
+ loginGrokBuildSession,
100
+ logoutGrokBuild,
101
+ } from "./auth.ts";
102
+ export type {
103
+ CodingOAuthWebStatus,
104
+ GrokBuildLoginMethod,
105
+ GrokBuildWebAuthStatus,
106
+ LoginChallenge,
107
+ SubscriptionLoginChallenge,
108
+ SubscriptionWebAuthStatus,
109
+ } from "./auth-routes.ts";
110
+ export {
111
+ CODING_OAUTH_LOGIN_CANCEL_PATH,
112
+ CODING_OAUTH_LOGIN_CODE_PATH,
113
+ CODING_OAUTH_LOGIN_PATH,
114
+ CODING_OAUTH_LOGOUT_PATH,
115
+ CODING_OAUTH_MODELS_PATH,
116
+ CODING_OAUTH_STATUS_PATH,
117
+ GROK_BUILD_AUTH_IMPORT_PATH,
118
+ GROK_BUILD_AUTH_LOGIN_CANCEL_PATH,
119
+ GROK_BUILD_AUTH_LOGIN_CODE_PATH,
120
+ GROK_BUILD_AUTH_LOGIN_PATH,
121
+ GROK_BUILD_AUTH_LOGOUT_PATH,
122
+ GROK_BUILD_AUTH_MODELS_PATH,
123
+ GROK_BUILD_AUTH_STATUS_PATH,
124
+ GrokBuildWebAuth,
125
+ registerCodingOAuthRoutes,
126
+ registerGrokBuildAuthRoutes,
127
+ SubscriptionWebAuth,
128
+ } from "./auth-routes.ts";
129
+ export type { CatalogSource, LiveModelDescriptor } from "./catalog.ts";
130
+ export {
131
+ extractLiveModels,
132
+ extractModelIds,
133
+ fetchLiveModelIds,
134
+ fetchLiveModels,
135
+ materializeLiveModel,
136
+ mergeLiveCatalog,
137
+ preferredGrokBuildModelFrom,
138
+ thinkingLevelMapFromLiveEfforts,
139
+ } from "./catalog.ts";
140
+ export { createDshHostAdapter } from "./dsh-host-adapter.ts";
141
+ export type { GrokImportProbe } from "./grok-import.ts";
142
+ export { grokAuthPath, importGrokAuth, parseGrokAuthDocument, probeGrokAuth } from "./grok-import.ts";
143
+ export type { CodingOAuthProviderSlug, CodingOAuthRoute } from "./ids.ts";
144
+ export {
145
+ ANTIGRAVITY_ROUTE,
146
+ CLAUDE_CODE_OAUTH_AUTH_FILENAME,
147
+ CLAUDE_CODE_OAUTH_MODELS_CACHE_FILENAME,
148
+ CLAUDE_CODE_OAUTH_ROUTE,
149
+ CLAUDE_PI_PROVIDER,
150
+ CODEX_OAUTH_AUTH_FILENAME,
151
+ CODEX_OAUTH_MODELS_CACHE_FILENAME,
152
+ CODEX_OAUTH_ROUTE,
153
+ CODEX_PI_PROVIDER,
154
+ CODING_OAUTH_ROUTES,
155
+ DEFAULT_GROK_BUILD_MODEL,
156
+ GROK_BUILD_AUTH_FILENAME,
157
+ GROK_BUILD_MODELS_CACHE_FILENAME,
158
+ GROK_BUILD_ROUTE,
159
+ GROK_BUILD_STREAM_IDLE_TIMEOUT_MS,
160
+ KIMI_CODE_OAUTH_AUTH_FILENAME,
161
+ KIMI_CODE_OAUTH_MODELS_CACHE_FILENAME,
162
+ KIMI_CODE_OAUTH_ROUTE,
163
+ KIMI_PI_PROVIDER,
164
+ XAI_PI_PROVIDER,
165
+ } from "./ids.ts";
166
+ export type { GrokBuildOAuthErrorCode, GrokBuildOAuthParams, PkceLoginCallbacks } from "./oauth.ts";
167
+ export {
168
+ buildAuthorizeUrl,
169
+ discoverOAuthEndpoints,
170
+ extractCode,
171
+ GROK_BUILD_OAUTH_CLIENT_ID,
172
+ GROK_BUILD_OAUTH_DEFAULT_PORT,
173
+ GROK_BUILD_OAUTH_ISSUER,
174
+ GROK_BUILD_OAUTH_SCOPE,
175
+ GrokBuildOAuthError,
176
+ generatePkce,
177
+ loginGrokBuildPkce,
178
+ refreshGrokBuildToken,
179
+ resolveOAuthParams,
180
+ } from "./oauth.ts";
181
+ export type { OAuthProviderDefinition, SubscriptionLoginMethod, SubscriptionProviderSlug } from "./oauth-providers.ts";
182
+ export {
183
+ CLAUDE_CODE_OAUTH_PROVIDER,
184
+ CODEX_OAUTH_PROVIDER,
185
+ KIMI_CODE_OAUTH_PROVIDER,
186
+ OAUTH_PROVIDER_DEFINITIONS,
187
+ oauthProviderDefinition,
188
+ } from "./oauth-providers.ts";
189
+ export type { OAuthProviderStatus } from "./oauth-session.ts";
190
+ export { OAuthProviderSession, oauthModelsCachePath } from "./oauth-session.ts";
191
+ export {
192
+ GROK_BUILD_BASE_URL,
193
+ GROK_BUILD_MODELS_URL,
194
+ GROK_CLIENT_VERSION,
195
+ grokBuildBaselineModels,
196
+ grokBuildFingerprintHeaders,
197
+ grokBuildProvider,
198
+ grokBuildReasoningMap,
199
+ } from "./provider.ts";
200
+ export type { CodingOAuthProxyOptions } from "./proxy.ts";
201
+ export {
202
+ codingOAuthProxyInEffect,
203
+ codingOAuthProxyUnreachableHint,
204
+ ensureCodingOAuthProxy,
205
+ ensureGrokBuildProxy,
206
+ grokBuildProxyInEffect,
207
+ } from "./proxy.ts";
208
+ export { redactProxyUrl, safeMessage } from "./redact.ts";
209
+ export { GrokBuildSession } from "./session.ts";
210
+ export {
211
+ GrokBuildCredentialStore,
212
+ grokBuildAuthPath,
213
+ OAuthCredentialFileStore,
214
+ oauthCredentialPath,
215
+ } from "./store.ts";
216
+ export type { OwnerRequestPolicy, OwnerRequestPolicyConfig } from "./web-origin.ts";
217
+ export {
218
+ createOwnerRequestPolicy,
219
+ LOOPBACK_OWNER_REQUEST_POLICY,
220
+ OWNER_CSRF_HEADER,
221
+ OWNER_PROOF_HEADER,
222
+ } from "./web-origin.ts";
223
+
224
+ /** Stable Cordis plugin name. */
225
+ export const name = "llm-grok-build-oauth";
226
+
227
+ /** Separate API-key credential used only by official xAI Imagine REST calls. */
228
+ export const XAI_API_KEY_CREDENTIAL = "XAI_API_KEY";
229
+ /** Validate locally because `credentialRef()` is a value export of the optional credentials peer. */
230
+ const XAI_API_KEY_REF = fixedCredentialRef(XAI_API_KEY_CREDENTIAL);
231
+
232
+ function fixedCredentialRef(value: string): CredentialRef {
233
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(value)) {
234
+ throw new TypeError(`invalid credential reference ${JSON.stringify(value)}`);
235
+ }
236
+ return value as CredentialRef;
237
+ }
238
+
239
+ /** Owner-private artifact directory below the resolved DSH home. */
240
+ export { IMAGINE_MEDIA_STORE_DIRNAME } from "./ids.ts";
241
+
242
+ /** Optional host services are acquired inside the elected child fiber. */
243
+ export const inject = ["webServer"] as const;
244
+
245
+ /** Plugin configuration; every field is optional. */
246
+ export interface Config {
247
+ /** HTTP(S) proxy URL for the audited coding-subscription host allowlist. */
248
+ proxy?: string;
249
+ /** Kimi China traffic stays direct unless explicitly opted into the proxy. */
250
+ proxyKimi?: boolean;
251
+ /**
252
+ * Optional provider retry policy override for the four OAuth routes. When
253
+ * omitted, the plugin retries transient failures (rate limit, server,
254
+ * timeout, transport, empty response) plus AUTH — the latter is safe because
255
+ * the stored credential is invalidated on every AUTH finish, so the retried
256
+ * step refreshes before reuse. Quota exhaustion is never retried.
257
+ */
258
+ retryPolicy?: RetryPolicyConfig;
259
+ /** Secret-free composition/YAML defaults below live user settings. */
260
+ capabilities?: CapabilitySettingsPatch;
261
+ /** Opt-in isolated local OpenAI-compatible gateway. Default off. */
262
+ gateway?: Partial<GatewayConfig>;
263
+ /** Owner-only request authorization for loopback, SSH tunnels, and trusted HTTPS proxies. */
264
+ ownerRequest?: {
265
+ loopbackAccessMode?: "loopback" | "ssh-tunnel";
266
+ trustedProxy?: {
267
+ peers?: string[];
268
+ origins?: string[];
269
+ ownerProof?: string;
270
+ csrfToken?: string;
271
+ };
272
+ };
273
+ }
274
+
275
+ export const Config: z<Config> = z.object({
276
+ proxy: z.string(),
277
+ proxyKimi: z.boolean().default(false),
278
+ retryPolicy: RetryPolicySchema,
279
+ capabilities: CapabilitySettingsSchema,
280
+ gateway: GatewayConfigSchema,
281
+ ownerRequest: z.object({
282
+ loopbackAccessMode: z.union([z.const("loopback"), z.const("ssh-tunnel")]),
283
+ trustedProxy: z.object({
284
+ peers: z.array(z.string()),
285
+ origins: z.array(z.string()),
286
+ ownerProof: z.string(),
287
+ csrfToken: z.string(),
288
+ }),
289
+ }),
290
+ });
291
+
292
+ const CODEX_TOOL_NAMES = new Set<string>([CODEX_IMAGE_GENERATE_TOOL, CODEX_IMAGE_EDIT_TOOL]);
293
+ const IMAGINE_TOOL_NAMES = new Set<string>([
294
+ GROK_IMAGINE_IMAGE_TOOL,
295
+ GROK_IMAGINE_VIDEO_TOOL,
296
+ GROK_IMAGINE_VIDEO_STATUS_TOOL,
297
+ ]);
298
+
299
+ function requireSubscription(
300
+ subscriptions: readonly OAuthProviderSession[],
301
+ nativeProviderId: string,
302
+ ): OAuthProviderSession {
303
+ const session = subscriptions.find((candidate) => candidate.definition.nativeProviderId === nativeProviderId);
304
+ if (session === undefined) throw new Error(`missing built-in OAuth provider ${nativeProviderId}`);
305
+ return session;
306
+ }
307
+
308
+ function asSourceCredential(credential: Credential | undefined): OAuthSourceCredential | undefined {
309
+ if (credential === undefined) return undefined;
310
+ if (credential.type !== "oauth") throw new Error("OAuth import destination contains a non-OAuth credential");
311
+ const accountId =
312
+ typeof credential.accountId === "string" && credential.accountId.length > 0 ? credential.accountId : undefined;
313
+ return {
314
+ type: "oauth",
315
+ access: credential.access,
316
+ refresh: credential.refresh,
317
+ expires: credential.expires,
318
+ ...(accountId === undefined ? {} : { accountId }),
319
+ };
320
+ }
321
+
322
+ function asStoredCredential(credential: OAuthSourceCredential): OAuthCredential {
323
+ return {
324
+ type: "oauth",
325
+ access: credential.access,
326
+ refresh: credential.refresh,
327
+ expires: credential.expires,
328
+ ...(credential.accountId === undefined ? {} : { accountId: credential.accountId }),
329
+ };
330
+ }
331
+
332
+ function oauthImportStore(store: OAuthCredentialFileStore): OAuthImportDestinationStore {
333
+ return {
334
+ filename: store.filename,
335
+ async modify(providerId, fn) {
336
+ const result = await store.modify(providerId, async (current) => {
337
+ const next = await fn(asSourceCredential(current));
338
+ return next === undefined ? current : asStoredCredential(next);
339
+ });
340
+ return asSourceCredential(result);
341
+ },
342
+ };
343
+ }
344
+
345
+ function oauthImportDestinations(
346
+ grok: GrokBuildSession,
347
+ subscriptions: readonly OAuthProviderSession[],
348
+ ): OAuthImportDestinations {
349
+ const codex = requireSubscription(subscriptions, CODEX_PI_PROVIDER);
350
+ const kimi = requireSubscription(subscriptions, KIMI_PI_PROVIDER);
351
+ const claude = requireSubscription(subscriptions, CLAUDE_PI_PROVIDER);
352
+ return {
353
+ grok: { providerId: XAI_PI_PROVIDER, store: oauthImportStore(grok.store) },
354
+ codex: { providerId: codex.definition.nativeProviderId, store: oauthImportStore(codex.store) },
355
+ kimi: { providerId: kimi.definition.nativeProviderId, store: oauthImportStore(kimi.store) },
356
+ claude: { providerId: claude.definition.nativeProviderId, store: oauthImportStore(claude.store) },
357
+ };
358
+ }
359
+
360
+ async function describeImagineCredential(credentials: CredentialProvider | undefined): Promise<CredentialInfo> {
361
+ if (credentials === undefined) return { configured: false, writable: false };
362
+ return credentials.describe(XAI_API_KEY_REF);
363
+ }
364
+
365
+ async function resolveImagineApiKey(credentials: CredentialProvider, operation: ImagineOperation): Promise<string> {
366
+ const resolved = await credentials.resolve(XAI_API_KEY_REF);
367
+ if (resolved === undefined) {
368
+ throw new GrokImagineError(
369
+ "MISSING_CREDENTIAL",
370
+ `${XAI_API_KEY_CREDENTIAL} is not configured for ${operation}. Grok Imagine does not use OAuth.`,
371
+ );
372
+ }
373
+ return assertUsableApiKey(resolved.value, "dsh-coding-subscription-oauth", XAI_API_KEY_CREDENTIAL);
374
+ }
375
+
376
+ function unavailableImagineClient(): {
377
+ generateImage(): Promise<never>;
378
+ startVideo(): Promise<never>;
379
+ videoStatus(): Promise<never>;
380
+ } {
381
+ const unavailable = async (): Promise<never> => {
382
+ throw new GrokImagineError("MISSING_CREDENTIAL", "Grok Imagine services are not composed");
383
+ };
384
+ return { generateImage: unavailable, startVideo: unavailable, videoStatus: unavailable };
385
+ }
386
+
387
+ /**
388
+ * Register the `grok-build` LLM route with a provider-native OAuth store.
389
+ * @param ctx - plugin context carrying the LLM registry plus optional web server.
390
+ */
391
+ export function apply(ctx: Context, config: Config = {}): void {
392
+ const host = createDshHostAdapter(ctx);
393
+ const lease: CodingOAuthRuntime = acquireCodingOAuthRuntime(host.scope(), {
394
+ id: "dsh-coding-subscription-oauth",
395
+ role: "standalone",
396
+ coreAbi: CODING_OAUTH_CORE_ABI,
397
+ async activate() {
398
+ let fiber: Fiber | undefined;
399
+ let ownerMounted = false;
400
+ fiber = ctx.inject([], async (injected) => {
401
+ await applyOwned(injected, config);
402
+ ownerMounted = true;
403
+ return () => {
404
+ ownerMounted = false;
405
+ };
406
+ });
407
+ try {
408
+ await fiber.await();
409
+ if (!ownerMounted) throw new Error("standalone Coding OAuth owner fiber did not activate");
410
+ } catch (error) {
411
+ try {
412
+ await fiber.dispose();
413
+ } catch {
414
+ // Preserve the startup error; Cordis already logs cleanup failures.
415
+ }
416
+ throw error;
417
+ }
418
+ return {
419
+ async dispose() {
420
+ await fiber?.dispose();
421
+ },
422
+ };
423
+ },
424
+ });
425
+ ctx.effect(() => () => lease.release(), "dsh-coding-subscription-oauth: release shared runtime ownership");
426
+ }
427
+
428
+ /**
429
+ * Owner runtime that survives optional LLM service churn. OAuth sessions and
430
+ * same-origin Web routes are deliberately owned here, rather than by the LLM
431
+ * child fiber, so a transient LLM unload cannot make account recovery vanish.
432
+ */
433
+ async function applyOwned(ctx: Context, config: Config): Promise<void> {
434
+ const host = createDshHostAdapter(ctx);
435
+ const ownerRequestPolicy = safeguardOwnerRequestPolicy(
436
+ host.ownerRequestPolicy() ?? createOwnerRequestPolicy(config.ownerRequest),
437
+ );
438
+ const proxyLease = acquireCodingOAuthProxy(
439
+ config.proxy,
440
+ config.proxyKimi === undefined ? {} : { proxyKimi: config.proxyKimi },
441
+ );
442
+ ctx.effect(() => () => proxyLease.release(), "dsh-coding-subscription-oauth: scoped proxy policy");
443
+ const logger = ctx.logger(name);
444
+ const baseCapabilities = resolveCapabilitySettings(config.capabilities);
445
+ const runtime = new CapabilityRuntimeState(baseCapabilities, () => {
446
+ logger.warn("an optional capability listener failed");
447
+ });
448
+ let active = true;
449
+ ctx.effect(
450
+ () => () => {
451
+ active = false;
452
+ },
453
+ "dsh-coding-subscription-oauth: startup lifetime",
454
+ );
455
+ let invalidateOptionalAuthState = (): void => undefined;
456
+ const notifyCatalogChange = (): void => {
457
+ if (!active) return;
458
+ try {
459
+ ctx.emit("llm/adapters-updated");
460
+ } catch (error) {
461
+ // Catalog observers are advisory; a broken listener must not turn an
462
+ // already-persisted OAuth login/logout into an apparent auth failure.
463
+ logger.warn("an llm/adapters-updated listener failed");
464
+ logger.warn(error);
465
+ }
466
+ };
467
+ const grok = new GrokBuildSession(new GrokBuildCredentialStore(), notifyCatalogChange);
468
+ const subscriptions = OAUTH_PROVIDER_DEFINITIONS.map(
469
+ (definition) =>
470
+ new OAuthProviderSession(definition, () => {
471
+ if (definition.nativeProviderId === CODEX_PI_PROVIDER) invalidateOptionalAuthState();
472
+ notifyCatalogChange();
473
+ }),
474
+ );
475
+ const codex = requireSubscription(subscriptions, CODEX_PI_PROVIDER);
476
+ const codexAuth = codexAuthFromSession(codex);
477
+ const usage = createCodexUsageReader({ auth: codexAuth });
478
+ const codexModels = createCodexModelCapabilities({ auth: codexAuth });
479
+ invalidateOptionalAuthState = () => {
480
+ usage.clear();
481
+ codexModels.clear();
482
+ runtime.refresh();
483
+ };
484
+
485
+ void Promise.allSettled([grok.loadCachedCatalog(), ...subscriptions.map((session) => session.loadCachedModels())])
486
+ .then(async (results) => {
487
+ if (!active) return;
488
+ if (results.some((result) => result.status === "rejected")) {
489
+ logger.warn("one or more OAuth model caches could not be loaded; using in-memory fallbacks");
490
+ }
491
+ await grok.refreshLiveCatalog();
492
+ })
493
+ .catch(() => {
494
+ // Contain every startup refresh failure so plugin activation cannot leave
495
+ // an unhandled rejection. The static provider catalogs remain usable.
496
+ if (active) logger.warn("background OAuth model catalog initialization failed; using static fallbacks");
497
+ });
498
+
499
+ let settingsOwner = 0;
500
+ const createFallbackCapabilityController = (): ReturnType<typeof createCapabilitySettingsController> =>
501
+ createCapabilitySettingsController({
502
+ ...(config.capabilities === undefined ? {} : { base: config.capabilities }),
503
+ onListenerError: () => logger.warn("a capability settings listener failed"),
504
+ });
505
+ let capabilityController = createFallbackCapabilityController();
506
+ const capabilityRoutesController = {
507
+ snapshot: () => capabilityController.snapshot(),
508
+ current: () => capabilityController.current(),
509
+ patch: (patch: CapabilitySettingsPatch, expectedRevision: number) =>
510
+ capabilityController.patch(patch, expectedRevision),
511
+ replace: (section: CapabilitySettingsPatch, expectedRevision: number) =>
512
+ capabilityController.replace(section, expectedRevision),
513
+ };
514
+ let releaseActiveSettings = (): void => undefined;
515
+ ctx.effect(
516
+ () => () => {
517
+ releaseActiveSettings();
518
+ capabilityController.dispose();
519
+ },
520
+ "dsh-coding-subscription-oauth: capability settings bridge",
521
+ );
522
+ ctx.inject(["settings"], (settingsCtx) => {
523
+ // Re-injection may happen before Cordis runs the previous child effect's
524
+ // disposer. Release it synchronously so an obsolete watcher cannot race a
525
+ // newly attached settings service.
526
+ releaseActiveSettings();
527
+ const owner = ++settingsOwner;
528
+ const previousController = capabilityController;
529
+ const controller = createCapabilitySettingsController({
530
+ settings: settingsCtx.get("settings") as CapabilitySettingsService,
531
+ ...(config.capabilities === undefined ? {} : { base: config.capabilities }),
532
+ onListenerError: () => logger.warn("a capability settings listener failed"),
533
+ });
534
+ capabilityController = controller;
535
+ previousController.dispose();
536
+ runtime.set(controller.current());
537
+ const unsubscribe = controller.subscribe((snapshot) => {
538
+ runtime.set(snapshot.value);
539
+ });
540
+ let released = false;
541
+ const release = (): void => {
542
+ if (released) return;
543
+ released = true;
544
+ unsubscribe();
545
+ controller.dispose();
546
+ if (owner === settingsOwner) {
547
+ releaseActiveSettings = (): void => undefined;
548
+ capabilityController = createFallbackCapabilityController();
549
+ runtime.set(capabilityController.current());
550
+ }
551
+ };
552
+ releaseActiveSettings = release;
553
+ settingsCtx.effect(() => release, "dsh-coding-subscription-oauth: capability settings");
554
+ });
555
+
556
+ const gateway = createCodingOAuthGatewayController({
557
+ ...(config.gateway === undefined ? {} : { config: config.gateway }),
558
+ grok,
559
+ subscriptions,
560
+ onError: (error) => {
561
+ logger.warn("local API gateway failed to start; LLM routes are unchanged");
562
+ logger.warn(error);
563
+ },
564
+ });
565
+ ctx.effect(() => {
566
+ void gateway.startIfEnabled().then((started) => {
567
+ if (started !== undefined) {
568
+ logger.warn("local API gateway is enabled; exposing a subscription as a local API can violate provider ToS");
569
+ }
570
+ });
571
+ return () => gateway.stop();
572
+ }, "dsh-coding-subscription-oauth: local API gateway");
573
+
574
+ registerCapabilityRoutes(ctx, {
575
+ controller: capabilityRoutesController,
576
+ usage: () => usage.read(),
577
+ credentialInfo: () => describeImagineCredential(ctx.get("credentials") as CredentialProvider | undefined),
578
+ ownerRequestPolicy,
356
579
  });
357
- let active = true;
358
- ctx.effect(
359
- () => () => {
360
- active = false;
361
- },
362
- "dsh-coding-subscription-oauth: startup lifetime",
363
- );
364
- let invalidateOptionalAuthState = (): void => undefined;
365
- const notifyCatalogChange = (): void => {
366
- if (!active) return;
367
- try {
368
- ctx.emit("llm/adapters-updated");
369
- } catch (error) {
370
- // Catalog observers are advisory; a broken listener must not turn an
371
- // already-persisted OAuth login/logout into an apparent auth failure.
372
- logger.warn("an llm/adapters-updated listener failed");
373
- logger.warn(error);
374
- }
375
- };
376
- const grok = new GrokBuildSession(new GrokBuildCredentialStore(), notifyCatalogChange);
377
- const subscriptions = OAUTH_PROVIDER_DEFINITIONS.map(
378
- (definition) =>
379
- new OAuthProviderSession(definition, () => {
380
- if (definition.nativeProviderId === CODEX_PI_PROVIDER) invalidateOptionalAuthState();
381
- notifyCatalogChange();
382
- }),
383
- );
384
- const codex = requireSubscription(subscriptions, CODEX_PI_PROVIDER);
385
- const codexAuth = codexAuthFromSession(codex);
386
- const usage = createCodexUsageReader({ auth: codexAuth });
387
- const codexModels = createCodexModelCapabilities({ auth: codexAuth });
388
- const resolveCodexImageRoute: ResolveCodexImageRoute = (exec) =>
389
- resolveCodexImageRouteFromLlm(exec, (provider, model, signal) => ctx.llm.resolveModelInfo(provider, model, signal));
390
- invalidateOptionalAuthState = () => {
391
- usage.clear();
392
- codexModels.clear();
393
- runtime.refresh();
394
- };
395
- const adapterRegistration = ctx.llm.registerAdapter(
396
- [...CODING_OAUTH_ROUTES],
397
- createCodingOAuthAdapter(grok, subscriptions, () => ctx.get("attachments"), config.retryPolicy, {
398
- codexFast: {
399
- isEligible: (modelId) => runtime.current().codexFast && codexModels.isPriorityEligible(modelId),
400
- },
580
+ registerGatewayRoutes(ctx, gateway, ownerRequestPolicy);
581
+ registerCodingOAuthRoutes(ctx, grok, subscriptions, ownerRequestPolicy, (accessMode) =>
582
+ host.compatibility({
583
+ accessMode,
584
+ uiOwner: "standalone",
585
+ diagnostics: ownerRequestPolicy.diagnostics(),
401
586
  }),
402
587
  );
403
- ctx.effect(
404
- () =>
405
- bindCodexFastRoute(runtime, codexModels, adapterRegistration, {
406
- onError: () => logger.warn("Codex Fast eligibility refresh failed closed"),
407
- }),
408
- "dsh-coding-subscription-oauth: Codex Fast route",
409
- );
410
-
411
- void Promise.allSettled([grok.loadCachedCatalog(), ...subscriptions.map((session) => session.loadCachedModels())])
412
- .then(async (results) => {
413
- if (!active) return;
414
- if (results.some((result) => result.status === "rejected")) {
415
- logger.warn("one or more OAuth model caches could not be loaded; using in-memory fallbacks");
416
- }
417
- await grok.refreshLiveCatalog();
418
- })
419
- .catch(() => {
420
- // Contain every startup refresh failure so plugin activation cannot leave
421
- // an unhandled rejection. The static provider catalogs remain usable.
422
- if (active) logger.warn("background OAuth model catalog initialization failed; using static fallbacks");
423
- });
424
-
425
- let settingsOwner = 0;
426
- let releaseActiveSettings = (): void => undefined;
427
- ctx.effect(() => () => releaseActiveSettings(), "dsh-coding-subscription-oauth: capability settings bridge");
428
- ctx.inject(["settings"], (settingsCtx) => {
429
- // Re-injection may happen before Cordis runs the previous child effect's
430
- // disposer. Release it synchronously so an obsolete watcher cannot race a
431
- // newly attached settings service.
432
- releaseActiveSettings();
433
- const owner = ++settingsOwner;
434
- const controller = createCapabilitySettingsController({
435
- settings: settingsCtx.get("settings") as CapabilitySettingsService,
436
- ...(config.capabilities === undefined ? {} : { base: config.capabilities }),
437
- onListenerError: () => logger.warn("a capability settings listener failed"),
438
- });
439
- runtime.set(controller.current());
440
- const unsubscribe = controller.subscribe((snapshot) => {
441
- runtime.set(snapshot.value);
442
- });
443
- let released = false;
444
- const release = (): void => {
445
- if (released) return;
446
- released = true;
447
- unsubscribe();
448
- controller.dispose();
449
- if (owner === settingsOwner) {
450
- releaseActiveSettings = (): void => undefined;
451
- runtime.set(baseCapabilities);
452
- }
453
- };
454
- releaseActiveSettings = release;
455
- settingsCtx.effect(() => release, "dsh-coding-subscription-oauth: capability settings");
456
- settingsCtx.inject(["webServer"], (webCtx) => {
457
- registerCapabilityRoutes(webCtx, {
458
- controller,
459
- usage: () => usage.read(),
460
- credentialInfo: () => describeImagineCredential(webCtx.get("credentials") as CredentialProvider | undefined),
461
- });
462
- });
463
- });
464
-
465
- const gateway = createCodingOAuthGatewayController({
466
- ...(config.gateway === undefined ? {} : { config: config.gateway }),
467
- grok,
468
- subscriptions,
469
- onError: (error) => {
470
- logger.warn("local API gateway failed to start; LLM routes are unchanged");
471
- logger.warn(error);
588
+ registerOAuthImportRoutes(ctx, oauthImportDestinations(grok, subscriptions), {
589
+ ownerRequestPolicy,
590
+ onImported: (event) => {
591
+ if (event.kind === "codex") invalidateOptionalAuthState();
592
+ notifyCatalogChange();
472
593
  },
473
594
  });
474
- ctx.effect(() => {
475
- void gateway.startIfEnabled().then((started) => {
476
- if (started !== undefined) {
477
- logger.warn("local API gateway is enabled; exposing a subscription as a local API can violate provider ToS");
478
- }
479
- });
480
- return () => {
481
- void gateway.stop();
482
- };
483
- }, "dsh-coding-subscription-oauth: local API gateway");
484
-
485
- ctx.inject(["webServer"], (webCtx) => {
486
- registerGatewayRoutes(webCtx, gateway);
487
- registerCodingOAuthRoutes(webCtx, grok, subscriptions);
488
- registerOAuthImportRoutes(webCtx, oauthImportDestinations(grok, subscriptions), {
489
- onImported: (event) => {
490
- if (event.kind === "codex") invalidateOptionalAuthState();
491
- notifyCatalogChange();
492
- },
493
- });
494
- });
495
-
496
- const search = createCodexSearchProvider({
497
- auth: codexAuth,
498
- // Login, import, model selection, and catalog refreshes can all change the
499
- // first visible Codex model after plugin startup.
500
- model: () => codex.visibleModels()[0]?.id ?? "",
501
- });
502
- ctx.inject(["web"], (webCtx) => {
503
- const web = webCtx.get("web") as CapabilitySearchRegistry;
504
- webCtx.effect(() => bindCapabilitySearch(runtime, web, search), "dsh-coding-subscription-oauth: Codex search");
505
- });
506
-
507
- ctx.inject(["tools", "attachments"], async (toolCtx) => {
508
- const tools = toolCtx.get("tools") as CapabilityToolRegistry;
509
- const attachments = toolCtx.get("attachments") as AttachmentStore;
510
- const definitions = (
511
- await createCapabilityTools({
512
- current: () => runtime.current(),
513
- auth: codexAuth,
514
- attachments,
515
- imagine: unavailableImagineClient(),
516
- resolveCodexImageRoute,
517
- })
518
- ).filter((definition) => CODEX_TOOL_NAMES.has(definition.name));
519
- toolCtx.effect(
520
- () => bindCapabilityTools(runtime, tools, definitions),
521
- "dsh-coding-subscription-oauth: Codex image tools",
522
- );
523
- });
524
-
525
- ctx.inject(["tools", "attachments", "credentials", "webServer"], async (toolCtx) => {
526
- const tools = toolCtx.get("tools") as CapabilityToolRegistry;
527
- const attachments = toolCtx.get("attachments") as AttachmentStore;
528
- const credentials = toolCtx.get("credentials") as CredentialProvider;
529
- const media = new MediaStore(join(dirname(grok.store.filename), IMAGINE_MEDIA_STORE_DIRNAME), {
530
- retentionMs: runtime.current().videoArtifactTtlMs,
531
- });
532
- const routeRegistry = registerImagineRoutes(toolCtx, {
533
- attachments,
534
- media: { readForDownload: (artifactId, authz) => media.openDownload(artifactId, authz) },
535
- });
536
- const imagine = createGrokImagineClient({
537
- resolveApiKey: (operation) => resolveImagineApiKey(credentials, operation),
538
- attachments,
539
- media,
540
- });
541
- const routedImagine = {
542
- async generateImage(input: Parameters<typeof imagine.generateImage>[0], signal?: AbortSignal) {
543
- const result = await imagine.generateImage(input, signal);
544
- if (runtime.current().grokImagineImage) {
545
- routeRegistry.rememberImages(result.images.map((image) => image.attachment));
546
- }
547
- return result;
548
- },
549
- startVideo: (input: Parameters<typeof imagine.startVideo>[0], signal?: AbortSignal) =>
550
- imagine.startVideo(input, signal),
551
- async videoStatus(requestId: string, options?: Parameters<typeof imagine.videoStatus>[1]) {
552
- const result = await imagine.videoStatus(requestId, options);
553
- if (result.artifact !== undefined && runtime.current().grokImagineVideo) {
554
- routeRegistry.rememberArtifact(result.artifact);
555
- }
556
- return result;
557
- },
558
- };
559
- const definitions = (
560
- await createCapabilityTools({
561
- current: () => runtime.current(),
562
- auth: codexAuth,
563
- attachments,
564
- imagine: routedImagine,
565
- resolveCodexImageRoute,
566
- })
567
- ).filter((definition) => IMAGINE_TOOL_NAMES.has(definition.name));
568
- let previousSettings = runtime.current();
569
- const releaseRetention = runtime.subscribe((settings) => {
570
- const previous = previousSettings;
571
- previousSettings = settings;
572
- if (previous.grokImagineImage && !settings.grokImagineImage) routeRegistry.revokeImages();
573
- if (previous.grokImagineVideo && !settings.grokImagineVideo) routeRegistry.revokeArtifacts();
574
- return media
575
- .applyRetentionMs(settings.videoArtifactTtlMs)
576
- .then(() => undefined)
577
- .catch(() => logger.warn("Imagine media retention cleanup failed"));
578
- });
579
- toolCtx.effect(
580
- () => bindCapabilityTools(runtime, tools, definitions),
581
- "dsh-coding-subscription-oauth: Grok Imagine tools",
582
- );
583
- toolCtx.effect(
584
- () => async () => {
585
- // Abort new/in-flight work before cleanup regardless of Cordis disposer
586
- // ordering. GrokImagineClient.dispose() is intentionally idempotent.
587
- imagine.dispose();
588
- releaseRetention();
589
- try {
590
- await media.cleanup();
591
- } catch {
592
- logger.warn("Imagine media cleanup failed");
593
- }
594
- },
595
- "dsh-coding-subscription-oauth: Imagine client and media lifetime",
596
- );
597
- });
595
+
596
+ const search = createCodexSearchProvider({
597
+ auth: codexAuth,
598
+ // Login, import, model selection, and catalog refreshes can all change the
599
+ // first visible Codex model after plugin startup.
600
+ model: () => codex.visibleModels()[0]?.id ?? "",
601
+ });
602
+ ctx.inject(["web"], (webCtx) => {
603
+ const web = webCtx.get("web") as CapabilitySearchRegistry;
604
+ webCtx.effect(() => bindCapabilitySearch(runtime, web, search), "dsh-coding-subscription-oauth: Codex search");
605
+ });
606
+
607
+ ctx.inject(["tools", "attachments", "credentials", "webServer"], async (toolCtx) => {
608
+ const tools = toolCtx.get("tools") as CapabilityToolRegistry;
609
+ const attachments = toolCtx.get("attachments") as AttachmentStore;
610
+ const credentials = toolCtx.get("credentials") as CredentialProvider;
611
+ const media = new MediaStore(join(dirname(grok.store.filename), IMAGINE_MEDIA_STORE_DIRNAME), {
612
+ retentionMs: runtime.current().videoArtifactTtlMs,
613
+ });
614
+ const routeRegistry = registerImagineRoutes(toolCtx, {
615
+ attachments,
616
+ media: { readForDownload: (artifactId, authz) => media.openDownload(artifactId, authz) },
617
+ ownerRequestPolicy,
618
+ });
619
+ const imagine = createGrokImagineClient({
620
+ resolveApiKey: (operation) => resolveImagineApiKey(credentials, operation),
621
+ attachments,
622
+ media,
623
+ });
624
+ const routedImagine = {
625
+ async generateImage(input: Parameters<typeof imagine.generateImage>[0], signal?: AbortSignal) {
626
+ const result = await imagine.generateImage(input, signal);
627
+ if (runtime.current().grokImagineImage) {
628
+ routeRegistry.rememberImages(result.images.map((image) => image.attachment));
629
+ }
630
+ return result;
631
+ },
632
+ startVideo: (input: Parameters<typeof imagine.startVideo>[0], signal?: AbortSignal) =>
633
+ imagine.startVideo(input, signal),
634
+ async videoStatus(requestId: string, options?: Parameters<typeof imagine.videoStatus>[1]) {
635
+ const result = await imagine.videoStatus(requestId, options);
636
+ if (result.artifact !== undefined && runtime.current().grokImagineVideo) {
637
+ routeRegistry.rememberArtifact(result.artifact);
638
+ }
639
+ return result;
640
+ },
641
+ };
642
+ const definitions = (
643
+ await createCapabilityTools({
644
+ current: () => runtime.current(),
645
+ auth: codexAuth,
646
+ attachments,
647
+ imagine: routedImagine,
648
+ })
649
+ ).filter((definition) => IMAGINE_TOOL_NAMES.has(definition.name));
650
+ let previousSettings = runtime.current();
651
+ const releaseRetention = runtime.subscribe((settings) => {
652
+ const previous = previousSettings;
653
+ previousSettings = settings;
654
+ if (previous.grokImagineImage && !settings.grokImagineImage) routeRegistry.revokeImages();
655
+ if (previous.grokImagineVideo && !settings.grokImagineVideo) routeRegistry.revokeArtifacts();
656
+ return media
657
+ .applyRetentionMs(settings.videoArtifactTtlMs)
658
+ .then(() => undefined)
659
+ .catch(() => logger.warn("Imagine media retention cleanup failed"));
660
+ });
661
+ toolCtx.effect(
662
+ () => bindCapabilityTools(runtime, tools, definitions),
663
+ "dsh-coding-subscription-oauth: Grok Imagine tools",
664
+ );
665
+ toolCtx.effect(
666
+ () => async () => {
667
+ // Abort new/in-flight work before cleanup regardless of Cordis disposer
668
+ // ordering. GrokImagineClient.dispose() is intentionally idempotent.
669
+ imagine.dispose();
670
+ releaseRetention();
671
+ try {
672
+ await media.cleanup();
673
+ } catch {
674
+ logger.warn("Imagine media cleanup failed");
675
+ }
676
+ },
677
+ "dsh-coding-subscription-oauth: Imagine client and media lifetime",
678
+ );
679
+ });
680
+
681
+ // Only adapters and LLM-backed model resolution depend on this service. Its
682
+ // child fiber may unload and reload without disturbing OAuth/Web ownership.
683
+ ctx.inject(["llm"], (llmCtx) =>
684
+ applyOwnedLlm(llmCtx, config, { grok, subscriptions, runtime, codexAuth, codexModels, logger }),
685
+ );
598
686
  }
687
+
688
+ interface OwnedLlmDependencies {
689
+ readonly grok: GrokBuildSession;
690
+ readonly subscriptions: readonly OAuthProviderSession[];
691
+ readonly runtime: CapabilityRuntimeState;
692
+ readonly codexAuth: ReturnType<typeof codexAuthFromSession>;
693
+ readonly codexModels: ReturnType<typeof createCodexModelCapabilities>;
694
+ readonly logger: ReturnType<Context["logger"]>;
695
+ }
696
+
697
+ /** LLM-only child runtime, independently restarted by Cordis when LLM changes. */
698
+ function applyOwnedLlm(ctx: Context, config: Config, owner: OwnedLlmDependencies): void {
699
+ createDshHostAdapter(ctx).assertCompatible();
700
+ const resolveCodexImageRoute: ResolveCodexImageRoute = (exec) =>
701
+ resolveCodexImageRouteFromLlm(exec, (provider, model, signal) => ctx.llm.resolveModelInfo(provider, model, signal));
702
+ const adapterRegistration = ctx.llm.registerAdapter(
703
+ [...CODING_OAUTH_ROUTES],
704
+ createCodingOAuthAdapter(owner.grok, owner.subscriptions, () => ctx.get("attachments"), config.retryPolicy, {
705
+ codexFast: {
706
+ isEligible: (modelId) => owner.runtime.current().codexFast && owner.codexModels.isPriorityEligible(modelId),
707
+ },
708
+ }),
709
+ );
710
+ ctx.effect(() => adapterRegistration, "dsh-coding-subscription-oauth: OAuth LLM adapters");
711
+ ctx.effect(
712
+ () =>
713
+ bindCodexFastRoute(owner.runtime, owner.codexModels, adapterRegistration, {
714
+ onError: () => owner.logger.warn("Codex Fast eligibility refresh failed closed"),
715
+ }),
716
+ "dsh-coding-subscription-oauth: Codex Fast route",
717
+ );
718
+ ctx.inject(["tools", "attachments"], async (toolCtx) => {
719
+ const tools = toolCtx.get("tools") as CapabilityToolRegistry;
720
+ const attachments = toolCtx.get("attachments") as AttachmentStore;
721
+ const definitions = (
722
+ await createCapabilityTools({
723
+ current: () => owner.runtime.current(),
724
+ auth: owner.codexAuth,
725
+ attachments,
726
+ imagine: unavailableImagineClient(),
727
+ resolveCodexImageRoute,
728
+ })
729
+ ).filter((definition) => CODEX_TOOL_NAMES.has(definition.name));
730
+ toolCtx.effect(
731
+ () => bindCapabilityTools(owner.runtime, tools, definitions),
732
+ "dsh-coding-subscription-oauth: Codex image tools",
733
+ );
734
+ });
735
+ }