pi-openai-toolkit 0.23.1 → 0.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +6 -2
  4. package/README.zh.md +6 -2
  5. package/config.schema.json +278 -278
  6. package/docs/configuration.md +306 -298
  7. package/docs/internals.md +184 -181
  8. package/package.json +136 -135
  9. package/src/compact-client.ts +412 -412
  10. package/src/compaction-projection.ts +35 -35
  11. package/src/config/migration.ts +103 -103
  12. package/src/config.ts +310 -310
  13. package/src/context-management/codex-provider.ts +270 -270
  14. package/src/context-management/history-notes.ts +357 -357
  15. package/src/context-management/manual-compact.ts +247 -599
  16. package/src/context-management/scoped-compaction.ts +89 -0
  17. package/src/context-management/tools.ts +371 -371
  18. package/src/context-management/types.ts +168 -168
  19. package/src/context-management/window-manager.ts +912 -905
  20. package/src/debug.ts +238 -238
  21. package/src/deferred-tool-carryover.ts +282 -282
  22. package/src/details-store.ts +151 -151
  23. package/src/extension-runtime.ts +1919 -1986
  24. package/src/image-generation/extension.ts +189 -189
  25. package/src/image-generation/protocol.ts +579 -579
  26. package/src/image-generation/types.ts +300 -300
  27. package/src/native-fallback.ts +32 -29
  28. package/src/payload-rewrite.ts +515 -515
  29. package/src/pi-context-hook.ts +117 -117
  30. package/src/remote-v2-client.ts +811 -811
  31. package/src/request-context-cache.ts +155 -155
  32. package/src/responses-headers.ts +180 -180
  33. package/src/runtime.ts +865 -865
  34. package/src/serializer.ts +882 -882
  35. package/src/supported-environment.ts +27 -27
  36. package/src/types.ts +565 -565
  37. package/src/web-search/alpha-client.ts +876 -876
  38. package/src/web-search/extension.ts +530 -530
  39. package/src/web-search/payload.ts +299 -299
  40. package/src/web-search/prompt.ts +60 -60
  41. package/src/web-search/types.ts +166 -166
  42. package/tsconfig.check.json +50 -50
