pi-openai-toolkit 0.20.8 → 0.21.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.
Files changed (54) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +8 -26
  4. package/README.zh.md +8 -26
  5. package/config.schema.json +278 -366
  6. package/docs/configuration.md +294 -310
  7. package/docs/internals.md +166 -175
  8. package/package.json +3 -13
  9. package/src/compact-client.ts +412 -389
  10. package/src/compaction-errors.ts +96 -0
  11. package/src/compaction-projection.ts +35 -35
  12. package/src/config/legacy.ts +519 -717
  13. package/src/config/migration.ts +103 -100
  14. package/src/config/notifications.ts +36 -28
  15. package/src/config/policy.ts +10 -18
  16. package/src/config/v2.ts +1167 -1380
  17. package/src/config.ts +310 -319
  18. package/src/context-management/codex-provider.ts +270 -270
  19. package/src/context-management/history-notes.ts +357 -357
  20. package/src/context-management/manual-compact.ts +0 -11
  21. package/src/context-management/tools.ts +371 -371
  22. package/src/context-management/types.ts +168 -168
  23. package/src/context-management/window-manager.ts +801 -801
  24. package/src/debug.ts +238 -237
  25. package/src/deferred-tool-carryover.ts +282 -282
  26. package/src/details-store.ts +151 -151
  27. package/src/extension-runtime.ts +1662 -1616
  28. package/src/image-generation/extension.ts +189 -189
  29. package/src/image-generation/protocol.ts +579 -579
  30. package/src/image-generation/types.ts +300 -300
  31. package/src/payload-rewrite.ts +515 -518
  32. package/src/pi-context-hook.ts +117 -117
  33. package/src/remote-v2-client.ts +811 -814
  34. package/src/request-context-cache.ts +155 -155
  35. package/src/responses-headers.ts +180 -180
  36. package/src/runtime.ts +865 -832
  37. package/src/serializer.ts +882 -882
  38. package/src/supported-environment.ts +27 -27
  39. package/src/types.ts +565 -648
  40. package/src/web-search/alpha-client.ts +876 -876
  41. package/src/web-search/extension.ts +530 -530
  42. package/src/web-search/payload.ts +299 -299
  43. package/src/web-search/prompt.ts +60 -60
  44. package/src/web-search/types.ts +166 -166
  45. package/tsconfig.check.json +50 -54
  46. package/src/auto-mode/classifier.ts +0 -161
  47. package/src/auto-mode/extension.ts +0 -691
  48. package/src/auto-mode/model-selection-guard.ts +0 -52
  49. package/src/auto-mode/policy.ts +0 -146
  50. package/src/auto-mode/prompt.ts +0 -279
  51. package/src/auto-mode/reviewer.ts +0 -325
  52. package/src/auto-mode/tool-review-tui.ts +0 -211
  53. package/src/auto-mode/transcript.ts +0 -135
  54. package/src/auto-mode/types.ts +0 -137
@@ -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
+ };