@gakr-gakr/codex 0.1.0 → 0.1.1

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 (115) hide show
  1. package/dist/client-DNN2uyJW.js +642 -0
  2. package/dist/client-factory-Bu9OClHJ.js +9 -0
  3. package/dist/command-formatters-BpPOTePl.js +520 -0
  4. package/dist/command-handlers-BBs7Vws9.js +1533 -0
  5. package/dist/compact-CDboBy7o.js +329 -0
  6. package/dist/computer-use-DCZB46Sw.js +367 -0
  7. package/dist/config-CLMSw0p2.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1171 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-jLA2SIvd.js +110 -0
  13. package/dist/node-cli-sessions-BLRDs_US.js +1216 -0
  14. package/dist/plugin-activation-CEy_oYpx.js +452 -0
  15. package/dist/prompt-overlay.js +12 -0
  16. package/dist/protocol-C9UWI98H.js +9 -0
  17. package/dist/protocol-validators-BGBspNmF.js +5988 -0
  18. package/dist/provider-catalog.js +84 -0
  19. package/dist/provider-discovery.js +33 -0
  20. package/dist/provider.js +150 -0
  21. package/dist/rate-limit-cache-9LxQdE0K.js +24 -0
  22. package/dist/request-DbSPeTcV.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-BoEwzQCv.js +5463 -0
  25. package/dist/session-binding-e2GFp9VH.js +222 -0
  26. package/dist/shared-client-D7Vy0glq.js +631 -0
  27. package/dist/side-question-BDLuEzFP.js +668 -0
  28. package/dist/test-api.js +49 -0
  29. package/dist/thread-lifecycle-Clo0EHMk.js +1565 -0
  30. package/dist/vision-tools-Cofrv35p.js +1379 -0
  31. package/package.json +16 -1
  32. package/doctor-contract-api.ts +0 -68
  33. package/harness.ts +0 -72
  34. package/index.ts +0 -124
  35. package/media-understanding-provider.ts +0 -521
  36. package/prompt-overlay.ts +0 -21
  37. package/provider-catalog.ts +0 -83
  38. package/provider-discovery.ts +0 -45
  39. package/provider.ts +0 -243
  40. package/src/app-server/app-inventory-cache.ts +0 -324
  41. package/src/app-server/approval-bridge.ts +0 -1211
  42. package/src/app-server/auth-bridge.ts +0 -614
  43. package/src/app-server/capabilities.ts +0 -27
  44. package/src/app-server/client-factory.ts +0 -24
  45. package/src/app-server/client.ts +0 -715
  46. package/src/app-server/compact.ts +0 -512
  47. package/src/app-server/computer-use.ts +0 -683
  48. package/src/app-server/config.ts +0 -1038
  49. package/src/app-server/context-engine-projection.ts +0 -403
  50. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  51. package/src/app-server/dynamic-tool-profile.ts +0 -70
  52. package/src/app-server/dynamic-tools.ts +0 -623
  53. package/src/app-server/elicitation-bridge.ts +0 -783
  54. package/src/app-server/event-projector.ts +0 -2065
  55. package/src/app-server/image-payload-sanitizer.ts +0 -167
  56. package/src/app-server/local-runtime-attribution.ts +0 -39
  57. package/src/app-server/managed-binary.ts +0 -193
  58. package/src/app-server/models.ts +0 -172
  59. package/src/app-server/native-hook-relay.ts +0 -150
  60. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  61. package/src/app-server/plugin-activation.ts +0 -283
  62. package/src/app-server/plugin-app-cache-key.ts +0 -74
  63. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  64. package/src/app-server/plugin-inventory.ts +0 -357
  65. package/src/app-server/plugin-thread-config.ts +0 -455
  66. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  67. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  68. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  69. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  70. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  71. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  72. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  73. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  74. package/src/app-server/protocol-validators.ts +0 -203
  75. package/src/app-server/protocol.ts +0 -520
  76. package/src/app-server/rate-limit-cache.ts +0 -48
  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.ts +0 -4862
  80. package/src/app-server/session-binding.ts +0 -398
  81. package/src/app-server/session-history.ts +0 -44
  82. package/src/app-server/shared-client.ts +0 -289
  83. package/src/app-server/side-question.ts +0 -1009
  84. package/src/app-server/test-support.ts +0 -48
  85. package/src/app-server/thread-lifecycle.ts +0 -959
  86. package/src/app-server/timeout.ts +0 -9
  87. package/src/app-server/tool-progress-normalization.ts +0 -77
  88. package/src/app-server/trajectory.ts +0 -368
  89. package/src/app-server/transcript-mirror.ts +0 -208
  90. package/src/app-server/transport-stdio.ts +0 -107
  91. package/src/app-server/transport-websocket.ts +0 -90
  92. package/src/app-server/transport.ts +0 -117
  93. package/src/app-server/user-input-bridge.ts +0 -316
  94. package/src/app-server/version.ts +0 -4
  95. package/src/app-server/vision-tools.ts +0 -12
  96. package/src/command-account.ts +0 -544
  97. package/src/command-formatters.ts +0 -426
  98. package/src/command-handlers.ts +0 -2021
  99. package/src/command-plugins-management.ts +0 -137
  100. package/src/command-rpc.ts +0 -142
  101. package/src/commands.ts +0 -65
  102. package/src/conversation-binding-data.ts +0 -124
  103. package/src/conversation-binding.ts +0 -561
  104. package/src/conversation-control.ts +0 -303
  105. package/src/conversation-turn-collector.ts +0 -186
  106. package/src/conversation-turn-input.ts +0 -106
  107. package/src/migration/apply.ts +0 -501
  108. package/src/migration/helpers.ts +0 -55
  109. package/src/migration/plan.ts +0 -461
  110. package/src/migration/provider.ts +0 -41
  111. package/src/migration/source.ts +0 -643
  112. package/src/migration/targets.ts +0 -25
  113. package/src/node-cli-sessions.ts +0 -711
  114. package/test-api.ts +0 -95
  115. package/tsconfig.json +0 -16