@@ -1,270 +1,270 @@
1
- import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai";
2
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { mergeProviderHeaders } from "../provider-headers";
4
- import {
5
- CODEX_AFFINITY_SCOPE,
6
- CODEX_CLIENT_VERSION,
7
- CODEX_GATEWAY_ORIGINATOR,
8
- buildCodexCliUserAgent,
9
- filterCodexGatewayHeaders,
10
- } from "../responses-headers";
11
- export { CODEX_AFFINITY_SCOPE } from "../responses-headers";
12
- import { normalizeBaseUrl, resolveEffectiveModel, VIRTUAL_MODEL_API } from "../runtime";
13
- import { isExactModelAllowed } from "../model-scope";
14
- import {
15
- isNonEmptyString,
16
- type CodexContextProvider,
17
- type CodexContextProviderResolution,
18
- } from "./types";
19
-
20
- const CODEX_PROVIDER = "openai-codex";
21
- const CODEX_API = "openai-codex-responses";
22
- const GATEWAY_API = "openai-responses";
23
- const CODEX_TOOL_ORIGINATOR = CODEX_GATEWAY_ORIGINATOR;
24
- const CODEX_TOOL_VERSION = "0.0.0";
25
- const CODEX_SESSION_ID_MAX_LENGTH = 64;
26
-
27
- export const CODEX_CONTEXT_PROVIDER_ERROR =
28
- "Remote Context management requires a configured Codex-compatible backend";
29
-
30
- export function isNativeCodexModel(
31
- model: ExtensionContext["model"] | undefined,
32
- ): boolean {
33
- return model?.provider === CODEX_PROVIDER && model.api === CODEX_API;
34
- }
35
-
36
- export function isCodexGatewayModel(
37
- model: ExtensionContext["model"] | undefined,
38
- gatewayModels: readonly string[] = [],
39
- ): boolean {
40
- // Gateway coverage is an operator allowlist of exact "provider/model" keys
41
- // (compaction.gatewayContextModels). The backend relay must actually pass
42
- // hosted window markers through; models outside the list stay on remote
43
- // compaction v2.
44
- if (!model || model.api !== GATEWAY_API) return false;
45
- return isExactModelAllowed(model, gatewayModels);
46
- }
47
-
48
- export function normalizeCodexBackendBaseUrl(baseUrl: string | undefined | null): string | undefined {
49
- const normalized = normalizeBaseUrl(baseUrl);
50
- if (!normalized) return undefined;
51
- try {
52
- const url = new URL(normalized);
53
- const pathname = url.pathname.replace(/\/+$/, "");
54
- if (pathname.endsWith("/codex/responses")) {
55
- url.pathname = pathname.slice(0, -"/responses".length);
56
- return url.toString().replace(/\/$/, "");
57
- }
58
- if (pathname.endsWith("/codex")) return normalized;
59
- if (pathname.endsWith("/backend-api") || pathname.endsWith("/api")) {
60
- return `${normalized}/codex`;
61
- }
62
- if (pathname === "") return `${normalized}/api/codex`;
63
- if (pathname === "/") return `${normalized}/api/codex`;
64
- return undefined;
65
- } catch {
66
- return undefined;
67
- }
68
- }
69
-
70
- function headerValue(headers: ProviderHeaders | undefined, name: string): string | undefined {
71
- const wanted = name.toLowerCase();
72
- for (const [key, value] of Object.entries(headers ?? {})) {
73
- if (key.toLowerCase() === wanted && typeof value === "string" && value.trim()) {
74
- return value.trim();
75
- }
76
- }
77
- return undefined;
78
- }
79
-
80
- function bearerToken(value: string | undefined): string | undefined {
81
- if (!value) return undefined;
82
- const match = value.trim().match(/^Bearer\s+(.+)$/i);
83
- return (match?.[1] ?? value).trim() || undefined;
84
- }
85
-
86
- function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
87
- const parts = token.split(".");
88
- if (parts.length !== 3) return undefined;
89
- try {
90
- const value: unknown = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8"));
91
- return value && typeof value === "object" && !Array.isArray(value)
92
- ? value as Record<string, unknown>
93
- : undefined;
94
- } catch {
95
- return undefined;
96
- }
97
- }
98
-
99
- function accountIdFromToken(token: string): string | undefined {
100
- const payload = decodeJwtPayload(token);
101
- const direct = payload?.chatgpt_account_id;
102
- if (isNonEmptyString(direct)) return direct.trim();
103
- const auth = payload?.["https://api.openai.com/auth"];
104
- if (!auth || typeof auth !== "object" || Array.isArray(auth)) return undefined;
105
- const nested = (auth as Record<string, unknown>).chatgpt_account_id;
106
- return isNonEmptyString(nested) ? nested.trim() : undefined;
107
- }
108
-
109
- function userAgent(version: string): string {
110
- return buildCodexCliUserAgent(version);
111
- }
112
-
113
- function clampSessionId(value: string | undefined): string | undefined {
114
- if (!value) return undefined;
115
- const chars = Array.from(value.trim());
116
- if (chars.length === 0) return undefined;
117
- return chars.length <= CODEX_SESSION_ID_MAX_LENGTH
118
- ? chars.join("")
119
- : chars.slice(0, CODEX_SESSION_ID_MAX_LENGTH).join("");
120
- }
121
-
122
- function resolveContextSessionId(ctx: ExtensionContext): string | undefined {
123
- try {
124
- return clampSessionId(ctx.sessionManager.getSessionId());
125
- } catch {
126
- return undefined;
127
- }
128
- }
129
-
130
- export type CodexContextProviderHeaderOptions = {
131
- sessionId?: string;
132
- clientRequestId?: string;
133
- };
134
-
135
- export function codexContextProviderHeaders(
136
- provider: CodexContextProvider,
137
- options: CodexContextProviderHeaderOptions = {},
138
- ): Headers {
139
- const headers = new Headers();
140
- for (const [name, value] of Object.entries(provider.headers)) {
141
- if (typeof value === "string") headers.set(name, value);
142
- }
143
-
144
- if (provider.kind === "native-codex") {
145
- headers.set("Authorization", `Bearer ${provider.token}`);
146
- headers.set("ChatGPT-Account-ID", provider.accountId);
147
- headers.set("originator", CODEX_TOOL_ORIGINATOR);
148
- headers.set("User-Agent", userAgent(CODEX_TOOL_VERSION));
149
- } else {
150
- headers.set("Authorization", `Bearer ${provider.apiKey}`);
151
- headers.delete("ChatGPT-Account-ID");
152
- headers.delete("Cookie");
153
- headers.set("originator", CODEX_GATEWAY_ORIGINATOR);
154
- headers.set("User-Agent", userAgent(CODEX_CLIENT_VERSION));
155
- // Let the gateway own its version policy; preserve an explicitly configured
156
- // version already copied from provider.headers above.
157
- headers.set("X-Codex-Affinity-Scope", CODEX_AFFINITY_SCOPE);
158
- headers.set("X-Codex-Model", provider.model);
159
- }
160
-
161
- const sessionId = clampSessionId(options.sessionId);
162
- if (sessionId) {
163
- headers.set("Session-Id", sessionId);
164
- headers.set("X-Client-Request-Id", clampSessionId(options.clientRequestId) ?? sessionId);
165
- }
166
- headers.set("content-type", "application/json");
167
- return headers;
168
- }
169
-
170
- export async function resolveCodexContextProvider(
171
- ctx: ExtensionContext,
172
- modelOverride: ExtensionContext["model"] = ctx.model,
173
- gatewayModels: readonly string[] = [],
174
- ): Promise<CodexContextProviderResolution> {
175
- const selectedModel = modelOverride;
176
- const selectedDescriptor = {
177
- provider: selectedModel?.provider,
178
- api: selectedModel?.api,
179
- model: selectedModel?.id,
180
- baseUrl: normalizeBaseUrl(selectedModel?.baseUrl),
181
- };
182
- const effective = await resolveEffectiveModel(ctx, selectedModel);
183
- if (!effective.ok) return { ok: false, reason: "unsupported-model", ...selectedDescriptor };
184
- const model = effective.model;
185
- const descriptor = {
186
- provider: model.provider,
187
- api: model.api,
188
- model: model.id,
189
- baseUrl: normalizeBaseUrl(model.baseUrl),
190
- };
191
-
192
- const isNative = isNativeCodexModel(model);
193
- const isLogicalVirtualGateway = selectedModel?.api === VIRTUAL_MODEL_API && isExactModelAllowed(selectedModel, gatewayModels);
194
- const isGateway = isCodexGatewayModel(model, gatewayModels) ||
195
- (isLogicalVirtualGateway && model.api === GATEWAY_API);
196
- if (!isNative && !isGateway) {
197
- return { ok: false, reason: "unsupported-model", ...descriptor };
198
- }
199
- if (!isNative && model.api !== GATEWAY_API) {
200
- return { ok: false, reason: "unsupported-api", ...descriptor };
201
- }
202
- if (isNative && model.api !== CODEX_API) {
203
- return { ok: false, reason: "unsupported-api", ...descriptor };
204
- }
205
-
206
- let auth: Awaited<ReturnType<typeof ctx.modelRegistry.getApiKeyAndHeaders>>;
207
- try {
208
- auth = await ctx.modelRegistry.getApiKeyAndHeaders(model as Model<Api>);
209
- } catch {
210
- return { ok: false, reason: "auth-resolution-failed", ...descriptor };
211
- }
212
- if (!auth.ok) return { ok: false, reason: "auth-resolution-failed", ...descriptor };
213
-
214
- const rawBaseUrl = normalizeBaseUrl(auth.baseUrl) ?? normalizeBaseUrl(model.baseUrl);
215
- if (!rawBaseUrl) return { ok: false, reason: "missing-base-url", ...descriptor };
216
-
217
- if (isGateway) {
218
- if (!resolveContextSessionId(ctx)) {
219
- return { ok: false, reason: "missing-session-id", ...descriptor, baseUrl: rawBaseUrl };
220
- }
221
- const apiKey = bearerToken(auth.apiKey) ?? bearerToken(headerValue(auth.headers, "authorization"));
222
- if (!apiKey) return { ok: false, reason: "missing-api-key", ...descriptor, baseUrl: rawBaseUrl };
223
- return {
224
- ok: true,
225
- provider: {
226
- kind: "codex-gateway",
227
- route: "codex-gateway",
228
- provider: model.provider,
229
- api: GATEWAY_API,
230
- model: model.id,
231
- baseUrl: rawBaseUrl,
232
- apiKey,
233
- headers: filterCodexGatewayHeaders(mergeProviderHeaders(model.headers, auth.headers)),
234
- },
235
- };
236
- }
237
-
238
- const token = bearerToken(auth.apiKey) ?? bearerToken(headerValue(auth.headers, "authorization"));
239
- if (!token) return { ok: false, reason: "missing-token", ...descriptor };
240
- const accountId = headerValue(auth.headers, "chatgpt-account-id") ?? accountIdFromToken(token);
241
- if (!accountId) return { ok: false, reason: "missing-account-id", ...descriptor };
242
- const baseUrl = normalizeCodexBackendBaseUrl(rawBaseUrl);
243
- if (!baseUrl) return { ok: false, reason: "unsupported-backend", ...descriptor };
244
-
245
- const headers = mergeProviderHeaders(model.headers, auth.headers);
246
- return {
247
- ok: true,
248
- provider: {
249
- kind: "native-codex",
250
- route: "openai-codex",
251
- provider: CODEX_PROVIDER,
252
- api: CODEX_API,
253
- model: model.id,
254
- baseUrl,
255
- token,
256
- accountId,
257
- headers,
258
- },
259
- };
260
- }
261
-
262
- export const _codexProviderTest = {
263
- accountIdFromToken,
264
- bearerToken,
265
- clampSessionId,
266
- decodeJwtPayload,
267
- headerValue,
268
- isCodexGatewayModel,
269
- userAgent,
270
- };
1
+ import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { mergeProviderHeaders } from "../provider-headers";
4
+ import {
5
+ CODEX_AFFINITY_SCOPE,
6
+ CODEX_CLIENT_VERSION,
7
+ CODEX_GATEWAY_ORIGINATOR,
8
+ buildCodexCliUserAgent,
9
+ filterCodexGatewayHeaders,
10
+ } from "../responses-headers";
11
+ export { CODEX_AFFINITY_SCOPE } from "../responses-headers";
12
+ import { normalizeBaseUrl, resolveEffectiveModel, VIRTUAL_MODEL_API } from "../runtime";
13
+ import { isExactModelAllowed } from "../model-scope";
14
+ import {
15
+ isNonEmptyString,
16
+ type CodexContextProvider,
17
+ type CodexContextProviderResolution,
18
+ } from "./types";
19
+
20
+ const CODEX_PROVIDER = "openai-codex";
21
+ const CODEX_API = "openai-codex-responses";
22
+ const GATEWAY_API = "openai-responses";
23
+ const CODEX_TOOL_ORIGINATOR = CODEX_GATEWAY_ORIGINATOR;
24
+ const CODEX_TOOL_VERSION = "0.0.0";
25
+ const CODEX_SESSION_ID_MAX_LENGTH = 64;
26
+
27
+ export const CODEX_CONTEXT_PROVIDER_ERROR =
28
+ "Remote Context management requires a configured Codex-compatible backend";
29
+
30
+ export function isNativeCodexModel(
31
+ model: ExtensionContext["model"] | undefined,
32
+ ): boolean {
33
+ return model?.provider === CODEX_PROVIDER && model.api === CODEX_API;
34
+ }
35
+
36
+ export function isCodexGatewayModel(
37
+ model: ExtensionContext["model"] | undefined,
38
+ gatewayModels: readonly string[] = [],
39
+ ): boolean {
40
+ // Gateway coverage is an operator allowlist of exact "provider/model" keys
41
+ // (compaction.gatewayContextModels). The backend relay must actually pass
42
+ // hosted window markers through; models outside the list stay on remote
43
+ // compaction v2.
44
+ if (!model || model.api !== GATEWAY_API) return false;
45
+ return isExactModelAllowed(model, gatewayModels);
46
+ }
47
+
48
+ export function normalizeCodexBackendBaseUrl(baseUrl: string | undefined | null): string | undefined {
49
+ const normalized = normalizeBaseUrl(baseUrl);
50
+ if (!normalized) return undefined;
51
+ try {
52
+ const url = new URL(normalized);
53
+ const pathname = url.pathname.replace(/\/+$/, "");
54
+ if (pathname.endsWith("/codex/responses")) {
55
+ url.pathname = pathname.slice(0, -"/responses".length);
56
+ return url.toString().replace(/\/$/, "");
57
+ }
58
+ if (pathname.endsWith("/codex")) return normalized;
59
+ if (pathname.endsWith("/backend-api") || pathname.endsWith("/api")) {
60
+ return `${normalized}/codex`;
61
+ }
62
+ if (pathname === "") return `${normalized}/api/codex`;
63
+ if (pathname === "/") return `${normalized}/api/codex`;
64
+ return undefined;
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ function headerValue(headers: ProviderHeaders | undefined, name: string): string | undefined {
71
+ const wanted = name.toLowerCase();
72
+ for (const [key, value] of Object.entries(headers ?? {})) {
73
+ if (key.toLowerCase() === wanted && typeof value === "string" && value.trim()) {
74
+ return value.trim();
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ function bearerToken(value: string | undefined): string | undefined {
81
+ if (!value) return undefined;
82
+ const match = value.trim().match(/^Bearer\s+(.+)$/i);
83
+ return (match?.[1] ?? value).trim() || undefined;
84
+ }
85
+
86
+ function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
87
+ const parts = token.split(".");
88
+ if (parts.length !== 3) return undefined;
89
+ try {
90
+ const value: unknown = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8"));
91
+ return value && typeof value === "object" && !Array.isArray(value)
92
+ ? value as Record<string, unknown>
93
+ : undefined;
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ }
98
+
99
+ function accountIdFromToken(token: string): string | undefined {
100
+ const payload = decodeJwtPayload(token);
101
+ const direct = payload?.chatgpt_account_id;
102
+ if (isNonEmptyString(direct)) return direct.trim();
103
+ const auth = payload?.["https://api.openai.com/auth"];
104
+ if (!auth || typeof auth !== "object" || Array.isArray(auth)) return undefined;
105
+ const nested = (auth as Record<string, unknown>).chatgpt_account_id;
106
+ return isNonEmptyString(nested) ? nested.trim() : undefined;
107
+ }
108
+
109
+ function userAgent(version: string): string {
110
+ return buildCodexCliUserAgent(version);
111
+ }
112
+
113
+ function clampSessionId(value: string | undefined): string | undefined {
114
+ if (!value) return undefined;
115
+ const chars = Array.from(value.trim());
116
+ if (chars.length === 0) return undefined;
117
+ return chars.length <= CODEX_SESSION_ID_MAX_LENGTH
118
+ ? chars.join("")
119
+ : chars.slice(0, CODEX_SESSION_ID_MAX_LENGTH).join("");
120
+ }
121
+
122
+ function resolveContextSessionId(ctx: ExtensionContext): string | undefined {
123
+ try {
124
+ return clampSessionId(ctx.sessionManager.getSessionId());
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ export type CodexContextProviderHeaderOptions = {
131
+ sessionId?: string;
132
+ clientRequestId?: string;
133
+ };
134
+
135
+ export function codexContextProviderHeaders(
136
+ provider: CodexContextProvider,
137
+ options: CodexContextProviderHeaderOptions = {},
138
+ ): Headers {
139
+ const headers = new Headers();
140
+ for (const [name, value] of Object.entries(provider.headers)) {
141
+ if (typeof value === "string") headers.set(name, value);
142
+ }
143
+
144
+ if (provider.kind === "native-codex") {
145
+ headers.set("Authorization", `Bearer ${provider.token}`);
146
+ headers.set("ChatGPT-Account-ID", provider.accountId);
147
+ headers.set("originator", CODEX_TOOL_ORIGINATOR);
148
+ headers.set("User-Agent", userAgent(CODEX_TOOL_VERSION));
149
+ } else {
150
+ headers.set("Authorization", `Bearer ${provider.apiKey}`);
151
+ headers.delete("ChatGPT-Account-ID");
152
+ headers.delete("Cookie");
153
+ headers.set("originator", CODEX_GATEWAY_ORIGINATOR);
154
+ headers.set("User-Agent", userAgent(CODEX_CLIENT_VERSION));
155
+ // Let the gateway own its version policy; preserve an explicitly configured
156
+ // version already copied from provider.headers above.
157
+ headers.set("X-Codex-Affinity-Scope", CODEX_AFFINITY_SCOPE);
158
+ headers.set("X-Codex-Model", provider.model);
159
+ }
160
+
161
+ const sessionId = clampSessionId(options.sessionId);
162
+ if (sessionId) {
163
+ headers.set("Session-Id", sessionId);
164
+ headers.set("X-Client-Request-Id", clampSessionId(options.clientRequestId) ?? sessionId);
165
+ }
166
+ headers.set("content-type", "application/json");
167
+ return headers;
168
+ }
169
+
170
+ export async function resolveCodexContextProvider(
171
+ ctx: ExtensionContext,
172
+ modelOverride: ExtensionContext["model"] = ctx.model,
173
+ gatewayModels: readonly string[] = [],
174
+ ): Promise<CodexContextProviderResolution> {
175
+ const selectedModel = modelOverride;
176
+ const selectedDescriptor = {
177
+ provider: selectedModel?.provider,
178
+ api: selectedModel?.api,
179
+ model: selectedModel?.id,
180
+ baseUrl: normalizeBaseUrl(selectedModel?.baseUrl),
181
+ };
182
+ const effective = await resolveEffectiveModel(ctx, selectedModel);
183
+ if (!effective.ok) return { ok: false, reason: "unsupported-model", ...selectedDescriptor };
184
+ const model = effective.model;
185
+ const descriptor = {
186
+ provider: model.provider,
187
+ api: model.api,
188
+ model: model.id,
189
+ baseUrl: normalizeBaseUrl(model.baseUrl),
190
+ };
191
+
192
+ const isNative = isNativeCodexModel(model);
193
+ const isLogicalVirtualGateway = selectedModel?.api === VIRTUAL_MODEL_API && isExactModelAllowed(selectedModel, gatewayModels);
194
+ const isGateway = isCodexGatewayModel(model, gatewayModels) ||
195
+ (isLogicalVirtualGateway && model.api === GATEWAY_API);
196
+ if (!isNative && !isGateway) {
197
+ return { ok: false, reason: "unsupported-model", ...descriptor };
198
+ }
199
+ if (!isNative && model.api !== GATEWAY_API) {
200
+ return { ok: false, reason: "unsupported-api", ...descriptor };
201
+ }
202
+ if (isNative && model.api !== CODEX_API) {
203
+ return { ok: false, reason: "unsupported-api", ...descriptor };
204
+ }
205
+
206
+ let auth: Awaited<ReturnType<typeof ctx.modelRegistry.getApiKeyAndHeaders>>;
207
+ try {
208
+ auth = await ctx.modelRegistry.getApiKeyAndHeaders(model as Model<Api>);
209
+ } catch {
210
+ return { ok: false, reason: "auth-resolution-failed", ...descriptor };
211
+ }
212
+ if (!auth.ok) return { ok: false, reason: "auth-resolution-failed", ...descriptor };
213
+
214
+ const rawBaseUrl = normalizeBaseUrl(auth.baseUrl) ?? normalizeBaseUrl(model.baseUrl);
215
+ if (!rawBaseUrl) return { ok: false, reason: "missing-base-url", ...descriptor };
216
+
217
+ if (isGateway) {
218
+ if (!resolveContextSessionId(ctx)) {
219
+ return { ok: false, reason: "missing-session-id", ...descriptor, baseUrl: rawBaseUrl };
220
+ }
221
+ const apiKey = bearerToken(auth.apiKey) ?? bearerToken(headerValue(auth.headers, "authorization"));
222
+ if (!apiKey) return { ok: false, reason: "missing-api-key", ...descriptor, baseUrl: rawBaseUrl };
223
+ return {
224
+ ok: true,
225
+ provider: {
226
+ kind: "codex-gateway",
227
+ route: "codex-gateway",
228
+ provider: model.provider,
229
+ api: GATEWAY_API,
230
+ model: model.id,
231
+ baseUrl: rawBaseUrl,
232
+ apiKey,
233
+ headers: filterCodexGatewayHeaders(mergeProviderHeaders(model.headers, auth.headers)),
234
+ },
235
+ };
236
+ }
237
+
238
+ const token = bearerToken(auth.apiKey) ?? bearerToken(headerValue(auth.headers, "authorization"));
239
+ if (!token) return { ok: false, reason: "missing-token", ...descriptor };
240
+ const accountId = headerValue(auth.headers, "chatgpt-account-id") ?? accountIdFromToken(token);
241
+ if (!accountId) return { ok: false, reason: "missing-account-id", ...descriptor };
242
+ const baseUrl = normalizeCodexBackendBaseUrl(rawBaseUrl);
243
+ if (!baseUrl) return { ok: false, reason: "unsupported-backend", ...descriptor };
244
+
245
+ const headers = mergeProviderHeaders(model.headers, auth.headers);
246
+ return {
247
+ ok: true,
248
+ provider: {
249
+ kind: "native-codex",
250
+ route: "openai-codex",
251
+ provider: CODEX_PROVIDER,
252
+ api: CODEX_API,
253
+ model: model.id,
254
+ baseUrl,
255
+ token,
256
+ accountId,
257
+ headers,
258
+ },
259
+ };
260
+ }
261
+
262
+ export const _codexProviderTest = {
263
+ accountIdFromToken,
264
+ bearerToken,
265
+ clampSessionId,
266
+ decodeJwtPayload,
267
+ headerValue,
268
+ isCodexGatewayModel,
269
+ userAgent,
270
+ };