@kodelyth/codex 2026.5.42 → 2026.6.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 (138) hide show
  1. package/package.json +17 -2
  2. package/doctor-contract-api.test.ts +0 -44
  3. package/doctor-contract-api.ts +0 -68
  4. package/harness.ts +0 -72
  5. package/index.test.ts +0 -230
  6. package/index.ts +0 -66
  7. package/media-understanding-provider.test.ts +0 -486
  8. package/media-understanding-provider.ts +0 -521
  9. package/prompt-overlay-runtime-contract.test.ts +0 -48
  10. package/prompt-overlay.ts +0 -21
  11. package/provider-catalog.ts +0 -83
  12. package/provider-discovery.ts +0 -45
  13. package/provider.test.ts +0 -384
  14. package/provider.ts +0 -243
  15. package/src/app-server/app-inventory-cache.test.ts +0 -176
  16. package/src/app-server/app-inventory-cache.ts +0 -324
  17. package/src/app-server/approval-bridge.test.ts +0 -1471
  18. package/src/app-server/approval-bridge.ts +0 -1211
  19. package/src/app-server/auth-bridge.test.ts +0 -1449
  20. package/src/app-server/auth-bridge.ts +0 -614
  21. package/src/app-server/auth-profile-runtime-contract.test.ts +0 -239
  22. package/src/app-server/capabilities.ts +0 -27
  23. package/src/app-server/client-factory.ts +0 -24
  24. package/src/app-server/client.test.ts +0 -563
  25. package/src/app-server/client.ts +0 -715
  26. package/src/app-server/compact.test.ts +0 -710
  27. package/src/app-server/compact.ts +0 -500
  28. package/src/app-server/computer-use.test.ts +0 -788
  29. package/src/app-server/computer-use.ts +0 -683
  30. package/src/app-server/config.test.ts +0 -879
  31. package/src/app-server/config.ts +0 -1038
  32. package/src/app-server/context-engine-projection.test.ts +0 -252
  33. package/src/app-server/context-engine-projection.ts +0 -403
  34. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +0 -80
  35. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  36. package/src/app-server/dynamic-tool-profile.ts +0 -69
  37. package/src/app-server/dynamic-tools.test.ts +0 -1302
  38. package/src/app-server/dynamic-tools.ts +0 -623
  39. package/src/app-server/elicitation-bridge.test.ts +0 -1056
  40. package/src/app-server/elicitation-bridge.ts +0 -783
  41. package/src/app-server/event-projector.test.ts +0 -2668
  42. package/src/app-server/event-projector.ts +0 -2057
  43. package/src/app-server/image-payload-sanitizer.test.ts +0 -49
  44. package/src/app-server/image-payload-sanitizer.ts +0 -167
  45. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +0 -456
  46. package/src/app-server/local-runtime-attribution.ts +0 -39
  47. package/src/app-server/managed-binary.test.ts +0 -139
  48. package/src/app-server/managed-binary.ts +0 -193
  49. package/src/app-server/models.test.ts +0 -246
  50. package/src/app-server/models.ts +0 -172
  51. package/src/app-server/native-hook-relay.test.ts +0 -271
  52. package/src/app-server/native-hook-relay.ts +0 -150
  53. package/src/app-server/native-subagent-task-mirror.test.ts +0 -573
  54. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  55. package/src/app-server/outcome-fallback-runtime-contract.test.ts +0 -404
  56. package/src/app-server/plugin-activation.test.ts +0 -336
  57. package/src/app-server/plugin-activation.ts +0 -283
  58. package/src/app-server/plugin-app-cache-key.ts +0 -74
  59. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  60. package/src/app-server/plugin-inventory.test.ts +0 -355
  61. package/src/app-server/plugin-inventory.ts +0 -357
  62. package/src/app-server/plugin-thread-config.test.ts +0 -865
  63. package/src/app-server/plugin-thread-config.ts +0 -455
  64. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  65. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  66. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  67. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  68. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  69. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  70. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  71. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  72. package/src/app-server/protocol-validators.test.ts +0 -75
  73. package/src/app-server/protocol-validators.ts +0 -203
  74. package/src/app-server/protocol.ts +0 -520
  75. package/src/app-server/rate-limit-cache.ts +0 -48
  76. package/src/app-server/rate-limits.test.ts +0 -202
  77. package/src/app-server/rate-limits.ts +0 -583
  78. package/src/app-server/request.ts +0 -73
  79. package/src/app-server/run-attempt.context-engine.test.ts +0 -1004
  80. package/src/app-server/run-attempt.test.ts +0 -9477
  81. package/src/app-server/run-attempt.ts +0 -4683
  82. package/src/app-server/run-attempt.vision-tools.test.ts +0 -35
  83. package/src/app-server/schema-normalization-runtime-contract.test.ts +0 -206
  84. package/src/app-server/session-binding.test.ts +0 -303
  85. package/src/app-server/session-binding.ts +0 -398
  86. package/src/app-server/session-history.ts +0 -44
  87. package/src/app-server/shared-client.test.ts +0 -589
  88. package/src/app-server/shared-client.ts +0 -289
  89. package/src/app-server/side-question.test.ts +0 -1175
  90. package/src/app-server/side-question.ts +0 -1007
  91. package/src/app-server/test-support.ts +0 -48
  92. package/src/app-server/thread-lifecycle.test.ts +0 -447
  93. package/src/app-server/thread-lifecycle.ts +0 -939
  94. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +0 -442
  95. package/src/app-server/timeout.ts +0 -9
  96. package/src/app-server/tool-progress-normalization.ts +0 -77
  97. package/src/app-server/trajectory.test.ts +0 -205
  98. package/src/app-server/trajectory.ts +0 -365
  99. package/src/app-server/transcript-mirror.test.ts +0 -524
  100. package/src/app-server/transcript-mirror.ts +0 -208
  101. package/src/app-server/transcript-repair-runtime-contract.test.ts +0 -44
  102. package/src/app-server/transport-stdio.test.ts +0 -171
  103. package/src/app-server/transport-stdio.ts +0 -107
  104. package/src/app-server/transport-websocket.test.ts +0 -69
  105. package/src/app-server/transport-websocket.ts +0 -90
  106. package/src/app-server/transport.ts +0 -117
  107. package/src/app-server/user-input-bridge.test.ts +0 -249
  108. package/src/app-server/user-input-bridge.ts +0 -316
  109. package/src/app-server/version.ts +0 -4
  110. package/src/app-server/vision-tools.ts +0 -12
  111. package/src/command-account.ts +0 -544
  112. package/src/command-formatters.ts +0 -425
  113. package/src/command-handlers.ts +0 -2004
  114. package/src/command-rpc.test.ts +0 -16
  115. package/src/command-rpc.ts +0 -142
  116. package/src/commands.test.ts +0 -3312
  117. package/src/commands.ts +0 -65
  118. package/src/conversation-binding-data.ts +0 -124
  119. package/src/conversation-binding.test.ts +0 -599
  120. package/src/conversation-binding.ts +0 -561
  121. package/src/conversation-control.test.ts +0 -126
  122. package/src/conversation-control.ts +0 -303
  123. package/src/conversation-turn-collector.test.ts +0 -191
  124. package/src/conversation-turn-collector.ts +0 -186
  125. package/src/conversation-turn-input.test.ts +0 -141
  126. package/src/conversation-turn-input.ts +0 -106
  127. package/src/manifest.test.ts +0 -20
  128. package/src/migration/apply.ts +0 -501
  129. package/src/migration/helpers.ts +0 -55
  130. package/src/migration/plan.ts +0 -461
  131. package/src/migration/provider.test.ts +0 -1741
  132. package/src/migration/provider.ts +0 -41
  133. package/src/migration/source.ts +0 -643
  134. package/src/migration/targets.ts +0 -25
  135. package/src/node-cli-sessions.test.ts +0 -180
  136. package/src/node-cli-sessions.ts +0 -711
  137. package/test-api.ts +0 -82
  138. package/tsconfig.json +0 -16
