@gakr-gakr/codex 0.1.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 (86) hide show
  1. package/autobot.plugin.json +374 -0
  2. package/doctor-contract-api.ts +68 -0
  3. package/harness.ts +72 -0
  4. package/index.ts +124 -0
  5. package/media-understanding-provider.ts +521 -0
  6. package/package.json +40 -0
  7. package/prompt-overlay.ts +21 -0
  8. package/provider-catalog.ts +83 -0
  9. package/provider-discovery.ts +45 -0
  10. package/provider.ts +243 -0
  11. package/src/app-server/app-inventory-cache.ts +324 -0
  12. package/src/app-server/approval-bridge.ts +1211 -0
  13. package/src/app-server/auth-bridge.ts +614 -0
  14. package/src/app-server/capabilities.ts +27 -0
  15. package/src/app-server/client-factory.ts +24 -0
  16. package/src/app-server/client.ts +715 -0
  17. package/src/app-server/compact.ts +512 -0
  18. package/src/app-server/computer-use.ts +683 -0
  19. package/src/app-server/config.ts +1038 -0
  20. package/src/app-server/context-engine-projection.ts +403 -0
  21. package/src/app-server/dynamic-tool-diagnostics.ts +73 -0
  22. package/src/app-server/dynamic-tool-profile.ts +70 -0
  23. package/src/app-server/dynamic-tools.ts +623 -0
  24. package/src/app-server/elicitation-bridge.ts +783 -0
  25. package/src/app-server/event-projector.ts +2065 -0
  26. package/src/app-server/image-payload-sanitizer.ts +167 -0
  27. package/src/app-server/local-runtime-attribution.ts +39 -0
  28. package/src/app-server/managed-binary.ts +193 -0
  29. package/src/app-server/models.ts +172 -0
  30. package/src/app-server/native-hook-relay.ts +150 -0
  31. package/src/app-server/native-subagent-task-mirror.ts +497 -0
  32. package/src/app-server/plugin-activation.ts +283 -0
  33. package/src/app-server/plugin-app-cache-key.ts +74 -0
  34. package/src/app-server/plugin-approval-roundtrip.ts +122 -0
  35. package/src/app-server/plugin-inventory.ts +357 -0
  36. package/src/app-server/plugin-thread-config.ts +455 -0
  37. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +33 -0
  38. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +199 -0
  39. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +102 -0
  40. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +227 -0
  41. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +2630 -0
  42. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +2630 -0
  43. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +1659 -0
  44. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +1655 -0
  45. package/src/app-server/protocol-validators.ts +203 -0
  46. package/src/app-server/protocol.ts +520 -0
  47. package/src/app-server/rate-limit-cache.ts +48 -0
  48. package/src/app-server/rate-limits.ts +583 -0
  49. package/src/app-server/request.ts +73 -0
  50. package/src/app-server/run-attempt.ts +4862 -0
  51. package/src/app-server/session-binding.ts +398 -0
  52. package/src/app-server/session-history.ts +44 -0
  53. package/src/app-server/shared-client.ts +289 -0
  54. package/src/app-server/side-question.ts +1009 -0
  55. package/src/app-server/test-support.ts +48 -0
  56. package/src/app-server/thread-lifecycle.ts +959 -0
  57. package/src/app-server/timeout.ts +9 -0
  58. package/src/app-server/tool-progress-normalization.ts +77 -0
  59. package/src/app-server/trajectory.ts +368 -0
  60. package/src/app-server/transcript-mirror.ts +208 -0
  61. package/src/app-server/transport-stdio.ts +107 -0
  62. package/src/app-server/transport-websocket.ts +90 -0
  63. package/src/app-server/transport.ts +117 -0
  64. package/src/app-server/user-input-bridge.ts +316 -0
  65. package/src/app-server/version.ts +4 -0
  66. package/src/app-server/vision-tools.ts +12 -0
  67. package/src/command-account.ts +544 -0
  68. package/src/command-formatters.ts +426 -0
  69. package/src/command-handlers.ts +2021 -0
  70. package/src/command-plugins-management.ts +137 -0
  71. package/src/command-rpc.ts +142 -0
  72. package/src/commands.ts +65 -0
  73. package/src/conversation-binding-data.ts +124 -0
  74. package/src/conversation-binding.ts +561 -0
  75. package/src/conversation-control.ts +303 -0
  76. package/src/conversation-turn-collector.ts +186 -0
  77. package/src/conversation-turn-input.ts +106 -0
  78. package/src/migration/apply.ts +501 -0
  79. package/src/migration/helpers.ts +55 -0
  80. package/src/migration/plan.ts +461 -0
  81. package/src/migration/provider.ts +41 -0
  82. package/src/migration/source.ts +643 -0
  83. package/src/migration/targets.ts +25 -0
  84. package/src/node-cli-sessions.ts +711 -0
  85. package/test-api.ts +95 -0
  86. package/tsconfig.json +16 -0
@@ -0,0 +1,614 @@
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 "autobot/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("autobot: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("autobot: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("autobot: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
+ }
@@ -0,0 +1,27 @@
1
+ import { CodexAppServerRpcError } from "./client.js";
2
+
3
+ export const CODEX_CONTROL_METHODS = {
4
+ account: "account/read",
5
+ compact: "thread/compact/start",
6
+ feedback: "feedback/upload",
7
+ listMcpServers: "mcpServerStatus/list",
8
+ listSkills: "skills/list",
9
+ listThreads: "thread/list",
10
+ rateLimits: "account/rateLimits/read",
11
+ resumeThread: "thread/resume",
12
+ review: "review/start",
13
+ } as const;
14
+
15
+ type CodexControlName = keyof typeof CODEX_CONTROL_METHODS;
16
+ export type CodexControlMethod = (typeof CODEX_CONTROL_METHODS)[CodexControlName];
17
+
18
+ export function describeControlFailure(error: unknown): string {
19
+ if (isUnsupportedControlError(error)) {
20
+ return "unsupported by this Codex app-server";
21
+ }
22
+ return error instanceof Error ? error.message : String(error);
23
+ }
24
+
25
+ function isUnsupportedControlError(error: unknown): error is CodexAppServerRpcError {
26
+ return error instanceof CodexAppServerRpcError && error.code === -32601;
27
+ }
@@ -0,0 +1,24 @@
1
+ import type { resolveCodexAppServerAuthProfileIdForAgent } from "./auth-bridge.js";
2
+ import type { CodexAppServerClient } from "./client.js";
3
+ import type { CodexAppServerStartOptions } from "./config.js";
4
+
5
+ type AuthProfileOrderConfig = Parameters<
6
+ typeof resolveCodexAppServerAuthProfileIdForAgent
7
+ >[0]["config"];
8
+
9
+ export type CodexAppServerClientFactory = (
10
+ startOptions?: CodexAppServerStartOptions,
11
+ authProfileId?: string,
12
+ agentDir?: string,
13
+ config?: AuthProfileOrderConfig,
14
+ ) => Promise<CodexAppServerClient>;
15
+
16
+ export const defaultCodexAppServerClientFactory: CodexAppServerClientFactory = (
17
+ startOptions,
18
+ authProfileId,
19
+ agentDir,
20
+ config,
21
+ ) =>
22
+ import("./shared-client.js").then(({ getSharedCodexAppServerClient }) =>
23
+ getSharedCodexAppServerClient({ startOptions, authProfileId, agentDir, config }),
24
+ );