@@ -0,0 +1,631 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-DUslC3ob.js";
2
+ import { c as resolveCodexAppServerRuntimeOptions, n as codexAppServerStartOptionsKey } from "./config-CLMSw0p2.js";
3
+ import { a as MANAGED_CODEX_APP_SERVER_PACKAGE, o as resolveCodexAppServerSpawnEnv, t as CodexAppServerClient } from "./client-DNN2uyJW.js";
4
+ import { createRequire } from "node:module";
5
+ import { createHash } from "node:crypto";
6
+ import { constants, readFileSync } from "node:fs";
7
+ import fs, { access } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { ensureAuthProfileStore, ensureAuthProfileStoreWithoutExternalProfiles, loadAuthProfileStoreForSecretsRuntime, refreshOAuthCredentialForRuntime, resolveApiKeyForProfile, resolveAuthProfileOrder, resolveDefaultAgentDir, resolvePersistedAuthProfileOwnerAgentDir, resolveProviderIdForAuth } from "autobot/plugin-sdk/agent-runtime";
10
+ import { fileURLToPath } from "node:url";
11
+ import { withTimeout } from "autobot/plugin-sdk/security-runtime";
12
+ //#region extensions/codex/src/app-server/auth-bridge.ts
13
+ const CODEX_APP_SERVER_AUTH_PROVIDER = "openai-codex";
14
+ const OPENAI_PROVIDER = "openai";
15
+ const OPENAI_CODEX_DEFAULT_PROFILE_ID = "openai-codex:default";
16
+ const CODEX_HOME_ENV_VAR = "CODEX_HOME";
17
+ const HOME_ENV_VAR = "HOME";
18
+ const CODEX_APP_SERVER_HOME_DIRNAME = "codex-home";
19
+ const CODEX_APP_SERVER_API_KEY_ENV_VARS = ["CODEX_API_KEY", "OPENAI_API_KEY"];
20
+ const CODEX_APP_SERVER_HOME_ENV_VARS = [CODEX_HOME_ENV_VAR, HOME_ENV_VAR];
21
+ async function bridgeCodexAppServerStartOptions(params) {
22
+ if (params.startOptions.transport !== "stdio") return params.startOptions;
23
+ const isolatedStartOptions = await withAgentCodexHomeEnvironment(params.startOptions, params.agentDir);
24
+ if (params.authProfileId === null) return isolatedStartOptions;
25
+ const store = ensureCodexAppServerAuthProfileStore({
26
+ agentDir: params.agentDir,
27
+ authProfileId: params.authProfileId,
28
+ config: params.config
29
+ });
30
+ return shouldClearOpenAiApiKeyForCodexAuthProfile({
31
+ store,
32
+ authProfileId: resolveCodexAppServerAuthProfileId({
33
+ authProfileId: params.authProfileId,
34
+ store,
35
+ config: params.config
36
+ }),
37
+ config: params.config
38
+ }) ? withClearedEnvironmentVariables(isolatedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS) : isolatedStartOptions;
39
+ }
40
+ function resolveCodexAppServerAuthProfileId(params) {
41
+ const requested = params.authProfileId?.trim();
42
+ if (requested) return requested;
43
+ return resolveAuthProfileOrder({
44
+ cfg: params.config,
45
+ store: params.store,
46
+ provider: CODEX_APP_SERVER_AUTH_PROVIDER
47
+ })[0]?.trim();
48
+ }
49
+ function resolveCodexAppServerAuthProfileIdForAgent(params) {
50
+ const store = ensureCodexAppServerAuthProfileStore({
51
+ agentDir: params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {}),
52
+ authProfileId: params.authProfileId,
53
+ config: params.config
54
+ });
55
+ return resolveCodexAppServerAuthProfileId({
56
+ authProfileId: params.authProfileId,
57
+ store,
58
+ config: params.config
59
+ });
60
+ }
61
+ function ensureCodexAppServerAuthProfileStore(params) {
62
+ return ensureAuthProfileStore(params.agentDir, {
63
+ allowKeychainPrompt: false,
64
+ config: params.config,
65
+ externalCliProviderIds: [CODEX_APP_SERVER_AUTH_PROVIDER],
66
+ ...params.authProfileId ? { externalCliProfileIds: [params.authProfileId] } : {}
67
+ });
68
+ }
69
+ function resolveCodexAppServerAuthProfileStore(params) {
70
+ const overlaidStore = ensureCodexAppServerAuthProfileStore({
71
+ agentDir: params.agentDir,
72
+ authProfileId: params.authProfileId,
73
+ config: params.config
74
+ });
75
+ if (!params.authProfileStore) return overlaidStore;
76
+ const order = params.authProfileStore.order || overlaidStore.order ? {
77
+ ...overlaidStore.order,
78
+ ...params.authProfileStore.order
79
+ } : void 0;
80
+ return {
81
+ ...params.authProfileStore,
82
+ ...order ? { order } : {},
83
+ profiles: {
84
+ ...overlaidStore.profiles,
85
+ ...params.authProfileStore.profiles
86
+ }
87
+ };
88
+ }
89
+ async function resolveCodexAppServerAuthAccountCacheKey(params) {
90
+ const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
91
+ const store = resolveCodexAppServerAuthProfileStore({
92
+ agentDir,
93
+ authProfileId: params.authProfileId,
94
+ authProfileStore: params.authProfileStore,
95
+ config: params.config
96
+ });
97
+ const profileId = resolveCodexAppServerAuthProfileId({
98
+ authProfileId: params.authProfileId,
99
+ store,
100
+ config: params.config
101
+ });
102
+ if (!profileId) return;
103
+ const credential = store.profiles[profileId];
104
+ if (!credential || !isCodexAppServerAuthProfileCredential(credential, params.config)) return;
105
+ if (credential.type === "api_key") {
106
+ const apiKey = (await resolveApiKeyForProfile({
107
+ store,
108
+ profileId,
109
+ agentDir
110
+ }))?.apiKey?.trim();
111
+ return apiKey ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintApiKeyAuthProfileCacheKey(apiKey)}` : resolveChatgptAccountId(profileId, credential);
112
+ }
113
+ if (credential.type === "token") {
114
+ const accessToken = (await resolveApiKeyForProfile({
115
+ store,
116
+ profileId,
117
+ agentDir
118
+ }))?.apiKey?.trim();
119
+ return accessToken ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintTokenAuthProfileCacheKey(accessToken)}` : resolveChatgptAccountId(profileId, credential);
120
+ }
121
+ return resolveChatgptAccountId(profileId, credential);
122
+ }
123
+ function resolveCodexAppServerEnvApiKeyCacheKey(params) {
124
+ if (params.startOptions.transport !== "stdio") return;
125
+ const apiKey = readFirstNonEmptyEnvEntry(resolveCodexAppServerSpawnEnv(params.startOptions, params.baseEnv ?? process.env, params.platform ?? process.platform), CODEX_APP_SERVER_API_KEY_ENV_VARS);
126
+ if (!apiKey) return;
127
+ const hash = createHash("sha256");
128
+ hash.update("autobot:codex:app-server-env-api-key:v1");
129
+ hash.update("\0");
130
+ hash.update(apiKey.key);
131
+ hash.update("\0");
132
+ hash.update(apiKey.value);
133
+ return `${apiKey.key}:sha256:${hash.digest("hex")}`;
134
+ }
135
+ function fingerprintApiKeyAuthProfileCacheKey(apiKey) {
136
+ const hash = createHash("sha256");
137
+ hash.update("autobot:codex:app-server-auth-profile-api-key:v1");
138
+ hash.update("\0");
139
+ hash.update(apiKey);
140
+ return `api_key:sha256:${hash.digest("hex")}`;
141
+ }
142
+ function fingerprintTokenAuthProfileCacheKey(accessToken) {
143
+ const hash = createHash("sha256");
144
+ hash.update("autobot:codex:app-server-auth-profile-token:v1");
145
+ hash.update("\0");
146
+ hash.update(accessToken);
147
+ return `token:sha256:${hash.digest("hex")}`;
148
+ }
149
+ function resolveCodexAppServerHomeDir(agentDir) {
150
+ return path.join(path.resolve(agentDir), CODEX_APP_SERVER_HOME_DIRNAME);
151
+ }
152
+ async function withAgentCodexHomeEnvironment(startOptions, agentDir) {
153
+ const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim() ? startOptions.env[CODEX_HOME_ENV_VAR] : resolveCodexAppServerHomeDir(agentDir);
154
+ const nativeHome = startOptions.env?.[HOME_ENV_VAR]?.trim() ? startOptions.env[HOME_ENV_VAR] : void 0;
155
+ await fs.mkdir(codexHome, { recursive: true });
156
+ if (nativeHome) await fs.mkdir(nativeHome, { recursive: true });
157
+ const nextStartOptions = {
158
+ ...startOptions,
159
+ env: {
160
+ ...startOptions.env,
161
+ [CODEX_HOME_ENV_VAR]: codexHome,
162
+ ...nativeHome ? { [HOME_ENV_VAR]: nativeHome } : {}
163
+ }
164
+ };
165
+ const clearEnv = withoutClearedCodexHomeEnv(startOptions.clearEnv);
166
+ if (clearEnv) nextStartOptions.clearEnv = clearEnv;
167
+ else delete nextStartOptions.clearEnv;
168
+ return nextStartOptions;
169
+ }
170
+ function withoutClearedCodexHomeEnv(clearEnv) {
171
+ if (!clearEnv) return;
172
+ const reserved = new Set(CODEX_APP_SERVER_HOME_ENV_VARS);
173
+ const filtered = clearEnv.filter((envVar) => !reserved.has(envVar.trim().toUpperCase()));
174
+ return filtered.length === clearEnv.length ? clearEnv : filtered;
175
+ }
176
+ async function applyCodexAppServerAuthProfile(params) {
177
+ if (params.authProfileId === null) return;
178
+ const loginParams = await resolveCodexAppServerAuthProfileLoginParams({
179
+ agentDir: params.agentDir,
180
+ authProfileId: params.authProfileId,
181
+ config: params.config
182
+ });
183
+ if (!loginParams) {
184
+ if (params.startOptions?.transport !== "stdio") return;
185
+ const env = resolveCodexAppServerSpawnEnv(params.startOptions, process.env);
186
+ const fallbackLoginParams = await resolveCodexAppServerEnvApiKeyLoginParams({
187
+ client: params.client,
188
+ env
189
+ });
190
+ if (fallbackLoginParams) await params.client.request("account/login/start", fallbackLoginParams);
191
+ return;
192
+ }
193
+ await params.client.request("account/login/start", loginParams);
194
+ }
195
+ function resolveCodexAppServerAuthProfileLoginParams(params) {
196
+ return resolveCodexAppServerAuthProfileLoginParamsInternal(params);
197
+ }
198
+ async function refreshCodexAppServerAuthTokens(params) {
199
+ const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
200
+ ...params,
201
+ forceOAuthRefresh: true
202
+ });
203
+ if (!loginParams || loginParams.type !== "chatgptAuthTokens") throw new Error("Codex app-server ChatGPT token refresh requires an OAuth auth profile.");
204
+ return {
205
+ accessToken: loginParams.accessToken,
206
+ chatgptAccountId: loginParams.chatgptAccountId,
207
+ chatgptPlanType: loginParams.chatgptPlanType ?? null
208
+ };
209
+ }
210
+ async function resolveCodexAppServerAuthProfileLoginParamsInternal(params) {
211
+ const store = ensureCodexAppServerAuthProfileStore({
212
+ agentDir: params.agentDir,
213
+ authProfileId: params.authProfileId,
214
+ config: params.config
215
+ });
216
+ const profileId = resolveCodexAppServerAuthProfileId({
217
+ authProfileId: params.authProfileId,
218
+ store,
219
+ config: params.config
220
+ });
221
+ if (!profileId) return;
222
+ const credential = store.profiles[profileId];
223
+ if (!credential) throw new Error(`Codex app-server auth profile "${profileId}" was not found.`);
224
+ if (!isCodexAppServerAuthProfileCredential(credential, params.config)) throw new Error(`Codex app-server auth profile "${profileId}" must be OpenAI Codex auth or an OpenAI API-key backup.`);
225
+ const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
226
+ agentDir: params.agentDir,
227
+ forceOAuthRefresh: params.forceOAuthRefresh === true,
228
+ config: params.config
229
+ });
230
+ if (!loginParams) throw new Error(`Codex app-server auth profile "${profileId}" does not contain usable credentials.`);
231
+ return loginParams;
232
+ }
233
+ async function resolveCodexAppServerEnvApiKeyLoginParams(params) {
234
+ const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS);
235
+ if (!apiKey) return;
236
+ const response = await params.client.request("account/read", { refreshToken: false });
237
+ if (response.account || !response.requiresOpenaiAuth) return;
238
+ return {
239
+ type: "apiKey",
240
+ apiKey
241
+ };
242
+ }
243
+ async function resolveLoginParamsForCredential(profileId, credential, params) {
244
+ if (credential.type === "api_key") {
245
+ const apiKey = (await resolveApiKeyForProfile({
246
+ store: ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
247
+ profileId,
248
+ agentDir: params.agentDir
249
+ }))?.apiKey?.trim();
250
+ return apiKey ? {
251
+ type: "apiKey",
252
+ apiKey
253
+ } : void 0;
254
+ }
255
+ if (credential.type === "token") {
256
+ const accessToken = (await resolveApiKeyForProfile({
257
+ store: ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
258
+ profileId,
259
+ agentDir: params.agentDir
260
+ }))?.apiKey?.trim();
261
+ return accessToken ? buildChatgptAuthTokensParams(profileId, credential, accessToken) : void 0;
262
+ }
263
+ if (credential.type !== "oauth") return;
264
+ const resolvedCredential = await resolveOAuthCredentialForCodexAppServer(profileId, credential, {
265
+ agentDir: params.agentDir,
266
+ forceRefresh: params.forceOAuthRefresh,
267
+ config: params.config
268
+ });
269
+ const accessToken = resolvedCredential.access?.trim();
270
+ return accessToken ? buildChatgptAuthTokensParams(profileId, resolvedCredential, accessToken) : void 0;
271
+ }
272
+ async function resolveOAuthCredentialForCodexAppServer(profileId, credential, params) {
273
+ const ownerAgentDir = resolvePersistedAuthProfileOwnerAgentDir({
274
+ agentDir: params.agentDir,
275
+ profileId
276
+ });
277
+ const store = ensureCodexAppServerAuthProfileStore({
278
+ agentDir: ownerAgentDir,
279
+ authProfileId: profileId,
280
+ config: params.config
281
+ });
282
+ const persistedCredential = ensureAuthProfileStoreWithoutExternalProfiles(ownerAgentDir, { allowKeychainPrompt: false }).profiles[profileId];
283
+ const persistedOAuthCredential = persistedCredential?.type === "oauth" && isCodexAppServerAuthProvider(persistedCredential.provider, params.config) ? persistedCredential : void 0;
284
+ const ownerCredential = store.profiles[profileId];
285
+ const overlaidOAuthCredential = ownerCredential?.type === "oauth" && isCodexAppServerAuthProvider(ownerCredential.provider, params.config) ? ownerCredential : void 0;
286
+ if (params.forceRefresh && !persistedOAuthCredential && overlaidOAuthCredential) {
287
+ const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({ credential: overlaidOAuthCredential });
288
+ if (!refreshedRuntimeCredential?.access?.trim()) throw new Error(`Codex app-server auth profile "${profileId}" could not refresh.`);
289
+ store.profiles[profileId] = refreshedRuntimeCredential;
290
+ return refreshedRuntimeCredential;
291
+ }
292
+ const resolved = await resolveApiKeyForProfile({
293
+ store,
294
+ profileId,
295
+ agentDir: ownerAgentDir,
296
+ forceRefresh: params.forceRefresh && Boolean(persistedOAuthCredential)
297
+ });
298
+ const refreshed = loadAuthProfileStoreForSecretsRuntime(ownerAgentDir).profiles[profileId];
299
+ const storedCredential = store.profiles[profileId];
300
+ const candidate = refreshed?.type === "oauth" && isCodexAppServerAuthProvider(refreshed.provider, params.config) ? refreshed : storedCredential?.type === "oauth" && isCodexAppServerAuthProvider(storedCredential.provider, params.config) ? storedCredential : credential;
301
+ return resolved?.apiKey ? {
302
+ ...candidate,
303
+ access: resolved.apiKey
304
+ } : candidate;
305
+ }
306
+ function isCodexAppServerAuthProvider(provider, config) {
307
+ return resolveProviderIdForAuth(provider, { config }) === CODEX_APP_SERVER_AUTH_PROVIDER;
308
+ }
309
+ function isOpenAIApiKeyBackupCredential(credential, config) {
310
+ return credential.type === "api_key" && resolveProviderIdForAuth(credential.provider, { config }) === OPENAI_PROVIDER;
311
+ }
312
+ function isCodexAppServerAuthProfileCredential(credential, config) {
313
+ return isCodexAppServerAuthProvider(credential.provider, config) || isOpenAIApiKeyBackupCredential(credential, config);
314
+ }
315
+ function shouldClearOpenAiApiKeyForCodexAuthProfile(params) {
316
+ const profileId = params.authProfileId?.trim();
317
+ return isCodexSubscriptionCredential(profileId ? params.store.profiles[profileId] : params.store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID], params.config);
318
+ }
319
+ function isCodexSubscriptionCredential(credential, config) {
320
+ if (!credential || !isCodexAppServerAuthProvider(credential.provider, config)) return false;
321
+ return credential.type === "oauth" || credential.type === "token";
322
+ }
323
+ function withClearedEnvironmentVariables(startOptions, envVars) {
324
+ const clearEnv = startOptions.clearEnv ?? [];
325
+ const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
326
+ if (missingEnvVars.length === 0) return startOptions;
327
+ return {
328
+ ...startOptions,
329
+ clearEnv: [...clearEnv, ...missingEnvVars]
330
+ };
331
+ }
332
+ function readFirstNonEmptyEnv(env, keys) {
333
+ return readFirstNonEmptyEnvEntry(env, keys)?.value;
334
+ }
335
+ function readFirstNonEmptyEnvEntry(env, keys) {
336
+ for (const key of keys) {
337
+ const value = env[key]?.trim();
338
+ if (value) return {
339
+ key,
340
+ value
341
+ };
342
+ }
343
+ }
344
+ function buildChatgptAuthTokensParams(profileId, credential, accessToken) {
345
+ return {
346
+ type: "chatgptAuthTokens",
347
+ accessToken,
348
+ chatgptAccountId: resolveChatgptAccountId(profileId, credential),
349
+ chatgptPlanType: resolveChatgptPlanType(credential)
350
+ };
351
+ }
352
+ function resolveChatgptPlanType(credential) {
353
+ const record = credential;
354
+ const planType = record.chatgptPlanType ?? record.planType;
355
+ return typeof planType === "string" && planType.trim() ? planType.trim() : null;
356
+ }
357
+ function resolveChatgptAccountId(profileId, credential) {
358
+ if ("accountId" in credential && typeof credential.accountId === "string") {
359
+ const accountId = credential.accountId.trim();
360
+ if (accountId) return accountId;
361
+ }
362
+ return credential.email?.trim() || profileId;
363
+ }
364
+ //#endregion
365
+ //#region extensions/codex/src/app-server/managed-binary.ts
366
+ const CODEX_PLUGIN_ROOT = resolveDefaultCodexPluginRoot(path.dirname(fileURLToPath(import.meta.url)));
367
+ async function resolveManagedCodexAppServerStartOptions(startOptions, options = {}) {
368
+ if (startOptions.transport !== "stdio" || startOptions.commandSource !== "managed") return startOptions;
369
+ const platform = options.platform ?? process.platform;
370
+ const paths = resolveManagedCodexAppServerPaths({
371
+ platform,
372
+ pluginRoot: options.pluginRoot
373
+ });
374
+ const pathExists = options.pathExists ?? commandPathExists;
375
+ const commandPath = await findManagedCodexAppServerCommandPath({
376
+ candidateCommandPaths: paths.candidateCommandPaths,
377
+ pathExists,
378
+ platform
379
+ });
380
+ return {
381
+ ...startOptions,
382
+ command: commandPath,
383
+ commandSource: "resolved-managed"
384
+ };
385
+ }
386
+ function resolveManagedCodexAppServerPaths(params) {
387
+ const platform = params.platform ?? process.platform;
388
+ const candidateCommandPaths = resolveManagedCodexAppServerCommandCandidates(params.pluginRoot ?? CODEX_PLUGIN_ROOT, platform);
389
+ return {
390
+ commandPath: candidateCommandPaths[0] ?? "",
391
+ candidateCommandPaths
392
+ };
393
+ }
394
+ function resolveManagedCodexAppServerCommandCandidates(pluginRoot, platform) {
395
+ const pathApi = pathForPlatform(platform);
396
+ const commandName = platform === "win32" ? "codex.cmd" : "codex";
397
+ const roots = resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform);
398
+ return [...new Set([...roots.map((root) => pathApi.join(root, "node_modules", ".bin", commandName)), ...resolveManagedCodexPackageBinCandidates(roots, platform)])];
399
+ }
400
+ function resolveDefaultCodexPluginRoot(moduleDir) {
401
+ const moduleBaseName = path.basename(moduleDir);
402
+ if (moduleBaseName === "dist" || moduleBaseName === "dist-runtime") return path.dirname(moduleDir);
403
+ return path.resolve(moduleDir, "..", "..");
404
+ }
405
+ function resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform) {
406
+ const pathApi = pathForPlatform(platform);
407
+ return [
408
+ pluginRoot,
409
+ pathApi.dirname(pluginRoot),
410
+ pathApi.dirname(pathApi.dirname(pluginRoot)),
411
+ isDistExtensionRoot(pluginRoot, platform) ? pathApi.dirname(pathApi.dirname(pathApi.dirname(pluginRoot))) : null
412
+ ].filter((root) => Boolean(root));
413
+ }
414
+ function resolveManagedCodexPackageBinCandidates(roots, platform) {
415
+ if (platform === "win32") return [];
416
+ const candidates = [];
417
+ for (const root of roots) {
418
+ const candidate = resolveManagedCodexPackageBinCandidate(root);
419
+ if (candidate) candidates.push(candidate);
420
+ }
421
+ return candidates;
422
+ }
423
+ function resolveManagedCodexPackageBinCandidate(root) {
424
+ try {
425
+ const packageJsonPath = createRequire(path.join(root, "package.json")).resolve(`${MANAGED_CODEX_APP_SERVER_PACKAGE}/package.json`);
426
+ const packageRoot = path.dirname(packageJsonPath);
427
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
428
+ const binPath = typeof packageJson.bin === "string" ? packageJson.bin : isRecord(packageJson.bin) && typeof packageJson.bin.codex === "string" ? packageJson.bin.codex : null;
429
+ return binPath ? path.resolve(packageRoot, binPath) : null;
430
+ } catch {
431
+ return null;
432
+ }
433
+ }
434
+ function isRecord(value) {
435
+ return typeof value === "object" && value !== null;
436
+ }
437
+ function isDistExtensionRoot(pluginRoot, platform) {
438
+ const pathApi = pathForPlatform(platform);
439
+ const extensionsDir = pathApi.dirname(pluginRoot);
440
+ const distDir = pathApi.dirname(extensionsDir);
441
+ return pathApi.basename(extensionsDir) === "extensions" && (pathApi.basename(distDir) === "dist" || pathApi.basename(distDir) === "dist-runtime");
442
+ }
443
+ function pathForPlatform(platform) {
444
+ return platform === "win32" ? path.win32 : path.posix;
445
+ }
446
+ async function findManagedCodexAppServerCommandPath(params) {
447
+ for (const commandPath of params.candidateCommandPaths) if (await params.pathExists(commandPath, params.platform)) return commandPath;
448
+ throw new Error([
449
+ `Managed Codex app-server binary was not found for ${MANAGED_CODEX_APP_SERVER_PACKAGE}.`,
450
+ "Reinstall or update AutoBot, or run pnpm install in a source checkout.",
451
+ "Set plugins.entries.codex.config.appServer.command or AUTOBOT_CODEX_APP_SERVER_BIN to use a custom Codex binary."
452
+ ].join(" "));
453
+ }
454
+ async function commandPathExists(filePath, platform) {
455
+ try {
456
+ await access(filePath, platform === "win32" ? constants.F_OK : constants.X_OK);
457
+ return true;
458
+ } catch {
459
+ return false;
460
+ }
461
+ }
462
+ //#endregion
463
+ //#region extensions/codex/src/app-server/timeout.ts
464
+ async function withTimeout$1(promise, timeoutMs, timeoutMessage) {
465
+ return await withTimeout(promise, timeoutMs, { message: timeoutMessage });
466
+ }
467
+ //#endregion
468
+ //#region extensions/codex/src/app-server/shared-client.ts
469
+ var shared_client_exports = /* @__PURE__ */ __exportAll({
470
+ clearSharedCodexAppServerClientAndWait: () => clearSharedCodexAppServerClientAndWait,
471
+ clearSharedCodexAppServerClientIfCurrent: () => clearSharedCodexAppServerClientIfCurrent,
472
+ clearSharedCodexAppServerClientIfCurrentAndWait: () => clearSharedCodexAppServerClientIfCurrentAndWait,
473
+ createIsolatedCodexAppServerClient: () => createIsolatedCodexAppServerClient,
474
+ getSharedCodexAppServerClient: () => getSharedCodexAppServerClient
475
+ });
476
+ const SHARED_CODEX_APP_SERVER_CLIENT_STATE = Symbol.for("autobot.codexAppServerClientState");
477
+ function getSharedCodexAppServerClientState() {
478
+ const globalState = globalThis;
479
+ const state = globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE];
480
+ if (isSharedCodexAppServerClientState(state)) return state;
481
+ const legacyState = readLegacySharedCodexAppServerClientState(state);
482
+ const clients = /* @__PURE__ */ new Map();
483
+ if (legacyState?.key && (legacyState.client || legacyState.promise)) {
484
+ const legacyKey = legacyState.key;
485
+ clients.set(legacyKey, {
486
+ client: legacyState.client,
487
+ promise: legacyState.promise
488
+ });
489
+ legacyState.client?.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(legacyKey, closedClient));
490
+ }
491
+ const nextState = { clients };
492
+ globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] = nextState;
493
+ return nextState;
494
+ }
495
+ function isSharedCodexAppServerClientState(value) {
496
+ return value !== null && typeof value === "object" && value.clients instanceof Map;
497
+ }
498
+ function readLegacySharedCodexAppServerClientState(value) {
499
+ if (value === null || typeof value !== "object") return;
500
+ return value;
501
+ }
502
+ async function getSharedCodexAppServerClient(options) {
503
+ const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
504
+ const usesNativeAuth = options?.authProfileId === null;
505
+ const requestedAuthProfileId = options?.authProfileId === null ? void 0 : options?.authProfileId;
506
+ const authProfileId = usesNativeAuth ? void 0 : resolveCodexAppServerAuthProfileIdForAgent({
507
+ authProfileId: requestedAuthProfileId,
508
+ agentDir,
509
+ config: options?.config
510
+ });
511
+ const startOptions = await bridgeCodexAppServerStartOptions({
512
+ startOptions: await resolveManagedCodexAppServerStartOptions(options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start),
513
+ agentDir,
514
+ authProfileId: usesNativeAuth ? null : authProfileId,
515
+ config: options?.config
516
+ });
517
+ const key = codexAppServerStartOptionsKey(startOptions, {
518
+ authProfileId,
519
+ agentDir: usesNativeAuth ? void 0 : agentDir
520
+ });
521
+ const state = getSharedCodexAppServerClientState();
522
+ const entry = getOrCreateSharedClientEntry(state, key);
523
+ const sharedPromise = entry.promise ?? (entry.promise = (async () => {
524
+ const client = CodexAppServerClient.start(startOptions);
525
+ entry.client = client;
526
+ client.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(key, closedClient));
527
+ try {
528
+ await client.initialize();
529
+ await applyCodexAppServerAuthProfile({
530
+ client,
531
+ agentDir,
532
+ authProfileId: usesNativeAuth ? null : authProfileId,
533
+ startOptions,
534
+ config: options?.config
535
+ });
536
+ return client;
537
+ } catch (error) {
538
+ client.close();
539
+ throw error;
540
+ }
541
+ })());
542
+ try {
543
+ return await withTimeout$1(sharedPromise, options?.timeoutMs ?? 0, "codex app-server initialize timed out");
544
+ } catch (error) {
545
+ const currentEntry = state.clients.get(key);
546
+ if (currentEntry?.promise === sharedPromise) clearSharedClientEntry(key, currentEntry);
547
+ throw error;
548
+ }
549
+ }
550
+ async function createIsolatedCodexAppServerClient(options) {
551
+ const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
552
+ const usesNativeAuth = options?.authProfileId === null;
553
+ const requestedAuthProfileId = options?.authProfileId === null ? void 0 : options?.authProfileId;
554
+ const authProfileId = usesNativeAuth ? void 0 : resolveCodexAppServerAuthProfileIdForAgent({
555
+ authProfileId: requestedAuthProfileId,
556
+ agentDir,
557
+ config: options?.config
558
+ });
559
+ const startOptions = await bridgeCodexAppServerStartOptions({
560
+ startOptions: await resolveManagedCodexAppServerStartOptions(options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start),
561
+ agentDir,
562
+ authProfileId: usesNativeAuth ? null : authProfileId,
563
+ config: options?.config
564
+ });
565
+ const client = CodexAppServerClient.start(startOptions);
566
+ const initialize = client.initialize();
567
+ try {
568
+ await withTimeout$1(initialize, options?.timeoutMs ?? 0, "codex app-server initialize timed out");
569
+ await applyCodexAppServerAuthProfile({
570
+ client,
571
+ agentDir,
572
+ authProfileId: usesNativeAuth ? null : authProfileId,
573
+ startOptions,
574
+ config: options?.config
575
+ });
576
+ return client;
577
+ } catch (error) {
578
+ client.close();
579
+ initialize.catch(() => void 0);
580
+ throw error;
581
+ }
582
+ }
583
+ function clearSharedCodexAppServerClientIfCurrent(client) {
584
+ if (!client) return false;
585
+ const state = getSharedCodexAppServerClientState();
586
+ for (const [key, entry] of state.clients) if (entry.client === client) {
587
+ state.clients.delete(key);
588
+ client.close();
589
+ return true;
590
+ }
591
+ return false;
592
+ }
593
+ async function clearSharedCodexAppServerClientIfCurrentAndWait(client, options) {
594
+ if (!client) return false;
595
+ const state = getSharedCodexAppServerClientState();
596
+ for (const [key, entry] of state.clients) if (entry.client === client) {
597
+ state.clients.delete(key);
598
+ await client.closeAndWait(options);
599
+ return true;
600
+ }
601
+ return false;
602
+ }
603
+ async function clearSharedCodexAppServerClientAndWait(options) {
604
+ const state = getSharedCodexAppServerClientState();
605
+ const clients = collectSharedClients(state);
606
+ state.clients.clear();
607
+ await Promise.all(clients.map((client) => client.closeAndWait(options)));
608
+ }
609
+ function getOrCreateSharedClientEntry(state, key) {
610
+ let entry = state.clients.get(key);
611
+ if (!entry) {
612
+ entry = {};
613
+ state.clients.set(key, entry);
614
+ }
615
+ return entry;
616
+ }
617
+ function clearSharedClientEntry(key, entry) {
618
+ const state = getSharedCodexAppServerClientState();
619
+ if (state.clients.get(key) !== entry) return;
620
+ state.clients.delete(key);
621
+ entry.client?.close();
622
+ }
623
+ function clearSharedClientEntryIfCurrent(key, client) {
624
+ const state = getSharedCodexAppServerClientState();
625
+ if (state.clients.get(key)?.client === client) state.clients.delete(key);
626
+ }
627
+ function collectSharedClients(state) {
628
+ return [...new Set([...state.clients.values()].map((entry) => entry.client).filter((client) => Boolean(client)))];
629
+ }
630
+ //#endregion
631
+ export { shared_client_exports as a, resolveCodexAppServerAuthAccountCacheKey as c, resolveCodexAppServerEnvApiKeyCacheKey as d, resolveCodexAppServerHomeDir as f, getSharedCodexAppServerClient as i, resolveCodexAppServerAuthProfileId as l, clearSharedCodexAppServerClientIfCurrentAndWait as n, withTimeout$1 as o, createIsolatedCodexAppServerClient as r, refreshCodexAppServerAuthTokens as s, clearSharedCodexAppServerClientIfCurrent as t, resolveCodexAppServerAuthProfileIdForAgent as u };