@@ -1,614 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
3
- import path from "node:path";
4
- import {
5
- ensureAuthProfileStore,
6
- ensureAuthProfileStoreWithoutExternalProfiles,
7
- loadAuthProfileStoreForSecretsRuntime,
8
- refreshOAuthCredentialForRuntime,
9
- resolveAuthProfileOrder,
10
- resolveProviderIdForAuth,
11
- resolveApiKeyForProfile,
12
- resolveDefaultAgentDir,
13
- resolvePersistedAuthProfileOwnerAgentDir,
14
- type AuthProfileCredential,
15
- type AuthProfileStore,
16
- type OAuthCredential,
17
- } from "klaw/plugin-sdk/agent-runtime";
18
- import type { CodexAppServerClient } from "./client.js";
19
- import type { CodexAppServerStartOptions } from "./config.js";
20
- import type {
21
- CodexChatgptAuthTokensRefreshResponse,
22
- CodexGetAccountResponse,
23
- CodexLoginAccountParams,
24
- } from "./protocol.js";
25
- import { resolveCodexAppServerSpawnEnv } from "./transport-stdio.js";
26
-
27
- const CODEX_APP_SERVER_AUTH_PROVIDER = "openai-codex";
28
- const OPENAI_PROVIDER = "openai";
29
- const OPENAI_CODEX_DEFAULT_PROFILE_ID = "openai-codex:default";
30
- const CODEX_HOME_ENV_VAR = "CODEX_HOME";
31
- const HOME_ENV_VAR = "HOME";
32
- const CODEX_APP_SERVER_HOME_DIRNAME = "codex-home";
33
- const CODEX_APP_SERVER_NATIVE_HOME_DIRNAME = "home";
34
- const CODEX_API_KEY_ENV_VAR = "CODEX_API_KEY";
35
- const OPENAI_API_KEY_ENV_VAR = "OPENAI_API_KEY";
36
- const CODEX_APP_SERVER_API_KEY_ENV_VARS = [CODEX_API_KEY_ENV_VAR, OPENAI_API_KEY_ENV_VAR];
37
- const CODEX_APP_SERVER_HOME_ENV_VARS = [CODEX_HOME_ENV_VAR, HOME_ENV_VAR];
38
-
39
- type AuthProfileOrderConfig = Parameters<typeof resolveAuthProfileOrder>[0]["cfg"];
40
-
41
- export async function bridgeCodexAppServerStartOptions(params: {
42
- startOptions: CodexAppServerStartOptions;
43
- agentDir: string;
44
- authProfileId?: string | null;
45
- config?: AuthProfileOrderConfig;
46
- }): Promise<CodexAppServerStartOptions> {
47
- if (params.startOptions.transport !== "stdio") {
48
- return params.startOptions;
49
- }
50
- const isolatedStartOptions = await withAgentCodexHomeEnvironment(
51
- params.startOptions,
52
- params.agentDir,
53
- );
54
- if (params.authProfileId === null) {
55
- return isolatedStartOptions;
56
- }
57
- const store = ensureCodexAppServerAuthProfileStore({
58
- agentDir: params.agentDir,
59
- authProfileId: params.authProfileId,
60
- config: params.config,
61
- });
62
- const authProfileId = resolveCodexAppServerAuthProfileId({
63
- authProfileId: params.authProfileId,
64
- store,
65
- config: params.config,
66
- });
67
- const shouldClearInheritedOpenAiApiKey = shouldClearOpenAiApiKeyForCodexAuthProfile({
68
- store,
69
- authProfileId,
70
- config: params.config,
71
- });
72
- return shouldClearInheritedOpenAiApiKey
73
- ? withClearedEnvironmentVariables(isolatedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS)
74
- : isolatedStartOptions;
75
- }
76
-
77
- export function resolveCodexAppServerAuthProfileId(params: {
78
- authProfileId?: string;
79
- store: ReturnType<typeof ensureAuthProfileStore>;
80
- config?: AuthProfileOrderConfig;
81
- }): string | undefined {
82
- const requested = params.authProfileId?.trim();
83
- if (requested) {
84
- return requested;
85
- }
86
- return resolveAuthProfileOrder({
87
- cfg: params.config,
88
- store: params.store,
89
- provider: CODEX_APP_SERVER_AUTH_PROVIDER,
90
- })[0]?.trim();
91
- }
92
-
93
- export function resolveCodexAppServerAuthProfileIdForAgent(params: {
94
- authProfileId?: string;
95
- agentDir?: string;
96
- config?: AuthProfileOrderConfig;
97
- }): string | undefined {
98
- const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
99
- const store = ensureCodexAppServerAuthProfileStore({
100
- agentDir,
101
- authProfileId: params.authProfileId,
102
- config: params.config,
103
- });
104
- return resolveCodexAppServerAuthProfileId({
105
- authProfileId: params.authProfileId,
106
- store,
107
- config: params.config,
108
- });
109
- }
110
-
111
- function ensureCodexAppServerAuthProfileStore(params: {
112
- agentDir?: string;
113
- authProfileId?: string;
114
- config?: AuthProfileOrderConfig;
115
- }): ReturnType<typeof ensureAuthProfileStore> {
116
- return ensureAuthProfileStore(params.agentDir, {
117
- allowKeychainPrompt: false,
118
- config: params.config,
119
- externalCliProviderIds: [CODEX_APP_SERVER_AUTH_PROVIDER],
120
- ...(params.authProfileId ? { externalCliProfileIds: [params.authProfileId] } : {}),
121
- });
122
- }
123
-
124
- function resolveCodexAppServerAuthProfileStore(params: {
125
- agentDir?: string;
126
- authProfileId?: string;
127
- authProfileStore?: AuthProfileStore;
128
- config?: AuthProfileOrderConfig;
129
- }): AuthProfileStore {
130
- const overlaidStore = ensureCodexAppServerAuthProfileStore({
131
- agentDir: params.agentDir,
132
- authProfileId: params.authProfileId,
133
- config: params.config,
134
- });
135
- if (!params.authProfileStore) {
136
- return overlaidStore;
137
- }
138
- const order =
139
- params.authProfileStore.order || overlaidStore.order
140
- ? {
141
- ...overlaidStore.order,
142
- ...params.authProfileStore.order,
143
- }
144
- : undefined;
145
- return {
146
- ...params.authProfileStore,
147
- ...(order ? { order } : {}),
148
- profiles: {
149
- ...overlaidStore.profiles,
150
- ...params.authProfileStore.profiles,
151
- },
152
- };
153
- }
154
-
155
- export async function resolveCodexAppServerAuthAccountCacheKey(params: {
156
- authProfileId?: string;
157
- authProfileStore?: AuthProfileStore;
158
- agentDir?: string;
159
- config?: AuthProfileOrderConfig;
160
- }): Promise<string | undefined> {
161
- const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
162
- const store = resolveCodexAppServerAuthProfileStore({
163
- agentDir,
164
- authProfileId: params.authProfileId,
165
- authProfileStore: params.authProfileStore,
166
- config: params.config,
167
- });
168
- const profileId = resolveCodexAppServerAuthProfileId({
169
- authProfileId: params.authProfileId,
170
- store,
171
- config: params.config,
172
- });
173
- if (!profileId) {
174
- return undefined;
175
- }
176
- const credential = store.profiles[profileId];
177
- if (!credential || !isCodexAppServerAuthProfileCredential(credential, params.config)) {
178
- return undefined;
179
- }
180
- if (credential.type === "api_key") {
181
- const resolved = await resolveApiKeyForProfile({
182
- store,
183
- profileId,
184
- agentDir,
185
- });
186
- const apiKey = resolved?.apiKey?.trim();
187
- return apiKey
188
- ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintApiKeyAuthProfileCacheKey(apiKey)}`
189
- : resolveChatgptAccountId(profileId, credential);
190
- }
191
- if (credential.type === "token") {
192
- const resolved = await resolveApiKeyForProfile({
193
- store,
194
- profileId,
195
- agentDir,
196
- });
197
- const accessToken = resolved?.apiKey?.trim();
198
- return accessToken
199
- ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintTokenAuthProfileCacheKey(accessToken)}`
200
- : resolveChatgptAccountId(profileId, credential);
201
- }
202
- return resolveChatgptAccountId(profileId, credential);
203
- }
204
-
205
- export function resolveCodexAppServerEnvApiKeyCacheKey(params: {
206
- startOptions: Pick<CodexAppServerStartOptions, "transport" | "env" | "clearEnv">;
207
- baseEnv?: NodeJS.ProcessEnv;
208
- platform?: NodeJS.Platform;
209
- }): string | undefined {
210
- if (params.startOptions.transport !== "stdio") {
211
- return undefined;
212
- }
213
- const env = resolveCodexAppServerSpawnEnv(
214
- params.startOptions,
215
- params.baseEnv ?? process.env,
216
- params.platform ?? process.platform,
217
- );
218
- const apiKey = readFirstNonEmptyEnvEntry(env, CODEX_APP_SERVER_API_KEY_ENV_VARS);
219
- if (!apiKey) {
220
- return undefined;
221
- }
222
- const hash = createHash("sha256");
223
- hash.update("klaw:codex:app-server-env-api-key:v1");
224
- hash.update("\0");
225
- hash.update(apiKey.key);
226
- hash.update("\0");
227
- hash.update(apiKey.value);
228
- return `${apiKey.key}:sha256:${hash.digest("hex")}`;
229
- }
230
-
231
- function fingerprintApiKeyAuthProfileCacheKey(apiKey: string): string {
232
- const hash = createHash("sha256");
233
- hash.update("klaw:codex:app-server-auth-profile-api-key:v1");
234
- hash.update("\0");
235
- hash.update(apiKey);
236
- return `api_key:sha256:${hash.digest("hex")}`;
237
- }
238
-
239
- function fingerprintTokenAuthProfileCacheKey(accessToken: string): string {
240
- const hash = createHash("sha256");
241
- hash.update("klaw:codex:app-server-auth-profile-token:v1");
242
- hash.update("\0");
243
- hash.update(accessToken);
244
- return `token:sha256:${hash.digest("hex")}`;
245
- }
246
-
247
- export function resolveCodexAppServerHomeDir(agentDir: string): string {
248
- return path.join(path.resolve(agentDir), CODEX_APP_SERVER_HOME_DIRNAME);
249
- }
250
-
251
- export function resolveCodexAppServerNativeHomeDir(agentDir: string): string {
252
- return path.join(resolveCodexAppServerHomeDir(agentDir), CODEX_APP_SERVER_NATIVE_HOME_DIRNAME);
253
- }
254
-
255
- async function withAgentCodexHomeEnvironment(
256
- startOptions: CodexAppServerStartOptions,
257
- agentDir: string,
258
- ): Promise<CodexAppServerStartOptions> {
259
- const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim()
260
- ? startOptions.env[CODEX_HOME_ENV_VAR]
261
- : resolveCodexAppServerHomeDir(agentDir);
262
- const nativeHome = startOptions.env?.[HOME_ENV_VAR]?.trim()
263
- ? startOptions.env[HOME_ENV_VAR]
264
- : undefined;
265
- await fs.mkdir(codexHome, { recursive: true });
266
- if (nativeHome) {
267
- await fs.mkdir(nativeHome, { recursive: true });
268
- }
269
- const nextStartOptions: CodexAppServerStartOptions = {
270
- ...startOptions,
271
- env: {
272
- ...startOptions.env,
273
- [CODEX_HOME_ENV_VAR]: codexHome,
274
- ...(nativeHome ? { [HOME_ENV_VAR]: nativeHome } : {}),
275
- },
276
- };
277
- const clearEnv = withoutClearedCodexHomeEnv(startOptions.clearEnv);
278
- if (clearEnv) {
279
- nextStartOptions.clearEnv = clearEnv;
280
- } else {
281
- delete nextStartOptions.clearEnv;
282
- }
283
- return nextStartOptions;
284
- }
285
-
286
- function withoutClearedCodexHomeEnv(clearEnv: string[] | undefined): string[] | undefined {
287
- if (!clearEnv) {
288
- return undefined;
289
- }
290
- const reserved = new Set(CODEX_APP_SERVER_HOME_ENV_VARS);
291
- const filtered = clearEnv.filter((envVar) => !reserved.has(envVar.trim().toUpperCase()));
292
- return filtered.length === clearEnv.length ? clearEnv : filtered;
293
- }
294
-
295
- export async function applyCodexAppServerAuthProfile(params: {
296
- client: CodexAppServerClient;
297
- agentDir: string;
298
- authProfileId?: string | null;
299
- startOptions?: CodexAppServerStartOptions;
300
- config?: AuthProfileOrderConfig;
301
- }): Promise<void> {
302
- if (params.authProfileId === null) {
303
- return;
304
- }
305
- const loginParams = await resolveCodexAppServerAuthProfileLoginParams({
306
- agentDir: params.agentDir,
307
- authProfileId: params.authProfileId,
308
- config: params.config,
309
- });
310
- if (!loginParams) {
311
- if (params.startOptions?.transport !== "stdio") {
312
- return;
313
- }
314
- const env = resolveCodexAppServerSpawnEnv(params.startOptions, process.env);
315
- const fallbackLoginParams = await resolveCodexAppServerEnvApiKeyLoginParams({
316
- client: params.client,
317
- env,
318
- });
319
- if (fallbackLoginParams) {
320
- await params.client.request("account/login/start", fallbackLoginParams);
321
- }
322
- return;
323
- }
324
- await params.client.request("account/login/start", loginParams);
325
- }
326
-
327
- function resolveCodexAppServerAuthProfileLoginParams(params: {
328
- agentDir: string;
329
- authProfileId?: string;
330
- config?: AuthProfileOrderConfig;
331
- }): Promise<CodexLoginAccountParams | undefined> {
332
- return resolveCodexAppServerAuthProfileLoginParamsInternal(params);
333
- }
334
-
335
- export async function refreshCodexAppServerAuthTokens(params: {
336
- agentDir: string;
337
- authProfileId?: string;
338
- config?: AuthProfileOrderConfig;
339
- }): Promise<CodexChatgptAuthTokensRefreshResponse> {
340
- const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
341
- ...params,
342
- forceOAuthRefresh: true,
343
- });
344
- if (!loginParams || loginParams.type !== "chatgptAuthTokens") {
345
- throw new Error("Codex app-server ChatGPT token refresh requires an OAuth auth profile.");
346
- }
347
- return {
348
- accessToken: loginParams.accessToken,
349
- chatgptAccountId: loginParams.chatgptAccountId,
350
- chatgptPlanType: loginParams.chatgptPlanType ?? null,
351
- };
352
- }
353
-
354
- async function resolveCodexAppServerAuthProfileLoginParamsInternal(params: {
355
- agentDir: string;
356
- authProfileId?: string;
357
- forceOAuthRefresh?: boolean;
358
- config?: AuthProfileOrderConfig;
359
- }): Promise<CodexLoginAccountParams | undefined> {
360
- const store = ensureCodexAppServerAuthProfileStore({
361
- agentDir: params.agentDir,
362
- authProfileId: params.authProfileId,
363
- config: params.config,
364
- });
365
- const profileId = resolveCodexAppServerAuthProfileId({
366
- authProfileId: params.authProfileId,
367
- store,
368
- config: params.config,
369
- });
370
- if (!profileId) {
371
- return undefined;
372
- }
373
- const credential = store.profiles[profileId];
374
- if (!credential) {
375
- throw new Error(`Codex app-server auth profile "${profileId}" was not found.`);
376
- }
377
- if (!isCodexAppServerAuthProfileCredential(credential, params.config)) {
378
- throw new Error(
379
- `Codex app-server auth profile "${profileId}" must be OpenAI Codex auth or an OpenAI API-key backup.`,
380
- );
381
- }
382
- const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
383
- agentDir: params.agentDir,
384
- forceOAuthRefresh: params.forceOAuthRefresh === true,
385
- config: params.config,
386
- });
387
- if (!loginParams) {
388
- throw new Error(
389
- `Codex app-server auth profile "${profileId}" does not contain usable credentials.`,
390
- );
391
- }
392
- return loginParams;
393
- }
394
-
395
- async function resolveCodexAppServerEnvApiKeyLoginParams(params: {
396
- client: CodexAppServerClient;
397
- env: NodeJS.ProcessEnv;
398
- }): Promise<CodexLoginAccountParams | undefined> {
399
- const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS);
400
- if (!apiKey) {
401
- return undefined;
402
- }
403
- const response = await params.client.request<CodexGetAccountResponse>("account/read", {
404
- refreshToken: false,
405
- });
406
- if (response.account || !response.requiresOpenaiAuth) {
407
- return undefined;
408
- }
409
- return { type: "apiKey", apiKey };
410
- }
411
-
412
- async function resolveLoginParamsForCredential(
413
- profileId: string,
414
- credential: AuthProfileCredential,
415
- params: { agentDir: string; forceOAuthRefresh: boolean; config?: AuthProfileOrderConfig },
416
- ): Promise<CodexLoginAccountParams | undefined> {
417
- if (credential.type === "api_key") {
418
- const resolved = await resolveApiKeyForProfile({
419
- store: ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
420
- profileId,
421
- agentDir: params.agentDir,
422
- });
423
- const apiKey = resolved?.apiKey?.trim();
424
- return apiKey ? { type: "apiKey", apiKey } : undefined;
425
- }
426
- if (credential.type === "token") {
427
- const resolved = await resolveApiKeyForProfile({
428
- store: ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
429
- profileId,
430
- agentDir: params.agentDir,
431
- });
432
- const accessToken = resolved?.apiKey?.trim();
433
- return accessToken
434
- ? buildChatgptAuthTokensParams(profileId, credential, accessToken)
435
- : undefined;
436
- }
437
- if (credential.type !== "oauth") {
438
- return undefined;
439
- }
440
- const resolvedCredential = await resolveOAuthCredentialForCodexAppServer(profileId, credential, {
441
- agentDir: params.agentDir,
442
- forceRefresh: params.forceOAuthRefresh,
443
- config: params.config,
444
- });
445
- const accessToken = resolvedCredential.access?.trim();
446
- return accessToken
447
- ? buildChatgptAuthTokensParams(profileId, resolvedCredential, accessToken)
448
- : undefined;
449
- }
450
-
451
- async function resolveOAuthCredentialForCodexAppServer(
452
- profileId: string,
453
- credential: OAuthCredential,
454
- params: { agentDir: string; forceRefresh: boolean; config?: AuthProfileOrderConfig },
455
- ): Promise<OAuthCredential> {
456
- const ownerAgentDir = resolvePersistedAuthProfileOwnerAgentDir({
457
- agentDir: params.agentDir,
458
- profileId,
459
- });
460
- const store = ensureCodexAppServerAuthProfileStore({
461
- agentDir: ownerAgentDir,
462
- authProfileId: profileId,
463
- config: params.config,
464
- });
465
- const persistedStore = ensureAuthProfileStoreWithoutExternalProfiles(ownerAgentDir, {
466
- allowKeychainPrompt: false,
467
- });
468
- const persistedCredential = persistedStore.profiles[profileId];
469
- const persistedOAuthCredential =
470
- persistedCredential?.type === "oauth" &&
471
- isCodexAppServerAuthProvider(persistedCredential.provider, params.config)
472
- ? persistedCredential
473
- : undefined;
474
- const ownerCredential = store.profiles[profileId];
475
- const overlaidOAuthCredential =
476
- ownerCredential?.type === "oauth" &&
477
- isCodexAppServerAuthProvider(ownerCredential.provider, params.config)
478
- ? ownerCredential
479
- : undefined;
480
- if (params.forceRefresh && !persistedOAuthCredential && overlaidOAuthCredential) {
481
- const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({
482
- credential: overlaidOAuthCredential,
483
- });
484
- if (!refreshedRuntimeCredential?.access?.trim()) {
485
- throw new Error(`Codex app-server auth profile "${profileId}" could not refresh.`);
486
- }
487
- store.profiles[profileId] = refreshedRuntimeCredential;
488
- return refreshedRuntimeCredential;
489
- }
490
- const resolved = await resolveApiKeyForProfile({
491
- store,
492
- profileId,
493
- agentDir: ownerAgentDir,
494
- forceRefresh: params.forceRefresh && Boolean(persistedOAuthCredential),
495
- });
496
- const refreshed = loadAuthProfileStoreForSecretsRuntime(ownerAgentDir).profiles[profileId];
497
- const storedCredential = store.profiles[profileId];
498
- const candidate =
499
- refreshed?.type === "oauth" && isCodexAppServerAuthProvider(refreshed.provider, params.config)
500
- ? refreshed
501
- : storedCredential?.type === "oauth" &&
502
- isCodexAppServerAuthProvider(storedCredential.provider, params.config)
503
- ? storedCredential
504
- : credential;
505
- return resolved?.apiKey ? { ...candidate, access: resolved.apiKey } : candidate;
506
- }
507
-
508
- function isCodexAppServerAuthProvider(provider: string, config?: AuthProfileOrderConfig): boolean {
509
- return resolveProviderIdForAuth(provider, { config }) === CODEX_APP_SERVER_AUTH_PROVIDER;
510
- }
511
-
512
- function isOpenAIApiKeyBackupCredential(
513
- credential: AuthProfileCredential,
514
- config?: AuthProfileOrderConfig,
515
- ): boolean {
516
- return (
517
- credential.type === "api_key" &&
518
- resolveProviderIdForAuth(credential.provider, { config }) === OPENAI_PROVIDER
519
- );
520
- }
521
-
522
- function isCodexAppServerAuthProfileCredential(
523
- credential: AuthProfileCredential,
524
- config?: AuthProfileOrderConfig,
525
- ): boolean {
526
- return (
527
- isCodexAppServerAuthProvider(credential.provider, config) ||
528
- isOpenAIApiKeyBackupCredential(credential, config)
529
- );
530
- }
531
-
532
- function shouldClearOpenAiApiKeyForCodexAuthProfile(params: {
533
- store: ReturnType<typeof ensureAuthProfileStore>;
534
- authProfileId?: string;
535
- config?: AuthProfileOrderConfig;
536
- }): boolean {
537
- const profileId = params.authProfileId?.trim();
538
- const credential = profileId
539
- ? params.store.profiles[profileId]
540
- : params.store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID];
541
- return isCodexSubscriptionCredential(credential, params.config);
542
- }
543
-
544
- function isCodexSubscriptionCredential(
545
- credential: AuthProfileCredential | undefined,
546
- config?: AuthProfileOrderConfig,
547
- ): boolean {
548
- if (!credential || !isCodexAppServerAuthProvider(credential.provider, config)) {
549
- return false;
550
- }
551
- return credential.type === "oauth" || credential.type === "token";
552
- }
553
-
554
- function withClearedEnvironmentVariables(
555
- startOptions: CodexAppServerStartOptions,
556
- envVars: readonly string[],
557
- ): CodexAppServerStartOptions {
558
- const clearEnv = startOptions.clearEnv ?? [];
559
- const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
560
- if (missingEnvVars.length === 0) {
561
- return startOptions;
562
- }
563
- return {
564
- ...startOptions,
565
- clearEnv: [...clearEnv, ...missingEnvVars],
566
- };
567
- }
568
-
569
- function readFirstNonEmptyEnv(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {
570
- return readFirstNonEmptyEnvEntry(env, keys)?.value;
571
- }
572
-
573
- function readFirstNonEmptyEnvEntry(
574
- env: NodeJS.ProcessEnv,
575
- keys: readonly string[],
576
- ): { key: string; value: string } | undefined {
577
- for (const key of keys) {
578
- const value = env[key]?.trim();
579
- if (value) {
580
- return { key, value };
581
- }
582
- }
583
- return undefined;
584
- }
585
-
586
- function buildChatgptAuthTokensParams(
587
- profileId: string,
588
- credential: AuthProfileCredential,
589
- accessToken: string,
590
- ): CodexLoginAccountParams {
591
- return {
592
- type: "chatgptAuthTokens",
593
- accessToken,
594
- chatgptAccountId: resolveChatgptAccountId(profileId, credential),
595
- chatgptPlanType: resolveChatgptPlanType(credential),
596
- };
597
- }
598
-
599
- function resolveChatgptPlanType(credential: AuthProfileCredential): string | null {
600
- const record = credential as Record<string, unknown>;
601
- const planType = record.chatgptPlanType ?? record.planType;
602
- return typeof planType === "string" && planType.trim() ? planType.trim() : null;
603
- }
604
-
605
- function resolveChatgptAccountId(profileId: string, credential: AuthProfileCredential): string {
606
- if ("accountId" in credential && typeof credential.accountId === "string") {
607
- const accountId = credential.accountId.trim();
608
- if (accountId) {
609
- return accountId;
610
- }
611
- }
612
- const email = credential.email?.trim();
613
- return email || profileId;
614
- }