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