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
@@ -1,320 +0,0 @@
1
- /**
2
- * Live Codex model service-tier cache and composable fast-route payload helpers.
3
- *
4
- * Fetches `GET /backend-api/codex/models?client_version=…`, caches `service_tiers`,
5
- * and never invents eligibility when the live catalog is missing or stale.
6
- * A stale TTL is unknown: Fast is default-deny until a live, non-stale catalog
7
- * explicitly lists `priority` for that model. `isEligible` is required and
8
- * fail-closed — omitting it or returning false injects nothing.
9
- *
10
- * Ordinary inference stays unchanged: the unwrapped provider is never mutated.
11
- * A wrapper may use a distinct profile provider id (`codex-oauth-fast`) while
12
- * restoring native `model.provider` for the base wire call and the same catalog.
13
- *
14
- * @module dsh-coding-subscription-oauth/codex-model-capabilities
15
- */
16
-
17
- import {
18
- type CodexAuthSession,
19
- type CodexFetch,
20
- type CodexHttpClient,
21
- createCodexHttpClient,
22
- isRecord,
23
- optionalNonEmptyString,
24
- } from "./codex-http.ts";
25
- import { CODEX_OAUTH_FAST_ROUTE } from "./ids.ts";
26
-
27
- /** Distinct optional Harness route; parent owns dynamic registration. */
28
- export { CODEX_OAUTH_FAST_ROUTE };
29
-
30
- export const CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models";
31
- export const DEFAULT_CODEX_CLIENT_VERSION = "0.144.0";
32
- export const DEFAULT_CODEX_SERVICE_TIER = "priority";
33
- export const CODEX_ROUTING_HINT_HEADER = "x-codex-routing-hint";
34
-
35
- const DEFAULT_TTL_MS = 15 * 60 * 1000;
36
-
37
- export interface CodexModelCapability {
38
- readonly id: string;
39
- readonly serviceTiers: readonly string[];
40
- }
41
-
42
- export interface CodexModelCapabilitiesOptions {
43
- readonly auth: CodexAuthSession;
44
- readonly http?: CodexHttpClient;
45
- readonly fetchImpl?: CodexFetch;
46
- readonly clientVersion?: string;
47
- readonly originator?: string;
48
- readonly userAgent?: string;
49
- readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
50
- readonly now?: () => number;
51
- readonly ttlMs?: number;
52
- }
53
-
54
- export interface CodexModelCapabilities {
55
- refresh(signal?: AbortSignal): Promise<readonly CodexModelCapability[]>;
56
- clear(): void;
57
- getCached(): readonly CodexModelCapability[] | undefined;
58
- serviceTiers(modelId: string): readonly string[];
59
- isPriorityEligible(modelId: string): boolean;
60
- isTierEligible(modelId: string, tier: string): boolean;
61
- }
62
-
63
- export type CodexOnPayload = (payload: unknown, model: unknown) => unknown | undefined | Promise<unknown | undefined>;
64
-
65
- export interface CodexFastStreamOptions {
66
- onPayload?: CodexOnPayload;
67
- headers?: Record<string, string | null>;
68
- [key: string]: unknown;
69
- }
70
-
71
- /**
72
- * Fast-route composition is default-deny.
73
- * `isEligible` is required; missing or false means no header and no `service_tier`.
74
- */
75
- export interface CodexFastRoutingOptions {
76
- readonly isEligible: (modelId: string) => boolean;
77
- readonly serviceTier?: string;
78
- /** Distinct profile/route id for the wrapper (e.g. {@link CODEX_OAUTH_FAST_ROUTE}). */
79
- readonly profileProviderId?: string;
80
- /** Native provider id restored on `model.provider` before the base wire call. */
81
- readonly nativeProviderId?: string;
82
- }
83
-
84
- export interface CodexStreamModel {
85
- readonly id: string;
86
- readonly provider?: string;
87
- readonly [key: string]: unknown;
88
- }
89
-
90
- /** Structural pi-ai provider face; `never` parameters keep native Provider assignable. */
91
- export interface CodexStreamableProvider {
92
- readonly id: string;
93
- readonly headers?: Record<string, string | null>;
94
- stream: (model: never, context: never, options?: never) => unknown;
95
- streamSimple: (model: never, context: never, options?: never) => unknown;
96
- }
97
-
98
- /** Wrapper face with callable stream methods and a possibly distinct profile id. */
99
- export type CodexFastWrappedProvider<P extends CodexStreamableProvider> = Omit<
100
- P,
101
- "id" | "headers" | "stream" | "streamSimple"
102
- > & {
103
- readonly id: string;
104
- readonly headers?: Record<string, string | null>;
105
- stream: (model: CodexStreamModel, context: unknown, options?: CodexFastStreamOptions) => unknown;
106
- streamSimple: (model: CodexStreamModel, context: unknown, options?: CodexFastStreamOptions) => unknown;
107
- };
108
-
109
- function parseServiceTiers(value: unknown): string[] {
110
- if (!Array.isArray(value)) return [];
111
- const tiers: string[] = [];
112
- const seen = new Set<string>();
113
- for (const item of value) {
114
- const id =
115
- typeof item === "string"
116
- ? optionalNonEmptyString(item)
117
- : isRecord(item)
118
- ? optionalNonEmptyString(item["id"])
119
- : undefined;
120
- if (id === undefined || seen.has(id)) continue;
121
- seen.add(id);
122
- tiers.push(id);
123
- }
124
- return tiers;
125
- }
126
-
127
- /** Parse the live models envelope. Unknown shapes yield an empty catalog, never a hardcoded fallback. */
128
- export function parseCodexModelCapabilities(value: unknown): CodexModelCapability[] {
129
- if (!isRecord(value)) return [];
130
- const raw = value["models"];
131
- if (!Array.isArray(raw)) return [];
132
- const models: CodexModelCapability[] = [];
133
- const seen = new Set<string>();
134
- for (const item of raw) {
135
- if (!isRecord(item)) continue;
136
- const id = optionalNonEmptyString(item["slug"]) ?? optionalNonEmptyString(item["id"]);
137
- if (id === undefined || seen.has(id)) continue;
138
- seen.add(id);
139
- models.push({ id, serviceTiers: parseServiceTiers(item["service_tiers"]) });
140
- }
141
- return models;
142
- }
143
-
144
- export function codexModelsUrl(clientVersion: string): string {
145
- const url = new URL(CODEX_MODELS_URL);
146
- url.searchParams.set("client_version", clientVersion);
147
- return url.toString();
148
- }
149
-
150
- /** Exact per-model Fast header value. Never a bare static `priority`. */
151
- export function codexRoutingHint(modelId: string, tier = DEFAULT_CODEX_SERVICE_TIER): string {
152
- return `model=${modelId};tier=${tier}`;
153
- }
154
-
155
- function modelIdOf(payload: unknown, model: unknown): string | undefined {
156
- if (isRecord(model)) {
157
- const id = optionalNonEmptyString(model["id"]);
158
- if (id !== undefined) return id;
159
- }
160
- return isRecord(payload) ? optionalNonEmptyString(payload["model"]) : undefined;
161
- }
162
-
163
- function isFastEligible(options: CodexFastRoutingOptions | undefined, modelId: string): boolean {
164
- return options?.isEligible?.(modelId) === true;
165
- }
166
-
167
- function restoreNativeProvider(model: CodexStreamModel, nativeProviderId: string): CodexStreamModel {
168
- if (model.provider === nativeProviderId) return model;
169
- return { ...model, provider: nativeProviderId };
170
- }
171
-
172
- /**
173
- * Compose an existing `onPayload` with service_tier injection.
174
- * Does not override a payload that already set `service_tier`.
175
- * Fail-closed: injection happens only when `isEligible(modelId)` is exactly true.
176
- */
177
- export function composeCodexFastOnPayload(
178
- inner: CodexOnPayload | undefined,
179
- options: CodexFastRoutingOptions,
180
- ): CodexOnPayload {
181
- const serviceTier = options.serviceTier ?? DEFAULT_CODEX_SERVICE_TIER;
182
- return async (payload, model) => {
183
- const next = inner === undefined ? payload : await inner(payload, model);
184
- const body = next === undefined ? payload : next;
185
- if (!isRecord(body)) return next;
186
- const modelId = modelIdOf(body, model);
187
- if (modelId === undefined || !isFastEligible(options, modelId)) return next;
188
- if (optionalNonEmptyString(body["service_tier"]) !== undefined) return next;
189
- return { ...body, service_tier: serviceTier };
190
- };
191
- }
192
-
193
- /** Merge `x-codex-routing-hint=model=<slug>;tier=<tier>` without dropping existing keys. */
194
- export function composeCodexFastHeaders(
195
- headers: Record<string, string | null> | undefined,
196
- modelId: string,
197
- tier = DEFAULT_CODEX_SERVICE_TIER,
198
- ): Record<string, string | null> {
199
- return { ...(headers ?? {}), [CODEX_ROUTING_HINT_HEADER]: codexRoutingHint(modelId, tier) };
200
- }
201
-
202
- /** Apply fast-route payload + per-model header composition to one stream-options object. */
203
- export function applyCodexFastStreamOptions<T extends CodexFastStreamOptions>(
204
- options: T | undefined,
205
- config: CodexFastRoutingOptions,
206
- modelId: string,
207
- ): T {
208
- const eligible = isFastEligible(config, modelId);
209
- const tier = config.serviceTier ?? DEFAULT_CODEX_SERVICE_TIER;
210
- const onPayload = eligible
211
- ? composeCodexFastOnPayload(options?.onPayload, { ...config, isEligible: () => true })
212
- : options?.onPayload;
213
- const next: CodexFastStreamOptions = {
214
- ...(options ?? {}),
215
- ...(onPayload === undefined ? {} : { onPayload }),
216
- headers: eligible ? composeCodexFastHeaders(options?.headers, modelId, tier) : { ...(options?.headers ?? {}) },
217
- };
218
- return next as T;
219
- }
220
-
221
- /**
222
- * Wrap a pi-ai provider for a future `codex-oauth-fast` route.
223
- * The original provider object is not mutated. The wrapper may advertise a
224
- * distinct profile provider id while restoring native `model.provider` so the
225
- * base wire call and model catalog stay on the native provider.
226
- */
227
- export function withCodexFastRouting<P extends CodexStreamableProvider>(
228
- provider: P,
229
- options: CodexFastRoutingOptions,
230
- ): CodexFastWrappedProvider<P> {
231
- const nativeProviderId = options.nativeProviderId ?? provider.id;
232
- const profileProviderId = options.profileProviderId ?? provider.id;
233
-
234
- const forward =
235
- (method: "stream" | "streamSimple") =>
236
- (model: CodexStreamModel, context: unknown, streamOptions?: CodexFastStreamOptions) => {
237
- const wireModel = restoreNativeProvider(model, nativeProviderId);
238
- return provider[method](
239
- wireModel as never,
240
- context as never,
241
- applyCodexFastStreamOptions(streamOptions, options, model.id) as never,
242
- );
243
- };
244
-
245
- return {
246
- ...provider,
247
- id: profileProviderId,
248
- stream: forward("stream"),
249
- streamSimple: forward("streamSimple"),
250
- };
251
- }
252
-
253
- /**
254
- * Live `/codex/models` cache. Fetch failures leave ordinary inference alone.
255
- * Eligibility is false until a live, non-stale catalog explicitly lists the tier.
256
- * A stale TTL is treated as unknown, not as the last known catalog.
257
- */
258
- export function createCodexModelCapabilities(options: CodexModelCapabilitiesOptions): CodexModelCapabilities {
259
- const http =
260
- options.http ??
261
- createCodexHttpClient({
262
- auth: options.auth,
263
- ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
264
- ...(options.originator === undefined ? {} : { originator: options.originator }),
265
- ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
266
- ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
267
- ...(options.now === undefined ? {} : { now: options.now }),
268
- });
269
- const clientVersion = options.clientVersion ?? DEFAULT_CODEX_CLIENT_VERSION;
270
- const now = options.now ?? Date.now;
271
- const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
272
- let cached: { fetchedAt: number; models: readonly CodexModelCapability[] } | undefined;
273
- let inFlight: Promise<readonly CodexModelCapability[]> | undefined;
274
- let epoch = 0;
275
-
276
- const isFresh = (): boolean => cached !== undefined && now() - cached.fetchedAt < ttlMs;
277
-
278
- const freshModels = (): readonly CodexModelCapability[] | undefined => (isFresh() ? cached?.models : undefined);
279
-
280
- const lookup = (modelId: string): CodexModelCapability | undefined =>
281
- freshModels()?.find((model) => model.id === modelId);
282
-
283
- const load = async (startedEpoch: number, signal?: AbortSignal): Promise<readonly CodexModelCapability[]> => {
284
- try {
285
- const payload = await http.requestJson({
286
- url: codexModelsUrl(clientVersion),
287
- method: "GET",
288
- headers: { "cache-control": "no-store" },
289
- ...(signal === undefined ? {} : { signal }),
290
- });
291
- const models = parseCodexModelCapabilities(payload);
292
- if (startedEpoch === epoch) cached = { fetchedAt: now(), models };
293
- return models;
294
- } catch {
295
- return freshModels() ?? [];
296
- }
297
- };
298
-
299
- return {
300
- async refresh(signal) {
301
- if (isFresh() && cached !== undefined) return cached.models;
302
- if (inFlight !== undefined) return inFlight;
303
- const startedEpoch = epoch;
304
- const current = load(startedEpoch, signal).finally(() => {
305
- if (inFlight === current) inFlight = undefined;
306
- });
307
- inFlight = current;
308
- return current;
309
- },
310
- clear() {
311
- epoch += 1;
312
- cached = undefined;
313
- inFlight = undefined;
314
- },
315
- getCached: () => freshModels(),
316
- serviceTiers: (modelId) => lookup(modelId)?.serviceTiers ?? [],
317
- isPriorityEligible: (modelId) => lookup(modelId)?.serviceTiers.includes(DEFAULT_CODEX_SERVICE_TIER) === true,
318
- isTierEligible: (modelId, tier) => lookup(modelId)?.serviceTiers.includes(tier) === true,
319
- };
320
- }
@@ -1,245 +0,0 @@
1
- /**
2
- * Optional Codex subscription search against the private ChatGPT backend.
3
- * Default-off: parent registers the returned provider only when the user enables it.
4
- *
5
- * @module dsh-coding-subscription-oauth/codex-search
6
- */
7
-
8
- import { LlmError } from "@deepseek-ai/dsh-llm";
9
- import {
10
- type CodexAuthSession,
11
- type CodexFetch,
12
- type CodexHttpClient,
13
- createCodexHttpClient,
14
- isRecord,
15
- optionalNonEmptyString,
16
- } from "./codex-http.ts";
17
-
18
- /** Stable search-provider id. Parent must not write this into `web.searchProvider` by default. */
19
- export const CODEX_SEARCH_PROVIDER_ID = "codex-oauth-search";
20
-
21
- /** Official Codex standalone search endpoint. */
22
- export const CODEX_SEARCH_URL = "https://chatgpt.com/backend-api/codex/alpha/search";
23
-
24
- export const CODEX_SEARCH_CONTEXT_SIZES = ["low", "medium", "high"] as const;
25
- export type CodexSearchContextSize = (typeof CODEX_SEARCH_CONTEXT_SIZES)[number];
26
-
27
- export const CODEX_SEARCH_MODES = ["live", "cached", "indexed"] as const;
28
- export type CodexSearchMode = (typeof CODEX_SEARCH_MODES)[number];
29
-
30
- export type CodexExternalWebAccess = true | false | "indexed";
31
-
32
- export interface CodexSearchSource {
33
- readonly url: string;
34
- readonly title?: string;
35
- readonly snippet?: string;
36
- }
37
-
38
- export interface CodexSearchRequest {
39
- readonly query: string;
40
- readonly maxResults?: number;
41
- }
42
-
43
- export interface CodexSearchResult {
44
- readonly content?: string;
45
- readonly sources: readonly CodexSearchSource[];
46
- readonly truncated: boolean;
47
- }
48
-
49
- export interface CodexSearchRequestBody {
50
- readonly id: string;
51
- readonly model: string;
52
- readonly input: readonly [
53
- {
54
- readonly type: "message";
55
- readonly role: "user";
56
- readonly content: readonly [{ readonly type: "input_text"; readonly text: string }];
57
- },
58
- ];
59
- readonly commands: {
60
- readonly search_query: readonly [{ readonly q: string }];
61
- };
62
- readonly settings: {
63
- readonly search_context_size: CodexSearchContextSize;
64
- readonly allowed_callers: readonly ["direct"];
65
- readonly external_web_access: CodexExternalWebAccess;
66
- };
67
- readonly max_output_tokens: number;
68
- }
69
-
70
- export interface CodexSearchProviderOptions {
71
- readonly auth: CodexAuthSession;
72
- readonly http?: CodexHttpClient;
73
- readonly fetchImpl?: CodexFetch;
74
- /** Current visible Codex model, or a live resolver for catalog/login changes. */
75
- readonly model: string | (() => string);
76
- readonly mode?: CodexSearchMode;
77
- readonly contextSize?: CodexSearchContextSize;
78
- readonly maxOutputTokens?: number;
79
- readonly resolveRequestId?: () => string;
80
- readonly originator?: string;
81
- readonly userAgent?: string;
82
- readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
83
- }
84
-
85
- /** Structural `WebSearchProvider` so parent can register without this module importing dsh-web. */
86
- export interface CodexSearchProvider {
87
- readonly id: typeof CODEX_SEARCH_PROVIDER_ID;
88
- available(): boolean;
89
- search(request: CodexSearchRequest, signal?: AbortSignal): Promise<CodexSearchResult>;
90
- }
91
-
92
- const DEFAULT_CONTEXT_SIZE: CodexSearchContextSize = "medium";
93
- const DEFAULT_MODE: CodexSearchMode = "live";
94
- const DEFAULT_MAX_OUTPUT_TOKENS = 1024;
95
-
96
- /** Map configured search mode onto the verified `external_web_access` field. */
97
- export function externalWebAccess(mode: CodexSearchMode): CodexExternalWebAccess {
98
- switch (mode) {
99
- case "cached":
100
- return false;
101
- case "indexed":
102
- return "indexed";
103
- case "live":
104
- return true;
105
- }
106
- }
107
-
108
- /** Accept only citeable http(s) URLs. */
109
- export function citeableHttpUrl(value: unknown): string | undefined {
110
- if (typeof value !== "string" || value.length === 0) return undefined;
111
- try {
112
- const url = new URL(value);
113
- if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
114
- if (url.username !== "" || url.password !== "") return undefined;
115
- return value;
116
- } catch {
117
- return undefined;
118
- }
119
- }
120
-
121
- /** Reject `<1` / non-finite `maxResults` rather than treating them as unlimited. */
122
- export function assertCodexSearchMaxResults(maxResults: number | undefined): void {
123
- if (maxResults === undefined) return;
124
- if (!Number.isFinite(maxResults) || maxResults < 1) {
125
- throw new LlmError("Codex search maxResults must be a finite number of at least 1", "INVALID_ARGS");
126
- }
127
- }
128
-
129
- /**
130
- * Map the standalone endpoint's forward-compatible result DTOs.
131
- * Only `type === "text_result"` items with valid http(s) URLs are kept; URLs are de-duplicated.
132
- */
133
- export function mapCodexSearchResponse(value: unknown, maxResults?: number): CodexSearchResult {
134
- assertCodexSearchMaxResults(maxResults);
135
- if (!isRecord(value) || typeof value["output"] !== "string") {
136
- throw new LlmError("Codex returned a search response without string output", "SERVER");
137
- }
138
- const output = value["output"];
139
- const rawResults = value["results"];
140
- if (rawResults !== undefined && !Array.isArray(rawResults)) {
141
- throw new LlmError("Codex returned a search response with non-array results", "SERVER");
142
- }
143
- const sources: CodexSearchSource[] = [];
144
- const seen = new Set<string>();
145
- for (const item of rawResults ?? []) {
146
- if (!isRecord(item) || item["type"] !== "text_result") continue;
147
- const url = citeableHttpUrl(item["url"]);
148
- if (url === undefined || seen.has(url)) continue;
149
- seen.add(url);
150
- const title = optionalNonEmptyString(item["title"]);
151
- const snippet = optionalNonEmptyString(item["snippet"]);
152
- sources.push({
153
- url,
154
- ...(title === undefined ? {} : { title }),
155
- ...(snippet === undefined ? {} : { snippet }),
156
- });
157
- }
158
- const limited = maxResults === undefined ? sources : sources.slice(0, maxResults);
159
- return {
160
- ...(output.length === 0 ? {} : { content: output }),
161
- sources: limited,
162
- truncated: limited.length < sources.length,
163
- };
164
- }
165
-
166
- export function buildCodexSearchRequestBody(
167
- query: string,
168
- options: {
169
- id: string;
170
- model: string;
171
- mode: CodexSearchMode;
172
- contextSize: CodexSearchContextSize;
173
- maxOutputTokens: number;
174
- },
175
- ): CodexSearchRequestBody {
176
- return {
177
- id: options.id,
178
- model: options.model,
179
- input: [
180
- {
181
- type: "message",
182
- role: "user",
183
- content: [{ type: "input_text", text: query }],
184
- },
185
- ],
186
- commands: { search_query: [{ q: query }] },
187
- settings: {
188
- search_context_size: options.contextSize,
189
- allowed_callers: ["direct"],
190
- external_web_access: externalWebAccess(options.mode),
191
- },
192
- max_output_tokens: options.maxOutputTokens,
193
- };
194
- }
195
-
196
- /** Factory for an injectable, default-off Codex search provider. */
197
- export function createCodexSearchProvider(options: CodexSearchProviderOptions): CodexSearchProvider {
198
- const http =
199
- options.http ??
200
- createCodexHttpClient({
201
- auth: options.auth,
202
- ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
203
- ...(options.originator === undefined ? {} : { originator: options.originator }),
204
- ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
205
- ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
206
- });
207
- const mode = options.mode ?? DEFAULT_MODE;
208
- const contextSize = options.contextSize ?? DEFAULT_CONTEXT_SIZE;
209
- const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
210
- const resolveRequestId = options.resolveRequestId ?? (() => crypto.randomUUID());
211
- const configuredModel = options.model;
212
- const resolveModel: () => string = typeof configuredModel === "function" ? configuredModel : () => configuredModel;
213
- const available = (): boolean =>
214
- resolveModel().trim().length > 0 && Number.isInteger(maxOutputTokens) && maxOutputTokens > 0;
215
-
216
- return {
217
- id: CODEX_SEARCH_PROVIDER_ID,
218
- available,
219
- async search(request, signal) {
220
- const query = request.query.trim();
221
- if (query.length === 0) {
222
- throw new LlmError("Codex search requires a non-empty query", "INVALID_ARGS");
223
- }
224
- assertCodexSearchMaxResults(request.maxResults);
225
- const model = resolveModel().trim();
226
- if (model.length === 0 || !Number.isInteger(maxOutputTokens) || maxOutputTokens <= 0) {
227
- throw new LlmError("Codex search is not configured", "INVALID_ARGS");
228
- }
229
- const body = buildCodexSearchRequestBody(query, {
230
- id: resolveRequestId(),
231
- model,
232
- mode,
233
- contextSize,
234
- maxOutputTokens,
235
- });
236
- const payload = await http.requestJson({
237
- url: CODEX_SEARCH_URL,
238
- method: "POST",
239
- body,
240
- ...(signal === undefined ? {} : { signal }),
241
- });
242
- return mapCodexSearchResponse(payload, request.maxResults);
243
- },
244
- };
245
- }