@openclaw/codex 2026.7.2-beta.7 → 2026.7.33

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 (64) hide show
  1. package/README.md +3 -27
  2. package/dist/{command-formatters-C336eRVS.js → .setup/app-server-policy-C_qTMEMy.mjs} +51 -9
  3. package/dist/{attempt-notifications-AP-a-Q5k.js → .setup/attempt-notifications-F8krwWL4.mjs} +6 -3
  4. package/dist/{command-handlers-DAHUSry9.js → .setup/command-handlers-DSRFfor4.mjs} +1156 -1319
  5. package/dist/.setup/command-rpc-BvYsfQ7G.mjs +786 -0
  6. package/dist/{compact-D_uvHurS.js → .setup/compact-BNgh7I4t.mjs} +10 -40
  7. package/dist/.setup/computer-use-C3QkmSO3.mjs +377 -0
  8. package/dist/.setup/config-CYEDnLJ2.mjs +1138 -0
  9. package/dist/{conversation-binding-data-BHRpYbX3.js → .setup/conversation-binding-data-CrRxtDBu.mjs} +1 -1
  10. package/dist/{bounded-turn-D2ZAgZVz.js → .setup/media-understanding-provider-EbJCyDqe.mjs} +203 -109
  11. package/dist/{models-BBMKU4jA.js → .setup/models-C_aZk03A.mjs} +11 -6
  12. package/dist/.setup/notification-correlation-iYs4WieS.mjs +35 -0
  13. package/dist/.setup/plugin-app-cache-key-DR8jV9oS.mjs +99 -0
  14. package/dist/.setup/protocol-2POPqAY4.mjs +13 -0
  15. package/dist/{transcript-mirror-DzsdNCf5.js → .setup/protocol-validators-dZQ-UTOa.mjs} +112 -922
  16. package/dist/{rate-limits-CU-gVCCS.js → .setup/provider-DGxDs6g8.mjs} +269 -13
  17. package/dist/{dynamic-tools-D2gYkSBO.js → .setup/provider-capabilities-DS2N_zc1.mjs} +5632 -3953
  18. package/dist/.setup/request-DFR0JyoV.mjs +36 -0
  19. package/dist/.setup/run-attempt-C7xEKFVB.mjs +8180 -0
  20. package/dist/{sandbox-guard-NuhpXmPB.js → .setup/sandbox-guard-DA2TQfZW.mjs} +1 -14
  21. package/dist/.setup/session-binding-DuihlMJc.mjs +628 -0
  22. package/dist/.setup/shared-client-B2KmLPRw.mjs +1854 -0
  23. package/dist/{side-question-_ulBk1AL.js → .setup/side-question-Cv6JXWCS.mjs} +84 -159
  24. package/dist/.setup/thread-lifecycle-u6CZdOOH.mjs +2593 -0
  25. package/dist/{web-search-provider.runtime-CCFhg2z5.js → .setup/web-search-provider.runtime-Ce2zOHxW.mjs} +3 -3
  26. package/dist/doctor-contract-api.js +122 -88
  27. package/dist/harness.js +20 -89
  28. package/dist/index.js +436 -1615
  29. package/dist/media-understanding-provider.js +1 -173
  30. package/dist/prompt-overlay.js +15 -0
  31. package/dist/provider-catalog.js +79 -0
  32. package/dist/provider-discovery.js +34 -0
  33. package/dist/provider.js +2 -0
  34. package/dist/web-search-contract-api.js +1 -1
  35. package/openclaw.plugin.json +178 -221
  36. package/package.json +8 -9
  37. package/dist/app-server-policy-BSaO2JIT.js +0 -49
  38. package/dist/auth-binding-B4FfbcCg.js +0 -62
  39. package/dist/capabilities-BFDTVYr4.js +0 -36
  40. package/dist/cli-metadata.js +0 -20
  41. package/dist/computer-use-CYEc8U3w.js +0 -693
  42. package/dist/conversation-control-xsIeXbo4.js +0 -287
  43. package/dist/effective-mcp-catalog-Bbd98Inw.js +0 -114
  44. package/dist/event-projector-assistant-message-DTgnPPVF.js +0 -101
  45. package/dist/event-projector-usage-Xp4AlR2k.js +0 -86
  46. package/dist/incognito-session-ET_ufDH-.js +0 -2
  47. package/dist/notification-correlation-CU6_AnOb.js +0 -67
  48. package/dist/plugin-app-cache-key-DztPafOA.js +0 -408
  49. package/dist/request-qKh331yu.js +0 -157
  50. package/dist/run-attempt-CY9WlDLc.js +0 -12413
  51. package/dist/runtime-artifact-CmtG_t1L.js +0 -554
  52. package/dist/session-binding-BXpo9ymA.js +0 -2214
  53. package/dist/session-catalog-DyOgR4WH.js +0 -2668
  54. package/dist/session-cli-2PZaFLRh.js +0 -175
  55. package/dist/session-upstream-marker-B6U7tLw5.js +0 -82
  56. package/dist/settled-turn-finalizer-CXY2Z9dT.js +0 -316
  57. package/dist/shared-client-DTbvH-XV.js +0 -3069
  58. package/dist/thread-lifecycle-DF53ogiA.js +0 -3987
  59. package/dist/transport-stdio-DXgGZ7Ib.js +0 -88
  60. package/dist/upstream-session-fork-Dy4Xvuoj.js +0 -320
  61. package/dist/usage-CQ6GhD5-.js +0 -25
  62. /package/dist/{rolldown-runtime-8H4AJuhK.js → .setup/rolldown-runtime-8H4AJuhK.mjs} +0 -0
  63. /package/dist/{session-binding-meta-B7aEMU7g.js → .setup/session-binding-meta-B7aEMU7g.mjs} +0 -0
  64. /package/dist/{web-search-provider.shared-BrZmlqyR.js → .setup/web-search-provider.shared-BrZmlqyR.mjs} +0 -0
