dsh-coding-subscription-oauth 0.5.0
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.
- package/CHANGELOG.md +136 -0
- package/CONTRIBUTING.md +109 -0
- package/INSTALL.md +220 -0
- package/LICENSE +19 -0
- package/NOTICE +11 -0
- package/README.de.md +254 -0
- package/README.es.md +254 -0
- package/README.fr.md +254 -0
- package/README.ja.md +254 -0
- package/README.ko.md +254 -0
- package/README.md +286 -0
- package/README.pt-BR.md +254 -0
- package/README.ru.md +254 -0
- package/README.zh-CN.md +271 -0
- package/cordis.patch.yml +13 -0
- package/docs/00-project-rules.md +195 -0
- package/docs/02-architecture.md +132 -0
- package/docs/02-architecture.zh-CN.md +128 -0
- package/lib/adapter.d.ts +24 -0
- package/lib/adapter.d.ts.map +1 -0
- package/lib/alias-adapter.d.ts +43 -0
- package/lib/alias-adapter.d.ts.map +1 -0
- package/lib/auth-routes.d.ts +155 -0
- package/lib/auth-routes.d.ts.map +1 -0
- package/lib/auth.d.ts +29 -0
- package/lib/auth.d.ts.map +1 -0
- package/lib/bin.d.ts +6 -0
- package/lib/bin.d.ts.map +1 -0
- package/lib/bin.js +27591 -0
- package/lib/bin.js.map +7 -0
- package/lib/capability-routes.d.ts +43 -0
- package/lib/capability-routes.d.ts.map +1 -0
- package/lib/capability-runtime.d.ts +56 -0
- package/lib/capability-runtime.d.ts.map +1 -0
- package/lib/capability-settings.d.ts +263 -0
- package/lib/capability-settings.d.ts.map +1 -0
- package/lib/capability-tools.d.ts +50 -0
- package/lib/capability-tools.d.ts.map +1 -0
- package/lib/catalog.d.ts +53 -0
- package/lib/catalog.d.ts.map +1 -0
- package/lib/client.js +3 -0
- package/lib/client.js.map +7 -0
- package/lib/codex-http.d.ts +77 -0
- package/lib/codex-http.d.ts.map +1 -0
- package/lib/codex-images.d.ts +109 -0
- package/lib/codex-images.d.ts.map +1 -0
- package/lib/codex-model-capabilities.d.ts +112 -0
- package/lib/codex-model-capabilities.d.ts.map +1 -0
- package/lib/codex-search.d.ts +96 -0
- package/lib/codex-search.d.ts.map +1 -0
- package/lib/codex-usage.d.ts +79 -0
- package/lib/codex-usage.d.ts.map +1 -0
- package/lib/gateway-anthropic-messages.d.ts +8 -0
- package/lib/gateway-anthropic-messages.d.ts.map +1 -0
- package/lib/gateway-auth.d.ts +22 -0
- package/lib/gateway-auth.d.ts.map +1 -0
- package/lib/gateway-backend.d.ts +62 -0
- package/lib/gateway-backend.d.ts.map +1 -0
- package/lib/gateway-body.d.ts +9 -0
- package/lib/gateway-body.d.ts.map +1 -0
- package/lib/gateway-config.d.ts +24 -0
- package/lib/gateway-config.d.ts.map +1 -0
- package/lib/gateway-http.d.ts +16 -0
- package/lib/gateway-http.d.ts.map +1 -0
- package/lib/gateway-openai-chat.d.ts +8 -0
- package/lib/gateway-openai-chat.d.ts.map +1 -0
- package/lib/gateway-openai-responses.d.ts +8 -0
- package/lib/gateway-openai-responses.d.ts.map +1 -0
- package/lib/gateway-parse.d.ts +10 -0
- package/lib/gateway-parse.d.ts.map +1 -0
- package/lib/gateway-protocol.d.ts +47 -0
- package/lib/gateway-protocol.d.ts.map +1 -0
- package/lib/gateway-routes.d.ts +21 -0
- package/lib/gateway-routes.d.ts.map +1 -0
- package/lib/gateway.d.ts +48 -0
- package/lib/gateway.d.ts.map +1 -0
- package/lib/grok-imagine.d.ts +271 -0
- package/lib/grok-imagine.d.ts.map +1 -0
- package/lib/grok-import.d.ts +21 -0
- package/lib/grok-import.d.ts.map +1 -0
- package/lib/http-json.d.ts +10 -0
- package/lib/http-json.d.ts.map +1 -0
- package/lib/ids.d.ts +33 -0
- package/lib/ids.d.ts.map +1 -0
- package/lib/imagine-routes.d.ts +59 -0
- package/lib/imagine-routes.d.ts.map +1 -0
- package/lib/index.d.ts +69 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +35355 -0
- package/lib/index.js.map +7 -0
- package/lib/invariant.d.ts +9 -0
- package/lib/invariant.d.ts.map +1 -0
- package/lib/invariant.js +14 -0
- package/lib/invariant.js.map +7 -0
- package/lib/kimi-errors.d.ts +13 -0
- package/lib/kimi-errors.d.ts.map +1 -0
- package/lib/media-store.d.ts +130 -0
- package/lib/media-store.d.ts.map +1 -0
- package/lib/oauth-import-routes.d.ts +52 -0
- package/lib/oauth-import-routes.d.ts.map +1 -0
- package/lib/oauth-providers.d.ts +26 -0
- package/lib/oauth-providers.d.ts.map +1 -0
- package/lib/oauth-session.d.ts +40 -0
- package/lib/oauth-session.d.ts.map +1 -0
- package/lib/oauth-sources.d.ts +205 -0
- package/lib/oauth-sources.d.ts.map +1 -0
- package/lib/oauth.d.ts +79 -0
- package/lib/oauth.d.ts.map +1 -0
- package/lib/provider.d.ts +38 -0
- package/lib/provider.d.ts.map +1 -0
- package/lib/proxy.d.ts +17 -0
- package/lib/proxy.d.ts.map +1 -0
- package/lib/redact.d.ts +5 -0
- package/lib/redact.d.ts.map +1 -0
- package/lib/session.d.ts +40 -0
- package/lib/session.d.ts.map +1 -0
- package/lib/store.d.ts +46 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/web-origin.d.ts +10 -0
- package/lib/web-origin.d.ts.map +1 -0
- package/lib/web-routes.d.ts +20 -0
- package/lib/web-routes.d.ts.map +1 -0
- package/package.json +185 -0
- package/patches/dsh-agy@0.1.2.patch +25 -0
- package/scripts/release.mjs +166 -0
- package/scripts/smoke-deployed-routes.mjs +146 -0
- package/scripts/verify-deployed-catalog.mjs +87 -0
- package/src/adapter.ts +282 -0
- package/src/alias-adapter.ts +152 -0
- package/src/auth-routes.ts +871 -0
- package/src/auth.ts +67 -0
- package/src/bin.ts +350 -0
- package/src/capability-routes.ts +275 -0
- package/src/capability-runtime.ts +313 -0
- package/src/capability-settings.ts +657 -0
- package/src/capability-tools.ts +666 -0
- package/src/catalog.ts +271 -0
- package/src/client/GrokBuildSettings.tsx +2221 -0
- package/src/client/index.tsx +37 -0
- package/src/client/locales.ts +421 -0
- package/src/codex-http.ts +447 -0
- package/src/codex-images.ts +485 -0
- package/src/codex-model-capabilities.ts +320 -0
- package/src/codex-search.ts +245 -0
- package/src/codex-usage.ts +263 -0
- package/src/gateway-anthropic-messages.ts +84 -0
- package/src/gateway-auth.ts +100 -0
- package/src/gateway-backend.ts +274 -0
- package/src/gateway-body.ts +49 -0
- package/src/gateway-config.ts +76 -0
- package/src/gateway-http.ts +104 -0
- package/src/gateway-openai-chat.ts +124 -0
- package/src/gateway-openai-responses.ts +53 -0
- package/src/gateway-parse.ts +224 -0
- package/src/gateway-protocol.ts +52 -0
- package/src/gateway-routes.ts +152 -0
- package/src/gateway.ts +242 -0
- package/src/grok-imagine.ts +1627 -0
- package/src/grok-import.ts +151 -0
- package/src/http-json.ts +82 -0
- package/src/ids.ts +45 -0
- package/src/imagine-routes.ts +461 -0
- package/src/index.ts +598 -0
- package/src/invariant.ts +17 -0
- package/src/kimi-errors.ts +26 -0
- package/src/media-store.ts +927 -0
- package/src/oauth-import-routes.ts +314 -0
- package/src/oauth-providers.ts +152 -0
- package/src/oauth-session.ts +183 -0
- package/src/oauth-sources.ts +1104 -0
- package/src/oauth.ts +620 -0
- package/src/provider.ts +128 -0
- package/src/proxy.ts +99 -0
- package/src/redact.ts +72 -0
- package/src/session.ts +218 -0
- package/src/store.ts +217 -0
- package/src/web-origin.ts +60 -0
- package/src/web-routes.ts +75 -0
|
@@ -0,0 +1,320 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
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
|
+
}
|