dsh-coding-subscription-oauth 0.6.3 → 0.6.5

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 (127) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/CONTRIBUTING.md +13 -4
  3. package/INSTALL.md +7 -5
  4. package/README.de.md +6 -6
  5. package/README.es.md +6 -6
  6. package/README.fr.md +6 -6
  7. package/README.ja.md +6 -6
  8. package/README.ko.md +6 -6
  9. package/README.md +6 -6
  10. package/README.pt-BR.md +6 -6
  11. package/README.ru.md +6 -6
  12. package/README.zh-CN.md +6 -6
  13. package/docs/00-project-rules.md +4 -4
  14. package/docs/02-architecture.md +7 -3
  15. package/docs/02-architecture.zh-CN.md +7 -3
  16. package/lib/bin.js +1333 -569
  17. package/lib/bin.js.map +4 -4
  18. package/lib/client.js +1 -1
  19. package/lib/client.js.map +2 -2
  20. package/lib/gateway-protocol.d.ts +3 -46
  21. package/lib/gateway-protocol.d.ts.map +1 -1
  22. package/lib/gateway-routes.d.ts.map +1 -1
  23. package/lib/grok-errors.d.ts +2 -12
  24. package/lib/grok-errors.d.ts.map +1 -1
  25. package/lib/grok-imagine/client.d.ts +73 -0
  26. package/lib/grok-imagine/client.d.ts.map +1 -0
  27. package/lib/grok-imagine/index.d.ts +8 -0
  28. package/lib/grok-imagine/index.d.ts.map +1 -0
  29. package/lib/grok-imagine/net.d.ts +10 -0
  30. package/lib/grok-imagine/net.d.ts.map +1 -0
  31. package/lib/grok-imagine/parse.d.ts +20 -0
  32. package/lib/grok-imagine/parse.d.ts.map +1 -0
  33. package/lib/grok-imagine/types.d.ts +191 -0
  34. package/lib/grok-imagine/types.d.ts.map +1 -0
  35. package/lib/grok-imagine.d.ts +3 -263
  36. package/lib/grok-imagine.d.ts.map +1 -1
  37. package/lib/http-json.d.ts +2 -9
  38. package/lib/http-json.d.ts.map +1 -1
  39. package/lib/index.js +1395 -26178
  40. package/lib/index.js.map +4 -4
  41. package/lib/kimi-errors.d.ts +2 -12
  42. package/lib/kimi-errors.d.ts.map +1 -1
  43. package/lib/runtime/gateway-protocol.d.ts +47 -0
  44. package/lib/runtime/gateway-protocol.d.ts.map +1 -0
  45. package/lib/runtime/grok-errors.d.ts +13 -0
  46. package/lib/runtime/grok-errors.d.ts.map +1 -0
  47. package/lib/runtime/http-json.d.ts +10 -0
  48. package/lib/runtime/http-json.d.ts.map +1 -0
  49. package/lib/runtime/kimi-errors.d.ts +13 -0
  50. package/lib/runtime/kimi-errors.d.ts.map +1 -0
  51. package/package.json +12 -7
  52. package/scripts/release.mjs +1 -0
  53. package/src/adapter.ts +0 -348
  54. package/src/alias-adapter.ts +0 -147
  55. package/src/auth-routes.ts +0 -921
  56. package/src/auth.ts +0 -67
  57. package/src/bin.ts +0 -350
  58. package/src/capability-routes.ts +0 -279
  59. package/src/capability-runtime.ts +0 -314
  60. package/src/capability-settings.ts +0 -671
  61. package/src/capability-tools.ts +0 -685
  62. package/src/catalog.ts +0 -271
  63. package/src/client/GrokBuildSettings.tsx +0 -771
  64. package/src/client/api.ts +0 -88
  65. package/src/client/components/AboutTab.tsx +0 -30
  66. package/src/client/components/AccountsTab.tsx +0 -241
  67. package/src/client/components/Badge.tsx +0 -33
  68. package/src/client/components/CapabilitiesTab.tsx +0 -265
  69. package/src/client/components/CliPullPreview.tsx +0 -116
  70. package/src/client/components/CopyButton.tsx +0 -57
  71. package/src/client/components/GatewayTab.tsx +0 -469
  72. package/src/client/components/NoticeBanner.tsx +0 -46
  73. package/src/client/components/ProgressBar.tsx +0 -53
  74. package/src/client/components/ProviderCard.tsx +0 -606
  75. package/src/client/components/SettingsTabs.tsx +0 -75
  76. package/src/client/components/ToggleSwitch.tsx +0 -71
  77. package/src/client/constants.ts +0 -230
  78. package/src/client/display.ts +0 -61
  79. package/src/client/dshClientAdapter.ts +0 -127
  80. package/src/client/gatewaySnippets.ts +0 -37
  81. package/src/client/index.tsx +0 -156
  82. package/src/client/locales.ts +0 -540
  83. package/src/client/microStyles.ts +0 -52
  84. package/src/client/parsers.ts +0 -398
  85. package/src/client/styles.ts +0 -325
  86. package/src/client/types.ts +0 -199
  87. package/src/codex-http.ts +0 -447
  88. package/src/codex-images.ts +0 -503
  89. package/src/codex-model-capabilities.ts +0 -320
  90. package/src/codex-search.ts +0 -245
  91. package/src/codex-usage.ts +0 -263
  92. package/src/compatibility.ts +0 -55
  93. package/src/dsh-host-adapter.ts +0 -173
  94. package/src/gateway-anthropic-messages.ts +0 -84
  95. package/src/gateway-auth.ts +0 -102
  96. package/src/gateway-backend.ts +0 -274
  97. package/src/gateway-body.ts +0 -49
  98. package/src/gateway-config.ts +0 -76
  99. package/src/gateway-http.ts +0 -104
  100. package/src/gateway-openai-chat.ts +0 -124
  101. package/src/gateway-openai-responses.ts +0 -53
  102. package/src/gateway-parse.ts +0 -224
  103. package/src/gateway-protocol.ts +0 -52
  104. package/src/gateway-routes.ts +0 -158
  105. package/src/gateway.ts +0 -258
  106. package/src/grok-errors.ts +0 -24
  107. package/src/grok-imagine.ts +0 -1627
  108. package/src/grok-import.ts +0 -151
  109. package/src/http-json.ts +0 -82
  110. package/src/ids.ts +0 -59
  111. package/src/imagine-routes.ts +0 -463
  112. package/src/index.ts +0 -735
  113. package/src/invariant.ts +0 -17
  114. package/src/kimi-errors.ts +0 -26
  115. package/src/media-store.ts +0 -927
  116. package/src/oauth-import-routes.ts +0 -324
  117. package/src/oauth-providers.ts +0 -152
  118. package/src/oauth-session.ts +0 -183
  119. package/src/oauth-sources.ts +0 -1104
  120. package/src/oauth.ts +0 -620
  121. package/src/provider.ts +0 -128
  122. package/src/proxy.ts +0 -11
  123. package/src/redact.ts +0 -72
  124. package/src/session.ts +0 -218
  125. package/src/store.ts +0 -217
  126. package/src/web-origin.ts +0 -296
  127. package/src/web-routes.ts +0 -38
package/src/index.ts DELETED
@@ -1,735 +0,0 @@
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,
579
- });
580
- registerGatewayRoutes(ctx, gateway, ownerRequestPolicy);
581
- registerCodingOAuthRoutes(ctx, grok, subscriptions, ownerRequestPolicy, (accessMode) =>
582
- host.compatibility({
583
- accessMode,
584
- uiOwner: "standalone",
585
- diagnostics: ownerRequestPolicy.diagnostics(),
586
- }),
587
- );
588
- registerOAuthImportRoutes(ctx, oauthImportDestinations(grok, subscriptions), {
589
- ownerRequestPolicy,
590
- onImported: (event) => {
591
- if (event.kind === "codex") invalidateOptionalAuthState();
592
- notifyCatalogChange();
593
- },
594
- });
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
- );
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
- }