@@ -0,0 +1,1854 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
+ import { i as isRpcResponse, r as isJsonObject$1 } from "./protocol-2POPqAY4.mjs";
3
+ import { d as resolveCodexAppServerRuntimeOptions, f as resolveCodexAppServerUserHomeDir, r as codexAppServerStartOptionsKey } from "./config-CYEDnLJ2.mjs";
4
+ import { createRequire } from "node:module";
5
+ import fs, { access } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { createHash } from "node:crypto";
8
+ import fsSync, { constants, readFileSync } from "node:fs";
9
+ import os from "node:os";
10
+ import { ensureAuthProfileStore, findPersistedAuthProfileCredential, loadAuthProfileStoreForSecretsRuntime, refreshOAuthCredentialForRuntime, resolveApiKeyForProfile, resolveAuthProfileOrder, resolveDefaultAgentDir, resolvePersistedAuthProfileOwnerAgentDir, resolveProviderIdForAuth } from "openclaw/plugin-sdk/agent-runtime";
11
+ import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
12
+ import { OPENCLAW_VERSION, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
13
+ import { isDeepStrictEqual } from "node:util";
14
+ import { hasUsableOAuthCredential } from "openclaw/plugin-sdk/provider-auth";
15
+ import { spawn } from "node:child_process";
16
+ import { createInterface } from "node:readline";
17
+ import { EventEmitter } from "node:events";
18
+ import { PassThrough, Writable } from "node:stream";
19
+ import WebSocket from "ws";
20
+ import { fileURLToPath } from "node:url";
21
+ import { withTimeout } from "openclaw/plugin-sdk/security-runtime";
22
+ //#region extensions/codex/src/app-server/transport-stdio.ts
23
+ /**
24
+ * Creates and configures stdio-backed Codex app-server transports, including
25
+ * Windows spawn normalization and environment filtering.
26
+ */
27
+ const UNSAFE_ENVIRONMENT_KEYS = /* @__PURE__ */ new Set([
28
+ "__proto__",
29
+ "constructor",
30
+ "prototype"
31
+ ]);
32
+ const QA_PARENT_PID_ENV = "OPENCLAW_QA_PARENT_PID";
33
+ const DEFAULT_SPAWN_RUNTIME = {
34
+ platform: process.platform,
35
+ env: process.env,
36
+ execPath: process.execPath
37
+ };
38
+ /** Resolves the concrete command/argv/shell settings used to spawn Codex app-server. */
39
+ function resolveCodexAppServerSpawnInvocation(options, runtime = DEFAULT_SPAWN_RUNTIME) {
40
+ if (options.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
41
+ const program = resolveWindowsSpawnProgram({
42
+ command: options.command,
43
+ platform: runtime.platform,
44
+ env: runtime.env,
45
+ execPath: runtime.execPath,
46
+ packageName: "@openai/codex"
47
+ });
48
+ const resolved = materializeWindowsSpawnProgram(program, options.args);
49
+ return {
50
+ command: resolved.command,
51
+ args: resolved.argv,
52
+ shell: resolved.shell,
53
+ windowsHide: resolved.windowsHide
54
+ };
55
+ }
56
+ /** Merges app-server environment overrides while honoring clearEnv and unsafe key filtering. */
57
+ function resolveCodexAppServerSpawnEnv(options, baseEnv = process.env, platform = process.platform) {
58
+ const env = Object.create(null);
59
+ copySafeEnvironmentEntries(env, baseEnv);
60
+ copySafeEnvironmentEntries(env, options.env ?? {});
61
+ const keysToClear = normalizedEnvironmentKeys(options.clearEnv ?? []);
62
+ if (platform === "win32") {
63
+ const lowerCaseKeysToClear = new Set(keysToClear.map((key) => key.toLowerCase()));
64
+ for (const candidate of Object.keys(env)) if (lowerCaseKeysToClear.has(candidate.toLowerCase())) delete env[candidate];
65
+ } else for (const key of keysToClear) delete env[key];
66
+ return env;
67
+ }
68
+ /** Keeps QA-owned app-server processes inside the gateway process-group cleanup boundary. */
69
+ function resolveCodexAppServerDetachedMode(env, platform = process.platform) {
70
+ return platform !== "win32" && !env[QA_PARENT_PID_ENV]?.trim();
71
+ }
72
+ function normalizedEnvironmentKeys(rawKeys) {
73
+ const keys = [];
74
+ for (const rawKey of rawKeys) {
75
+ const key = rawKey.trim();
76
+ if (key.length > 0) keys.push(key);
77
+ }
78
+ return keys;
79
+ }
80
+ function copySafeEnvironmentEntries(target, source) {
81
+ for (const [key, value] of Object.entries(source)) {
82
+ if (UNSAFE_ENVIRONMENT_KEYS.has(key)) continue;
83
+ target[key] = value;
84
+ }
85
+ }
86
+ /** Spawns the Codex app-server process and returns the shared transport interface. */
87
+ function createStdioTransport(options) {
88
+ const env = resolveCodexAppServerSpawnEnv(options);
89
+ const invocation = resolveCodexAppServerSpawnInvocation(options, {
90
+ platform: process.platform,
91
+ env,
92
+ execPath: process.execPath
93
+ });
94
+ return spawn(invocation.command, invocation.args, {
95
+ env,
96
+ detached: resolveCodexAppServerDetachedMode(env),
97
+ shell: invocation.shell,
98
+ stdio: [
99
+ "pipe",
100
+ "pipe",
101
+ "pipe"
102
+ ],
103
+ windowsHide: invocation.windowsHide
104
+ });
105
+ }
106
+ //#endregion
107
+ //#region extensions/codex/src/app-server/auth-bridge.ts
108
+ const CODEX_APP_SERVER_AUTH_PROVIDER = "openai";
109
+ const OPENAI_CODEX_APP_SERVER_AUTH_PROVIDER = "openai-codex";
110
+ const LEGACY_CODEX_APP_SERVER_AUTH_PROVIDER = "codex-cli";
111
+ const CODEX_APP_SERVER_EXTERNAL_CLI_PROVIDER_IDS = [CODEX_APP_SERVER_AUTH_PROVIDER, LEGACY_CODEX_APP_SERVER_AUTH_PROVIDER];
112
+ const OPENAI_PROVIDER = "openai";
113
+ const OPENAI_CODEX_DEFAULT_PROFILE_ID = "openai:default";
114
+ const CODEX_HOME_ENV_VAR = "CODEX_HOME";
115
+ const HOME_ENV_VAR = "HOME";
116
+ const CODEX_APP_SERVER_HOME_DIRNAME = "codex-home";
117
+ const CODEX_APP_SERVER_API_KEY_ENV_VARS = ["CODEX_API_KEY", "OPENAI_API_KEY"];
118
+ const CODEX_APP_SERVER_HOME_ENV_VARS = [CODEX_HOME_ENV_VAR, HOME_ENV_VAR];
119
+ const CODEX_AUTH_JSON_FILENAME = "auth.json";
120
+ const CODEX_HOME_DIRNAME = ".codex";
121
+ const scopedOAuthRefreshQueues = /* @__PURE__ */ new WeakMap();
122
+ async function bridgeCodexAppServerStartOptions(params) {
123
+ if (params.startOptions.transport !== "stdio") return params.startOptions;
124
+ const scopedStartOptions = await withCodexHomeEnvironment(params.startOptions, params.agentDir);
125
+ if (params.authProfileId === null) return scopedStartOptions;
126
+ const store = resolveCodexAppServerAuthProfileStore({
127
+ agentDir: params.agentDir,
128
+ authProfileId: params.authProfileId,
129
+ authProfileStore: params.authProfileStore,
130
+ config: params.config
131
+ });
132
+ return shouldClearOpenAiApiKeyForCodexAuthProfile({
133
+ store,
134
+ authProfileId: resolveCodexAppServerAuthProfileId({
135
+ authProfileId: params.authProfileId,
136
+ store,
137
+ config: params.config
138
+ }),
139
+ config: params.config
140
+ }) ? withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS) : scopedStartOptions;
141
+ }
142
+ function resolveCodexAppServerAuthProfileId(params) {
143
+ const requested = params.authProfileId?.trim();
144
+ if (requested) return requested;
145
+ return resolveAuthProfileOrder({
146
+ cfg: params.config,
147
+ store: params.store,
148
+ provider: CODEX_APP_SERVER_AUTH_PROVIDER
149
+ })[0]?.trim();
150
+ }
151
+ function resolveCodexAppServerAuthProfileIdForAgent(params) {
152
+ const store = resolveCodexAppServerAuthProfileStore({
153
+ agentDir: params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {}),
154
+ authProfileId: params.authProfileId,
155
+ authProfileStore: params.authProfileStore,
156
+ config: params.config
157
+ });
158
+ return resolveCodexAppServerAuthProfileId({
159
+ authProfileId: params.authProfileId,
160
+ store,
161
+ config: params.config
162
+ });
163
+ }
164
+ function ensureCodexAppServerAuthProfileStore(params) {
165
+ return ensureAuthProfileStore(params.agentDir, {
166
+ allowKeychainPrompt: false,
167
+ config: params.config,
168
+ externalCliProviderIds: CODEX_APP_SERVER_EXTERNAL_CLI_PROVIDER_IDS,
169
+ ...params.authProfileId ? { externalCliProfileIds: [params.authProfileId] } : {}
170
+ });
171
+ }
172
+ function resolveCodexAppServerAuthProfileStore(params) {
173
+ if (params.authProfileStore) {
174
+ const providedProfileId = resolveCodexAppServerAuthProfileId({
175
+ authProfileId: params.authProfileId,
176
+ store: params.authProfileStore,
177
+ config: params.config
178
+ });
179
+ if (providedProfileId && params.authProfileStore.profiles[providedProfileId]) return params.authProfileStore;
180
+ }
181
+ const overlaidStore = ensureCodexAppServerAuthProfileStore({
182
+ agentDir: params.agentDir,
183
+ authProfileId: params.authProfileId,
184
+ config: params.config
185
+ });
186
+ if (!params.authProfileStore) return overlaidStore;
187
+ const order = params.authProfileStore.order || overlaidStore.order ? {
188
+ ...overlaidStore.order,
189
+ ...params.authProfileStore.order
190
+ } : void 0;
191
+ const profiles = {
192
+ ...overlaidStore.profiles,
193
+ ...params.authProfileStore.profiles
194
+ };
195
+ const suppliedProfileIds = new Set(Object.keys(params.authProfileStore.profiles));
196
+ const mergeRuntimeProfileIds = (overlaidIds, suppliedIds) => [...(overlaidIds ?? []).filter((profileId) => !suppliedProfileIds.has(profileId)), ...suppliedIds ?? []];
197
+ const runtimePersistedProfileIds = mergeRuntimeProfileIds(overlaidStore.runtimePersistedProfileIds, params.authProfileStore.runtimePersistedProfileIds).filter((profileId) => profiles[profileId]);
198
+ const runtimeExternalProfileIds = mergeRuntimeProfileIds(overlaidStore.runtimeExternalProfileIds, params.authProfileStore.runtimeExternalProfileIds).filter((profileId) => profiles[profileId]);
199
+ const runtimeExternalProfileIdsAuthoritative = overlaidStore.runtimeExternalProfileIdsAuthoritative === true || params.authProfileStore.runtimeExternalProfileIdsAuthoritative === true;
200
+ return {
201
+ ...params.authProfileStore,
202
+ ...order ? { order } : {},
203
+ profiles,
204
+ ...runtimePersistedProfileIds.length > 0 ? { runtimePersistedProfileIds: [...new Set(runtimePersistedProfileIds)] } : {},
205
+ ...runtimeExternalProfileIds.length > 0 || runtimeExternalProfileIdsAuthoritative ? {
206
+ runtimeExternalProfileIds: [...new Set(runtimeExternalProfileIds)],
207
+ ...runtimeExternalProfileIdsAuthoritative ? { runtimeExternalProfileIdsAuthoritative: true } : {}
208
+ } : {}
209
+ };
210
+ }
211
+ async function resolveCodexAppServerAuthAccountCacheKey(params) {
212
+ const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
213
+ const store = resolveCodexAppServerAuthProfileStore({
214
+ agentDir,
215
+ authProfileId: params.authProfileId,
216
+ authProfileStore: params.authProfileStore,
217
+ config: params.config
218
+ });
219
+ const profileId = resolveCodexAppServerAuthProfileId({
220
+ authProfileId: params.authProfileId,
221
+ store,
222
+ config: params.config
223
+ });
224
+ if (!profileId) return;
225
+ const credential = store.profiles[profileId];
226
+ if (!credential || !isCodexAppServerAuthProfileCredential(credential, params.config)) return;
227
+ if (credential.type === "api_key") {
228
+ const apiKey = (await resolveApiKeyForProfile({
229
+ store,
230
+ profileId,
231
+ agentDir
232
+ }))?.apiKey?.trim();
233
+ return apiKey ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintApiKeyAuthProfileCacheKey(apiKey)}` : resolveChatgptAccountId(profileId, credential);
234
+ }
235
+ if (credential.type === "token") {
236
+ const accessToken = (await resolveApiKeyForProfile({
237
+ store,
238
+ profileId,
239
+ agentDir
240
+ }))?.apiKey?.trim();
241
+ return accessToken ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintTokenAuthProfileCacheKey(accessToken)}` : resolveChatgptAccountId(profileId, credential);
242
+ }
243
+ return resolveChatgptAccountId(profileId, credential);
244
+ }
245
+ function resolveCodexAppServerEnvApiKeyCacheKey(params) {
246
+ if (params.startOptions.transport !== "stdio") return;
247
+ const apiKey = readFirstNonEmptyEnvEntry(resolveCodexAppServerSpawnEnv(params.startOptions, params.baseEnv ?? process.env, params.platform ?? process.platform), CODEX_APP_SERVER_API_KEY_ENV_VARS);
248
+ if (!apiKey) return;
249
+ const hash = createHash("sha256");
250
+ hash.update("openclaw:codex:app-server-env-api-key:v1");
251
+ hash.update("\0");
252
+ hash.update(apiKey.key);
253
+ hash.update("\0");
254
+ hash.update(apiKey.value);
255
+ return `${apiKey.key}:sha256:${hash.digest("hex")}`;
256
+ }
257
+ function resolveCodexAppServerFallbackApiKeyCacheKey(params) {
258
+ if (params.startOptions.transport !== "stdio") return;
259
+ return resolveCodexAppServerEnvApiKeyCacheKey(params) ?? resolveCodexCliAuthFileApiKeyCacheKey(params.baseEnv ?? process.env);
260
+ }
261
+ function fingerprintApiKeyAuthProfileCacheKey(apiKey) {
262
+ const hash = createHash("sha256");
263
+ hash.update("openclaw:codex:app-server-auth-profile-api-key:v1");
264
+ hash.update("\0");
265
+ hash.update(apiKey);
266
+ return `api_key:sha256:${hash.digest("hex")}`;
267
+ }
268
+ function fingerprintTokenAuthProfileCacheKey(accessToken) {
269
+ const hash = createHash("sha256");
270
+ hash.update("openclaw:codex:app-server-auth-profile-token:v1");
271
+ hash.update("\0");
272
+ hash.update(accessToken);
273
+ return `token:sha256:${hash.digest("hex")}`;
274
+ }
275
+ function fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) {
276
+ const hash = createHash("sha256");
277
+ hash.update("openclaw:codex:app-server-cli-auth-json-api-key:v1");
278
+ hash.update("\0");
279
+ hash.update(apiKey);
280
+ return `CODEX_AUTH_JSON:sha256:${hash.digest("hex")}`;
281
+ }
282
+ function resolveCodexAppServerHomeDir(agentDir) {
283
+ return path.join(path.resolve(agentDir), CODEX_APP_SERVER_HOME_DIRNAME);
284
+ }
285
+ async function withCodexHomeEnvironment(startOptions, agentDir) {
286
+ const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim() ? startOptions.env[CODEX_HOME_ENV_VAR] : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir(process.env) : resolveCodexAppServerHomeDir(agentDir);
287
+ const nativeHome = startOptions.env?.[HOME_ENV_VAR]?.trim() ? startOptions.env[HOME_ENV_VAR] : void 0;
288
+ await fs.mkdir(codexHome, { recursive: true });
289
+ if (nativeHome) await fs.mkdir(nativeHome, { recursive: true });
290
+ const nextStartOptions = {
291
+ ...startOptions,
292
+ env: {
293
+ ...startOptions.env,
294
+ [CODEX_HOME_ENV_VAR]: codexHome,
295
+ ...nativeHome ? { [HOME_ENV_VAR]: nativeHome } : {}
296
+ }
297
+ };
298
+ const clearEnv = withoutClearedCodexHomeEnv(startOptions.clearEnv);
299
+ if (clearEnv) nextStartOptions.clearEnv = clearEnv;
300
+ else delete nextStartOptions.clearEnv;
301
+ return nextStartOptions;
302
+ }
303
+ function withoutClearedCodexHomeEnv(clearEnv) {
304
+ if (!clearEnv) return;
305
+ const reserved = new Set(CODEX_APP_SERVER_HOME_ENV_VARS);
306
+ const filtered = clearEnv.filter((envVar) => !reserved.has(envVar.trim().toUpperCase()));
307
+ return filtered.length === clearEnv.length ? clearEnv : filtered;
308
+ }
309
+ async function applyCodexAppServerAuthProfile(params) {
310
+ if (params.authProfileId === null) return;
311
+ const loginParams = await resolveCodexAppServerAuthProfileLoginParams({
312
+ agentDir: params.agentDir,
313
+ authProfileId: params.authProfileId,
314
+ authProfileStore: params.authProfileStore,
315
+ config: params.config
316
+ });
317
+ if (!loginParams) {
318
+ if (params.startOptions?.transport !== "stdio") return;
319
+ const env = resolveCodexAppServerSpawnEnv(params.startOptions, process.env);
320
+ const fallbackLoginParams = await resolveCodexAppServerFallbackApiKeyLoginParams({
321
+ client: params.client,
322
+ env,
323
+ codexCliAuthEnv: process.env
324
+ });
325
+ if (fallbackLoginParams) await params.client.request("account/login/start", fallbackLoginParams);
326
+ return;
327
+ }
328
+ await params.client.request("account/login/start", loginParams);
329
+ }
330
+ function resolveCodexAppServerAuthProfileLoginParams(params) {
331
+ return resolveCodexAppServerAuthProfileLoginParamsInternal(params);
332
+ }
333
+ async function refreshCodexAppServerAuthTokens(params) {
334
+ const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
335
+ ...params,
336
+ forceOAuthRefresh: true
337
+ });
338
+ if (!loginParams || loginParams.type !== "chatgptAuthTokens") throw new Error("Codex app-server ChatGPT token refresh requires an OAuth auth profile.");
339
+ return {
340
+ accessToken: loginParams.accessToken,
341
+ chatgptAccountId: loginParams.chatgptAccountId,
342
+ chatgptPlanType: loginParams.chatgptPlanType ?? null
343
+ };
344
+ }
345
+ async function resolveCodexAppServerAuthProfileLoginParamsInternal(params) {
346
+ const store = resolveCodexAppServerAuthProfileStore({
347
+ agentDir: params.agentDir,
348
+ authProfileId: params.authProfileId,
349
+ authProfileStore: params.authProfileStore,
350
+ config: params.config
351
+ });
352
+ const profileId = resolveCodexAppServerAuthProfileId({
353
+ authProfileId: params.authProfileId,
354
+ store,
355
+ config: params.config
356
+ });
357
+ if (!profileId) return;
358
+ const credential = store.profiles[profileId];
359
+ if (!credential) throw new Error(`Codex app-server auth profile "${profileId}" was not found.`);
360
+ 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.`);
361
+ const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
362
+ agentDir: params.agentDir,
363
+ store,
364
+ preferStoreCredential: Boolean(params.authProfileStore?.profiles[profileId]),
365
+ forceOAuthRefresh: params.forceOAuthRefresh === true,
366
+ config: params.config
367
+ });
368
+ if (!loginParams) throw new Error(`Codex app-server auth profile "${profileId}" does not contain usable credentials.`);
369
+ return loginParams;
370
+ }
371
+ async function resolveCodexAppServerFallbackApiKeyLoginParams(params) {
372
+ const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS) ?? await readCodexCliAuthFileApiKey(params.codexCliAuthEnv);
373
+ if (!apiKey) return;
374
+ if ((await params.client.request("account/read", { refreshToken: false })).account) return;
375
+ return {
376
+ type: "apiKey",
377
+ apiKey
378
+ };
379
+ }
380
+ function resolveCodexCliAuthFilePath(env) {
381
+ const configuredCodexHome = env[CODEX_HOME_ENV_VAR]?.trim();
382
+ if (configuredCodexHome) return path.join(resolveHomeRelativePath(configuredCodexHome, env), CODEX_AUTH_JSON_FILENAME);
383
+ const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
384
+ return path.join(home, CODEX_HOME_DIRNAME, CODEX_AUTH_JSON_FILENAME);
385
+ }
386
+ function resolveHomeRelativePath(value, env) {
387
+ if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
388
+ const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
389
+ return path.join(home, value.slice(value === "~" ? 1 : 2));
390
+ }
391
+ return value;
392
+ }
393
+ function parseCodexCliAuthFileApiKey(raw) {
394
+ let parsed;
395
+ try {
396
+ parsed = JSON.parse(raw);
397
+ } catch {
398
+ return;
399
+ }
400
+ if (!parsed || typeof parsed !== "object") return;
401
+ const apiKey = parsed.OPENAI_API_KEY;
402
+ return typeof apiKey === "string" && apiKey.trim() ? apiKey.trim() : void 0;
403
+ }
404
+ async function readCodexCliAuthFileApiKey(env) {
405
+ try {
406
+ return parseCodexCliAuthFileApiKey(await fs.readFile(resolveCodexCliAuthFilePath(env), "utf8"));
407
+ } catch {
408
+ return;
409
+ }
410
+ }
411
+ function resolveCodexCliAuthFileApiKeyCacheKey(env) {
412
+ try {
413
+ const apiKey = parseCodexCliAuthFileApiKey(fsSync.readFileSync(resolveCodexCliAuthFilePath(env), "utf8"));
414
+ return apiKey ? fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) : void 0;
415
+ } catch {
416
+ return;
417
+ }
418
+ }
419
+ async function resolveLoginParamsForCredential(profileId, credential, params) {
420
+ if (credential.type === "api_key") {
421
+ const apiKey = (await resolveApiKeyForProfile({
422
+ store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
423
+ profileId,
424
+ agentDir: params.agentDir
425
+ }))?.apiKey?.trim();
426
+ return apiKey ? {
427
+ type: "apiKey",
428
+ apiKey
429
+ } : void 0;
430
+ }
431
+ if (credential.type === "token") {
432
+ const accessToken = (await resolveApiKeyForProfile({
433
+ store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
434
+ profileId,
435
+ agentDir: params.agentDir
436
+ }))?.apiKey?.trim();
437
+ return accessToken ? buildChatgptAuthTokensParams(profileId, credential, accessToken) : void 0;
438
+ }
439
+ if (credential.type !== "oauth") return;
440
+ const resolvedCredential = await resolveOAuthCredentialForCodexAppServer(profileId, credential, {
441
+ agentDir: params.agentDir,
442
+ store: params.store,
443
+ preferStoreCredential: params.preferStoreCredential,
444
+ forceRefresh: params.forceOAuthRefresh,
445
+ config: params.config
446
+ });
447
+ const accessToken = resolvedCredential.access?.trim();
448
+ return accessToken ? buildChatgptAuthTokensParams(profileId, resolvedCredential, accessToken) : void 0;
449
+ }
450
+ async function resolveOAuthCredentialForCodexAppServer(profileId, credential, params) {
451
+ const ownerAgentDir = resolvePersistedAuthProfileOwnerAgentDir({
452
+ agentDir: params.agentDir,
453
+ profileId
454
+ });
455
+ const persistedCredential = findPersistedAuthProfileCredential({
456
+ agentDir: ownerAgentDir,
457
+ profileId
458
+ });
459
+ const useScopedCredential = params.preferStoreCredential && shouldUseScopedOAuthCredential({
460
+ store: params.store,
461
+ profileId,
462
+ persistedCredential,
463
+ suppliedCredential: credential,
464
+ config: params.config
465
+ });
466
+ const store = useScopedCredential ? params.store : ensureCodexAppServerAuthProfileStore({
467
+ agentDir: ownerAgentDir,
468
+ authProfileId: profileId,
469
+ config: params.config
470
+ });
471
+ const persistedOAuthCredential = !useScopedCredential && persistedCredential?.type === "oauth" && isCodexAppServerAuthProvider(persistedCredential.provider, params.config) ? persistedCredential : void 0;
472
+ const ownerCredential = store.profiles[profileId];
473
+ const overlaidOAuthCredential = ownerCredential?.type === "oauth" && isCodexAppServerAuthProvider(ownerCredential.provider, params.config) ? ownerCredential : void 0;
474
+ if (useScopedCredential && overlaidOAuthCredential) return await resolveScopedOAuthCredential({
475
+ store,
476
+ profileId,
477
+ credential: overlaidOAuthCredential,
478
+ forceRefresh: params.forceRefresh
479
+ });
480
+ if (params.forceRefresh && !persistedOAuthCredential && overlaidOAuthCredential) {
481
+ const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({ credential: overlaidOAuthCredential });
482
+ if (!refreshedRuntimeCredential?.access?.trim()) throw new Error(`Codex app-server auth profile "${profileId}" could not refresh.`);
483
+ store.profiles[profileId] = refreshedRuntimeCredential;
484
+ return refreshedRuntimeCredential;
485
+ }
486
+ const resolved = await resolveApiKeyForProfile({
487
+ store,
488
+ profileId,
489
+ agentDir: ownerAgentDir,
490
+ forceRefresh: params.forceRefresh && Boolean(persistedOAuthCredential)
491
+ });
492
+ const refreshed = useScopedCredential ? void 0 : loadAuthProfileStoreForSecretsRuntime(ownerAgentDir).profiles[profileId];
493
+ const refreshedOAuthCredential = refreshed?.type === "oauth" && isCodexAppServerAuthProvider(refreshed.provider, params.config) ? refreshed : void 0;
494
+ if (refreshedOAuthCredential && isDeepStrictEqual(params.store.profiles[profileId], credential)) params.store.profiles[profileId] = refreshedOAuthCredential;
495
+ const storedCredential = store.profiles[profileId];
496
+ const candidate = refreshedOAuthCredential ? refreshedOAuthCredential : storedCredential?.type === "oauth" && isCodexAppServerAuthProvider(storedCredential.provider, params.config) ? storedCredential : credential;
497
+ return resolved?.apiKey ? {
498
+ ...candidate,
499
+ access: resolved.apiKey
500
+ } : candidate;
501
+ }
502
+ function shouldUseScopedOAuthCredential(params) {
503
+ if (!params.store.runtimePersistedProfileIds?.includes(params.profileId)) return true;
504
+ const persisted = params.persistedCredential;
505
+ if (persisted?.type !== "oauth") return true;
506
+ if (resolveProviderIdForAuth(persisted.provider, { config: params.config }) !== resolveProviderIdForAuth(params.suppliedCredential.provider, { config: params.config })) return true;
507
+ return !isDeepStrictEqual(persisted, params.suppliedCredential) && !hasMatchingOAuthIdentity(persisted, params.suppliedCredential);
508
+ }
509
+ function hasMatchingOAuthIdentity(persisted, supplied) {
510
+ const persistedAccountId = persisted.accountId?.trim();
511
+ const suppliedAccountId = supplied.accountId?.trim();
512
+ if (persistedAccountId && suppliedAccountId) return persistedAccountId === suppliedAccountId;
513
+ const persistedEmail = persisted.email?.trim().toLowerCase();
514
+ const suppliedEmail = supplied.email?.trim().toLowerCase();
515
+ return Boolean(persistedEmail && suppliedEmail && persistedEmail === suppliedEmail);
516
+ }
517
+ async function resolveScopedOAuthCredential(params) {
518
+ const existingRefresh = scopedOAuthRefreshQueues.get(params.store)?.get(params.profileId);
519
+ if (existingRefresh) return await existingRefresh;
520
+ if (!params.forceRefresh && hasUsableOAuthCredential(params.credential)) return params.credential;
521
+ const storeRefreshes = scopedOAuthRefreshQueues.get(params.store) ?? /* @__PURE__ */ new Map();
522
+ scopedOAuthRefreshQueues.set(params.store, storeRefreshes);
523
+ const refresh = (async () => {
524
+ const current = params.store.profiles[params.profileId];
525
+ const credential = current?.type === "oauth" ? current : params.credential;
526
+ if (!params.forceRefresh && hasUsableOAuthCredential(credential)) return credential;
527
+ const refreshed = await refreshOAuthCredentialForRuntime({ credential });
528
+ if (!refreshed?.access?.trim()) throw new Error(`Codex app-server auth profile "${params.profileId}" could not refresh.`);
529
+ if (!isDeepStrictEqual(params.store.profiles[params.profileId], credential)) throw new Error(`Codex app-server auth profile "${params.profileId}" changed while refreshing.`);
530
+ params.store.profiles[params.profileId] = refreshed;
531
+ return refreshed;
532
+ })();
533
+ storeRefreshes.set(params.profileId, refresh);
534
+ try {
535
+ return await refresh;
536
+ } finally {
537
+ if (storeRefreshes.get(params.profileId) === refresh) storeRefreshes.delete(params.profileId);
538
+ }
539
+ }
540
+ function isCodexAppServerAuthProvider(provider, config) {
541
+ const resolvedProvider = resolveProviderIdForAuth(provider, { config });
542
+ return resolvedProvider === CODEX_APP_SERVER_AUTH_PROVIDER || resolvedProvider === OPENAI_CODEX_APP_SERVER_AUTH_PROVIDER || resolvedProvider === LEGACY_CODEX_APP_SERVER_AUTH_PROVIDER;
543
+ }
544
+ function isOpenAIApiKeyBackupCredential(credential, config) {
545
+ return credential.type === "api_key" && resolveProviderIdForAuth(credential.provider, { config }) === OPENAI_PROVIDER;
546
+ }
547
+ function isCodexAppServerAuthProfileCredential(credential, config) {
548
+ return isCodexAppServerAuthProvider(credential.provider, config) || isOpenAIApiKeyBackupCredential(credential, config);
549
+ }
550
+ function shouldClearOpenAiApiKeyForCodexAuthProfile(params) {
551
+ const profileId = params.authProfileId?.trim();
552
+ return isCodexSubscriptionCredential(profileId ? params.store.profiles[profileId] : params.store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID], params.config);
553
+ }
554
+ function isCodexSubscriptionCredential(credential, config) {
555
+ if (!credential || !isCodexAppServerAuthProvider(credential.provider, config)) return false;
556
+ return credential.type === "oauth" || credential.type === "token";
557
+ }
558
+ function withClearedEnvironmentVariables(startOptions, envVars) {
559
+ const clearEnv = startOptions.clearEnv ?? [];
560
+ const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
561
+ if (missingEnvVars.length === 0) return startOptions;
562
+ return {
563
+ ...startOptions,
564
+ clearEnv: [...clearEnv, ...missingEnvVars]
565
+ };
566
+ }
567
+ function readFirstNonEmptyEnv(env, keys) {
568
+ return readFirstNonEmptyEnvEntry(env, keys)?.value;
569
+ }
570
+ function readFirstNonEmptyEnvEntry(env, keys) {
571
+ for (const key of keys) {
572
+ const value = env[key]?.trim();
573
+ if (value) return {
574
+ key,
575
+ value
576
+ };
577
+ }
578
+ }
579
+ function buildChatgptAuthTokensParams(profileId, credential, accessToken) {
580
+ return {
581
+ type: "chatgptAuthTokens",
582
+ accessToken,
583
+ chatgptAccountId: resolveChatgptAccountId(profileId, credential),
584
+ chatgptPlanType: resolveChatgptPlanType(credential)
585
+ };
586
+ }
587
+ function resolveChatgptPlanType(credential) {
588
+ const record = credential;
589
+ const planType = record.chatgptPlanType ?? record.planType;
590
+ return typeof planType === "string" && planType.trim() ? planType.trim() : null;
591
+ }
592
+ function resolveChatgptAccountId(profileId, credential) {
593
+ if ("accountId" in credential && typeof credential.accountId === "string") {
594
+ const accountId = credential.accountId.trim();
595
+ if (accountId) return accountId;
596
+ }
597
+ return credential.email?.trim() || profileId;
598
+ }
599
+ //#endregion
600
+ //#region extensions/codex/src/app-server/rate-limit-cache.ts
601
+ const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 6e5;
602
+ const SPARSE_ACCOUNT_METADATA_KEYS = [
603
+ "credits",
604
+ "individualLimit",
605
+ "planType"
606
+ ];
607
+ const rateLimitsByClient = /* @__PURE__ */ new WeakMap();
608
+ /** Replaces one physical client's cache with an authoritative rate-limit read response. */
609
+ function rememberCodexRateLimitsRead(client, value, nowMs = Date.now()) {
610
+ if (value !== void 0) {
611
+ const revisionsByLimitId = { ...rateLimitsByClient.get(client)?.revisionsByLimitId };
612
+ for (const limitId of readRateLimitIds(value)) revisionsByLimitId[limitId] = (revisionsByLimitId[limitId] ?? 0) + 1;
613
+ rateLimitsByClient.set(client, {
614
+ value,
615
+ updatedAtMs: nowMs,
616
+ revisionsByLimitId
617
+ });
618
+ }
619
+ }
620
+ /** Merges a sparse rolling notification into one physical client's latest read response. */
621
+ function mergeCodexRateLimitsUpdate(client, value, nowMs = Date.now()) {
622
+ const update = isJsonObject$1(value) && isJsonObject$1(value.rateLimits) ? value.rateLimits : void 0;
623
+ if (!update) return;
624
+ const currentState = rateLimitsByClient.get(client);
625
+ const current = currentState?.value;
626
+ const limitId = readLimitId(update);
627
+ rateLimitsByClient.set(client, {
628
+ value: mergeRateLimitUpdate(current, update),
629
+ updatedAtMs: nowMs,
630
+ revisionsByLimitId: {
631
+ ...currentState?.revisionsByLimitId,
632
+ [limitId]: (currentState?.revisionsByLimitId[limitId] ?? 0) + 1
633
+ }
634
+ });
635
+ }
636
+ /** Per-limit marker used to trust only primary Codex updates from one turn startup. */
637
+ function readCodexRateLimitsRevision(client, limitId = "codex") {
638
+ return rateLimitsByClient.get(client)?.revisionsByLimitId[limitId] ?? 0;
639
+ }
640
+ /** Reads one physical client's cached rate-limit payload within the max-age window. */
641
+ function readRecentCodexRateLimits(client, options) {
642
+ const state = rateLimitsByClient.get(client);
643
+ if (!state) return;
644
+ const nowMs = options?.nowMs ?? Date.now();
645
+ const maxAgeMs = options?.maxAgeMs ?? DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS;
646
+ return maxAgeMs >= 0 && nowMs - state.updatedAtMs > maxAgeMs ? void 0 : state.value;
647
+ }
648
+ function mergeRateLimitUpdate(current, update) {
649
+ const currentEnvelope = isJsonObject$1(current) ? current : void 0;
650
+ const currentPrimary = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimits) ? currentEnvelope.rateLimits : void 0;
651
+ const currentByLimitId = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimitsByLimitId) ? currentEnvelope.rateLimitsByLimitId : void 0;
652
+ const limitId = readLimitId(update);
653
+ const currentPrimaryLimitId = currentPrimary ? readLimitId(currentPrimary) : void 0;
654
+ const currentForLimit = (currentByLimitId && isJsonObject$1(currentByLimitId[limitId]) ? currentByLimitId[limitId] : void 0) ?? (currentPrimaryLimitId === limitId ? currentPrimary : void 0);
655
+ const merged = mergeSparseSnapshot(isJsonObject$1(currentForLimit) ? currentForLimit : void 0, currentPrimary, update, limitId);
656
+ const nextPrimary = !currentPrimary || currentPrimaryLimitId === limitId ? merged : currentPrimary;
657
+ let nextByLimitId;
658
+ if (currentByLimitId) nextByLimitId = {
659
+ ...currentByLimitId,
660
+ [limitId]: merged
661
+ };
662
+ else if (currentPrimary && currentPrimaryLimitId && currentPrimaryLimitId !== limitId) nextByLimitId = {
663
+ [currentPrimaryLimitId]: currentPrimary,
664
+ [limitId]: merged
665
+ };
666
+ return {
667
+ ...currentEnvelope,
668
+ rateLimits: nextPrimary,
669
+ ...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
670
+ };
671
+ }
672
+ function readRateLimitIds(value) {
673
+ if (!isJsonObject$1(value)) return [];
674
+ const ids = /* @__PURE__ */ new Set();
675
+ if (isJsonObject$1(value.rateLimits)) ids.add(readLimitId(value.rateLimits));
676
+ if (isJsonObject$1(value.rateLimitsByLimitId)) for (const [key, snapshot] of Object.entries(value.rateLimitsByLimitId)) {
677
+ const snapshotLimitId = isJsonObject$1(snapshot) && typeof snapshot.limitId === "string" ? snapshot.limitId.trim() : "";
678
+ ids.add(snapshotLimitId || key);
679
+ }
680
+ return [...ids];
681
+ }
682
+ function mergeSparseSnapshot(current, accountFallback, update, limitId) {
683
+ const merged = {
684
+ ...update,
685
+ limitId
686
+ };
687
+ for (const key of SPARSE_ACCOUNT_METADATA_KEYS) {
688
+ const previous = current?.[key] ?? accountFallback?.[key];
689
+ if (merged[key] == null && previous != null) merged[key] = previous;
690
+ }
691
+ return merged;
692
+ }
693
+ function readLimitId(snapshot) {
694
+ const value = snapshot.limitId;
695
+ return typeof value === "string" && value.trim() ? value.trim() : "codex";
696
+ }
697
+ //#endregion
698
+ //#region extensions/codex/src/app-server/client-runtime.ts
699
+ /** Client-scoped Codex auth and account observers. */
700
+ const configuredClients = /* @__PURE__ */ new WeakMap();
701
+ /** Installs one auth-refresh handler and one rate-limit observer per physical client. */
702
+ function ensureCodexAppServerClientRuntime(client, context) {
703
+ const existing = configuredClients.get(client);
704
+ if (existing) {
705
+ existing.context = context;
706
+ return;
707
+ }
708
+ const runtime = { context };
709
+ configuredClients.set(client, runtime);
710
+ client.addRequestHandler(async (request) => {
711
+ if (request.method !== "account/chatgptAuthTokens/refresh") return;
712
+ return await refreshCodexAppServerAuthTokens({
713
+ agentDir: runtime.context.agentDir,
714
+ authProfileId: runtime.context.authProfileId,
715
+ ...runtime.context.authProfileStore ? { authProfileStore: runtime.context.authProfileStore } : {},
716
+ config: runtime.context.config
717
+ });
718
+ });
719
+ client.addNotificationHandler((notification) => {
720
+ if (notification.method === "account/rateLimits/updated") mergeCodexRateLimitsUpdate(client, notification.params);
721
+ });
722
+ }
723
+ //#endregion
724
+ //#region extensions/codex/src/app-server/transport-websocket.ts
725
+ /**
726
+ * Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
727
+ * transport interface.
728
+ */
729
+ /** Opens a WebSocket app-server transport and maps newline-delimited frames to stdout/stdin. */
730
+ function createWebSocketTransport(options) {
731
+ if (!options.url) throw new Error("codex app-server websocket transport requires plugins.entries.codex.config.appServer.url");
732
+ const events = new EventEmitter();
733
+ const stdout = new PassThrough();
734
+ const stderr = new PassThrough();
735
+ const headers = {
736
+ ...options.headers,
737
+ ...options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}
738
+ };
739
+ const socket = new WebSocket(options.url, { headers });
740
+ const pendingFrames = [];
741
+ let killed = false;
742
+ const sendFrame = (frame) => {
743
+ const trimmed = frame.trim();
744
+ if (!trimmed) return;
745
+ if (socket.readyState === WebSocket.OPEN) {
746
+ socket.send(trimmed);
747
+ return;
748
+ }
749
+ pendingFrames.push(trimmed);
750
+ };
751
+ socket.once("open", () => {
752
+ for (const frame of pendingFrames.splice(0)) socket.send(frame);
753
+ });
754
+ socket.once("error", (error) => events.emit("error", error));
755
+ socket.once("close", (code, reason) => {
756
+ killed = true;
757
+ events.emit("exit", code, reason.toString("utf8"));
758
+ });
759
+ socket.on("message", (data) => {
760
+ const text = websocketFrameToText(data);
761
+ stdout.write(text.endsWith("\n") ? text : `${text}\n`);
762
+ });
763
+ const stdin = new Writable({ write(chunk, _encoding, callback) {
764
+ for (const frame of chunk.toString("utf8").split("\n")) sendFrame(frame);
765
+ callback();
766
+ } });
767
+ const closeSocket = () => {
768
+ if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
769
+ socket.close();
770
+ };
771
+ stdin.once("finish", closeSocket);
772
+ stdin.once("close", closeSocket);
773
+ return {
774
+ stdin,
775
+ stdout,
776
+ stderr,
777
+ get killed() {
778
+ return killed;
779
+ },
780
+ kill: () => {
781
+ killed = true;
782
+ socket.close();
783
+ },
784
+ once: (event, listener) => events.once(event, listener)
785
+ };
786
+ }
787
+ function websocketFrameToText(data) {
788
+ if (typeof data === "string") return data;
789
+ if (Buffer.isBuffer(data)) return data.toString("utf8");
790
+ if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
791
+ return Buffer.from(data).toString("utf8");
792
+ }
793
+ //#endregion
794
+ //#region extensions/codex/src/app-server/transport.ts
795
+ /** Starts graceful transport shutdown and schedules a force kill fallback. */
796
+ function closeCodexAppServerTransport(child, options = {}) {
797
+ child.stdin.end?.();
798
+ child.stdin.destroy?.();
799
+ const forceKillDelayMs = options.forceKillDelayMs ?? 1e3;
800
+ const forceKill = setTimeout(() => {
801
+ if (hasCodexAppServerTransportExited(child)) return;
802
+ signalCodexAppServerTransport(child, "SIGKILL");
803
+ }, Math.max(1, forceKillDelayMs));
804
+ forceKill.unref?.();
805
+ child.once("exit", () => {
806
+ clearTimeout(forceKill);
807
+ child.stdout.destroy?.();
808
+ child.stderr.destroy?.();
809
+ });
810
+ child.unref?.();
811
+ child.stdout.unref?.();
812
+ child.stderr.unref?.();
813
+ child.stdin.unref?.();
814
+ }
815
+ /** Closes a transport and waits briefly for an exit event. */
816
+ async function closeCodexAppServerTransportAndWait(child, options = {}) {
817
+ if (!hasCodexAppServerTransportExited(child)) closeCodexAppServerTransport(child, options);
818
+ return await waitForCodexAppServerTransportExit(child, options.exitTimeoutMs ?? 2e3);
819
+ }
820
+ function hasCodexAppServerTransportExited(child) {
821
+ return child.exitCode !== null && child.exitCode !== void 0 ? true : child.signalCode !== null && child.signalCode !== void 0;
822
+ }
823
+ async function waitForCodexAppServerTransportExit(child, timeoutMs) {
824
+ if (hasCodexAppServerTransportExited(child)) return true;
825
+ return await new Promise((resolve) => {
826
+ let settled = false;
827
+ const onExit = () => {
828
+ if (settled) return;
829
+ settled = true;
830
+ clearTimeout(timeout);
831
+ resolve(true);
832
+ };
833
+ const timeout = setTimeout(() => {
834
+ if (settled) return;
835
+ settled = true;
836
+ child.off?.("exit", onExit);
837
+ resolve(false);
838
+ }, Math.max(1, timeoutMs));
839
+ child.once("exit", onExit);
840
+ });
841
+ }
842
+ function signalCodexAppServerTransport(child, signal) {
843
+ if (child.pid && process.platform !== "win32") try {
844
+ process.kill(-child.pid, signal);
845
+ return;
846
+ } catch {}
847
+ child.kill?.(signal);
848
+ }
849
+ //#endregion
850
+ //#region extensions/codex/src/app-server/version.ts
851
+ /**
852
+ * Version and package pins for the managed Codex app-server runtime.
853
+ */
854
+ /** Minimum Codex app-server version supported by the OpenClaw Codex bridge. */
855
+ const MIN_CODEX_APP_SERVER_VERSION = "0.143.0";
856
+ /** npm package name for the managed Codex app-server binary. */
857
+ const MANAGED_CODEX_APP_SERVER_PACKAGE = "@openai/codex";
858
+ //#endregion
859
+ //#region extensions/codex/src/app-server/client.ts
860
+ /**
861
+ * JSON-RPC client for Codex app-server transports, including request/response
862
+ * routing, notification fanout, server request handlers, and version checks.
863
+ */
864
+ const CODEX_APP_SERVER_PARSE_LOG_MAX = 500;
865
+ const CODEX_APP_SERVER_PARSE_BUFFER_MAX = 1e6;
866
+ const CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES = 1e3;
867
+ const CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS = 6e5;
868
+ const CODEX_APP_SERVER_STDERR_TAIL_MAX = 2e3;
869
+ const UNPAIRED_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
870
+ /** RPC error wrapper that preserves app-server error code and data. */
871
+ var CodexAppServerRpcError = class extends Error {
872
+ constructor(error, method) {
873
+ super(formatCodexAppServerRpcErrorMessage(error, method));
874
+ this.name = "CodexAppServerRpcError";
875
+ this.code = error.code;
876
+ this.data = error.data;
877
+ }
878
+ };
879
+ function formatCodexAppServerRpcErrorMessage(error, method) {
880
+ const message = error.message || `${method} failed`;
881
+ const detail = readCodexAppServerRpcReloginDetail(error.data);
882
+ return detail && !message.includes(detail) ? `${message}: ${detail}` : message;
883
+ }
884
+ function readCodexAppServerRpcReloginDetail(data) {
885
+ const record = isJsonObject(data) ? data : void 0;
886
+ const nested = isJsonObject(record?.error) ? record.error : record;
887
+ if (!nested) return;
888
+ const isRelogin = nested.action === "relogin" || nested.reason === "cloudRequirements" && nested.errorCode === "Auth";
889
+ const detail = typeof nested.detail === "string" ? nested.detail.trim() : "";
890
+ return isRelogin && detail ? detail : void 0;
891
+ }
892
+ function isJsonObject(value) {
893
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
894
+ }
895
+ /** Returns true for errors that mean the app-server transport is closed. */
896
+ function isCodexAppServerConnectionClosedError(error) {
897
+ if (!(error instanceof Error)) return false;
898
+ return error.message === "codex app-server client is closed" || error.message.startsWith("codex app-server exited:");
899
+ }
900
+ /** Stateful app-server JSON-RPC client over stdio or websocket transport. */
901
+ var CodexAppServerClient = class CodexAppServerClient {
902
+ constructor(child) {
903
+ this.pending = /* @__PURE__ */ new Map();
904
+ this.requestHandlers = /* @__PURE__ */ new Set();
905
+ this.notificationHandlers = /* @__PURE__ */ new Set();
906
+ this.closeHandlers = /* @__PURE__ */ new Set();
907
+ this.nextId = 1;
908
+ this.initialized = false;
909
+ this.closed = false;
910
+ this.stderrTail = "";
911
+ this.child = child;
912
+ this.lines = createInterface({ input: child.stdout });
913
+ this.lines.on("line", (line) => this.handleLine(line));
914
+ this.lines.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
915
+ child.stdout.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
916
+ child.stderr.on("data", (chunk) => {
917
+ const text = chunk.toString("utf8");
918
+ this.stderrTail = appendBoundedTail(this.stderrTail, text, CODEX_APP_SERVER_STDERR_TAIL_MAX);
919
+ const trimmed = text.trim();
920
+ if (trimmed) embeddedAgentLog.debug(`codex app-server stderr: ${trimmed}`);
921
+ });
922
+ child.stderr.on("error", (error) => {
923
+ embeddedAgentLog.warn("codex app-server stderr stream failed", { error });
924
+ });
925
+ child.once("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
926
+ child.once("exit", (code, signal) => {
927
+ this.closeWithError(buildCodexAppServerExitError(code, signal, this.stderrTail));
928
+ });
929
+ child.stdin.on?.("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
930
+ }
931
+ /** Starts a new app-server client using resolved runtime start options. */
932
+ static start(options) {
933
+ const defaults = resolveCodexAppServerRuntimeOptions().start;
934
+ const startOptions = {
935
+ ...defaults,
936
+ ...options,
937
+ headers: options?.headers ?? defaults.headers
938
+ };
939
+ if (startOptions.transport === "stdio" && startOptions.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
940
+ if (startOptions.transport === "websocket") return new CodexAppServerClient(createWebSocketTransport(startOptions));
941
+ return new CodexAppServerClient(createStdioTransport(startOptions));
942
+ }
943
+ /** Builds a client around a fake transport for tests. */
944
+ static fromTransportForTests(child) {
945
+ return new CodexAppServerClient(child);
946
+ }
947
+ /** Performs the app-server initialize handshake and validates protocol version. */
948
+ async initialize() {
949
+ if (this.initialized) return;
950
+ const response = await this.request("initialize", {
951
+ clientInfo: {
952
+ name: "openclaw",
953
+ title: "OpenClaw",
954
+ version: OPENCLAW_VERSION
955
+ },
956
+ capabilities: { experimentalApi: true }
957
+ });
958
+ this.serverVersion = assertSupportedCodexAppServerVersion(response);
959
+ this.runtimeIdentity = buildCodexAppServerRuntimeIdentity(response, this.serverVersion);
960
+ this.notify("initialized");
961
+ this.initialized = true;
962
+ }
963
+ /** Returns the version detected during initialize. */
964
+ getServerVersion() {
965
+ return this.serverVersion;
966
+ }
967
+ /** Returns runtime metadata detected during initialize. */
968
+ getRuntimeIdentity() {
969
+ return this.runtimeIdentity ? { ...this.runtimeIdentity } : void 0;
970
+ }
971
+ request(method, params, optionsInput) {
972
+ let options = optionsInput;
973
+ options ??= {};
974
+ if (this.closed) return Promise.reject(this.closeError ?? /* @__PURE__ */ new Error("codex app-server client is closed"));
975
+ if (options.signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(`${method} aborted`));
976
+ const id = this.nextId++;
977
+ const message = {
978
+ id,
979
+ method,
980
+ params
981
+ };
982
+ return new Promise((resolve, reject) => {
983
+ let timeout;
984
+ let cleanupAbort;
985
+ const cleanup = () => {
986
+ if (timeout) {
987
+ clearTimeout(timeout);
988
+ timeout = void 0;
989
+ }
990
+ cleanupAbort?.();
991
+ cleanupAbort = void 0;
992
+ };
993
+ const rejectPending = (error) => {
994
+ if (!this.pending.has(id)) return;
995
+ this.pending.delete(id);
996
+ cleanup();
997
+ reject(error);
998
+ };
999
+ if (options.timeoutMs && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0) {
1000
+ timeout = setTimeout(() => rejectPending(/* @__PURE__ */ new Error(`${method} timed out`)), Math.max(100, options.timeoutMs));
1001
+ timeout.unref?.();
1002
+ }
1003
+ if (options.signal) {
1004
+ const abortListener = () => rejectPending(/* @__PURE__ */ new Error(`${method} aborted`));
1005
+ options.signal.addEventListener("abort", abortListener, { once: true });
1006
+ cleanupAbort = () => options.signal?.removeEventListener("abort", abortListener);
1007
+ }
1008
+ this.pending.set(id, {
1009
+ method,
1010
+ resolve: (value) => {
1011
+ cleanup();
1012
+ resolve(value);
1013
+ },
1014
+ reject: (error) => {
1015
+ cleanup();
1016
+ reject(error);
1017
+ },
1018
+ cleanup
1019
+ });
1020
+ if (options.signal?.aborted) {
1021
+ rejectPending(/* @__PURE__ */ new Error(`${method} aborted`));
1022
+ return;
1023
+ }
1024
+ try {
1025
+ this.writeMessage(message, (error) => rejectPending(error));
1026
+ } catch (error) {
1027
+ rejectPending(error instanceof Error ? error : new Error(String(error)));
1028
+ }
1029
+ });
1030
+ }
1031
+ /** Sends a fire-and-forget JSON-RPC notification to the app-server. */
1032
+ notify(method, params) {
1033
+ this.writeMessage({
1034
+ method,
1035
+ params
1036
+ });
1037
+ }
1038
+ /** Registers a handler for app-server requests sent back to OpenClaw. */
1039
+ addRequestHandler(handler) {
1040
+ this.requestHandlers.add(handler);
1041
+ return () => this.requestHandlers.delete(handler);
1042
+ }
1043
+ /** Registers a notification handler and returns its disposer. */
1044
+ addNotificationHandler(handler) {
1045
+ this.notificationHandlers.add(handler);
1046
+ return () => this.notificationHandlers.delete(handler);
1047
+ }
1048
+ /** Registers a close handler and returns its disposer. */
1049
+ addCloseHandler(handler) {
1050
+ this.closeHandlers.add(handler);
1051
+ return () => this.closeHandlers.delete(handler);
1052
+ }
1053
+ /** Closes the transport without waiting for process/socket shutdown. */
1054
+ close() {
1055
+ if (!this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"))) return;
1056
+ closeCodexAppServerTransport(this.child);
1057
+ }
1058
+ /** Closes the transport and waits for shutdown according to transport policy. */
1059
+ async closeAndWait(options) {
1060
+ this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"));
1061
+ return await closeCodexAppServerTransportAndWait(this.child, options);
1062
+ }
1063
+ writeMessage(message, onError) {
1064
+ if (this.closed) return;
1065
+ const id = "id" in message ? message.id : void 0;
1066
+ const method = "method" in message ? message.method : void 0;
1067
+ this.child.stdin.write(`${stringifyCodexAppServerMessage(message)}\n`, (error) => {
1068
+ if (error) {
1069
+ embeddedAgentLog.warn("codex app-server write failed", {
1070
+ error,
1071
+ id,
1072
+ method
1073
+ });
1074
+ onError?.(error);
1075
+ }
1076
+ });
1077
+ }
1078
+ handleLine(line) {
1079
+ const rawLine = line.endsWith("\r") ? line.slice(0, -1) : line;
1080
+ if (this.pendingParse) {
1081
+ this.handlePendingParseLine(rawLine);
1082
+ return;
1083
+ }
1084
+ const trimmed = rawLine.trim();
1085
+ if (!trimmed) return;
1086
+ let parsed;
1087
+ try {
1088
+ parsed = JSON.parse(trimmed);
1089
+ } catch (error) {
1090
+ if (shouldBufferCodexAppServerParseFailure(trimmed, error)) {
1091
+ this.pendingParse = {
1092
+ text: trimmed,
1093
+ lineCount: 1,
1094
+ firstError: error
1095
+ };
1096
+ return;
1097
+ }
1098
+ logCodexAppServerParseFailure(trimmed, error, 1);
1099
+ return;
1100
+ }
1101
+ this.handleParsedMessage(parsed);
1102
+ }
1103
+ handlePendingParseLine(line) {
1104
+ const pending = this.pendingParse;
1105
+ if (!pending) return;
1106
+ const candidate = `${pending.text}\\n${line}`;
1107
+ let parsed;
1108
+ try {
1109
+ parsed = JSON.parse(candidate);
1110
+ } catch (error) {
1111
+ const lineCount = pending.lineCount + 1;
1112
+ if (shouldBufferCodexAppServerParseFailure(candidate.trim(), error) && candidate.length <= CODEX_APP_SERVER_PARSE_BUFFER_MAX && lineCount <= CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES) {
1113
+ this.pendingParse = {
1114
+ text: candidate,
1115
+ lineCount,
1116
+ firstError: pending.firstError
1117
+ };
1118
+ return;
1119
+ }
1120
+ this.pendingParse = void 0;
1121
+ logCodexAppServerParseFailure(candidate, error, lineCount);
1122
+ return;
1123
+ }
1124
+ this.pendingParse = void 0;
1125
+ this.handleParsedMessage(parsed);
1126
+ }
1127
+ handleParsedMessage(parsed) {
1128
+ if (!parsed || typeof parsed !== "object") return;
1129
+ const message = parsed;
1130
+ if (isRpcResponse(message)) {
1131
+ this.handleResponse(message);
1132
+ return;
1133
+ }
1134
+ if (!("method" in message)) return;
1135
+ if ("id" in message && message.id !== void 0) {
1136
+ this.handleServerRequest({
1137
+ id: message.id,
1138
+ method: message.method,
1139
+ params: message.params
1140
+ });
1141
+ return;
1142
+ }
1143
+ this.handleNotification({
1144
+ method: message.method,
1145
+ params: message.params
1146
+ });
1147
+ }
1148
+ handleResponse(response) {
1149
+ const pending = this.pending.get(response.id);
1150
+ if (!pending) return;
1151
+ this.pending.delete(response.id);
1152
+ if (response.error) {
1153
+ pending.reject(new CodexAppServerRpcError(response.error, pending.method));
1154
+ return;
1155
+ }
1156
+ pending.resolve(response.result);
1157
+ }
1158
+ async handleServerRequest(request) {
1159
+ try {
1160
+ const result = await this.runServerRequestHandlers(request);
1161
+ if (result !== void 0) {
1162
+ this.writeMessage({
1163
+ id: request.id,
1164
+ result
1165
+ });
1166
+ return;
1167
+ }
1168
+ this.writeMessage({
1169
+ id: request.id,
1170
+ result: defaultServerRequestResponse(request)
1171
+ });
1172
+ } catch (error) {
1173
+ const message = error instanceof Error ? error.message : String(error);
1174
+ embeddedAgentLog.warn("codex app-server server request handler failed", {
1175
+ id: request.id,
1176
+ method: request.method,
1177
+ error
1178
+ });
1179
+ this.writeMessage({
1180
+ id: request.id,
1181
+ error: {
1182
+ code: -32603,
1183
+ message
1184
+ }
1185
+ });
1186
+ }
1187
+ }
1188
+ async runServerRequestHandlers(request) {
1189
+ const timeoutResponse = timeoutServerRequestResponse(request);
1190
+ if (!timeoutResponse) return await this.runServerRequestHandlersWithoutTimeout(request);
1191
+ let timeout;
1192
+ try {
1193
+ return await Promise.race([this.runServerRequestHandlersWithoutTimeout(request), new Promise((resolve) => {
1194
+ timeout = setTimeout(() => {
1195
+ embeddedAgentLog.warn("codex app-server server request timed out", {
1196
+ id: request.id,
1197
+ method: request.method,
1198
+ timeoutMs: CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS
1199
+ });
1200
+ resolve(timeoutResponse);
1201
+ }, CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS);
1202
+ timeout.unref?.();
1203
+ })]);
1204
+ } finally {
1205
+ if (timeout) clearTimeout(timeout);
1206
+ }
1207
+ }
1208
+ async runServerRequestHandlersWithoutTimeout(request) {
1209
+ for (const handler of this.requestHandlers) {
1210
+ const result = await handler(request);
1211
+ if (result !== void 0) return result;
1212
+ }
1213
+ }
1214
+ handleNotification(notification) {
1215
+ for (const handler of this.notificationHandlers) Promise.resolve(handler(notification)).catch((error) => {
1216
+ embeddedAgentLog.warn("codex app-server notification handler failed", { error });
1217
+ });
1218
+ }
1219
+ closeWithError(error) {
1220
+ if (this.markClosed(error)) closeCodexAppServerTransport(this.child);
1221
+ }
1222
+ markClosed(error) {
1223
+ if (this.closed) return false;
1224
+ this.closed = true;
1225
+ this.closeError = error;
1226
+ this.lines.close();
1227
+ this.rejectPendingRequests(error);
1228
+ return true;
1229
+ }
1230
+ rejectPendingRequests(error) {
1231
+ for (const pending of this.pending.values()) {
1232
+ pending.cleanup();
1233
+ pending.reject(error);
1234
+ }
1235
+ this.pending.clear();
1236
+ for (const handler of this.closeHandlers) handler(this);
1237
+ }
1238
+ };
1239
+ function defaultServerRequestResponse(request) {
1240
+ if (request.method === "item/tool/call") return {
1241
+ contentItems: [{
1242
+ type: "inputText",
1243
+ text: "OpenClaw did not register a handler for this app-server tool call."
1244
+ }],
1245
+ success: false
1246
+ };
1247
+ if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return { decision: "decline" };
1248
+ if (request.method === "item/permissions/requestApproval") return {
1249
+ permissions: {},
1250
+ scope: "turn"
1251
+ };
1252
+ if (request.method === "item/tool/requestUserInput") return { answers: {} };
1253
+ if (request.method === "mcpServer/elicitation/request") return { action: "decline" };
1254
+ return {};
1255
+ }
1256
+ function stringifyCodexAppServerMessage(message) {
1257
+ return JSON.stringify(message, (_key, value) => typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value) ?? "null";
1258
+ }
1259
+ function timeoutServerRequestResponse(request) {
1260
+ if (request.method !== "item/tool/call") return;
1261
+ return {
1262
+ contentItems: [{
1263
+ type: "inputText",
1264
+ text: `OpenClaw dynamic tool call timed out after ${CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS}ms before sending a response to Codex.`
1265
+ }],
1266
+ success: false
1267
+ };
1268
+ }
1269
+ /** Raised when the initialize handshake detects an unsupported app-server version. */
1270
+ var CodexAppServerVersionError = class extends Error {
1271
+ constructor(detectedVersion) {
1272
+ const detected = detectedVersion ? `detected ${detectedVersion}` : "OpenClaw could not determine the running Codex version";
1273
+ super(`Codex app-server ${MIN_CODEX_APP_SERVER_VERSION} or newer is required, but ${detected}. Update the configured Codex app-server binary, or remove custom command overrides to use the managed binary.`);
1274
+ this.name = "CodexAppServerVersionError";
1275
+ this.detectedVersion = detectedVersion;
1276
+ }
1277
+ };
1278
+ function assertSupportedCodexAppServerVersion(response) {
1279
+ const detectedVersion = readCodexVersionFromUserAgent(response.userAgent);
1280
+ if (!detectedVersion || compareCodexAppServerVersions(detectedVersion, "0.143.0") < 0) throw new CodexAppServerVersionError(detectedVersion);
1281
+ return detectedVersion;
1282
+ }
1283
+ function isUnsupportedCodexAppServerVersionError(error) {
1284
+ return error instanceof CodexAppServerVersionError;
1285
+ }
1286
+ function buildCodexAppServerRuntimeIdentity(response, serverVersion) {
1287
+ const userAgent = readNonEmptyInitializeString(response.userAgent);
1288
+ const codexHome = readNonEmptyInitializeString(response.codexHome);
1289
+ const platformFamily = readNonEmptyInitializeString(response.platformFamily);
1290
+ const platformOs = readNonEmptyInitializeString(response.platformOs);
1291
+ return {
1292
+ serverVersion,
1293
+ ...userAgent ? { userAgent } : {},
1294
+ ...codexHome ? { codexHome } : {},
1295
+ ...platformFamily ? { platformFamily } : {},
1296
+ ...platformOs ? { platformOs } : {}
1297
+ };
1298
+ }
1299
+ function readNonEmptyInitializeString(value) {
1300
+ const trimmed = value?.trim();
1301
+ return trimmed ? trimmed : void 0;
1302
+ }
1303
+ /** Extracts the Codex version from the app-server initialize user-agent field. */
1304
+ function readCodexVersionFromUserAgent(userAgent) {
1305
+ return (userAgent?.match(/^[^/]+\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:[\s(]|$)/))?.[1];
1306
+ }
1307
+ /** Compares stable Codex app-server versions for protocol floor checks. */
1308
+ function compareCodexAppServerVersions(left, right) {
1309
+ const leftVersion = parseVersionForComparison(left);
1310
+ const rightVersion = parseVersionForComparison(right);
1311
+ const leftParts = leftVersion.parts;
1312
+ const rightParts = rightVersion.parts;
1313
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
1314
+ const leftPart = leftParts[index] ?? 0;
1315
+ const rightPart = rightParts[index] ?? 0;
1316
+ if (leftPart !== rightPart) return leftPart < rightPart ? -1 : 1;
1317
+ }
1318
+ if (leftVersion.unstableSuffix && !rightVersion.unstableSuffix) return -1;
1319
+ if (!leftVersion.unstableSuffix && rightVersion.unstableSuffix) return 1;
1320
+ return 0;
1321
+ }
1322
+ function parseVersionForComparison(version) {
1323
+ const hasBuildMetadata = version.includes("+");
1324
+ const [withoutBuild = version] = version.split("+", 1);
1325
+ const prereleaseIndex = withoutBuild.indexOf("-");
1326
+ return {
1327
+ parts: (prereleaseIndex >= 0 ? withoutBuild.slice(0, prereleaseIndex) : withoutBuild).split(".").map((part) => Number.parseInt(part, 10)).map((part) => Number.isFinite(part) ? part : 0),
1328
+ unstableSuffix: prereleaseIndex >= 0 || hasBuildMetadata
1329
+ };
1330
+ }
1331
+ function redactCodexAppServerLinePreview(value) {
1332
+ const redacted = value.replace(/\s+/g, " ").trim().replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+/gi, "$1<redacted>").replace(/("(?:api_?key|authorization|token|access_token|refresh_token)"\s*:\s*")([^"]+)(")/gi, "$1<redacted>$3").replace(/\b([a-z0-9_]*(?:api_?key|authorization|access_token|refresh_token|token))(\s*=\s*)(["']?)[^\s"']+(\3)/gi, "$1$2$3<redacted>$4");
1333
+ return redacted.length > CODEX_APP_SERVER_PARSE_LOG_MAX ? `${redacted.slice(0, CODEX_APP_SERVER_PARSE_LOG_MAX)}...` : redacted;
1334
+ }
1335
+ function appendBoundedTail(current, next, maxLength) {
1336
+ const combined = `${current}${next}`;
1337
+ return combined.length > maxLength ? combined.slice(combined.length - maxLength) : combined;
1338
+ }
1339
+ function buildCodexAppServerExitError(code, signal, stderrTail) {
1340
+ const stderrPreview = redactCodexAppServerLinePreview(stderrTail);
1341
+ const suffix = stderrPreview ? ` stderr=${JSON.stringify(stderrPreview)}` : "";
1342
+ return /* @__PURE__ */ new Error(`codex app-server exited: code=${formatExitValue(code)} signal=${formatExitValue(signal)}${suffix}`);
1343
+ }
1344
+ function shouldBufferCodexAppServerParseFailure(value, error) {
1345
+ if (!value.startsWith("{") && !value.startsWith("[")) return false;
1346
+ const message = error instanceof Error ? error.message : String(error);
1347
+ return message.includes("Unterminated string") || message.includes("Unexpected end of JSON input");
1348
+ }
1349
+ function logCodexAppServerParseFailure(value, error, fragmentCount) {
1350
+ const linePreview = redactCodexAppServerLinePreview(value);
1351
+ const suffix = fragmentCount > 1 ? ` fragments=${fragmentCount}` : "";
1352
+ embeddedAgentLog.warn("failed to parse codex app-server message", {
1353
+ error,
1354
+ errorMessage: error instanceof Error ? error.message : String(error),
1355
+ fragmentCount,
1356
+ linePreview,
1357
+ consoleMessage: `failed to parse codex app-server message${suffix}: preview=${JSON.stringify(linePreview)}`
1358
+ });
1359
+ }
1360
+ const CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS = /* @__PURE__ */ new Set([
1361
+ "item/commandExecution/requestApproval",
1362
+ "item/fileChange/requestApproval",
1363
+ "item/permissions/requestApproval"
1364
+ ]);
1365
+ /** Returns true for app-server approval request methods OpenClaw can answer. */
1366
+ function isCodexAppServerApprovalRequest(method) {
1367
+ return CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS.has(method);
1368
+ }
1369
+ function formatExitValue(value) {
1370
+ if (value === null || value === void 0) return "null";
1371
+ if (typeof value === "string" || typeof value === "number") return String(value);
1372
+ return "unknown";
1373
+ }
1374
+ //#endregion
1375
+ //#region extensions/codex/src/app-server/managed-binary.ts
1376
+ /**
1377
+ * Resolves the managed Codex app-server binary shipped with or installed beside
1378
+ * the Codex plugin before stdio startup.
1379
+ */
1380
+ const CODEX_PLUGIN_ROOT = resolveDefaultCodexPluginRoot(path.dirname(fileURLToPath(import.meta.url)));
1381
+ const MACOS_DESKTOP_CODEX_APP_SERVER_COMMAND = "/Applications/Codex.app/Contents/Resources/codex";
1382
+ /** Rewrites managed stdio start options to point at an executable Codex binary path. */
1383
+ async function resolveManagedCodexAppServerStartOptions(startOptions, options = {}) {
1384
+ if (startOptions.transport !== "stdio" || startOptions.commandSource !== "managed") return startOptions;
1385
+ const platform = options.platform ?? process.platform;
1386
+ const paths = resolveManagedCodexAppServerPaths({
1387
+ platform,
1388
+ pluginRoot: options.pluginRoot
1389
+ });
1390
+ const pathExists = options.pathExists ?? commandPathExists;
1391
+ const commandPaths = await findManagedCodexAppServerCommandPaths({
1392
+ candidateCommandPaths: paths.candidateCommandPaths,
1393
+ pathExists,
1394
+ platform
1395
+ });
1396
+ const commandPath = commandPaths[0];
1397
+ const managedFallbackCommandPaths = commandPaths.slice(1);
1398
+ return {
1399
+ ...startOptions,
1400
+ command: commandPath,
1401
+ commandSource: "resolved-managed",
1402
+ ...managedFallbackCommandPaths.length > 0 ? { managedFallbackCommandPaths } : {}
1403
+ };
1404
+ }
1405
+ /** Returns the preferred and fallback managed Codex binary paths for a plugin root. */
1406
+ function resolveManagedCodexAppServerPaths(params) {
1407
+ const platform = params.platform ?? process.platform;
1408
+ const candidateCommandPaths = resolveManagedCodexAppServerCommandCandidates(params.pluginRoot ?? CODEX_PLUGIN_ROOT, platform);
1409
+ return {
1410
+ commandPath: candidateCommandPaths[0] ?? "",
1411
+ candidateCommandPaths
1412
+ };
1413
+ }
1414
+ function resolveManagedCodexAppServerCommandCandidates(pluginRoot, platform) {
1415
+ const pathApi = pathForPlatform(platform);
1416
+ const commandName = platform === "win32" ? "codex.cmd" : "codex";
1417
+ const roots = resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform);
1418
+ return [.../* @__PURE__ */ new Set([
1419
+ ...resolveDesktopCodexAppServerCommandCandidates(platform),
1420
+ ...roots.map((root) => pathApi.join(root, "node_modules", ".bin", commandName)),
1421
+ ...resolveManagedCodexPackageBinCandidates(roots, platform)
1422
+ ])];
1423
+ }
1424
+ function resolveDesktopCodexAppServerCommandCandidates(platform) {
1425
+ return platform === "darwin" ? [MACOS_DESKTOP_CODEX_APP_SERVER_COMMAND] : [];
1426
+ }
1427
+ function resolveDefaultCodexPluginRoot(moduleDir) {
1428
+ const moduleBaseName = path.basename(moduleDir);
1429
+ if (moduleBaseName === "dist" || moduleBaseName === "dist-runtime") return path.dirname(moduleDir);
1430
+ return path.resolve(moduleDir, "..", "..");
1431
+ }
1432
+ function resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform) {
1433
+ const pathApi = pathForPlatform(platform);
1434
+ const directRoots = [
1435
+ pluginRoot,
1436
+ pathApi.dirname(pluginRoot),
1437
+ pathApi.dirname(pathApi.dirname(pluginRoot)),
1438
+ isDistExtensionRoot(pluginRoot, platform) ? pathApi.dirname(pathApi.dirname(pathApi.dirname(pluginRoot))) : null
1439
+ ].filter((root) => Boolean(root));
1440
+ return [.../* @__PURE__ */ new Set([...directRoots, ...resolveNearestNodeModulesProjectRoots(directRoots, platform)])];
1441
+ }
1442
+ function resolveNearestNodeModulesProjectRoots(roots, platform) {
1443
+ const pathApi = pathForPlatform(platform);
1444
+ const projectRoots = [];
1445
+ for (const root of roots) {
1446
+ let current = pathApi.resolve(root);
1447
+ while (true) {
1448
+ if (pathApi.basename(current) === "node_modules") {
1449
+ projectRoots.push(pathApi.dirname(current));
1450
+ break;
1451
+ }
1452
+ const parent = pathApi.dirname(current);
1453
+ if (parent === current) break;
1454
+ current = parent;
1455
+ }
1456
+ }
1457
+ return projectRoots;
1458
+ }
1459
+ function resolveManagedCodexPackageBinCandidates(roots, platform) {
1460
+ if (platform === "win32") return [];
1461
+ const candidates = [];
1462
+ for (const root of roots) {
1463
+ const candidate = resolveManagedCodexPackageBinCandidate(root);
1464
+ if (candidate) candidates.push(candidate);
1465
+ }
1466
+ return candidates;
1467
+ }
1468
+ function resolveManagedCodexPackageBinCandidate(root) {
1469
+ try {
1470
+ const packageJsonPath = createRequire(path.join(root, "package.json")).resolve(`${MANAGED_CODEX_APP_SERVER_PACKAGE}/package.json`);
1471
+ const packageRoot = path.dirname(packageJsonPath);
1472
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
1473
+ const binPath = typeof packageJson.bin === "string" ? packageJson.bin : isRecord(packageJson.bin) && typeof packageJson.bin.codex === "string" ? packageJson.bin.codex : null;
1474
+ return binPath ? path.resolve(packageRoot, binPath) : null;
1475
+ } catch {
1476
+ return null;
1477
+ }
1478
+ }
1479
+ function isRecord(value) {
1480
+ return typeof value === "object" && value !== null;
1481
+ }
1482
+ function isDistExtensionRoot(pluginRoot, platform) {
1483
+ const pathApi = pathForPlatform(platform);
1484
+ const extensionsDir = pathApi.dirname(pluginRoot);
1485
+ const distDir = pathApi.dirname(extensionsDir);
1486
+ return pathApi.basename(extensionsDir) === "extensions" && (pathApi.basename(distDir) === "dist" || pathApi.basename(distDir) === "dist-runtime");
1487
+ }
1488
+ function pathForPlatform(platform) {
1489
+ return platform === "win32" ? path.win32 : path.posix;
1490
+ }
1491
+ async function findManagedCodexAppServerCommandPaths(params) {
1492
+ const commandPaths = [];
1493
+ for (const commandPath of params.candidateCommandPaths) if (await params.pathExists(commandPath, params.platform)) commandPaths.push(commandPath);
1494
+ if (commandPaths.length > 0) return commandPaths;
1495
+ throw new Error([
1496
+ `Managed Codex app-server binary was not found for ${MANAGED_CODEX_APP_SERVER_PACKAGE}.`,
1497
+ "Reinstall or update OpenClaw, or run pnpm install in a source checkout.",
1498
+ "Set plugins.entries.codex.config.appServer.command or OPENCLAW_CODEX_APP_SERVER_BIN to use a custom Codex binary."
1499
+ ].join(" "));
1500
+ }
1501
+ async function commandPathExists(filePath, platform) {
1502
+ try {
1503
+ await access(filePath, platform === "win32" ? constants.F_OK : constants.X_OK);
1504
+ return true;
1505
+ } catch {
1506
+ return false;
1507
+ }
1508
+ }
1509
+ //#endregion
1510
+ //#region extensions/codex/src/app-server/timeout.ts
1511
+ /**
1512
+ * Thin Codex app-server timeout adapter around OpenClaw's shared security
1513
+ * runtime timeout helper.
1514
+ */
1515
+ /** Awaits a promise with a Codex-specific timeout error message. */
1516
+ async function withTimeout$1(promise, timeoutMs, timeoutMessage) {
1517
+ return await withTimeout(promise, timeoutMs, { message: timeoutMessage });
1518
+ }
1519
+ //#endregion
1520
+ //#region extensions/codex/src/app-server/shared-client.ts
1521
+ /**
1522
+ * Owns shared and isolated Codex app-server client startup, auth application,
1523
+ * lease tracking, and teardown.
1524
+ */
1525
+ var shared_client_exports = /* @__PURE__ */ __exportAll({
1526
+ clearSharedCodexAppServerClientAndWait: () => clearSharedCodexAppServerClientAndWait,
1527
+ clearSharedCodexAppServerClientIfCurrent: () => clearSharedCodexAppServerClientIfCurrent,
1528
+ clearSharedCodexAppServerClientIfCurrentAndUnclaimed: () => clearSharedCodexAppServerClientIfCurrentAndUnclaimed,
1529
+ clearSharedCodexAppServerClientIfCurrentAndWait: () => clearSharedCodexAppServerClientIfCurrentAndWait,
1530
+ createIsolatedCodexAppServerClient: () => createIsolatedCodexAppServerClient,
1531
+ getLeasedSharedCodexAppServerClient: () => getLeasedSharedCodexAppServerClient,
1532
+ releaseLeasedSharedCodexAppServerClient: () => releaseLeasedSharedCodexAppServerClient,
1533
+ retireSharedCodexAppServerClientIfCurrent: () => retireSharedCodexAppServerClientIfCurrent
1534
+ });
1535
+ const SHARED_CODEX_APP_SERVER_CLIENT_STATE = Symbol.for("openclaw.codexAppServerClientState");
1536
+ function getSharedCodexAppServerClientState() {
1537
+ const globalState = globalThis;
1538
+ globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] ??= {
1539
+ clients: /* @__PURE__ */ new Map(),
1540
+ leasedReleases: /* @__PURE__ */ new WeakMap()
1541
+ };
1542
+ return globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE];
1543
+ }
1544
+ async function resolveCodexAppServerClientStartContext(options) {
1545
+ const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
1546
+ const requestedStartOptions = options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start;
1547
+ const usesNativeAuth = options?.authProfileId === null || requestedStartOptions.homeScope === "user";
1548
+ const requestedAuthProfileId = options?.authProfileId === null ? void 0 : options?.authProfileId;
1549
+ const authProfileStore = !usesNativeAuth && options?.authProfileStore ? resolveCodexAppServerAuthProfileStore({
1550
+ agentDir,
1551
+ authProfileId: requestedAuthProfileId,
1552
+ authProfileStore: options.authProfileStore,
1553
+ config: options.config
1554
+ }) : options?.authProfileStore;
1555
+ const authProfileId = usesNativeAuth ? void 0 : resolveCodexAppServerAuthProfileIdForAgent({
1556
+ authProfileId: requestedAuthProfileId,
1557
+ agentDir,
1558
+ config: options?.config,
1559
+ ...authProfileStore ? { authProfileStore } : {}
1560
+ });
1561
+ return {
1562
+ agentDir,
1563
+ usesNativeAuth,
1564
+ authProfileId,
1565
+ authProfileStore,
1566
+ startOptions: await bridgeCodexAppServerStartOptions({
1567
+ startOptions: await resolveManagedCodexAppServerStartOptions(requestedStartOptions),
1568
+ agentDir,
1569
+ authProfileId: usesNativeAuth ? null : authProfileId,
1570
+ config: options?.config,
1571
+ ...authProfileStore ? { authProfileStore } : {}
1572
+ })
1573
+ };
1574
+ }
1575
+ /** Gets or starts a shared Codex app-server client and records a release lease. */
1576
+ async function getLeasedSharedCodexAppServerClient(options) {
1577
+ const acquired = await acquireSharedCodexAppServerClient(options, { leased: true });
1578
+ const state = getSharedCodexAppServerClientState();
1579
+ const releases = state.leasedReleases.get(acquired.client) ?? [];
1580
+ releases.push(acquired.release);
1581
+ state.leasedReleases.set(acquired.client, releases);
1582
+ return acquired.client;
1583
+ }
1584
+ /** Releases one outstanding lease for a shared Codex app-server client. */
1585
+ function releaseLeasedSharedCodexAppServerClient(client) {
1586
+ const state = getSharedCodexAppServerClientState();
1587
+ const releases = state.leasedReleases.get(client);
1588
+ if (!releases) return false;
1589
+ const release = releases.pop();
1590
+ if (!release) return false;
1591
+ if (releases.length === 0) state.leasedReleases.delete(client);
1592
+ release();
1593
+ return true;
1594
+ }
1595
+ async function acquireSharedCodexAppServerClient(options, leaseOptions) {
1596
+ const { agentDir, usesNativeAuth, authProfileId, startOptions } = await resolveCodexAppServerClientStartContext(options);
1597
+ const fallbackApiKeyCacheKey = authProfileId ? void 0 : resolveCodexAppServerFallbackApiKeyCacheKey({ startOptions });
1598
+ const key = codexAppServerStartOptionsKey(startOptions, {
1599
+ authProfileId,
1600
+ agentDir: usesNativeAuth ? void 0 : agentDir,
1601
+ fallbackApiKeyCacheKey
1602
+ });
1603
+ const state = getSharedCodexAppServerClientState();
1604
+ const entry = getOrCreateSharedClientEntry(state, key);
1605
+ const releasePendingAcquire = retainPendingSharedClientAcquire(entry);
1606
+ let cleanupAbandonSignal;
1607
+ if (options?.abandonSignal) {
1608
+ const abandon = () => {
1609
+ releasePendingAcquire();
1610
+ closeSharedClientEntryIfUnclaimed(key, entry);
1611
+ };
1612
+ options.abandonSignal.addEventListener("abort", abandon, { once: true });
1613
+ cleanupAbandonSignal = () => options.abandonSignal?.removeEventListener("abort", abandon);
1614
+ if (options.abandonSignal.aborted) abandon();
1615
+ }
1616
+ const sharedPromise = entry.promise ?? (entry.promise = (async () => {
1617
+ const client = await startInitializedCodexAppServerClient({
1618
+ startOptions,
1619
+ agentDir,
1620
+ authProfileId: usesNativeAuth ? null : authProfileId,
1621
+ config: options?.config,
1622
+ onStartedClient: (startedClient) => {
1623
+ entry.client = startedClient;
1624
+ options?.onStartedClient?.(startedClient);
1625
+ }
1626
+ });
1627
+ entry.client = client;
1628
+ client.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(key, closedClient));
1629
+ return client;
1630
+ })());
1631
+ try {
1632
+ const client = await withTimeout$1(sharedPromise, options?.timeoutMs ?? 0, "codex app-server initialize timed out");
1633
+ ensureCodexAppServerClientRuntime(client, {
1634
+ agentDir,
1635
+ authProfileId: usesNativeAuth ? void 0 : authProfileId,
1636
+ config: options?.config
1637
+ });
1638
+ const release = leaseOptions?.leased ? retainSharedClientEntry(entry) : void 0;
1639
+ return release ? {
1640
+ client,
1641
+ release
1642
+ } : { client };
1643
+ } catch (error) {
1644
+ const currentEntry = state.clients.get(key);
1645
+ if (currentEntry?.promise === sharedPromise) clearSharedClientEntry(key, currentEntry);
1646
+ throw error;
1647
+ } finally {
1648
+ cleanupAbandonSignal?.();
1649
+ releasePendingAcquire();
1650
+ }
1651
+ }
1652
+ /** Starts a non-shared Codex app-server client owned entirely by the caller. */
1653
+ async function createIsolatedCodexAppServerClient(options) {
1654
+ const { agentDir, usesNativeAuth, authProfileId, authProfileStore, startOptions } = await resolveCodexAppServerClientStartContext(options);
1655
+ return await startInitializedCodexAppServerClient({
1656
+ startOptions,
1657
+ agentDir,
1658
+ authProfileId: usesNativeAuth ? null : authProfileId,
1659
+ authProfileStore,
1660
+ config: options?.config,
1661
+ timeoutMs: options?.timeoutMs,
1662
+ onStartedClient: options?.onStartedClient
1663
+ });
1664
+ }
1665
+ async function startInitializedCodexAppServerClient(params) {
1666
+ const startOptionsCandidates = resolveManagedFallbackStartOptions(params.startOptions);
1667
+ for (let index = 0; index < startOptionsCandidates.length; index += 1) {
1668
+ const startOptions = startOptionsCandidates[index];
1669
+ const client = CodexAppServerClient.start(startOptions);
1670
+ params.onStartedClient?.(client);
1671
+ const initialize = client.initialize();
1672
+ try {
1673
+ await withTimeout$1(initialize, params.timeoutMs ?? 0, "codex app-server initialize timed out");
1674
+ } catch (error) {
1675
+ client.close();
1676
+ initialize.catch(() => void 0);
1677
+ if (shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates)) continue;
1678
+ throw error;
1679
+ }
1680
+ ensureCodexAppServerClientRuntime(client, {
1681
+ agentDir: params.agentDir,
1682
+ authProfileId: params.authProfileId ?? void 0,
1683
+ ...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {},
1684
+ config: params.config
1685
+ });
1686
+ try {
1687
+ await applyCodexAppServerAuthProfile({
1688
+ client,
1689
+ agentDir: params.agentDir,
1690
+ authProfileId: params.authProfileId,
1691
+ startOptions,
1692
+ config: params.config,
1693
+ ...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {}
1694
+ });
1695
+ return client;
1696
+ } catch (error) {
1697
+ client.close();
1698
+ throw error;
1699
+ }
1700
+ }
1701
+ throw new Error("Managed Codex app-server fallback candidates were exhausted.");
1702
+ }
1703
+ function resolveManagedFallbackStartOptions(startOptions) {
1704
+ const commands = [startOptions.command, ...startOptions.managedFallbackCommandPaths ?? []];
1705
+ const candidates = [];
1706
+ for (let index = 0; index < commands.length; index += 1) {
1707
+ const command = commands[index];
1708
+ const managedFallbackCommandPaths = commands.slice(index + 1);
1709
+ const candidate = {
1710
+ ...startOptions,
1711
+ command
1712
+ };
1713
+ if (managedFallbackCommandPaths.length === 0) delete candidate.managedFallbackCommandPaths;
1714
+ else candidate.managedFallbackCommandPaths = managedFallbackCommandPaths;
1715
+ candidates.push(candidate);
1716
+ }
1717
+ return candidates;
1718
+ }
1719
+ function shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates) {
1720
+ return startOptions.commandSource === "resolved-managed" && index < startOptionsCandidates.length - 1 && isUnsupportedCodexAppServerVersionError(error);
1721
+ }
1722
+ /** Clears and closes the shared entry only if it still owns the supplied client. */
1723
+ function clearSharedCodexAppServerClientIfCurrent(client) {
1724
+ if (!client) return false;
1725
+ const state = getSharedCodexAppServerClientState();
1726
+ for (const [key, entry] of state.clients) if (entry.client === client) {
1727
+ state.clients.delete(key);
1728
+ client.close();
1729
+ return true;
1730
+ }
1731
+ return false;
1732
+ }
1733
+ /** Marks a matching shared client to close after active leases/acquires drain. */
1734
+ function retireSharedCodexAppServerClientIfCurrent(client) {
1735
+ if (!client) return;
1736
+ const state = getSharedCodexAppServerClientState();
1737
+ for (const [key, entry] of state.clients) if (entry.client === client) {
1738
+ state.clients.delete(key);
1739
+ entry.closeWhenIdle = true;
1740
+ const closed = closeRetiredSharedClientEntryIfIdle(entry);
1741
+ return {
1742
+ activeLeases: entry.activeLeases,
1743
+ closed
1744
+ };
1745
+ }
1746
+ const activeLeases = state.leasedReleases.get(client)?.length ?? 0;
1747
+ if (activeLeases > 0) return {
1748
+ activeLeases,
1749
+ closed: false
1750
+ };
1751
+ }
1752
+ /** Clears a matching shared client and waits for its process to exit. */
1753
+ async function clearSharedCodexAppServerClientIfCurrentAndWait(client, options) {
1754
+ if (!client) return false;
1755
+ const state = getSharedCodexAppServerClientState();
1756
+ for (const [key, entry] of state.clients) if (entry.client === client) {
1757
+ state.clients.delete(key);
1758
+ await client.closeAndWait(options);
1759
+ return true;
1760
+ }
1761
+ return false;
1762
+ }
1763
+ /** Clears all shared clients and waits for their processes to exit. */
1764
+ async function clearSharedCodexAppServerClientAndWait(options) {
1765
+ const state = getSharedCodexAppServerClientState();
1766
+ const clients = collectSharedClients(state);
1767
+ state.clients.clear();
1768
+ await Promise.all(clients.map((client) => client.closeAndWait(options)));
1769
+ }
1770
+ function getOrCreateSharedClientEntry(state, key) {
1771
+ let entry = state.clients.get(key);
1772
+ if (!entry) {
1773
+ entry = {
1774
+ activeLeases: 0,
1775
+ pendingAcquires: 0,
1776
+ closeWhenIdle: false
1777
+ };
1778
+ state.clients.set(key, entry);
1779
+ }
1780
+ return entry;
1781
+ }
1782
+ function clearSharedClientEntry(key, entry) {
1783
+ const state = getSharedCodexAppServerClientState();
1784
+ if (state.clients.get(key) !== entry) return;
1785
+ state.clients.delete(key);
1786
+ entry.client?.close();
1787
+ }
1788
+ function clearSharedClientEntryIfCurrent(key, client) {
1789
+ const state = getSharedCodexAppServerClientState();
1790
+ if (state.clients.get(key)?.client === client) state.clients.delete(key);
1791
+ }
1792
+ /** Clears a matching shared client only when no lease or acquire currently claims it. */
1793
+ function clearSharedCodexAppServerClientIfCurrentAndUnclaimed(client) {
1794
+ if (!client) return {
1795
+ found: false,
1796
+ closed: false,
1797
+ activeLeases: 0,
1798
+ pendingAcquires: 0
1799
+ };
1800
+ const state = getSharedCodexAppServerClientState();
1801
+ for (const [key, entry] of state.clients) if (entry.client === client) return {
1802
+ found: true,
1803
+ closed: closeSharedClientEntryIfUnclaimed(key, entry),
1804
+ activeLeases: entry.activeLeases,
1805
+ pendingAcquires: entry.pendingAcquires
1806
+ };
1807
+ return {
1808
+ found: false,
1809
+ closed: false,
1810
+ activeLeases: 0,
1811
+ pendingAcquires: 0
1812
+ };
1813
+ }
1814
+ function retainPendingSharedClientAcquire(entry) {
1815
+ let released = false;
1816
+ entry.pendingAcquires += 1;
1817
+ return () => {
1818
+ if (released) return;
1819
+ released = true;
1820
+ entry.pendingAcquires = Math.max(0, entry.pendingAcquires - 1);
1821
+ closeRetiredSharedClientEntryIfIdle(entry);
1822
+ };
1823
+ }
1824
+ function retainSharedClientEntry(entry) {
1825
+ let released = false;
1826
+ entry.activeLeases += 1;
1827
+ return () => {
1828
+ if (released) return;
1829
+ released = true;
1830
+ entry.activeLeases = Math.max(0, entry.activeLeases - 1);
1831
+ closeRetiredSharedClientEntryIfIdle(entry);
1832
+ };
1833
+ }
1834
+ function closeRetiredSharedClientEntryIfIdle(entry) {
1835
+ if (!entry.closeWhenIdle || entry.activeLeases > 0 || entry.pendingAcquires > 0 || !entry.client) return false;
1836
+ const client = entry.client;
1837
+ entry.closeWhenIdle = false;
1838
+ entry.client = void 0;
1839
+ client.close();
1840
+ return true;
1841
+ }
1842
+ function closeSharedClientEntryIfUnclaimed(key, entry) {
1843
+ if (entry.activeLeases > 0 || entry.pendingAcquires > 0) return false;
1844
+ const state = getSharedCodexAppServerClientState();
1845
+ if (state.clients.get(key) !== entry) return false;
1846
+ state.clients.delete(key);
1847
+ entry.client?.close();
1848
+ return Boolean(entry.client);
1849
+ }
1850
+ function collectSharedClients(state) {
1851
+ return [...new Set([...state.clients.values()].map((entry) => entry.client).filter((client) => Boolean(client)))];
1852
+ }
1853
+ //#endregion
1854
+ export { resolveCodexAppServerAuthAccountCacheKey as _, getLeasedSharedCodexAppServerClient as a, resolveCodexAppServerFallbackApiKeyCacheKey as b, shared_client_exports as c, isCodexAppServerApprovalRequest as d, isCodexAppServerConnectionClosedError as f, rememberCodexRateLimitsRead as g, readRecentCodexRateLimits as h, createIsolatedCodexAppServerClient as i, withTimeout$1 as l, readCodexRateLimitsRevision as m, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as n, releaseLeasedSharedCodexAppServerClient as o, ensureCodexAppServerClientRuntime as p, clearSharedCodexAppServerClientIfCurrentAndWait as r, retireSharedCodexAppServerClientIfCurrent as s, clearSharedCodexAppServerClientIfCurrent as t, CodexAppServerRpcError as u, resolveCodexAppServerAuthProfileId as v, resolveCodexAppServerHomeDir as x, resolveCodexAppServerAuthProfileIdForAgent as y };