@openclaw/codex 2026.7.2-beta.7 → 2026.7.34

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
@@ -1,3069 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { _ as resolveCodexAppServerStartOptionsForAgent, g as resolveCodexAppServerRuntimeOptions, o as isCodexAppServerNativeAuthProfile, p as codexAppServerStartOptionsKey, v as resolveCodexComputerUseConfig, w as resolveCodexAppServerUserHomeDir } from "./session-binding-BXpo9ymA.js";
3
- import { n as resolveCodexAppServerSpawnEnv, t as createStdioTransport } from "./transport-stdio-DXgGZ7Ib.js";
4
- import { createRequire } from "node:module";
5
- import fs, { access } from "node:fs/promises";
6
- import path from "node:path";
7
- import { addTimerTimeoutGraceMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
8
- import { AgentHarnessPreflightError, OPENCLAW_VERSION, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
9
- import { createHash, randomUUID } from "node:crypto";
10
- import { ensureAuthProfileStore, findPersistedAuthProfileCredential, loadAuthProfileStoreForSecretsRuntime, refreshOAuthCredentialForRuntime, resolveApiKeyForProfile, resolveAuthProfileOrder, resolveDefaultAgentDir, resolvePersistedAuthProfileOwnerAgentDir, resolveProviderIdForAuth } from "openclaw/plugin-sdk/agent-runtime";
11
- import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
12
- import fsSync, { constants, existsSync, readFileSync, realpathSync } from "node:fs";
13
- import os from "node:os";
14
- import { isDeepStrictEqual } from "node:util";
15
- import { hasUsableOAuthCredential } from "openclaw/plugin-sdk/provider-auth";
16
- import { readSecretFile } from "openclaw/plugin-sdk/secret-file";
17
- import { runExec } from "openclaw/plugin-sdk/process-runtime";
18
- import { createInterface } from "node:readline";
19
- import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
20
- import { EventEmitter } from "node:events";
21
- import net from "node:net";
22
- import { PassThrough, Writable } from "node:stream";
23
- import { StringDecoder } from "node:string_decoder";
24
- import WebSocket from "ws";
25
- import { fileURLToPath } from "node:url";
26
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
27
- import { withTimeout } from "openclaw/plugin-sdk/security-runtime";
28
- //#region extensions/codex/src/app-server/attempt-timeouts.ts
29
- /**
30
- * Timeout defaults and normalizers for Codex app-server startup and turn
31
- * liveness watches.
32
- */
33
- /** Minimum startup timeout accepted by the Codex app-server harness. */
34
- const CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS = 100;
35
- /** Default idle timeout while waiting for app-server turn completion. */
36
- const CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS = 6e4;
37
- /** Short guard after apparent assistant completion. */
38
- const CODEX_TURN_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS = 1e4;
39
- const CODEX_POST_TOOL_RAW_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS = 5 * 6e4;
40
- /** Guard after reasoning/commentary progress when no tool handoff occurred. */
41
- const CODEX_POST_REASONING_REPLY_IDLE_TIMEOUT_MS = 5 * 6e4;
42
- /** Long terminal idle watch for app-server turns that never send completion. */
43
- const CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS = 30 * 6e4;
44
- var CodexAppServerStartupError = class extends Error {
45
- constructor(reason, message = reason === "timed_out" ? "codex app-server startup timed out" : "codex app-server startup aborted") {
46
- super(message);
47
- this.reason = reason;
48
- this.code = "CODEX_APP_SERVER_STARTUP_CANCELLED";
49
- this.name = "CodexAppServerStartupError";
50
- }
51
- };
52
- function isCodexAppServerStartupError(error, reason) {
53
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_STARTUP_CANCELLED" && "reason" in error && (error.reason === "aborted" || error.reason === "timed_out") && (reason === void 0 || error.reason === reason);
54
- }
55
- function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
56
- return resolveTimerTimeoutMs(value, resolveTimerTimeoutMs(fallbackMs, 1));
57
- }
58
- /** Runs startup work with abort and timeout handling plus optional cleanup. */
59
- async function withCodexStartupTimeout(params) {
60
- if (params.signal.aborted) throw new CodexAppServerStartupError("aborted");
61
- let timeout;
62
- let abortCleanup;
63
- let timeoutError;
64
- let timeoutCleanup;
65
- try {
66
- return await Promise.race([params.operation(), new Promise((_, reject) => {
67
- const rejectOnce = (error) => {
68
- if (timeout) {
69
- clearTimeout(timeout);
70
- timeout = void 0;
71
- }
72
- reject(error);
73
- };
74
- timeout = setTimeout(() => {
75
- timeoutError = new CodexAppServerStartupError("timed_out");
76
- timeoutCleanup = Promise.resolve(params.onTimeout?.()).then(() => void 0, () => void 0);
77
- timeoutCleanup.finally(() => {
78
- rejectOnce(timeoutError);
79
- });
80
- }, params.timeoutMs);
81
- const abortListener = () => rejectOnce(new CodexAppServerStartupError("aborted"));
82
- params.signal.addEventListener("abort", abortListener, { once: true });
83
- abortCleanup = () => params.signal.removeEventListener("abort", abortListener);
84
- })]);
85
- } catch (error) {
86
- if (timeoutError) {
87
- await timeoutCleanup;
88
- throw timeoutError;
89
- }
90
- throw error;
91
- } finally {
92
- if (timeout) clearTimeout(timeout);
93
- abortCleanup?.();
94
- }
95
- }
96
- /** Resolves startup timeout while honoring the configured floor. */
97
- function resolveCodexStartupTimeoutMs(params) {
98
- const timeoutFloorMs = resolvePositiveIntegerTimeoutMs(params.timeoutFloorMs, CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS);
99
- const timeoutMs = resolvePositiveIntegerTimeoutMs(params.timeoutMs, timeoutFloorMs);
100
- return Math.max(timeoutFloorMs, timeoutMs);
101
- }
102
- /** Resolves the completion-idle timeout for an active turn. */
103
- function resolveCodexTurnCompletionIdleTimeoutMs(value) {
104
- return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS);
105
- }
106
- /** Resolves the short assistant-completion release timeout. */
107
- function resolveCodexTurnAssistantCompletionIdleTimeoutMs(value) {
108
- return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS);
109
- }
110
- /** Resolves the conservative post-tool raw assistant guard timeout. */
111
- function resolveCodexPostToolRawAssistantCompletionIdleTimeoutMs(value, fallbackMs) {
112
- return resolvePositiveIntegerTimeoutMs(value, Math.max(resolvePositiveIntegerTimeoutMs(void 0, fallbackMs), CODEX_POST_TOOL_RAW_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS));
113
- }
114
- /** Resolves the long terminal turn idle timeout. */
115
- function resolveCodexTurnTerminalIdleTimeoutMs(value, runTimeoutOverrideMs) {
116
- const explicitRunBudgetMs = resolvePositiveIntegerTimeoutMs(runTimeoutOverrideMs, CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS);
117
- return resolvePositiveIntegerTimeoutMs(value, Math.max(CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS, explicitRunBudgetMs));
118
- }
119
- /** Adds gateway grace time to a caller timeout without overflowing invalid values. */
120
- function resolveCodexGatewayTimeoutWithGraceMs(timeoutMs, graceMs = 1e4) {
121
- const timeout = resolvePositiveIntegerTimeoutMs(timeoutMs, 1);
122
- return addTimerTimeoutGraceMs(timeout, resolveTimerTimeoutMs(graceMs, 0, 0)) ?? timeout;
123
- }
124
- //#endregion
125
- //#region extensions/codex/src/app-server/auth-start-options.ts
126
- const CODEX_APP_SERVER_HOME_DIRNAME = "codex-home";
127
- const CODEX_EPHEMERAL_AUTH_STORE_OVERRIDE = "cli_auth_credentials_store=\"ephemeral\"";
128
- function resolveCodexAppServerHomeDir(agentDir) {
129
- return path.join(path.resolve(agentDir), CODEX_APP_SERVER_HOME_DIRNAME);
130
- }
131
- /** Forces OpenClaw-owned Codex auth to remain process-local. */
132
- function withEphemeralCodexAuthStore(params) {
133
- const { startOptions } = params;
134
- if (!(startOptions.commandSource === "managed" || startOptions.commandSource === "resolved-managed") || !params.preparedAuth && params.authProfileId === null) return startOptions;
135
- if (startOptions.args.at(-2) === "-c" && startOptions.args.at(-1) === CODEX_EPHEMERAL_AUTH_STORE_OVERRIDE) return startOptions;
136
- return {
137
- ...startOptions,
138
- args: [
139
- ...startOptions.args,
140
- "-c",
141
- CODEX_EPHEMERAL_AUTH_STORE_OVERRIDE
142
- ]
143
- };
144
- }
145
- //#endregion
146
- //#region extensions/codex/src/app-server/desktop-app-paths.ts
147
- /** Shared path candidates for Codex's macOS desktop app bundle. */
148
- const MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES = [{
149
- appName: "ChatGPT.app",
150
- appBundlePath: "/Applications/ChatGPT.app",
151
- appServerCommandPath: "/Applications/ChatGPT.app/Contents/Resources/codex",
152
- bundledMarketplacePath: "/Applications/ChatGPT.app/Contents/Resources/plugins/openai-bundled",
153
- computerUseServiceAppPaths: ["/Applications/ChatGPT.app/Contents/Resources/cua_node/lib/node_modules/@oai/sky/Codex Computer Use.app", "/Applications/ChatGPT.app/Contents/Resources/plugins/openai-bundled/plugins/computer-use/Codex Computer Use.app"]
154
- }, {
155
- appName: "Codex.app",
156
- appBundlePath: "/Applications/Codex.app",
157
- appServerCommandPath: "/Applications/Codex.app/Contents/Resources/codex",
158
- bundledMarketplacePath: "/Applications/Codex.app/Contents/Resources/plugins/openai-bundled",
159
- computerUseServiceAppPaths: ["/Applications/Codex.app/Contents/Resources/plugins/openai-bundled/plugins/computer-use/Codex Computer Use.app", "/Applications/Codex.app/Contents/Resources/cua_node/lib/node_modules/@oai/sky/Codex Computer Use.app"]
160
- }];
161
- function resolveMacOSDesktopCodexBundledMarketplaceCandidates(platform = process.platform) {
162
- return platform === "darwin" ? MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.map((candidate) => candidate.bundledMarketplacePath) : [];
163
- }
164
- function resolveMacOSDesktopCodexComputerUseServiceAppCandidates(platform = process.platform, appServerCommand) {
165
- if (platform !== "darwin") return [];
166
- const matchingCandidate = appServerCommand ? MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.find((candidate) => path.resolve(candidate.appServerCommandPath) === path.resolve(appServerCommand)) : void 0;
167
- const orderedCandidates = matchingCandidate ? [matchingCandidate, ...MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.filter((candidate) => candidate !== matchingCandidate)] : MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES;
168
- return [...new Set(orderedCandidates.flatMap((candidate) => candidate.computerUseServiceAppPaths))];
169
- }
170
- function resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath(params = {}) {
171
- const candidates = params.candidates ?? resolveMacOSDesktopCodexBundledMarketplaceCandidates(params.platform);
172
- const pathExists = params.pathExists ?? existsSync;
173
- return candidates.find((candidate) => pathExists(candidate));
174
- }
175
- //#endregion
176
- //#region extensions/codex/src/app-server/computer-use-cache.ts
177
- /** Shared Computer Use plugin cache reconciliation for isolated Codex homes. */
178
- const DEFAULT_CODEX_COMPUTER_USE_BUNDLED_MARKETPLACE_PATH = resolveMacOSDesktopCodexBundledMarketplaceCandidates("darwin")[0] ?? "";
179
- const DEFAULT_BUNDLED_MARKETPLACE_NAME = "openai-bundled";
180
- async function ensureCodexComputerUseSharedPluginCache(params) {
181
- if (!params.config.enabled) return skippedCacheResult("disabled", "Computer Use cache sharing skipped because it is disabled.");
182
- if (params.config.pluginCacheMode === "independent") return skippedCacheResult("independent", "Computer Use cache sharing skipped because pluginCacheMode is independent.");
183
- if (params.config.marketplaceName || params.config.marketplacePath) return skippedCacheResult("explicit_marketplace", "Computer Use cache sharing skipped because an explicit marketplace is configured.");
184
- const bundledMarketplacePath = resolveComputerUseBundledMarketplacePath(params);
185
- const sourcePluginRoot = path.join(bundledMarketplacePath, "plugins", params.config.pluginName);
186
- const version = await readBundledPluginVersion(sourcePluginRoot);
187
- if (!version) return skippedCacheResult("source_missing", `Computer Use bundled plugin source was not found at ${sourcePluginRoot}.`);
188
- const marketplaceName = params.config.marketplaceName ?? DEFAULT_BUNDLED_MARKETPLACE_NAME;
189
- const cacheRoot = path.join(params.codexHome, "plugins", "cache", marketplaceName, params.config.pluginName);
190
- const cachePath = path.join(cacheRoot, version);
191
- return {
192
- status: "shared",
193
- changed: await ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version),
194
- cachePath,
195
- targetPath: sourcePluginRoot,
196
- version,
197
- removedStaleVersions: [],
198
- warnings: [],
199
- message: `Computer Use plugin cache ${cachePath} contains bundled plugin ${sourcePluginRoot}.`
200
- };
201
- }
202
- function resolveComputerUseBundledMarketplacePath(params) {
203
- return params.bundledMarketplacePath ?? resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath({ candidates: params.bundledMarketplacePathCandidates }) ?? params.bundledMarketplacePathCandidates?.[0] ?? DEFAULT_CODEX_COMPUTER_USE_BUNDLED_MARKETPLACE_PATH;
204
- }
205
- async function readBundledPluginVersion(sourcePluginRoot) {
206
- const pluginJsonPath = path.join(sourcePluginRoot, ".codex-plugin", "plugin.json");
207
- let raw;
208
- try {
209
- raw = await fs.readFile(pluginJsonPath, "utf8");
210
- } catch {
211
- return;
212
- }
213
- try {
214
- const parsed = JSON.parse(raw);
215
- return typeof parsed.version === "string" && parsed.version.trim() ? parsed.version.trim() : void 0;
216
- } catch {
217
- return;
218
- }
219
- }
220
- async function ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version) {
221
- await fs.mkdir(path.dirname(cachePath), { recursive: true });
222
- const stat = await fs.lstat(cachePath).catch(() => void 0);
223
- if (stat?.isDirectory() && !stat.isSymbolicLink()) {
224
- if (await readBundledPluginVersion(cachePath) === version) return false;
225
- }
226
- const cacheRoot = path.dirname(cachePath);
227
- const cacheName = path.basename(cachePath);
228
- const stagingRoot = await fs.mkdtemp(path.join(cacheRoot, `.${cacheName}.staging-`));
229
- const stagedPath = path.join(stagingRoot, cacheName);
230
- const backupPath = path.join(cacheRoot, `.${cacheName}.backup-${process.pid}-${Date.now()}`);
231
- let backupCreated = false;
232
- try {
233
- await fs.cp(sourcePluginRoot, stagedPath, { recursive: true });
234
- if (stat) {
235
- await fs.rename(cachePath, backupPath);
236
- backupCreated = true;
237
- }
238
- try {
239
- await fs.rename(stagedPath, cachePath);
240
- } catch (error) {
241
- if (backupCreated) try {
242
- await fs.rename(backupPath, cachePath);
243
- backupCreated = false;
244
- } catch (restoreError) {
245
- throw new Error(`Failed to install Computer Use cache ${cachePath} and restore its prior copy: ${String(error)}`, { cause: restoreError });
246
- }
247
- throw error;
248
- }
249
- if (backupCreated) await fs.rm(backupPath, {
250
- recursive: true,
251
- force: true
252
- });
253
- return true;
254
- } finally {
255
- await fs.rm(stagingRoot, {
256
- recursive: true,
257
- force: true
258
- });
259
- }
260
- }
261
- function skippedCacheResult(status, message) {
262
- return {
263
- status,
264
- changed: false,
265
- message,
266
- removedStaleVersions: [],
267
- warnings: status === "source_missing" ? [message] : []
268
- };
269
- }
270
- //#endregion
271
- //#region extensions/codex/src/app-server/computer-use-service.ts
272
- /** Native Computer Use service provisioning for isolated Codex homes. */
273
- const SERVICE_APP_NAME = "Codex Computer Use.app";
274
- const CLIENT_RELATIVE_PATH = path.join("Contents", "SharedSupport", "SkyComputerUseClient.app", "Contents", "MacOS", "SkyComputerUseClient");
275
- const COPY_TIMEOUT_MS = 12e4;
276
- const activeInstalls = /* @__PURE__ */ new Map();
277
- /** Ensures the official native client exists beneath the CODEX_HOME used by its launcher. */
278
- async function ensureCodexComputerUseServiceApp(params) {
279
- const platform = params.platform ?? process.platform;
280
- if (platform !== "darwin") return {
281
- status: "unsupported",
282
- changed: false
283
- };
284
- const targetPath = path.join(path.resolve(params.codexHome), "computer-use", SERVICE_APP_NAME);
285
- const active = activeInstalls.get(targetPath);
286
- if (active) return await active;
287
- const install = ensureCodexComputerUseServiceAppOnce({
288
- ...params,
289
- targetPath,
290
- platform
291
- });
292
- activeInstalls.set(targetPath, install);
293
- try {
294
- return await install;
295
- } finally {
296
- if (activeInstalls.get(targetPath) === install) activeInstalls.delete(targetPath);
297
- }
298
- }
299
- async function ensureCodexComputerUseServiceAppOnce(params) {
300
- if (await hasExecutableClient(params.targetPath)) return {
301
- status: "already_installed",
302
- changed: false,
303
- targetPath: params.targetPath
304
- };
305
- const sourcePath = await findUsableServiceApp(params.sourceAppCandidates ?? resolveMacOSDesktopCodexComputerUseServiceAppCandidates(params.platform, params.appServerCommand));
306
- if (!sourcePath) return {
307
- status: "source_missing",
308
- changed: false,
309
- targetPath: params.targetPath
310
- };
311
- const targetParent = path.dirname(params.targetPath);
312
- await fs.mkdir(targetParent, { recursive: true });
313
- const stagingRoot = await fs.mkdtemp(path.join(targetParent, ".service-app.staging-"));
314
- const stagedPath = path.join(stagingRoot, SERVICE_APP_NAME);
315
- const backupPath = path.join(targetParent, `.service-app.backup-${process.pid}-${Date.now()}`);
316
- let backupCreated = false;
317
- try {
318
- await (params.copyServiceApp ?? copyServiceAppWithDitto)(sourcePath, stagedPath);
319
- if (!await hasExecutableClient(stagedPath)) throw new Error(`Copied Computer Use service app is incomplete at ${stagedPath}.`);
320
- if (await pathExists$1(params.targetPath)) {
321
- await fs.rename(params.targetPath, backupPath);
322
- backupCreated = true;
323
- if (await hasExecutableClient(backupPath)) {
324
- await fs.rename(backupPath, params.targetPath);
325
- backupCreated = false;
326
- return {
327
- status: "already_installed",
328
- changed: false,
329
- targetPath: params.targetPath,
330
- sourcePath
331
- };
332
- }
333
- }
334
- try {
335
- await fs.rename(stagedPath, params.targetPath);
336
- } catch (error) {
337
- if (!await hasExecutableClient(params.targetPath)) {
338
- if (backupCreated) {
339
- await fs.rename(backupPath, params.targetPath);
340
- backupCreated = false;
341
- }
342
- throw error;
343
- }
344
- if (backupCreated) {
345
- await fs.rm(backupPath, {
346
- recursive: true,
347
- force: true
348
- });
349
- backupCreated = false;
350
- }
351
- return {
352
- status: "already_installed",
353
- changed: false,
354
- targetPath: params.targetPath,
355
- sourcePath
356
- };
357
- }
358
- if (backupCreated) {
359
- await fs.rm(backupPath, {
360
- recursive: true,
361
- force: true
362
- });
363
- backupCreated = false;
364
- }
365
- return {
366
- status: "installed",
367
- changed: true,
368
- targetPath: params.targetPath,
369
- sourcePath
370
- };
371
- } finally {
372
- await fs.rm(stagingRoot, {
373
- recursive: true,
374
- force: true
375
- });
376
- }
377
- }
378
- async function pathExists$1(filePath) {
379
- return await fs.lstat(filePath).then(() => true, () => false);
380
- }
381
- async function findUsableServiceApp(candidates) {
382
- for (const candidate of candidates) if (await hasExecutableClient(candidate)) return candidate;
383
- }
384
- async function hasExecutableClient(appPath) {
385
- try {
386
- await fs.access(path.join(appPath, CLIENT_RELATIVE_PATH), constants.X_OK);
387
- return true;
388
- } catch {
389
- return false;
390
- }
391
- }
392
- async function copyServiceAppWithDitto(sourcePath, targetPath) {
393
- await runExec("/usr/bin/ditto", [
394
- "--noqtn",
395
- sourcePath,
396
- targetPath
397
- ], {
398
- logOutput: false,
399
- timeoutMs: COPY_TIMEOUT_MS
400
- });
401
- }
402
- //#endregion
403
- //#region extensions/codex/src/app-server/protocol.ts
404
- /** Namespace Codex keeps directly model-visible without exposing it to Code Mode guests. */
405
- const CODEX_OPENCLAW_DIRECT_DYNAMIC_TOOL_NAMESPACE = "openclaw_direct";
406
- function flattenCodexDynamicToolFunctions(tools) {
407
- return (tools ?? []).flatMap((tool) => tool.type === "namespace" ? tool.tools : [tool]);
408
- }
409
- const CODEX_INTERACTIVE_THREAD_SOURCE_KINDS = ["cli", "vscode"];
410
- const CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES = ["atlas", "chatgpt"];
411
- function isJsonObject$1(value) {
412
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
413
- }
414
- function isRpcResponse(message) {
415
- return "id" in message && !("method" in message);
416
- }
417
- //#endregion
418
- //#region extensions/codex/src/app-server/auth-bridge.ts
419
- const CODEX_APP_SERVER_AUTH_PROVIDER = "openai";
420
- const CODEX_APP_SERVER_EXTERNAL_CLI_PROVIDER_IDS = [CODEX_APP_SERVER_AUTH_PROVIDER];
421
- const OPENAI_CODEX_DEFAULT_PROFILE_ID = "openai:default";
422
- const CODEX_HOME_ENV_VAR = "CODEX_HOME";
423
- const HOME_ENV_VAR = "HOME";
424
- const CODEX_API_KEY_ENV_VAR = "CODEX_API_KEY";
425
- const OPENAI_API_KEY_ENV_VAR = "OPENAI_API_KEY";
426
- const CODEX_ACCESS_TOKEN_ENV_VAR = "CODEX_ACCESS_TOKEN";
427
- const CODEX_APP_SERVER_API_KEY_ENV_VARS = [CODEX_API_KEY_ENV_VAR, OPENAI_API_KEY_ENV_VAR];
428
- const CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS = [
429
- CODEX_API_KEY_ENV_VAR,
430
- OPENAI_API_KEY_ENV_VAR,
431
- CODEX_ACCESS_TOKEN_ENV_VAR
432
- ];
433
- const CODEX_APP_SERVER_HOME_ENV_VARS = [CODEX_HOME_ENV_VAR, HOME_ENV_VAR];
434
- const CODEX_AUTH_JSON_FILENAME = "auth.json";
435
- const CODEX_HOME_DIRNAME = ".codex";
436
- const scopedOAuthRefreshQueues = /* @__PURE__ */ new WeakMap();
437
- async function bridgeCodexAppServerStartOptions(params) {
438
- if (params.startOptions.transport !== "stdio") return params.startOptions;
439
- const scopedStartOptions = await withCodexHomeEnvironment(withEphemeralCodexAuthStore(params), params.agentDir, params.pluginConfig);
440
- if (params.preparedAuth) return withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS);
441
- if (params.authProfileId === null) return scopedStartOptions;
442
- const store = resolveCodexAppServerAuthProfileStore({
443
- agentDir: params.agentDir,
444
- authProfileId: params.authProfileId,
445
- authProfileStore: params.authProfileStore,
446
- config: params.config
447
- });
448
- return shouldClearOpenAiApiKeyForCodexAuthProfile({
449
- store,
450
- authProfileId: resolveCodexAppServerAuthProfileId({
451
- authProfileId: params.authProfileId,
452
- store,
453
- config: params.config
454
- })
455
- }) ? withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS) : scopedStartOptions;
456
- }
457
- function resolveCodexAppServerAuthProfileId(params) {
458
- const requested = params.authProfileId?.trim();
459
- if (requested) return requested;
460
- return resolveAuthProfileOrder({
461
- cfg: params.config,
462
- store: params.store,
463
- provider: CODEX_APP_SERVER_AUTH_PROVIDER
464
- })[0]?.trim();
465
- }
466
- function resolveCodexAppServerAuthProfileIdForAgent(params) {
467
- const store = resolveCodexAppServerAuthProfileStore({
468
- agentDir: params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {}),
469
- authProfileId: params.authProfileId,
470
- authProfileStore: params.authProfileStore,
471
- config: params.config
472
- });
473
- return resolveCodexAppServerAuthProfileId({
474
- authProfileId: params.authProfileId,
475
- store,
476
- config: params.config
477
- });
478
- }
479
- function ensureCodexAppServerAuthProfileStore(params) {
480
- return ensureAuthProfileStore(params.agentDir, {
481
- allowKeychainPrompt: false,
482
- config: params.config,
483
- externalCliProviderIds: CODEX_APP_SERVER_EXTERNAL_CLI_PROVIDER_IDS,
484
- ...params.authProfileId ? { externalCliProfileIds: [params.authProfileId] } : {}
485
- });
486
- }
487
- function resolveCodexAppServerAuthProfileStore(params) {
488
- if (params.authProfileStore) return params.authProfileStore;
489
- return ensureCodexAppServerAuthProfileStore({
490
- agentDir: params.agentDir,
491
- authProfileId: params.authProfileId,
492
- config: params.config
493
- });
494
- }
495
- /** Resolves prepared profile login material once so cache identity and RPC login cannot drift. */
496
- async function resolveCodexAppServerPreparedAuthProfileSnapshot(params) {
497
- const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
498
- const store = resolveCodexAppServerAuthProfileStore({
499
- agentDir,
500
- authProfileId: params.authProfileId,
501
- authProfileStore: params.authProfileStore,
502
- config: params.config
503
- });
504
- const profileId = resolveCodexAppServerAuthProfileId({
505
- authProfileId: params.authProfileId,
506
- store,
507
- config: params.config
508
- });
509
- if (!profileId) return;
510
- const credential = store.profiles[profileId];
511
- if (!credential || !isCodexAppServerAuthProfileCredential(credential)) return;
512
- const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
513
- agentDir,
514
- authProfileId: profileId,
515
- authProfileStore: store,
516
- config: params.config
517
- });
518
- if (!loginParams) return;
519
- const accountId = loginParams.type === "chatgptAuthTokens" ? loginParams.chatgptAccountId : resolveChatgptAccountId(profileId, credential);
520
- const stableChatgptAccountId = resolveStableChatgptAccountId(credential);
521
- return {
522
- loginParams,
523
- secretFreeCacheKey: credential.type === "api_key" && loginParams.type === "apiKey" ? `${accountId}:${fingerprintApiKeyAuthProfileCacheKey(loginParams.apiKey)}` : loginParams.type === "chatgptAuthTokens" && (credential.type === "token" || !stableChatgptAccountId) ? `${accountId}:${fingerprintTokenAuthProfileCacheKey(loginParams.accessToken)}` : accountId
524
- };
525
- }
526
- /** Maps one prepared route to one mutually exclusive app-server auth handoff. */
527
- async function resolveCodexAppServerPreparedAuthHandoff(params) {
528
- const usesNativeHome = params.homeScope === "user";
529
- if (params.authRequirement === "api-key" && !usesNativeHome) {
530
- const apiKey = params.resolvedApiKey?.trim();
531
- if (!apiKey) throw new Error("Prepared Codex API-key route is missing its resolved API key.");
532
- return {
533
- nativeAuthProfile: false,
534
- preparedAuth: {
535
- kind: "api-key",
536
- apiKey
537
- }
538
- };
539
- }
540
- const authProfileId = params.authProfileId?.trim() || void 0;
541
- const nativeAuthProfile = isCodexAppServerNativeAuthProfile({
542
- authProfileId,
543
- authProfileStore: params.authProfileStore,
544
- agentDir: params.agentDir,
545
- config: params.config
546
- });
547
- if (usesNativeHome || params.authRequirement !== "subscription") return {
548
- authProfileId,
549
- nativeAuthProfile
550
- };
551
- if (!authProfileId || !nativeAuthProfile) throw createCodexAppServerAuthError(params.subscriptionProfileRequiredError);
552
- const snapshot = await resolveCodexAppServerPreparedAuthProfileSnapshot({
553
- authProfileId,
554
- authProfileStore: params.authProfileStore,
555
- agentDir: params.agentDir,
556
- config: params.config
557
- });
558
- if (!snapshot) throw createCodexAppServerAuthError(params.subscriptionProfileUnusableError);
559
- return {
560
- authProfileId,
561
- nativeAuthProfile,
562
- preparedAuth: {
563
- kind: "profile",
564
- profileId: authProfileId,
565
- store: params.authProfileStore,
566
- snapshot
567
- }
568
- };
569
- }
570
- async function resolveCodexAppServerAuthAccountCacheKey(params) {
571
- const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
572
- const store = resolveCodexAppServerAuthProfileStore({
573
- agentDir,
574
- authProfileId: params.authProfileId,
575
- authProfileStore: params.authProfileStore,
576
- config: params.config
577
- });
578
- const profileId = resolveCodexAppServerAuthProfileId({
579
- authProfileId: params.authProfileId,
580
- store,
581
- config: params.config
582
- });
583
- if (!profileId) return;
584
- const credential = store.profiles[profileId];
585
- if (!credential || !isCodexAppServerAuthProfileCredential(credential)) return;
586
- if (credential.type === "api_key") {
587
- const apiKey = (await resolveApiKeyForProfile({
588
- store,
589
- profileId,
590
- agentDir
591
- }))?.apiKey?.trim();
592
- return apiKey ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintApiKeyAuthProfileCacheKey(apiKey)}` : resolveChatgptAccountId(profileId, credential);
593
- }
594
- if (credential.type === "token") {
595
- const accessToken = (await resolveApiKeyForProfile({
596
- store,
597
- profileId,
598
- agentDir
599
- }))?.apiKey?.trim();
600
- return accessToken ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintTokenAuthProfileCacheKey(accessToken)}` : resolveChatgptAccountId(profileId, credential);
601
- }
602
- return resolveChatgptAccountId(profileId, credential);
603
- }
604
- function resolveCodexAppServerEnvApiKeyCacheKey(params) {
605
- if (params.startOptions.transport !== "stdio") return;
606
- const apiKey = readFirstNonEmptyEnvEntry(resolveCodexAppServerSpawnEnv(params.startOptions, params.baseEnv ?? process.env, params.platform ?? process.platform), CODEX_APP_SERVER_API_KEY_ENV_VARS);
607
- if (!apiKey) return;
608
- const hash = createHash("sha256");
609
- hash.update("openclaw:codex:app-server-env-api-key:v1");
610
- hash.update("\0");
611
- hash.update(apiKey.key);
612
- hash.update("\0");
613
- hash.update(apiKey.value);
614
- return `${apiKey.key}:sha256:${hash.digest("hex")}`;
615
- }
616
- function resolveCodexAppServerFallbackApiKeyCacheKey(params) {
617
- if (params.startOptions.transport !== "stdio") return;
618
- return resolveCodexAppServerEnvApiKeyCacheKey(params) ?? resolveCodexCliAuthFileApiKeyCacheKey(params.baseEnv ?? process.env);
619
- }
620
- /** Secret-free cache identity for an API key already resolved by the runtime plan. */
621
- function resolveCodexAppServerPreparedApiKeyCacheKey(apiKey) {
622
- const resolved = apiKey?.trim();
623
- return resolved ? fingerprintApiKeyAuthProfileCacheKey(resolved) : void 0;
624
- }
625
- function fingerprintApiKeyAuthProfileCacheKey(apiKey) {
626
- const hash = createHash("sha256");
627
- hash.update("openclaw:codex:app-server-auth-profile-api-key:v1");
628
- hash.update("\0");
629
- hash.update(apiKey);
630
- return `api_key:sha256:${hash.digest("hex")}`;
631
- }
632
- function fingerprintTokenAuthProfileCacheKey(accessToken) {
633
- const hash = createHash("sha256");
634
- hash.update("openclaw:codex:app-server-auth-profile-token:v1");
635
- hash.update("\0");
636
- hash.update(accessToken);
637
- return `token:sha256:${hash.digest("hex")}`;
638
- }
639
- function fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) {
640
- const hash = createHash("sha256");
641
- hash.update("openclaw:codex:app-server-cli-auth-json-api-key:v1");
642
- hash.update("\0");
643
- hash.update(apiKey);
644
- return `CODEX_AUTH_JSON:sha256:${hash.digest("hex")}`;
645
- }
646
- async function withCodexHomeEnvironment(startOptions, agentDir, pluginConfig) {
647
- const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim() ? startOptions.env[CODEX_HOME_ENV_VAR] : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir(process.env) : resolveCodexAppServerHomeDir(agentDir);
648
- const nativeHome = startOptions.env?.[HOME_ENV_VAR]?.trim() ? startOptions.env[HOME_ENV_VAR] : void 0;
649
- await fs.mkdir(codexHome, { recursive: true });
650
- const computerUseConfig = resolveCodexComputerUseConfig({ pluginConfig });
651
- await ensureCodexComputerUseSharedPluginCache({
652
- codexHome,
653
- config: computerUseConfig
654
- });
655
- if (computerUseConfig.enabled && computerUseConfig.autoInstall) try {
656
- await ensureCodexComputerUseServiceApp({
657
- codexHome,
658
- appServerCommand: startOptions.command
659
- });
660
- } catch (error) {
661
- throw new AgentHarnessPreflightError("Codex Computer Use client provisioning failed.", { cause: error });
662
- }
663
- if (nativeHome) await fs.mkdir(nativeHome, { recursive: true });
664
- const nextStartOptions = {
665
- ...startOptions,
666
- env: {
667
- ...startOptions.env,
668
- [CODEX_HOME_ENV_VAR]: codexHome,
669
- ...nativeHome ? { [HOME_ENV_VAR]: nativeHome } : {}
670
- }
671
- };
672
- const clearEnv = withoutClearedCodexHomeEnv(startOptions.clearEnv);
673
- if (clearEnv) nextStartOptions.clearEnv = clearEnv;
674
- else delete nextStartOptions.clearEnv;
675
- return nextStartOptions;
676
- }
677
- function withoutClearedCodexHomeEnv(clearEnv) {
678
- if (!clearEnv) return;
679
- const reserved = new Set(CODEX_APP_SERVER_HOME_ENV_VARS);
680
- const filtered = clearEnv.filter((envVar) => !reserved.has(envVar.trim().toUpperCase()));
681
- return filtered.length === clearEnv.length ? clearEnv : filtered;
682
- }
683
- async function applyCodexAppServerAuthProfile(params) {
684
- if (params.preparedAuth?.kind === "profile") {
685
- await params.client.request("account/login/start", params.preparedAuth.snapshot.loginParams);
686
- return;
687
- }
688
- if (params.preparedAuth?.kind === "api-key") {
689
- await params.client.request("account/login/start", {
690
- type: "apiKey",
691
- apiKey: params.preparedAuth.apiKey
692
- });
693
- return;
694
- }
695
- if (params.authProfileId === null) {
696
- await assertNativeCodexAccountMatchesRoute(params.client, params.authRequirement);
697
- return;
698
- }
699
- let loginParams;
700
- try {
701
- loginParams = await resolveCodexAppServerAuthProfileLoginParams({
702
- agentDir: params.agentDir,
703
- authProfileId: params.authProfileId,
704
- authProfileStore: params.authProfileStore,
705
- config: params.config
706
- });
707
- } catch (error) {
708
- if (params.authRequirement === "subscription" && error instanceof CodexAppServerAuthProfileUnavailableError) throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.", error);
709
- throw error;
710
- }
711
- if (params.authRequirement === "subscription" && loginParams?.type !== "chatgptAuthTokens") throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.");
712
- if (!loginParams) {
713
- if (params.authRequirement === "subscription") throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.");
714
- if (params.authRequirement !== "api-key" || params.startOptions?.transport !== "stdio") return;
715
- const env = resolveCodexAppServerSpawnEnv(params.startOptions, process.env);
716
- const fallbackLoginParams = await resolveCodexAppServerFallbackApiKeyLoginParams({
717
- client: params.client,
718
- env,
719
- codexCliAuthEnv: process.env
720
- });
721
- if (fallbackLoginParams) await params.client.request("account/login/start", fallbackLoginParams);
722
- return;
723
- }
724
- await params.client.request("account/login/start", loginParams);
725
- }
726
- /**
727
- * Native-home connections are verified, never logged into. Both directions of the
728
- * check protect the same billing boundary: a subscription route cannot run without
729
- * ChatGPT tokens, and a Platform route must not silently spend the operator's
730
- * ChatGPT plan. An absent account is left alone because the native home may serve a
731
- * custom model provider that reports no OpenAI account at all.
732
- */
733
- async function assertNativeCodexAccountMatchesRoute(client, authRequirement) {
734
- if (!authRequirement) return;
735
- const response = await client.request("account/read", { refreshToken: false });
736
- const accountType = isJsonObject$1(response.account) ? response.account.type : void 0;
737
- if (authRequirement === "subscription") {
738
- if (accountType !== "chatgpt") throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.");
739
- return;
740
- }
741
- if (accountType === "chatgpt") throw createCodexAppServerAuthError("Codex Platform route requires an API-key account, but the native Codex home is signed in with a ChatGPT subscription. Sign that home in with `codex login --with-api-key`, or set appServer.homeScope=\"agent\" so OpenClaw can inject its own key.");
742
- }
743
- function createCodexAppServerAuthError(message, cause) {
744
- const error = cause === void 0 ? new Error(message) : new Error(message, { cause });
745
- return Object.assign(error, { status: 401 });
746
- }
747
- var CodexAppServerAuthProfileUnavailableError = class extends Error {};
748
- async function resolveCodexAppServerAuthProfileLoginParams(params) {
749
- const store = resolveCodexAppServerAuthProfileStore(params);
750
- const profileId = resolveCodexAppServerAuthProfileId({
751
- authProfileId: params.authProfileId,
752
- store,
753
- config: params.config
754
- });
755
- const profile = profileId ? store.profiles[profileId] : void 0;
756
- if (profileId && !profile) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" was not found.`);
757
- if (profileId && profile && !isCodexAppServerAuthProfileCredential(profile)) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" must use the canonical OpenAI auth provider; run "openclaw doctor --fix" to migrate legacy provider IDs.`);
758
- return await resolveCodexAppServerAuthProfileLoginParamsInternal({
759
- ...params,
760
- authProfileStore: store
761
- });
762
- }
763
- async function refreshCodexAppServerAuthTokens(params) {
764
- const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
765
- ...params,
766
- forceOAuthRefresh: true
767
- });
768
- if (!loginParams || loginParams.type !== "chatgptAuthTokens") throw new Error("Codex app-server ChatGPT token refresh requires an OAuth auth profile.");
769
- return {
770
- accessToken: loginParams.accessToken,
771
- chatgptAccountId: loginParams.chatgptAccountId,
772
- chatgptPlanType: loginParams.chatgptPlanType ?? null
773
- };
774
- }
775
- async function resolveCodexAppServerAuthProfileLoginParamsInternal(params) {
776
- const store = resolveCodexAppServerAuthProfileStore({
777
- agentDir: params.agentDir,
778
- authProfileId: params.authProfileId,
779
- authProfileStore: params.authProfileStore,
780
- config: params.config
781
- });
782
- const profileId = resolveCodexAppServerAuthProfileId({
783
- authProfileId: params.authProfileId,
784
- store,
785
- config: params.config
786
- });
787
- if (!profileId) return;
788
- const credential = store.profiles[profileId];
789
- if (!credential) throw new Error(`Codex app-server auth profile "${profileId}" was not found.`);
790
- if (!isCodexAppServerAuthProfileCredential(credential)) throw new Error(`Codex app-server auth profile "${profileId}" must use the canonical OpenAI auth provider; run "openclaw doctor --fix" to migrate legacy provider IDs.`);
791
- const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
792
- agentDir: params.agentDir,
793
- store,
794
- preferStoreCredential: Boolean(params.authProfileStore?.profiles[profileId]),
795
- forceOAuthRefresh: params.forceOAuthRefresh === true,
796
- config: params.config
797
- });
798
- if (!loginParams) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" does not contain usable credentials.`);
799
- return loginParams;
800
- }
801
- async function resolveCodexAppServerFallbackApiKeyLoginParams(params) {
802
- const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS) ?? await readCodexCliAuthFileApiKey(params.codexCliAuthEnv);
803
- if (!apiKey) return;
804
- if ((await params.client.request("account/read", { refreshToken: false })).account) return;
805
- return {
806
- type: "apiKey",
807
- apiKey
808
- };
809
- }
810
- function resolveCodexCliAuthFilePath(env) {
811
- const configuredCodexHome = env[CODEX_HOME_ENV_VAR]?.trim();
812
- if (configuredCodexHome) return path.join(resolveHomeRelativePath(configuredCodexHome, env), CODEX_AUTH_JSON_FILENAME);
813
- const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
814
- return path.join(home, CODEX_HOME_DIRNAME, CODEX_AUTH_JSON_FILENAME);
815
- }
816
- function resolveHomeRelativePath(value, env) {
817
- if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
818
- const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
819
- return path.join(home, value.slice(value === "~" ? 1 : 2));
820
- }
821
- return value;
822
- }
823
- function parseCodexCliAuthFileApiKey(raw) {
824
- let parsed;
825
- try {
826
- parsed = JSON.parse(raw);
827
- } catch {
828
- return;
829
- }
830
- if (!parsed || typeof parsed !== "object") return;
831
- const apiKey = parsed.OPENAI_API_KEY;
832
- return typeof apiKey === "string" && apiKey.trim() ? apiKey.trim() : void 0;
833
- }
834
- async function readCodexCliAuthFileApiKey(env) {
835
- try {
836
- return parseCodexCliAuthFileApiKey(await readSecretFile(resolveCodexCliAuthFilePath(env), "Codex CLI auth file"));
837
- } catch {
838
- return;
839
- }
840
- }
841
- function resolveCodexCliAuthFileApiKeyCacheKey(env) {
842
- try {
843
- const apiKey = parseCodexCliAuthFileApiKey(fsSync.readFileSync(resolveCodexCliAuthFilePath(env), "utf8"));
844
- return apiKey ? fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) : void 0;
845
- } catch {
846
- return;
847
- }
848
- }
849
- async function resolveLoginParamsForCredential(profileId, credential, params) {
850
- if (credential.type === "api_key") {
851
- const apiKey = (await resolveApiKeyForProfile({
852
- store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
853
- profileId,
854
- agentDir: params.agentDir
855
- }))?.apiKey?.trim();
856
- return apiKey ? {
857
- type: "apiKey",
858
- apiKey
859
- } : void 0;
860
- }
861
- if (credential.type === "token") {
862
- const accessToken = (await resolveApiKeyForProfile({
863
- store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
864
- profileId,
865
- agentDir: params.agentDir
866
- }))?.apiKey?.trim();
867
- return accessToken ? buildChatgptAuthTokensParams(profileId, credential, accessToken) : void 0;
868
- }
869
- if (credential.type !== "oauth") return;
870
- const resolvedCredential = await resolveOAuthCredentialForCodexAppServer(profileId, credential, {
871
- agentDir: params.agentDir,
872
- store: params.store,
873
- preferStoreCredential: params.preferStoreCredential,
874
- forceRefresh: params.forceOAuthRefresh,
875
- config: params.config
876
- });
877
- const accessToken = resolvedCredential.access?.trim();
878
- return accessToken ? buildChatgptAuthTokensParams(profileId, resolvedCredential, accessToken) : void 0;
879
- }
880
- async function resolveOAuthCredentialForCodexAppServer(profileId, credential, params) {
881
- const ownerAgentDir = resolvePersistedAuthProfileOwnerAgentDir({
882
- agentDir: params.agentDir,
883
- profileId
884
- });
885
- const persistedCredential = findPersistedAuthProfileCredential({
886
- agentDir: ownerAgentDir,
887
- profileId
888
- });
889
- const useScopedCredential = params.preferStoreCredential && shouldUseScopedOAuthCredential({
890
- store: params.store,
891
- profileId,
892
- persistedCredential,
893
- suppliedCredential: credential,
894
- config: params.config
895
- });
896
- const store = useScopedCredential ? params.store : ensureCodexAppServerAuthProfileStore({
897
- agentDir: ownerAgentDir,
898
- authProfileId: profileId,
899
- config: params.config
900
- });
901
- const persistedOAuthCredential = !useScopedCredential && persistedCredential?.type === "oauth" && isCodexAppServerAuthProvider(persistedCredential.provider) ? persistedCredential : void 0;
902
- const ownerCredential = store.profiles[profileId];
903
- const overlaidOAuthCredential = ownerCredential?.type === "oauth" && isCodexAppServerAuthProvider(ownerCredential.provider) ? ownerCredential : void 0;
904
- if (useScopedCredential && overlaidOAuthCredential) return await resolveScopedOAuthCredential({
905
- store,
906
- profileId,
907
- credential: overlaidOAuthCredential,
908
- forceRefresh: params.forceRefresh
909
- });
910
- if (params.forceRefresh && !persistedOAuthCredential && overlaidOAuthCredential) {
911
- const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({ credential: overlaidOAuthCredential });
912
- if (!refreshedRuntimeCredential?.access?.trim()) throw new Error(`Codex app-server auth profile "${profileId}" could not refresh.`);
913
- store.profiles[profileId] = refreshedRuntimeCredential;
914
- return refreshedRuntimeCredential;
915
- }
916
- const resolved = await resolveApiKeyForProfile({
917
- store,
918
- profileId,
919
- agentDir: ownerAgentDir,
920
- forceRefresh: params.forceRefresh && Boolean(persistedOAuthCredential)
921
- });
922
- const refreshed = useScopedCredential ? void 0 : loadAuthProfileStoreForSecretsRuntime(ownerAgentDir).profiles[profileId];
923
- const refreshedOAuthCredential = refreshed?.type === "oauth" && isCodexAppServerAuthProvider(refreshed.provider) ? refreshed : void 0;
924
- if (refreshedOAuthCredential && isDeepStrictEqual(params.store.profiles[profileId], credential)) params.store.profiles[profileId] = refreshedOAuthCredential;
925
- const storedCredential = store.profiles[profileId];
926
- const candidate = refreshedOAuthCredential ? refreshedOAuthCredential : storedCredential?.type === "oauth" && isCodexAppServerAuthProvider(storedCredential.provider) ? storedCredential : credential;
927
- return resolved?.apiKey ? {
928
- ...candidate,
929
- access: resolved.apiKey
930
- } : candidate;
931
- }
932
- function shouldUseScopedOAuthCredential(params) {
933
- if (!params.store.runtimePersistedProfileIds?.includes(params.profileId)) return true;
934
- const persisted = params.persistedCredential;
935
- if (persisted?.type !== "oauth") return true;
936
- if (resolveProviderIdForAuth(persisted.provider, { config: params.config }) !== resolveProviderIdForAuth(params.suppliedCredential.provider, { config: params.config })) return true;
937
- return !isDeepStrictEqual(persisted, params.suppliedCredential) && !hasMatchingOAuthIdentity(persisted, params.suppliedCredential);
938
- }
939
- function hasMatchingOAuthIdentity(persisted, supplied) {
940
- const persistedAccountId = persisted.accountId?.trim();
941
- const suppliedAccountId = supplied.accountId?.trim();
942
- if (persistedAccountId && suppliedAccountId) return persistedAccountId === suppliedAccountId;
943
- const persistedEmail = persisted.email?.trim().toLowerCase();
944
- const suppliedEmail = supplied.email?.trim().toLowerCase();
945
- return Boolean(persistedEmail && suppliedEmail && persistedEmail === suppliedEmail);
946
- }
947
- async function resolveScopedOAuthCredential(params) {
948
- const existingRefresh = scopedOAuthRefreshQueues.get(params.store)?.get(params.profileId);
949
- if (existingRefresh) return await existingRefresh;
950
- if (!params.forceRefresh && hasUsableOAuthCredential(params.credential)) return params.credential;
951
- const storeRefreshes = scopedOAuthRefreshQueues.get(params.store) ?? /* @__PURE__ */ new Map();
952
- scopedOAuthRefreshQueues.set(params.store, storeRefreshes);
953
- const refresh = (async () => {
954
- const current = params.store.profiles[params.profileId];
955
- const credential = current?.type === "oauth" ? current : params.credential;
956
- if (!params.forceRefresh && hasUsableOAuthCredential(credential)) return credential;
957
- const refreshed = await refreshOAuthCredentialForRuntime({ credential });
958
- if (!refreshed?.access?.trim()) throw new Error(`Codex app-server auth profile "${params.profileId}" could not refresh.`);
959
- if (!isDeepStrictEqual(params.store.profiles[params.profileId], credential)) throw new Error(`Codex app-server auth profile "${params.profileId}" changed while refreshing.`);
960
- params.store.profiles[params.profileId] = refreshed;
961
- return refreshed;
962
- })();
963
- storeRefreshes.set(params.profileId, refresh);
964
- try {
965
- return await refresh;
966
- } finally {
967
- if (storeRefreshes.get(params.profileId) === refresh) storeRefreshes.delete(params.profileId);
968
- }
969
- }
970
- function isCodexAppServerAuthProvider(provider) {
971
- return provider.trim().toLowerCase() === CODEX_APP_SERVER_AUTH_PROVIDER;
972
- }
973
- function isCodexAppServerAuthProfileCredential(credential) {
974
- return isCodexAppServerAuthProvider(credential.provider);
975
- }
976
- function shouldClearOpenAiApiKeyForCodexAuthProfile(params) {
977
- const profileId = params.authProfileId?.trim();
978
- return isCodexSubscriptionCredential(profileId ? params.store.profiles[profileId] : params.store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID]);
979
- }
980
- function isCodexSubscriptionCredential(credential) {
981
- if (!credential || !isCodexAppServerAuthProvider(credential.provider)) return false;
982
- return credential.type === "oauth" || credential.type === "token";
983
- }
984
- function withClearedEnvironmentVariables(startOptions, envVars) {
985
- const clearEnv = startOptions.clearEnv ?? [];
986
- const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
987
- if (missingEnvVars.length === 0) return startOptions;
988
- return {
989
- ...startOptions,
990
- clearEnv: [...clearEnv, ...missingEnvVars]
991
- };
992
- }
993
- function readFirstNonEmptyEnv(env, keys) {
994
- return readFirstNonEmptyEnvEntry(env, keys)?.value;
995
- }
996
- function readFirstNonEmptyEnvEntry(env, keys) {
997
- for (const key of keys) {
998
- const value = env[key]?.trim();
999
- if (value) return {
1000
- key,
1001
- value
1002
- };
1003
- }
1004
- }
1005
- function buildChatgptAuthTokensParams(profileId, credential, accessToken) {
1006
- return {
1007
- type: "chatgptAuthTokens",
1008
- accessToken,
1009
- chatgptAccountId: resolveChatgptAccountId(profileId, credential),
1010
- chatgptPlanType: resolveChatgptPlanType(credential)
1011
- };
1012
- }
1013
- function resolveChatgptPlanType(credential) {
1014
- const record = credential;
1015
- const planType = record.chatgptPlanType ?? record.planType;
1016
- return typeof planType === "string" && planType.trim() ? planType.trim() : null;
1017
- }
1018
- function resolveChatgptAccountId(profileId, credential) {
1019
- return resolveStableChatgptAccountId(credential) ?? profileId;
1020
- }
1021
- function resolveStableChatgptAccountId(credential) {
1022
- if ("accountId" in credential && typeof credential.accountId === "string") {
1023
- const accountId = credential.accountId.trim();
1024
- if (accountId) return accountId;
1025
- }
1026
- return credential.email?.trim() || void 0;
1027
- }
1028
- //#endregion
1029
- //#region extensions/codex/src/app-server/rate-limit-cache.ts
1030
- const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 10 * 6e4;
1031
- const SPARSE_ACCOUNT_METADATA_KEYS = [
1032
- "credits",
1033
- "individualLimit",
1034
- "planType"
1035
- ];
1036
- const rateLimitsByClient = /* @__PURE__ */ new WeakMap();
1037
- /** Replaces one physical client's cache with an authoritative rate-limit read response. */
1038
- function rememberCodexRateLimitsRead(client, value, nowMs = Date.now()) {
1039
- if (value !== void 0) {
1040
- const revisionsByLimitId = { ...rateLimitsByClient.get(client)?.revisionsByLimitId };
1041
- for (const limitId of readRateLimitIds(value)) revisionsByLimitId[limitId] = (revisionsByLimitId[limitId] ?? 0) + 1;
1042
- rateLimitsByClient.set(client, {
1043
- value,
1044
- updatedAtMs: nowMs,
1045
- revisionsByLimitId
1046
- });
1047
- }
1048
- }
1049
- /** Merges a sparse rolling notification into one physical client's latest read response. */
1050
- function mergeCodexRateLimitsUpdate(client, value, nowMs = Date.now()) {
1051
- const update = isJsonObject$1(value) && isJsonObject$1(value.rateLimits) ? value.rateLimits : void 0;
1052
- if (!update) return;
1053
- const currentState = rateLimitsByClient.get(client);
1054
- const current = currentState?.value;
1055
- const limitId = readLimitId(update);
1056
- rateLimitsByClient.set(client, {
1057
- value: mergeRateLimitUpdate(current, update),
1058
- updatedAtMs: nowMs,
1059
- revisionsByLimitId: {
1060
- ...currentState?.revisionsByLimitId,
1061
- [limitId]: (currentState?.revisionsByLimitId[limitId] ?? 0) + 1
1062
- }
1063
- });
1064
- }
1065
- /** Per-limit marker used to trust only primary Codex updates from one turn startup. */
1066
- function readCodexRateLimitsRevision(client, limitId = "codex") {
1067
- return rateLimitsByClient.get(client)?.revisionsByLimitId[limitId] ?? 0;
1068
- }
1069
- /** Reads one physical client's cached rate-limit payload within the max-age window. */
1070
- function readRecentCodexRateLimits(client, options) {
1071
- const state = rateLimitsByClient.get(client);
1072
- if (!state) return;
1073
- const nowMs = options?.nowMs ?? Date.now();
1074
- const maxAgeMs = options?.maxAgeMs ?? DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS;
1075
- return maxAgeMs >= 0 && nowMs - state.updatedAtMs > maxAgeMs ? void 0 : state.value;
1076
- }
1077
- function mergeRateLimitUpdate(current, update) {
1078
- const currentEnvelope = isJsonObject$1(current) ? current : void 0;
1079
- const currentPrimary = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimits) ? currentEnvelope.rateLimits : void 0;
1080
- const currentByLimitId = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimitsByLimitId) ? currentEnvelope.rateLimitsByLimitId : void 0;
1081
- const limitId = readLimitId(update);
1082
- const currentPrimaryLimitId = currentPrimary ? readLimitId(currentPrimary) : void 0;
1083
- const currentForLimit = (currentByLimitId && isJsonObject$1(currentByLimitId[limitId]) ? currentByLimitId[limitId] : void 0) ?? (currentPrimaryLimitId === limitId ? currentPrimary : void 0);
1084
- const merged = mergeSparseSnapshot(isJsonObject$1(currentForLimit) ? currentForLimit : void 0, currentPrimary, update, limitId);
1085
- const nextPrimary = !currentPrimary || currentPrimaryLimitId === limitId ? merged : currentPrimary;
1086
- let nextByLimitId;
1087
- if (currentByLimitId) nextByLimitId = {
1088
- ...currentByLimitId,
1089
- [limitId]: merged
1090
- };
1091
- else if (currentPrimary && currentPrimaryLimitId && currentPrimaryLimitId !== limitId) nextByLimitId = {
1092
- [currentPrimaryLimitId]: currentPrimary,
1093
- [limitId]: merged
1094
- };
1095
- return {
1096
- ...currentEnvelope,
1097
- rateLimits: nextPrimary,
1098
- ...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
1099
- };
1100
- }
1101
- function readRateLimitIds(value) {
1102
- if (!isJsonObject$1(value)) return [];
1103
- const ids = /* @__PURE__ */ new Set();
1104
- if (isJsonObject$1(value.rateLimits)) ids.add(readLimitId(value.rateLimits));
1105
- if (isJsonObject$1(value.rateLimitsByLimitId)) for (const [key, snapshot] of Object.entries(value.rateLimitsByLimitId)) {
1106
- const snapshotLimitId = isJsonObject$1(snapshot) && typeof snapshot.limitId === "string" ? snapshot.limitId.trim() : "";
1107
- ids.add(snapshotLimitId || key);
1108
- }
1109
- return [...ids];
1110
- }
1111
- function mergeSparseSnapshot(current, accountFallback, update, limitId) {
1112
- const merged = {
1113
- ...update,
1114
- limitId
1115
- };
1116
- for (const key of SPARSE_ACCOUNT_METADATA_KEYS) {
1117
- const previous = current?.[key] ?? accountFallback?.[key];
1118
- if (merged[key] == null && previous != null) merged[key] = previous;
1119
- }
1120
- return merged;
1121
- }
1122
- function readLimitId(snapshot) {
1123
- const value = snapshot.limitId;
1124
- return typeof value === "string" && value.trim() ? value.trim() : "codex";
1125
- }
1126
- //#endregion
1127
- //#region extensions/codex/src/app-server/client-runtime.ts
1128
- /** Client-scoped Codex auth and account observers. */
1129
- const configuredClients = /* @__PURE__ */ new WeakMap();
1130
- /** Installs one auth-refresh handler and one rate-limit observer per physical client. */
1131
- function ensureCodexAppServerClientRuntime(client, context) {
1132
- const existing = configuredClients.get(client);
1133
- if (existing) {
1134
- existing.context = context;
1135
- return;
1136
- }
1137
- const runtime = { context };
1138
- configuredClients.set(client, runtime);
1139
- client.addRequestHandler(async (request) => {
1140
- if (request.method !== "account/chatgptAuthTokens/refresh") return;
1141
- if (runtime.context.authMode === "prepared-api-key") throw new Error("ChatGPT token refresh is unavailable for prepared Codex API-key auth.");
1142
- return await refreshCodexAppServerAuthTokens({
1143
- agentDir: runtime.context.agentDir,
1144
- authProfileId: runtime.context.authProfileId,
1145
- ...runtime.context.authProfileStore ? { authProfileStore: runtime.context.authProfileStore } : {},
1146
- config: runtime.context.config
1147
- });
1148
- });
1149
- client.addNotificationHandler((notification) => {
1150
- if (notification.method === "account/rateLimits/updated") mergeCodexRateLimitsUpdate(client, notification.params);
1151
- });
1152
- }
1153
- /** Keep at most one idle, still-subscribed thread on a physical Codex client. */
1154
- async function retainCodexAppServerLiveThread(client, threadId, releasePreviousThread, configFingerprint) {
1155
- const runtime = configuredClients.get(client);
1156
- if (!runtime) return;
1157
- if (runtime.retainedThreadRelease) await runtime.retainedThreadRelease;
1158
- const previousThreadId = runtime.retainedThreadId;
1159
- if (previousThreadId && previousThreadId !== threadId && releasePreviousThread) {
1160
- const release = releasePreviousThread(previousThreadId);
1161
- runtime.retainedThreadRelease = release;
1162
- try {
1163
- await release;
1164
- } catch (error) {
1165
- runtime.retainedThreadId = void 0;
1166
- runtime.retainedThreadConfigFingerprint = void 0;
1167
- throw error;
1168
- } finally {
1169
- if (runtime.retainedThreadRelease === release) runtime.retainedThreadRelease = void 0;
1170
- }
1171
- }
1172
- runtime.retainedThreadId = threadId;
1173
- runtime.retainedThreadConfigFingerprint = configFingerprint;
1174
- return previousThreadId ? { previousThreadId } : {};
1175
- }
1176
- /** A warm turn can skip resume only when this exact subscription was retained. */
1177
- async function consumeCodexAppServerLiveThread(client, threadId, configFingerprint) {
1178
- const runtime = configuredClients.get(client);
1179
- if (!runtime) return false;
1180
- if (runtime.retainedThreadRelease) await runtime.retainedThreadRelease;
1181
- if (runtime.retainedThreadId !== threadId || configFingerprint !== void 0 && runtime.retainedThreadConfigFingerprint !== configFingerprint) return false;
1182
- runtime.retainedThreadId = void 0;
1183
- runtime.retainedThreadConfigFingerprint = void 0;
1184
- return true;
1185
- }
1186
- //#endregion
1187
- //#region extensions/codex/src/app-server/transport-websocket.ts
1188
- /**
1189
- * Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
1190
- * transport interface.
1191
- */
1192
- /** Opens a WebSocket app-server transport and maps newline-delimited frames to stdout/stdin. */
1193
- function createWebSocketTransport(options) {
1194
- if (!options.url) throw new Error("codex app-server websocket transport requires plugins.entries.codex.config.appServer.url");
1195
- const events = new EventEmitter();
1196
- const stdout = new PassThrough();
1197
- const stderr = new PassThrough();
1198
- const websocketOptions = {
1199
- headers: {
1200
- ...options.headers,
1201
- ...options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}
1202
- },
1203
- perMessageDeflate: false
1204
- };
1205
- const unixSocketPath = resolveCodexAppServerUnixSocketPath(options);
1206
- const socket = unixSocketPath ? new WebSocket("ws://localhost/", {
1207
- ...websocketOptions,
1208
- createConnection: () => connectCodexAppServerUnixSocket(unixSocketPath)
1209
- }) : new WebSocket(options.url, websocketOptions);
1210
- const pendingFrames = [];
1211
- const stdinDecoder = new StringDecoder("utf8");
1212
- let pendingLine = "";
1213
- let killed = false;
1214
- const sendFrame = (frame) => {
1215
- const trimmed = frame.trim();
1216
- if (!trimmed) return;
1217
- if (socket.readyState === WebSocket.OPEN) {
1218
- socket.send(trimmed);
1219
- return;
1220
- }
1221
- pendingFrames.push(trimmed);
1222
- };
1223
- socket.once("open", () => {
1224
- for (const frame of pendingFrames.splice(0)) socket.send(frame);
1225
- });
1226
- socket.once("error", (error) => events.emit("error", error));
1227
- socket.once("close", (code, reason) => {
1228
- killed = true;
1229
- events.emit("exit", code, reason.toString("utf8"));
1230
- });
1231
- socket.on("message", (data) => {
1232
- const text = websocketFrameToText(data);
1233
- stdout.write(text.endsWith("\n") ? text : `${text}\n`);
1234
- });
1235
- const stdin = new Writable({
1236
- write(chunk, _encoding, callback) {
1237
- pendingLine += stdinDecoder.write(chunk);
1238
- const lines = pendingLine.split("\n");
1239
- pendingLine = lines.pop() ?? "";
1240
- for (const frame of lines) sendFrame(frame);
1241
- callback();
1242
- },
1243
- final(callback) {
1244
- pendingLine += stdinDecoder.end();
1245
- if (pendingLine) sendFrame(pendingLine);
1246
- pendingLine = "";
1247
- callback();
1248
- }
1249
- });
1250
- const closeSocket = () => {
1251
- if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
1252
- socket.close();
1253
- };
1254
- stdin.once("finish", closeSocket);
1255
- stdin.once("close", closeSocket);
1256
- return {
1257
- stdin,
1258
- stdout,
1259
- stderr,
1260
- get killed() {
1261
- return killed;
1262
- },
1263
- kill: () => {
1264
- killed = true;
1265
- socket.close();
1266
- },
1267
- once: (event, listener) => events.once(event, listener)
1268
- };
1269
- }
1270
- /** Opens the owner-scoped Codex control socket used by the WebSocket upgrade. */
1271
- function connectCodexAppServerUnixSocket(socketPath) {
1272
- return net.createConnection(socketPath);
1273
- }
1274
- /** Resolves the canonical or explicitly configured Codex control socket. */
1275
- function resolveCodexAppServerUnixSocketPath(options) {
1276
- if (options.transport !== "unix") {
1277
- if (options.url?.startsWith("unix://")) throw new Error("codex app-server unix URL requires unix transport");
1278
- return;
1279
- }
1280
- const url = options.url ?? "unix://";
1281
- if (!url.startsWith("unix://")) throw new Error("codex app-server unix transport requires a unix:// URL");
1282
- return url.slice(7) || path.join(resolveCodexAppServerUserHomeDir(options.env ?? process.env), "app-server-control", "app-server-control.sock");
1283
- }
1284
- function websocketFrameToText(data) {
1285
- if (typeof data === "string") return data;
1286
- if (Buffer.isBuffer(data)) return data.toString("utf8");
1287
- if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
1288
- return Buffer.from(data).toString("utf8");
1289
- }
1290
- //#endregion
1291
- //#region extensions/codex/src/app-server/transport.ts
1292
- /** Starts graceful transport shutdown and schedules a force kill fallback. */
1293
- function closeCodexAppServerTransport(child, options = {}) {
1294
- child.stdin.end?.();
1295
- child.stdin.destroy?.();
1296
- const forceKillDelayMs = options.forceKillDelayMs ?? 1e3;
1297
- const forceKill = setTimeout(() => {
1298
- if (hasCodexAppServerTransportExited(child)) return;
1299
- signalCodexAppServerTransport(child, "SIGKILL");
1300
- }, Math.max(1, forceKillDelayMs));
1301
- forceKill.unref?.();
1302
- child.once("exit", () => {
1303
- clearTimeout(forceKill);
1304
- child.stdout.destroy?.();
1305
- child.stderr.destroy?.();
1306
- });
1307
- child.unref?.();
1308
- child.stdout.unref?.();
1309
- child.stderr.unref?.();
1310
- child.stdin.unref?.();
1311
- }
1312
- /** Closes a transport and waits briefly for an exit event. */
1313
- async function closeCodexAppServerTransportAndWait(child, options = {}) {
1314
- if (!hasCodexAppServerTransportExited(child)) closeCodexAppServerTransport(child, options);
1315
- return await waitForCodexAppServerTransportExit(child, options.exitTimeoutMs ?? 2e3);
1316
- }
1317
- function hasCodexAppServerTransportExited(child) {
1318
- return child.exitCode !== null && child.exitCode !== void 0 ? true : child.signalCode !== null && child.signalCode !== void 0;
1319
- }
1320
- async function waitForCodexAppServerTransportExit(child, timeoutMs) {
1321
- if (hasCodexAppServerTransportExited(child)) return true;
1322
- return await new Promise((resolve) => {
1323
- let settled = false;
1324
- const onExit = () => {
1325
- if (settled) return;
1326
- settled = true;
1327
- clearTimeout(timeout);
1328
- resolve(true);
1329
- };
1330
- const timeout = setTimeout(() => {
1331
- if (settled) return;
1332
- settled = true;
1333
- child.off?.("exit", onExit);
1334
- resolve(false);
1335
- }, Math.max(1, timeoutMs));
1336
- child.once("exit", onExit);
1337
- });
1338
- }
1339
- function signalCodexAppServerTransport(child, signal) {
1340
- if (child.pid && process.platform !== "win32") try {
1341
- process.kill(-child.pid, signal);
1342
- return;
1343
- } catch {}
1344
- child.kill?.(signal);
1345
- }
1346
- //#endregion
1347
- //#region extensions/codex/src/app-server/version.ts
1348
- /**
1349
- * Version and package pins for the managed Codex app-server runtime.
1350
- */
1351
- /** Exact Codex app-server version shipped and supported by the OpenClaw Codex bridge. */
1352
- const CODEX_APP_SERVER_VERSION = "0.146.0";
1353
- /** npm package name for the managed Codex app-server binary. */
1354
- const MANAGED_CODEX_APP_SERVER_PACKAGE = "@openai/codex";
1355
- //#endregion
1356
- //#region extensions/codex/src/app-server/client.ts
1357
- /**
1358
- * JSON-RPC client for Codex app-server transports, including request/response
1359
- * routing, notification fanout, server request handlers, and version checks.
1360
- */
1361
- const CODEX_APP_SERVER_PARSE_LOG_MAX = 500;
1362
- const CODEX_APP_SERVER_PARSE_BUFFER_MAX = 8 * 1024 * 1024;
1363
- const CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES = 1e3;
1364
- const CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS = 66e4;
1365
- const CODEX_APP_SERVER_STDERR_TAIL_MAX = 2e3;
1366
- const CODEX_APP_SERVER_OVERLOADED_ERROR_CODE = -32001;
1367
- const CODEX_APP_SERVER_OVERLOAD_MAX_RETRIES = 3;
1368
- const CODEX_APP_SERVER_OVERLOAD_RETRY_BASE_MS = 50;
1369
- const CODEX_APP_SERVER_CLIENT_INSTANCE_IDS = /* @__PURE__ */ new WeakMap();
1370
- const UNPAIRED_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
1371
- /** Process-local generation fence for bindings tied to one app-server client instance. */
1372
- function getCodexAppServerClientInstanceId(client) {
1373
- const current = CODEX_APP_SERVER_CLIENT_INSTANCE_IDS.get(client);
1374
- if (current) return current;
1375
- const created = randomUUID();
1376
- CODEX_APP_SERVER_CLIENT_INSTANCE_IDS.set(client, created);
1377
- return created;
1378
- }
1379
- function resolveCodexAppServerClientInstanceId(client) {
1380
- return client.getInstanceId?.call(client) ?? getCodexAppServerClientInstanceId(client);
1381
- }
1382
- /** RPC error wrapper that preserves app-server error code and data. */
1383
- var CodexAppServerRpcError = class extends Error {
1384
- constructor(error, method) {
1385
- super(formatCodexAppServerRpcErrorMessage(error, method));
1386
- this.name = "CodexAppServerRpcError";
1387
- this.code = error.code;
1388
- this.data = error.data;
1389
- this.method = method;
1390
- }
1391
- };
1392
- var CodexAppServerLocalRequestCancellationError = class extends Error {
1393
- constructor(method, reason, mayHaveWritten) {
1394
- super(`${method} ${reason}`);
1395
- this.reason = reason;
1396
- this.mayHaveWritten = mayHaveWritten;
1397
- this.code = "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED";
1398
- this.name = "CodexAppServerLocalRequestCancellationError";
1399
- }
1400
- };
1401
- function isCodexAppServerRequestTimeoutError(error) {
1402
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED" && "reason" in error && error.reason === "timed out";
1403
- }
1404
- function isCodexAppServerBrokenPipeError(error) {
1405
- const seen = /* @__PURE__ */ new Set();
1406
- let current = error;
1407
- while (current && typeof current === "object" && !seen.has(current)) {
1408
- seen.add(current);
1409
- if ("code" in current && current.code === "EPIPE") return true;
1410
- current = "cause" in current ? current.cause : void 0;
1411
- }
1412
- return false;
1413
- }
1414
- var CodexAppServerIndeterminateTransportError = class extends Error {
1415
- constructor(method, cause) {
1416
- super(`${method} transport failed after request write: ${cause.message}`, { cause });
1417
- this.code = "CODEX_APP_SERVER_REQUEST_TRANSPORT_INDETERMINATE";
1418
- this.mayHaveWritten = true;
1419
- this.name = "CodexAppServerIndeterminateTransportError";
1420
- }
1421
- };
1422
- /** True when a local cancellation can leave an app-server request in flight. */
1423
- function isCodexAppServerIndeterminateRequestCancellationError(error) {
1424
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED" && "mayHaveWritten" in error && error.mayHaveWritten === true;
1425
- }
1426
- /** True when local cancellation happened before a request write was attempted. */
1427
- function isCodexAppServerPrewriteRequestCancellationError(error) {
1428
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED" && "mayHaveWritten" in error && error.mayHaveWritten === false;
1429
- }
1430
- /** True when transport failure cannot prove a written request stopped running. */
1431
- function isCodexAppServerIndeterminateTransportError(error) {
1432
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_REQUEST_TRANSPORT_INDETERMINATE" && "mayHaveWritten" in error && error.mayHaveWritten === true;
1433
- }
1434
- function formatCodexAppServerRpcErrorMessage(error, method) {
1435
- const message = error.message || `${method} failed`;
1436
- const detail = readCodexAppServerRpcReloginDetail(error.data);
1437
- return detail && !message.includes(detail) ? `${message}: ${detail}` : message;
1438
- }
1439
- function readCodexAppServerRpcReloginDetail(data) {
1440
- const record = isJsonObject(data) ? data : void 0;
1441
- const nested = isJsonObject(record?.error) ? record.error : record;
1442
- if (!nested) return;
1443
- const isRelogin = nested.action === "relogin" || nested.reason === "cloudRequirements" && nested.errorCode === "Auth";
1444
- const detail = typeof nested.detail === "string" ? nested.detail.trim() : "";
1445
- return isRelogin && detail ? detail : void 0;
1446
- }
1447
- function isJsonObject(value) {
1448
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
1449
- }
1450
- /** Returns true for errors that mean the app-server transport is closed. */
1451
- function isCodexAppServerConnectionClosedError(error) {
1452
- if (!(error instanceof Error)) return false;
1453
- if (isCodexAppServerIndeterminateTransportError(error)) return true;
1454
- return error.message === "codex app-server client is closed" || error.message.startsWith("codex app-server exited:");
1455
- }
1456
- /** Stateful app-server JSON-RPC client over stdio or websocket transport. */
1457
- var CodexAppServerClient = class CodexAppServerClient {
1458
- constructor(child) {
1459
- this.instanceId = randomUUID();
1460
- this.pending = /* @__PURE__ */ new Map();
1461
- this.requestHandlers = /* @__PURE__ */ new Set();
1462
- this.notificationHandlers = /* @__PURE__ */ new Set();
1463
- this.closeHandlers = /* @__PURE__ */ new Set();
1464
- this.nextId = 1;
1465
- this.initialized = false;
1466
- this.closed = false;
1467
- this.transportExited = false;
1468
- this.stderrTail = "";
1469
- this.child = child;
1470
- this.lines = createInterface({ input: child.stdout });
1471
- this.lines.on("line", (line) => this.handleLine(line));
1472
- this.lines.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
1473
- child.stdout.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
1474
- child.stderr.setEncoding("utf8");
1475
- child.stderr.on("data", (text) => {
1476
- this.stderrTail = appendBoundedTail(this.stderrTail, text, CODEX_APP_SERVER_STDERR_TAIL_MAX);
1477
- const trimmed = text.trim();
1478
- if (trimmed) embeddedAgentLog.debug(`codex app-server stderr: ${trimmed}`);
1479
- });
1480
- child.stderr.on("error", (error) => {
1481
- embeddedAgentLog.warn("codex app-server stderr stream failed", { error });
1482
- });
1483
- child.once("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
1484
- child.once("exit", (code, signal) => {
1485
- this.transportExited = true;
1486
- this.closeWithError(buildCodexAppServerExitError(code, signal, this.stderrTail));
1487
- });
1488
- child.stdin.on?.("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
1489
- }
1490
- /** Starts a new app-server client using resolved runtime start options. */
1491
- static start(options) {
1492
- const defaults = resolveCodexAppServerRuntimeOptions().start;
1493
- const startOptions = {
1494
- ...defaults,
1495
- ...options,
1496
- headers: options?.headers ?? defaults.headers
1497
- };
1498
- if (startOptions.transport === "stdio" && startOptions.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
1499
- if (startOptions.transport === "websocket" || startOptions.transport === "unix") return new CodexAppServerClient(createWebSocketTransport(startOptions));
1500
- return new CodexAppServerClient(createStdioTransport(startOptions));
1501
- }
1502
- /** Builds a client around a fake transport for tests. */
1503
- static fromTransportForTests(child) {
1504
- return new CodexAppServerClient(child);
1505
- }
1506
- /** Performs the app-server initialize handshake and validates protocol version. */
1507
- async initialize() {
1508
- if (this.initialized) return;
1509
- const response = await this.request("initialize", {
1510
- clientInfo: {
1511
- name: "openclaw",
1512
- title: "OpenClaw",
1513
- version: OPENCLAW_VERSION
1514
- },
1515
- capabilities: { experimentalApi: true }
1516
- });
1517
- this.serverVersion = assertSupportedCodexAppServerVersion(response);
1518
- this.runtimeIdentity = buildCodexAppServerRuntimeIdentity(response, this.serverVersion);
1519
- this.notify("initialized");
1520
- this.initialized = true;
1521
- }
1522
- /** Returns the version detected during initialize. */
1523
- getServerVersion() {
1524
- return this.serverVersion;
1525
- }
1526
- /** Returns runtime metadata detected during initialize. */
1527
- getRuntimeIdentity() {
1528
- return this.runtimeIdentity ? { ...this.runtimeIdentity } : void 0;
1529
- }
1530
- /** Returns a bounded, redacted stderr diagnostic from the app-server process. */
1531
- getStderrDiagnostic() {
1532
- return redactCodexAppServerLinePreview(this.stderrTail) || void 0;
1533
- }
1534
- /** Stable generation id for this exact physical client instance. */
1535
- getInstanceId() {
1536
- return this.instanceId;
1537
- }
1538
- /** Installs the spawn-owner check run before config-loading thread requests. */
1539
- setThreadSessionRequestGuard(guard) {
1540
- this.threadSessionRequestGuard = guard;
1541
- }
1542
- /** Returns the local transport PID for scoped child-process cleanup, when available. */
1543
- getTransportPid() {
1544
- return this.child.pid;
1545
- }
1546
- request(method, params, optionsInput) {
1547
- let options = optionsInput;
1548
- options ??= {};
1549
- if (this.closed) return Promise.reject(this.closeError ?? /* @__PURE__ */ new Error("codex app-server client is closed"));
1550
- if (options.signal?.aborted) return Promise.reject(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
1551
- const guard = method === "thread/start" || method === "thread/resume" || method === "thread/fork" ? this.threadSessionRequestGuard : void 0;
1552
- if (guard) {
1553
- if (!options.signal && !(options.timeoutMs !== void 0 && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0)) return Promise.reject(/* @__PURE__ */ new TypeError(`${method} requires a positive finite timeout or abort signal`));
1554
- return (async () => {
1555
- const guardStartedAt = Date.now();
1556
- const timeoutMessage = `${method} timed out`;
1557
- const abortMessage = `${method} aborted`;
1558
- let releaseGuard;
1559
- try {
1560
- releaseGuard = await guard({
1561
- signal: options.signal,
1562
- timeoutMs: options.timeoutMs,
1563
- timeoutMessage,
1564
- abortMessage
1565
- });
1566
- } catch (error) {
1567
- if (error instanceof Error && error.message === timeoutMessage) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
1568
- if (error instanceof Error && error.message === abortMessage) throw new CodexAppServerLocalRequestCancellationError(method, "aborted", false);
1569
- throw error;
1570
- }
1571
- let released = false;
1572
- const release = () => {
1573
- if (released) return;
1574
- released = true;
1575
- releaseGuard();
1576
- };
1577
- let releaseWhenRequestSettles = true;
1578
- let requestMayHaveWritten = false;
1579
- try {
1580
- const elapsedMs = Date.now() - guardStartedAt;
1581
- const remainingTimeoutMs = options.timeoutMs === void 0 ? void 0 : options.timeoutMs - elapsedMs;
1582
- if (remainingTimeoutMs !== void 0 && remainingTimeoutMs <= 0) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
1583
- return await this.requestWithoutThreadSessionGuard(method, params, {
1584
- ...options,
1585
- ...remainingTimeoutMs !== void 0 ? { timeoutMs: remainingTimeoutMs } : {}
1586
- }, () => {
1587
- requestMayHaveWritten = true;
1588
- });
1589
- } catch (error) {
1590
- if (requestMayHaveWritten && !(error instanceof CodexAppServerRpcError)) {
1591
- releaseWhenRequestSettles = false;
1592
- await this.closeAndRunAfterExit(release, method);
1593
- }
1594
- throw error;
1595
- } finally {
1596
- if (releaseWhenRequestSettles) release();
1597
- }
1598
- })();
1599
- }
1600
- return this.requestWithoutThreadSessionGuard(method, params, options);
1601
- }
1602
- requestWithoutThreadSessionGuard(method, params, options, onWriteAttempt) {
1603
- return this.requestWithOverloadRetry(method, params, options, onWriteAttempt);
1604
- }
1605
- async requestWithOverloadRetry(method, params, options, onWriteAttempt) {
1606
- const deadline = options.timeoutMs !== void 0 && Number.isFinite(options.timeoutMs) ? Date.now() + options.timeoutMs : void 0;
1607
- for (let retry = 0;; retry += 1) {
1608
- if (options.signal?.aborted) throw new CodexAppServerLocalRequestCancellationError(method, "aborted", false);
1609
- const remainingTimeoutMs = deadline === void 0 ? void 0 : deadline - Date.now();
1610
- if (remainingTimeoutMs !== void 0 && remainingTimeoutMs <= 0) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
1611
- try {
1612
- return await this.requestOnce(method, params, {
1613
- ...options,
1614
- ...remainingTimeoutMs !== void 0 ? { timeoutMs: remainingTimeoutMs } : {}
1615
- }, onWriteAttempt);
1616
- } catch (error) {
1617
- if (!(error instanceof CodexAppServerRpcError) || error.code !== CODEX_APP_SERVER_OVERLOADED_ERROR_CODE || retry >= CODEX_APP_SERVER_OVERLOAD_MAX_RETRIES) throw error;
1618
- const backoffMs = Math.round(CODEX_APP_SERVER_OVERLOAD_RETRY_BASE_MS * 2 ** retry * (.75 + Math.random() * .5));
1619
- await this.waitForOverloadRetry(method, backoffMs, deadline, options.signal);
1620
- }
1621
- }
1622
- }
1623
- async waitForOverloadRetry(method, backoffMs, deadline, signal) {
1624
- if (signal?.aborted) throw new CodexAppServerLocalRequestCancellationError(method, "aborted", false);
1625
- const remainingMs = deadline === void 0 ? void 0 : deadline - Date.now();
1626
- if (remainingMs !== void 0 && remainingMs <= 0) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
1627
- const delayMs = remainingMs === void 0 ? backoffMs : Math.min(backoffMs, remainingMs);
1628
- await new Promise((resolve, reject) => {
1629
- const timer = setTimeout(() => {
1630
- cleanup();
1631
- resolve();
1632
- }, delayMs);
1633
- timer.unref?.();
1634
- const abortListener = () => {
1635
- cleanup();
1636
- reject(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
1637
- };
1638
- const cleanup = () => {
1639
- clearTimeout(timer);
1640
- signal?.removeEventListener("abort", abortListener);
1641
- };
1642
- signal?.addEventListener("abort", abortListener, { once: true });
1643
- if (signal?.aborted) abortListener();
1644
- });
1645
- }
1646
- requestOnce(method, params, options, onWriteAttempt) {
1647
- if (this.closed) return Promise.reject(this.closeError ?? /* @__PURE__ */ new Error("codex app-server client is closed"));
1648
- if (options.signal?.aborted) return Promise.reject(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
1649
- const id = this.nextId++;
1650
- const message = {
1651
- id,
1652
- method,
1653
- params
1654
- };
1655
- return new Promise((resolve, reject) => {
1656
- let timeout;
1657
- let cleanupAbort;
1658
- let mayHaveWritten = false;
1659
- const cleanup = () => {
1660
- if (timeout) {
1661
- clearTimeout(timeout);
1662
- timeout = void 0;
1663
- }
1664
- cleanupAbort?.();
1665
- cleanupAbort = void 0;
1666
- };
1667
- const rejectPending = (error) => {
1668
- if (!this.pending.has(id)) return;
1669
- this.pending.delete(id);
1670
- cleanup();
1671
- reject(mayHaveWritten && !(error instanceof CodexAppServerRpcError) && !isCodexAppServerIndeterminateRequestCancellationError(error) && !isCodexAppServerIndeterminateTransportError(error) ? new CodexAppServerIndeterminateTransportError(method, error) : error);
1672
- };
1673
- if (options.timeoutMs && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0) {
1674
- timeout = setTimeout(() => rejectPending(new CodexAppServerLocalRequestCancellationError(method, "timed out", mayHaveWritten)), Math.max(100, options.timeoutMs));
1675
- timeout.unref?.();
1676
- }
1677
- if (options.signal) {
1678
- const abortListener = () => rejectPending(new CodexAppServerLocalRequestCancellationError(method, "aborted", mayHaveWritten));
1679
- options.signal.addEventListener("abort", abortListener, { once: true });
1680
- cleanupAbort = () => options.signal?.removeEventListener("abort", abortListener);
1681
- }
1682
- this.pending.set(id, {
1683
- method,
1684
- resolve: (value) => {
1685
- cleanup();
1686
- resolve(value);
1687
- },
1688
- reject: (error) => {
1689
- cleanup();
1690
- reject(mayHaveWritten && !(error instanceof CodexAppServerRpcError) && !isCodexAppServerIndeterminateRequestCancellationError(error) && !isCodexAppServerIndeterminateTransportError(error) ? new CodexAppServerIndeterminateTransportError(method, error) : error);
1691
- },
1692
- cleanup
1693
- });
1694
- if (options.signal?.aborted) {
1695
- rejectPending(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
1696
- return;
1697
- }
1698
- try {
1699
- mayHaveWritten = true;
1700
- onWriteAttempt?.();
1701
- this.writeMessage(message, (error) => rejectPending(error));
1702
- } catch (error) {
1703
- rejectPending(error instanceof Error ? error : new Error(String(error)));
1704
- }
1705
- });
1706
- }
1707
- /** Sends a fire-and-forget JSON-RPC notification to the app-server. */
1708
- notify(method, params) {
1709
- this.writeMessage({
1710
- method,
1711
- params
1712
- });
1713
- }
1714
- /** Registers a handler for app-server requests sent back to OpenClaw. */
1715
- addRequestHandler(handler) {
1716
- this.requestHandlers.add(handler);
1717
- return () => this.requestHandlers.delete(handler);
1718
- }
1719
- /** Registers a notification handler and returns its disposer. */
1720
- addNotificationHandler(handler) {
1721
- this.notificationHandlers.add(handler);
1722
- return () => this.notificationHandlers.delete(handler);
1723
- }
1724
- /** Registers a close handler and returns its disposer. */
1725
- addCloseHandler(handler) {
1726
- this.closeHandlers.add(handler);
1727
- return () => this.closeHandlers.delete(handler);
1728
- }
1729
- /** Closes the transport without waiting for process/socket shutdown. */
1730
- close() {
1731
- if (!this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"))) return;
1732
- closeCodexAppServerTransport(this.child);
1733
- }
1734
- /** Closes the transport and waits for shutdown according to transport policy. */
1735
- async closeAndWait(options) {
1736
- this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"));
1737
- return await closeCodexAppServerTransportAndWait(this.child, options);
1738
- }
1739
- /** Closes this transport and runs cleanup only after physical process exit. */
1740
- async closeAndRunAfterExit(onExit, operation) {
1741
- let settled = false;
1742
- const runOnExit = () => {
1743
- if (settled) return;
1744
- settled = true;
1745
- onExit();
1746
- };
1747
- if (this.transportExited) {
1748
- runOnExit();
1749
- return;
1750
- }
1751
- this.child.once("exit", runOnExit);
1752
- try {
1753
- if (await this.closeAndWait()) {
1754
- this.child.off?.("exit", runOnExit);
1755
- runOnExit();
1756
- }
1757
- } catch (closeError) {
1758
- embeddedAgentLog.warn("codex app-server shutdown after indeterminate request failed", {
1759
- closeError,
1760
- operation
1761
- });
1762
- }
1763
- }
1764
- writeMessage(message, onError) {
1765
- if (this.closed) return;
1766
- const id = "id" in message ? message.id : void 0;
1767
- const method = "method" in message ? message.method : void 0;
1768
- this.child.stdin.write(`${stringifyCodexAppServerMessage(message)}\n`, (error) => {
1769
- if (error) {
1770
- embeddedAgentLog.warn("codex app-server write failed", {
1771
- error,
1772
- id,
1773
- method
1774
- });
1775
- onError?.(error);
1776
- }
1777
- });
1778
- }
1779
- handleLine(line) {
1780
- const rawLine = line.endsWith("\r") ? line.slice(0, -1) : line;
1781
- if (this.pendingParse) {
1782
- this.handlePendingParseLine(rawLine);
1783
- return;
1784
- }
1785
- const trimmed = rawLine.trim();
1786
- if (!trimmed) return;
1787
- let parsed;
1788
- try {
1789
- parsed = JSON.parse(trimmed);
1790
- } catch (error) {
1791
- if (shouldBufferCodexAppServerParseFailure(trimmed, error)) {
1792
- this.pendingParse = {
1793
- text: trimmed,
1794
- lineCount: 1,
1795
- firstError: error
1796
- };
1797
- return;
1798
- }
1799
- logCodexAppServerParseFailure(trimmed, error, 1);
1800
- return;
1801
- }
1802
- this.handleParsedMessage(parsed);
1803
- }
1804
- handlePendingParseLine(line) {
1805
- const pending = this.pendingParse;
1806
- if (!pending) return;
1807
- const candidate = `${pending.text}\\n${line}`;
1808
- let parsed;
1809
- try {
1810
- parsed = JSON.parse(candidate);
1811
- } catch (error) {
1812
- const lineCount = pending.lineCount + 1;
1813
- if (shouldBufferCodexAppServerParseFailure(candidate.trim(), error) && candidate.length <= CODEX_APP_SERVER_PARSE_BUFFER_MAX && lineCount <= CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES) {
1814
- this.pendingParse = {
1815
- text: candidate,
1816
- lineCount,
1817
- firstError: pending.firstError
1818
- };
1819
- return;
1820
- }
1821
- this.pendingParse = void 0;
1822
- logCodexAppServerParseFailure(candidate, error, lineCount);
1823
- return;
1824
- }
1825
- this.pendingParse = void 0;
1826
- this.handleParsedMessage(parsed);
1827
- }
1828
- handleParsedMessage(parsed) {
1829
- if (!parsed || typeof parsed !== "object") return;
1830
- const message = parsed;
1831
- if (isRpcResponse(message)) {
1832
- this.handleResponse(message);
1833
- return;
1834
- }
1835
- if (!("method" in message)) return;
1836
- if ("id" in message && message.id !== void 0) {
1837
- this.handleServerRequest({
1838
- id: message.id,
1839
- method: message.method,
1840
- params: message.params
1841
- });
1842
- return;
1843
- }
1844
- this.handleNotification({
1845
- method: message.method,
1846
- params: message.params
1847
- });
1848
- }
1849
- handleResponse(response) {
1850
- const pending = this.pending.get(response.id);
1851
- if (!pending) return;
1852
- this.pending.delete(response.id);
1853
- if (response.error) {
1854
- pending.reject(new CodexAppServerRpcError(response.error, pending.method));
1855
- return;
1856
- }
1857
- pending.resolve(response.result);
1858
- }
1859
- async handleServerRequest(request) {
1860
- try {
1861
- const result = await this.runServerRequestHandlers(request);
1862
- if (result !== void 0) {
1863
- this.writeMessage({
1864
- id: request.id,
1865
- result
1866
- });
1867
- return;
1868
- }
1869
- this.writeMessage({
1870
- id: request.id,
1871
- result: defaultServerRequestResponse(request)
1872
- });
1873
- } catch (error) {
1874
- const message = error instanceof Error ? error.message : String(error);
1875
- embeddedAgentLog.warn("codex app-server server request handler failed", {
1876
- id: request.id,
1877
- method: request.method,
1878
- error
1879
- });
1880
- this.writeMessage({
1881
- id: request.id,
1882
- error: {
1883
- code: -32603,
1884
- message
1885
- }
1886
- });
1887
- }
1888
- }
1889
- async runServerRequestHandlers(request) {
1890
- const controller = new AbortController();
1891
- const timeoutResponse = timeoutServerRequestResponse(request);
1892
- if (!timeoutResponse) return await this.runServerRequestHandlersWithoutTimeout(request, controller.signal);
1893
- let timeout;
1894
- try {
1895
- return await Promise.race([this.runServerRequestHandlersWithoutTimeout(request, controller.signal), new Promise((resolve) => {
1896
- timeout = setTimeout(() => {
1897
- embeddedAgentLog.warn("codex app-server server request timed out", {
1898
- id: request.id,
1899
- method: request.method,
1900
- timeoutMs: CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS
1901
- });
1902
- controller.abort(/* @__PURE__ */ new Error("codex app-server server request timed out"));
1903
- resolve(timeoutResponse);
1904
- }, CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS);
1905
- timeout.unref?.();
1906
- })]);
1907
- } finally {
1908
- if (timeout) clearTimeout(timeout);
1909
- }
1910
- }
1911
- async runServerRequestHandlersWithoutTimeout(request, signal) {
1912
- for (const handler of this.requestHandlers) {
1913
- if (signal.aborted) return;
1914
- const result = await handler(request, signal);
1915
- if (result !== void 0) return result;
1916
- }
1917
- }
1918
- handleNotification(notification) {
1919
- for (const handler of this.notificationHandlers) try {
1920
- Promise.resolve(handler(notification)).catch((error) => {
1921
- embeddedAgentLog.warn("codex app-server notification handler failed", { error });
1922
- });
1923
- } catch (error) {
1924
- embeddedAgentLog.warn("codex app-server notification handler failed", { error });
1925
- }
1926
- }
1927
- closeWithError(error) {
1928
- if (this.markClosed(error)) closeCodexAppServerTransport(this.child);
1929
- }
1930
- markClosed(error) {
1931
- if (this.closed) return false;
1932
- this.closed = true;
1933
- this.closeError = error;
1934
- this.lines.close();
1935
- this.rejectPendingRequests(error);
1936
- return true;
1937
- }
1938
- rejectPendingRequests(error) {
1939
- for (const pending of this.pending.values()) {
1940
- pending.cleanup();
1941
- pending.reject(error);
1942
- }
1943
- this.pending.clear();
1944
- for (const handler of this.closeHandlers) handler(this);
1945
- }
1946
- };
1947
- function defaultServerRequestResponse(request) {
1948
- if (request.method === "item/tool/call") return {
1949
- contentItems: [{
1950
- type: "inputText",
1951
- text: "OpenClaw did not register a handler for this app-server tool call."
1952
- }],
1953
- success: false
1954
- };
1955
- if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return { decision: "decline" };
1956
- if (request.method === "item/permissions/requestApproval") return {
1957
- permissions: {},
1958
- scope: "turn"
1959
- };
1960
- if (request.method === "item/tool/requestUserInput") return { answers: {} };
1961
- if (request.method === "mcpServer/elicitation/request") return { action: "decline" };
1962
- return {};
1963
- }
1964
- function stringifyCodexAppServerMessage(message) {
1965
- return JSON.stringify(message, (_key, value) => typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value) ?? "null";
1966
- }
1967
- function timeoutServerRequestResponse(request) {
1968
- if (request.method !== "item/tool/call") return;
1969
- return {
1970
- contentItems: [{
1971
- type: "inputText",
1972
- text: `OpenClaw dynamic tool call timed out after ${CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS}ms before sending a response to Codex.`
1973
- }],
1974
- success: false
1975
- };
1976
- }
1977
- /** Raised when the initialize handshake detects an unsupported app-server version. */
1978
- var CodexAppServerVersionError = class extends Error {
1979
- constructor(detectedVersion) {
1980
- const detected = detectedVersion ? `detected ${detectedVersion}` : "OpenClaw could not determine the running Codex version";
1981
- super(`Codex app-server ${CODEX_APP_SERVER_VERSION} is required, but ${detected}. Update the configured Codex app-server binary, or remove custom command overrides to use the managed binary.`);
1982
- this.name = "CodexAppServerVersionError";
1983
- this.detectedVersion = detectedVersion;
1984
- }
1985
- };
1986
- function assertSupportedCodexAppServerVersion(response) {
1987
- const detectedVersion = readCodexVersionFromUserAgent(response.userAgent);
1988
- if (detectedVersion !== "0.146.0") throw new CodexAppServerVersionError(detectedVersion);
1989
- return detectedVersion;
1990
- }
1991
- function isUnsupportedCodexAppServerVersionError(error) {
1992
- return error instanceof CodexAppServerVersionError;
1993
- }
1994
- function buildCodexAppServerRuntimeIdentity(response, serverVersion) {
1995
- const userAgent = readNonEmptyInitializeString(response.userAgent);
1996
- const codexHome = readNonEmptyInitializeString(response.codexHome);
1997
- const platformFamily = readNonEmptyInitializeString(response.platformFamily);
1998
- const platformOs = readNonEmptyInitializeString(response.platformOs);
1999
- return {
2000
- serverVersion,
2001
- ...userAgent ? { userAgent } : {},
2002
- ...codexHome ? { codexHome } : {},
2003
- ...platformFamily ? { platformFamily } : {},
2004
- ...platformOs ? { platformOs } : {}
2005
- };
2006
- }
2007
- function readNonEmptyInitializeString(value) {
2008
- const trimmed = value?.trim();
2009
- return trimmed ? trimmed : void 0;
2010
- }
2011
- /** Extracts the Codex version from the app-server initialize user-agent field. */
2012
- function readCodexVersionFromUserAgent(userAgent) {
2013
- return (userAgent?.match(/^[^/]+\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:[\s(]|$)/))?.[1];
2014
- }
2015
- function redactCodexAppServerLinePreview(value) {
2016
- 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");
2017
- return redacted.length > CODEX_APP_SERVER_PARSE_LOG_MAX ? `${truncateUtf16Safe(redacted, CODEX_APP_SERVER_PARSE_LOG_MAX)}...` : redacted;
2018
- }
2019
- function appendBoundedTail(current, next, maxLength) {
2020
- const combined = `${current}${next}`;
2021
- return combined.length > maxLength ? sliceUtf16Safe(combined, -maxLength) : combined;
2022
- }
2023
- function buildCodexAppServerExitError(code, signal, stderrTail) {
2024
- const stderrPreview = redactCodexAppServerLinePreview(stderrTail);
2025
- const suffix = stderrPreview ? ` stderr=${JSON.stringify(stderrPreview)}` : "";
2026
- return /* @__PURE__ */ new Error(`codex app-server exited: code=${formatExitValue(code)} signal=${formatExitValue(signal)}${suffix}`);
2027
- }
2028
- function shouldBufferCodexAppServerParseFailure(value, error) {
2029
- if (!value.startsWith("{") && !value.startsWith("[")) return false;
2030
- const message = error instanceof Error ? error.message : String(error);
2031
- return message.includes("Unterminated string") || message.includes("Unexpected end of JSON input");
2032
- }
2033
- function logCodexAppServerParseFailure(value, error, fragmentCount) {
2034
- const linePreview = redactCodexAppServerLinePreview(value);
2035
- const suffix = fragmentCount > 1 ? ` fragments=${fragmentCount}` : "";
2036
- embeddedAgentLog.warn("failed to parse codex app-server message", {
2037
- error,
2038
- errorMessage: error instanceof Error ? error.message : String(error),
2039
- fragmentCount,
2040
- linePreview,
2041
- consoleMessage: `failed to parse codex app-server message${suffix}: preview=${JSON.stringify(linePreview)}`
2042
- });
2043
- }
2044
- const CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS = /* @__PURE__ */ new Set([
2045
- "item/commandExecution/requestApproval",
2046
- "item/fileChange/requestApproval",
2047
- "item/permissions/requestApproval"
2048
- ]);
2049
- /** Returns true for app-server approval request methods OpenClaw can answer. */
2050
- function isCodexAppServerApprovalRequest(method) {
2051
- return CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS.has(method);
2052
- }
2053
- function formatExitValue(value) {
2054
- if (value === null || value === void 0) return "null";
2055
- if (typeof value === "string" || typeof value === "number") return String(value);
2056
- return "unknown";
2057
- }
2058
- //#endregion
2059
- //#region extensions/codex/src/app-server/managed-binary.ts
2060
- /**
2061
- * Resolves the managed Codex app-server binary shipped with or installed beside
2062
- * the Codex plugin before stdio startup.
2063
- */
2064
- const CODEX_PLUGIN_ROOT = resolveDefaultCodexPluginRoot(path.dirname(fileURLToPath(import.meta.url)));
2065
- const MACOS_DESKTOP_CODEX_APP_SERVER_COMMANDS = ["/Applications/ChatGPT.app/Contents/Resources/codex", "/Applications/Codex.app/Contents/Resources/codex"];
2066
- /** Rewrites managed stdio start options to point at an executable Codex binary path. */
2067
- async function resolveManagedCodexAppServerStartOptions(startOptions, options = {}) {
2068
- if (startOptions.transport !== "stdio" || startOptions.commandSource !== "managed") return startOptions;
2069
- const platform = options.platform ?? process.platform;
2070
- const paths = resolveManagedCodexAppServerPaths({
2071
- platform,
2072
- pluginRoot: options.pluginRoot,
2073
- managedCommandOrder: startOptions.managedCommandOrder
2074
- });
2075
- const pathExists = options.pathExists ?? commandPathExists;
2076
- const commandPaths = await findManagedCodexAppServerCommandPaths({
2077
- candidateCommandPaths: paths.candidateCommandPaths,
2078
- pathExists,
2079
- platform
2080
- });
2081
- const commandPath = expectDefined(commandPaths[0], "resolved managed Codex command path");
2082
- const managedFallbackCommandPaths = commandPaths.slice(1);
2083
- return {
2084
- ...startOptions,
2085
- command: commandPath,
2086
- commandSource: "resolved-managed",
2087
- ...managedFallbackCommandPaths.length > 0 ? { managedFallbackCommandPaths } : {}
2088
- };
2089
- }
2090
- /** Resolves the native artifact behind a successful managed launcher selection. */
2091
- function resolveManagedCodexNativeCommand(command, options = {}) {
2092
- const platform = options.platform ?? process.platform;
2093
- if (platform === "darwin" && MACOS_DESKTOP_CODEX_APP_SERVER_COMMANDS.some((candidate) => candidate === command)) return command;
2094
- const target = resolveCodexNativeTarget(platform, options.arch ?? process.arch);
2095
- if (!target) return;
2096
- const packageRoot = resolveManagedCodexPackageRootForCommand(command, platform);
2097
- if (!packageRoot) return;
2098
- const resolvePackageJson = options.resolvePackageJson ?? resolvePackageJsonFromRoot;
2099
- const pathExists = options.pathExists ?? existsSync;
2100
- for (const packageName of [target.packageName, MANAGED_CODEX_APP_SERVER_PACKAGE]) {
2101
- const packageJsonPath = resolvePackageJson(packageName, packageRoot);
2102
- if (!packageJsonPath) continue;
2103
- const candidate = path.join(path.dirname(packageJsonPath), "vendor", target.triple, "bin", platform === "win32" ? "codex.exe" : "codex");
2104
- if (pathExists(candidate)) return candidate;
2105
- }
2106
- }
2107
- function resolveManagedCodexPackageRootForCommand(command, platform) {
2108
- const pathApi = pathForPlatform(platform);
2109
- const commandPaths = [command];
2110
- try {
2111
- commandPaths.unshift(realpathSync(command));
2112
- } catch {}
2113
- for (const commandPath of commandPaths) {
2114
- let current = pathApi.dirname(commandPath);
2115
- while (true) {
2116
- if (pathApi.basename(current) === "codex" && pathApi.basename(pathApi.dirname(current)) === "@openai") return current;
2117
- if (pathApi.basename(current) === ".bin") return pathApi.join(pathApi.dirname(current), "@openai", "codex");
2118
- const parent = pathApi.dirname(current);
2119
- if (parent === current) break;
2120
- current = parent;
2121
- }
2122
- }
2123
- }
2124
- function resolveCodexNativeTarget(platform, arch) {
2125
- if ((platform === "linux" || platform === "android") && arch === "x64") return {
2126
- packageName: "@openai/codex-linux-x64",
2127
- triple: "x86_64-unknown-linux-musl"
2128
- };
2129
- if ((platform === "linux" || platform === "android") && arch === "arm64") return {
2130
- packageName: "@openai/codex-linux-arm64",
2131
- triple: "aarch64-unknown-linux-musl"
2132
- };
2133
- if (platform === "darwin" && arch === "x64") return {
2134
- packageName: "@openai/codex-darwin-x64",
2135
- triple: "x86_64-apple-darwin"
2136
- };
2137
- if (platform === "darwin" && arch === "arm64") return {
2138
- packageName: "@openai/codex-darwin-arm64",
2139
- triple: "aarch64-apple-darwin"
2140
- };
2141
- if (platform === "win32" && arch === "x64") return {
2142
- packageName: "@openai/codex-win32-x64",
2143
- triple: "x86_64-pc-windows-msvc"
2144
- };
2145
- if (platform === "win32" && arch === "arm64") return {
2146
- packageName: "@openai/codex-win32-arm64",
2147
- triple: "aarch64-pc-windows-msvc"
2148
- };
2149
- }
2150
- function resolvePackageJsonFromRoot(packageName, root) {
2151
- try {
2152
- return createRequire(path.join(root, "package.json")).resolve(`${packageName}/package.json`);
2153
- } catch {
2154
- return;
2155
- }
2156
- }
2157
- /** Returns the preferred and fallback managed Codex binary paths for a plugin root. */
2158
- function resolveManagedCodexAppServerPaths(params) {
2159
- const platform = params.platform ?? process.platform;
2160
- const candidateCommandPaths = resolveManagedCodexAppServerCommandCandidates(params.pluginRoot ?? CODEX_PLUGIN_ROOT, platform, params.managedCommandOrder ?? "package-first");
2161
- return {
2162
- commandPath: candidateCommandPaths[0] ?? "",
2163
- candidateCommandPaths
2164
- };
2165
- }
2166
- function resolveManagedCodexAppServerCommandCandidates(pluginRoot, platform, managedCommandOrder) {
2167
- const pathApi = pathForPlatform(platform);
2168
- const commandName = platform === "win32" ? "codex.cmd" : "codex";
2169
- const roots = resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform);
2170
- const packageCommandPaths = [...roots.map((root) => pathApi.join(root, "node_modules", ".bin", commandName)), ...resolveManagedCodexPackageBinCandidates(roots, platform)];
2171
- const desktopCommandPaths = resolveDesktopCodexAppServerCommandCandidates(platform);
2172
- const orderedCommandPaths = managedCommandOrder === "desktop-first" ? [...desktopCommandPaths, ...packageCommandPaths] : [...packageCommandPaths, ...desktopCommandPaths];
2173
- return [...new Set(orderedCommandPaths)];
2174
- }
2175
- function resolveDesktopCodexAppServerCommandCandidates(platform) {
2176
- return platform === "darwin" ? [...MACOS_DESKTOP_CODEX_APP_SERVER_COMMANDS] : [];
2177
- }
2178
- function resolveDefaultCodexPluginRoot(moduleDir) {
2179
- const moduleBaseName = path.basename(moduleDir);
2180
- if (moduleBaseName === "dist" || moduleBaseName === "dist-runtime") return path.dirname(moduleDir);
2181
- return path.resolve(moduleDir, "..", "..");
2182
- }
2183
- function resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform) {
2184
- const pathApi = pathForPlatform(platform);
2185
- const directRoots = [
2186
- pluginRoot,
2187
- pathApi.dirname(pluginRoot),
2188
- pathApi.dirname(pathApi.dirname(pluginRoot)),
2189
- isDistExtensionRoot(pluginRoot, platform) ? pathApi.dirname(pathApi.dirname(pathApi.dirname(pluginRoot))) : null
2190
- ].filter((root) => Boolean(root));
2191
- return [.../* @__PURE__ */ new Set([...directRoots, ...resolveNearestNodeModulesProjectRoots(directRoots, platform)])];
2192
- }
2193
- function resolveNearestNodeModulesProjectRoots(roots, platform) {
2194
- const pathApi = pathForPlatform(platform);
2195
- const projectRoots = [];
2196
- for (const root of roots) {
2197
- let current = pathApi.resolve(root);
2198
- while (true) {
2199
- if (pathApi.basename(current) === "node_modules") {
2200
- projectRoots.push(pathApi.dirname(current));
2201
- break;
2202
- }
2203
- const parent = pathApi.dirname(current);
2204
- if (parent === current) break;
2205
- current = parent;
2206
- }
2207
- }
2208
- return projectRoots;
2209
- }
2210
- function resolveManagedCodexPackageBinCandidates(roots, platform) {
2211
- if (platform === "win32") return [];
2212
- const candidates = [];
2213
- for (const root of roots) {
2214
- const candidate = resolveManagedCodexPackageBinCandidate(root);
2215
- if (candidate) candidates.push(candidate);
2216
- }
2217
- return candidates;
2218
- }
2219
- function resolveManagedCodexPackageBinCandidate(root) {
2220
- try {
2221
- const packageJsonPath = createRequire(path.join(root, "package.json")).resolve(`${MANAGED_CODEX_APP_SERVER_PACKAGE}/package.json`);
2222
- const packageRoot = path.dirname(packageJsonPath);
2223
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
2224
- const binPath = typeof packageJson.bin === "string" ? packageJson.bin : isRecord(packageJson.bin) && typeof packageJson.bin.codex === "string" ? packageJson.bin.codex : null;
2225
- return binPath ? path.resolve(packageRoot, binPath) : null;
2226
- } catch {
2227
- return null;
2228
- }
2229
- }
2230
- function isRecord(value) {
2231
- return typeof value === "object" && value !== null;
2232
- }
2233
- function isDistExtensionRoot(pluginRoot, platform) {
2234
- const pathApi = pathForPlatform(platform);
2235
- const extensionsDir = pathApi.dirname(pluginRoot);
2236
- const distDir = pathApi.dirname(extensionsDir);
2237
- return pathApi.basename(extensionsDir) === "extensions" && (pathApi.basename(distDir) === "dist" || pathApi.basename(distDir) === "dist-runtime");
2238
- }
2239
- function pathForPlatform(platform) {
2240
- return platform === "win32" ? path.win32 : path.posix;
2241
- }
2242
- async function findManagedCodexAppServerCommandPaths(params) {
2243
- const commandPaths = [];
2244
- for (const commandPath of params.candidateCommandPaths) if (await params.pathExists(commandPath, params.platform)) commandPaths.push(commandPath);
2245
- if (commandPaths.length > 0) return commandPaths;
2246
- throw new Error([
2247
- `Managed Codex app-server binary was not found for ${MANAGED_CODEX_APP_SERVER_PACKAGE}.`,
2248
- "Reinstall or update OpenClaw, or run pnpm install in a source checkout.",
2249
- "Set plugins.entries.codex.config.appServer.command or OPENCLAW_CODEX_APP_SERVER_BIN to use a custom Codex binary."
2250
- ].join(" "));
2251
- }
2252
- async function commandPathExists(filePath, platform) {
2253
- try {
2254
- await access(filePath, platform === "win32" ? constants.F_OK : constants.X_OK);
2255
- return true;
2256
- } catch {
2257
- return false;
2258
- }
2259
- }
2260
- //#endregion
2261
- //#region extensions/codex/src/app-server/native-config-fence.ts
2262
- const CODEX_NATIVE_CONFIG_FENCE_STATE = Symbol.for("openclaw.codexNativeConfigFenceState");
2263
- function getFenceState() {
2264
- const globalState = globalThis;
2265
- globalState[CODEX_NATIVE_CONFIG_FENCE_STATE] ??= /* @__PURE__ */ new Map();
2266
- return globalState[CODEX_NATIVE_CONFIG_FENCE_STATE];
2267
- }
2268
- /** Acquires the per-CODEX_HOME fence and returns an idempotent release. */
2269
- async function acquireCodexNativeConfigFence(key, options = {}) {
2270
- const state = getFenceState();
2271
- const previous = state.get(key) ?? Promise.resolve();
2272
- let resolveCurrent = () => void 0;
2273
- const current = new Promise((resolve) => {
2274
- resolveCurrent = resolve;
2275
- });
2276
- state.set(key, current);
2277
- try {
2278
- await waitForPreviousFence(previous, options);
2279
- } catch (error) {
2280
- previous.then(() => {
2281
- resolveCurrent();
2282
- if (state.get(key) === current) state.delete(key);
2283
- });
2284
- throw error;
2285
- }
2286
- let released = false;
2287
- return () => {
2288
- if (released) return;
2289
- released = true;
2290
- resolveCurrent();
2291
- if (state.get(key) === current) state.delete(key);
2292
- };
2293
- }
2294
- async function waitForPreviousFence(previous, options) {
2295
- if (options.signal?.aborted) throw new Error(options.abortMessage ?? "Codex native config fence aborted");
2296
- if (options.timeoutMs === void 0 && !options.signal) {
2297
- await previous;
2298
- return;
2299
- }
2300
- await new Promise((resolve, reject) => {
2301
- let timeout;
2302
- const cleanup = () => {
2303
- if (timeout) {
2304
- clearTimeout(timeout);
2305
- timeout = void 0;
2306
- }
2307
- options.signal?.removeEventListener("abort", onAbort);
2308
- };
2309
- const settle = (run) => {
2310
- cleanup();
2311
- run();
2312
- };
2313
- const onAbort = () => settle(() => reject(new Error(options.abortMessage ?? "Codex native config fence aborted")));
2314
- previous.then(() => settle(resolve));
2315
- if (options.signal) options.signal.addEventListener("abort", onAbort, { once: true });
2316
- if (options.timeoutMs !== void 0) {
2317
- timeout = setTimeout(() => settle(() => reject(new Error(options.timeoutMessage ?? "Codex native config fence timed out"))), Math.max(1, options.timeoutMs));
2318
- timeout.unref?.();
2319
- }
2320
- });
2321
- }
2322
- //#endregion
2323
- //#region extensions/codex/src/app-server/timeout.ts
2324
- /**
2325
- * Thin Codex app-server timeout adapter around OpenClaw's shared security
2326
- * runtime timeout helper.
2327
- */
2328
- /** Awaits a promise with a Codex-specific timeout error message. */
2329
- async function withTimeout$1(promise, timeoutMs, timeoutMessage, createError) {
2330
- return await withTimeout(promise, timeoutMs, {
2331
- message: timeoutMessage,
2332
- ...createError ? { createError } : {}
2333
- });
2334
- }
2335
- //#endregion
2336
- //#region extensions/codex/src/app-server/shared-client.ts
2337
- /**
2338
- * Owns shared and isolated Codex app-server client startup, auth application,
2339
- * lease tracking, and teardown.
2340
- */
2341
- var shared_client_exports = /* @__PURE__ */ __exportAll({
2342
- assertCodexAppServerClientStartSelectionCurrent: () => assertCodexAppServerClientStartSelectionCurrent,
2343
- clearSharedCodexAppServerClientAndWait: () => clearSharedCodexAppServerClientAndWait,
2344
- clearSharedCodexAppServerClientIfCurrent: () => clearSharedCodexAppServerClientIfCurrent,
2345
- clearSharedCodexAppServerClientIfCurrentAndUnclaimed: () => clearSharedCodexAppServerClientIfCurrentAndUnclaimed,
2346
- clearSharedCodexAppServerClientIfCurrentAndWait: () => clearSharedCodexAppServerClientIfCurrentAndWait,
2347
- createIsolatedCodexAppServerClient: () => createIsolatedCodexAppServerClient,
2348
- getLeasedSharedCodexAppServerClient: () => getLeasedSharedCodexAppServerClient,
2349
- getSharedCodexAppServerClient: () => getSharedCodexAppServerClient,
2350
- isCodexAppServerStartSelectionChangedError: () => isCodexAppServerStartSelectionChangedError,
2351
- releaseCodexAppServerClientLease: () => releaseCodexAppServerClientLease,
2352
- releaseLeasedSharedCodexAppServerClient: () => releaseLeasedSharedCodexAppServerClient,
2353
- resolveCodexAppServerSpawnIdentity: () => resolveCodexAppServerSpawnIdentity,
2354
- resolveCodexNativeConfigFenceKey: () => resolveCodexNativeConfigFenceKey,
2355
- retainSharedCodexAppServerClientByInstanceId: () => retainSharedCodexAppServerClientByInstanceId,
2356
- retainSharedCodexAppServerClientIfCurrent: () => retainSharedCodexAppServerClientIfCurrent,
2357
- retireSharedCodexAppServerClientIfCurrent: () => retireSharedCodexAppServerClientIfCurrent,
2358
- withLeasedCodexAppServerClientStartSelectionRetry: () => withLeasedCodexAppServerClientStartSelectionRetry
2359
- });
2360
- const CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE = "codex app-server initialize timed out";
2361
- const suspectClosedClients = /* @__PURE__ */ new WeakSet();
2362
- const SHARED_CODEX_APP_SERVER_CLIENT_STATE = Symbol.for("openclaw.codexAppServerClientState");
2363
- const SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER = Symbol.for("openclaw.codexAppServerClientDisposer");
2364
- const CODEX_APP_SERVER_CLIENT_START_METADATA = Symbol.for("openclaw.codexAppServerClientStartMetadata");
2365
- function getSharedCodexAppServerClientState() {
2366
- const globalState = globalThis;
2367
- globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] ??= {
2368
- clients: /* @__PURE__ */ new Map(),
2369
- leasedReleases: /* @__PURE__ */ new WeakMap()
2370
- };
2371
- return globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE];
2372
- }
2373
- function getCodexAppServerClientStartMetadata() {
2374
- const globalState = globalThis;
2375
- globalState[CODEX_APP_SERVER_CLIENT_START_METADATA] ??= /* @__PURE__ */ new WeakMap();
2376
- return globalState[CODEX_APP_SERVER_CLIENT_START_METADATA];
2377
- }
2378
- /** Resolves non-secret spawn identity before startup; argv is represented only by its hash. */
2379
- function resolveCodexAppServerSpawnIdentity(startOptions, resolvedNativeCommand) {
2380
- const nativeCommand = resolvedNativeCommand ?? (startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0);
2381
- return {
2382
- command: startOptions.command,
2383
- argsFingerprint: createHash("sha256").update(JSON.stringify(startOptions.args)).digest("hex"),
2384
- ...startOptions.commandSource ? { commandSource: startOptions.commandSource } : {},
2385
- ...startOptions.managedCommandOrder ? { managedCommandOrder: startOptions.managedCommandOrder } : {},
2386
- ...nativeCommand ? { nativeCommand } : {}
2387
- };
2388
- }
2389
- var CodexAppServerStartSelectionChangedError = class extends Error {
2390
- constructor() {
2391
- super("Codex app-server managed executable selection changed during startup");
2392
- this.code = "CODEX_APP_SERVER_START_SELECTION_CHANGED";
2393
- this.name = "CodexAppServerStartSelectionChangedError";
2394
- }
2395
- };
2396
- /** Cross-bundle-safe check for a managed executable selection retry. */
2397
- function isCodexAppServerStartSelectionChangedError(error) {
2398
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_START_SELECTION_CHANGED";
2399
- }
2400
- /**
2401
- * Rechecks mutable Codex-owned plugin state immediately before thread start/resume.
2402
- * The synchronous check prevents another gateway task from installing Computer
2403
- * Use between the check and the JSON-RPC write on the same event loop turn.
2404
- */
2405
- function assertCodexAppServerClientStartSelectionCurrent(params) {
2406
- const metadata = getCodexAppServerClientStartMetadata().get(params.client);
2407
- if (!metadata) return;
2408
- const requestedStartOptions = params.startOptions ?? metadata.requestedStartOptions;
2409
- if (requestedStartOptions.commandSource !== "managed") return;
2410
- const current = resolveCodexAppServerStartOptionsForAgent({
2411
- startOptions: requestedStartOptions,
2412
- agentDir: params.agentDir ?? metadata.agentDir
2413
- });
2414
- if ((metadata.startOptions.managedCommandOrder ?? "package-first") !== (current.managedCommandOrder ?? "package-first")) throw new CodexAppServerStartSelectionChangedError();
2415
- }
2416
- /** Resolves the per-CODEX_HOME key used to serialize native config loading. */
2417
- function resolveCodexNativeConfigFenceKey(params) {
2418
- const metadata = params.client ? getCodexAppServerClientStartMetadata().get(params.client) : void 0;
2419
- const startOptions = params.startOptions ?? metadata?.startOptions;
2420
- if (!startOptions || startOptions.transport !== "stdio") return;
2421
- const configuredHome = startOptions.env?.CODEX_HOME?.trim();
2422
- const agentDir = params.agentDir ?? metadata?.agentDir ?? resolveDefaultAgentDir(params.config ?? {});
2423
- const codexHome = configuredHome ? configuredHome : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir() : agentDir ? resolveCodexAppServerHomeDir(agentDir) : void 0;
2424
- return codexHome ? `codex-home:${path.resolve(codexHome)}` : void 0;
2425
- }
2426
- function inferAuthRequirement(preparedAuth) {
2427
- if (preparedAuth?.kind === "api-key") return "api-key";
2428
- return preparedAuth?.kind === "profile" ? "subscription" : void 0;
2429
- }
2430
- async function resolveCodexAppServerClientStartContext(options) {
2431
- const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
2432
- const requestedStartOptions = options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start;
2433
- const preparedAuth = options?.preparedAuth;
2434
- const preparedApiKey = preparedAuth?.kind === "api-key" ? preparedAuth.apiKey.trim() : void 0;
2435
- if (preparedAuth && options?.authProfileId !== void 0) throw new Error("Prepared Codex auth cannot also select a legacy auth profile.");
2436
- if (preparedAuth?.kind === "profile" && !preparedAuth.store.profiles[preparedAuth.profileId]) throw new Error(`Prepared Codex auth profile "${preparedAuth.profileId}" was not found.`);
2437
- if (preparedAuth?.kind === "api-key" && !preparedApiKey) throw new Error("Prepared Codex API-key auth is missing its resolved key.");
2438
- if (preparedAuth && requestedStartOptions.homeScope === "user") throw new Error("Prepared Codex auth requires an isolated app-server home.");
2439
- const preparedAuthRequirement = inferAuthRequirement(preparedAuth);
2440
- if (options?.authRequirement && preparedAuthRequirement && options.authRequirement !== preparedAuthRequirement) throw new Error("Prepared Codex auth does not satisfy the requested auth requirement.");
2441
- const authRequirement = options?.authRequirement ?? preparedAuthRequirement;
2442
- const usesNativeAuth = !preparedAuth && (options?.authProfileId === null || requestedStartOptions.homeScope === "user");
2443
- const requestedAuthProfileId = preparedAuth?.kind === "profile" ? preparedAuth.profileId : options?.authProfileId ?? void 0;
2444
- const authProfileStore = preparedAuth?.kind === "profile" ? preparedAuth.store : !usesNativeAuth && options?.authProfileStore ? resolveCodexAppServerAuthProfileStore({
2445
- agentDir,
2446
- authProfileId: requestedAuthProfileId,
2447
- authProfileStore: options.authProfileStore,
2448
- config: options.config
2449
- }) : options?.authProfileStore;
2450
- const authProfileId = preparedAuth?.kind === "profile" ? preparedAuth.profileId : usesNativeAuth || preparedAuth?.kind === "api-key" ? void 0 : resolveCodexAppServerAuthProfileIdForAgent({
2451
- authProfileId: requestedAuthProfileId,
2452
- agentDir,
2453
- config: options?.config,
2454
- ...authProfileStore ? { authProfileStore } : {}
2455
- });
2456
- const preparedAuthProfileSnapshot = preparedAuth?.kind === "profile" ? preparedAuth.snapshot ?? await resolveCodexAppServerPreparedAuthProfileSnapshot({
2457
- authProfileId,
2458
- authProfileStore,
2459
- agentDir,
2460
- config: options?.config
2461
- }) : void 0;
2462
- if (preparedAuth?.kind === "profile" && !preparedAuthProfileSnapshot) throw new Error(`Prepared Codex auth profile "${preparedAuth.profileId}" is unusable.`);
2463
- const resolvedPreparedAuth = preparedAuth?.kind === "api-key" ? {
2464
- kind: "api-key",
2465
- apiKey: preparedApiKey
2466
- } : preparedAuth?.kind === "profile" ? {
2467
- ...preparedAuth,
2468
- snapshot: preparedAuthProfileSnapshot
2469
- } : void 0;
2470
- return {
2471
- agentDir,
2472
- usesNativeAuth,
2473
- authProfileId,
2474
- authProfileStore,
2475
- requestedStartOptions,
2476
- preparedAuth: resolvedPreparedAuth,
2477
- authRequirement,
2478
- startOptions: await bridgeCodexAppServerStartOptions({
2479
- startOptions: await resolveManagedCodexAppServerStartOptions(resolveCodexAppServerStartOptionsForAgent({
2480
- startOptions: requestedStartOptions,
2481
- agentDir
2482
- })),
2483
- agentDir,
2484
- authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
2485
- ...resolvedPreparedAuth ? { preparedAuth: resolvedPreparedAuth } : {},
2486
- config: options?.config,
2487
- pluginConfig: options?.pluginConfig,
2488
- ...authProfileStore ? { authProfileStore } : {}
2489
- })
2490
- };
2491
- }
2492
- function resolveWarmSharedCodexAppServerClientIdentity(options) {
2493
- if (!options?.config || typeof options.config !== "object" || !options.startOptions || options.pluginConfig !== void 0 || options.authProfileStore !== void 0 || options.preparedAuth !== void 0 || options.runtimeArtifactMode !== void 0 || options.expectedRuntimeArtifact !== void 0) return;
2494
- const authProfileSelector = options.authProfileId === null ? ["native"] : options.authProfileId === void 0 ? ["implicit"] : ["profile", options.authProfileId];
2495
- return {
2496
- config: options.config,
2497
- startOptions: options.startOptions,
2498
- selectorKey: JSON.stringify([
2499
- options.agentDir ?? resolveDefaultAgentDir(options.config),
2500
- authProfileSelector,
2501
- options.authBindingFingerprint ?? null,
2502
- options.authRequirement ?? null
2503
- ])
2504
- };
2505
- }
2506
- function readWarmSharedCodexAppServerClient(state, identity) {
2507
- const aliases = state.warmClientsByConfig?.get(identity.config)?.get(identity.startOptions);
2508
- const warm = aliases?.get(identity.selectorKey);
2509
- if (!warm) return;
2510
- if (state.clients.get(warm.key) !== warm.entry || warm.entry.client !== warm.client || warm.entry.closeWhenIdle || warm.entry.closeError) {
2511
- aliases?.delete(identity.selectorKey);
2512
- return;
2513
- }
2514
- return warm;
2515
- }
2516
- function rememberWarmSharedCodexAppServerClient(state, identity, warm) {
2517
- state.warmClientsByConfig ??= /* @__PURE__ */ new WeakMap();
2518
- let byStartOptions = state.warmClientsByConfig.get(identity.config);
2519
- if (!byStartOptions) {
2520
- byStartOptions = /* @__PURE__ */ new WeakMap();
2521
- state.warmClientsByConfig.set(identity.config, byStartOptions);
2522
- }
2523
- let aliases = byStartOptions.get(identity.startOptions);
2524
- if (!aliases) {
2525
- aliases = /* @__PURE__ */ new Map();
2526
- byStartOptions.set(identity.startOptions, aliases);
2527
- }
2528
- aliases.set(identity.selectorKey, warm);
2529
- }
2530
- /** Gets or starts a shared Codex app-server client without retaining a lease. */
2531
- async function getSharedCodexAppServerClient(options) {
2532
- return (await acquireSharedCodexAppServerClient(options)).client;
2533
- }
2534
- /** Gets or starts a shared Codex app-server client and records a release lease. */
2535
- async function getLeasedSharedCodexAppServerClient(options) {
2536
- const acquired = await acquireSharedCodexAppServerClient(options, { leased: true });
2537
- const state = getSharedCodexAppServerClientState();
2538
- const releases = state.leasedReleases.get(acquired.client) ?? [];
2539
- releases.push(acquired.release);
2540
- state.leasedReleases.set(acquired.client, releases);
2541
- return acquired.client;
2542
- }
2543
- /** Releases one outstanding lease for a shared Codex app-server client. */
2544
- function releaseLeasedSharedCodexAppServerClient(client) {
2545
- const state = getSharedCodexAppServerClientState();
2546
- const releases = state.leasedReleases.get(client);
2547
- if (!releases) return false;
2548
- const release = releases.pop();
2549
- if (!release) return false;
2550
- if (releases.length === 0) state.leasedReleases.delete(client);
2551
- release();
2552
- return true;
2553
- }
2554
- /** Releases the currently owned client exactly once. */
2555
- function releaseCodexAppServerClientLease(lease) {
2556
- const client = lease.client;
2557
- lease.client = void 0;
2558
- return client ? releaseLeasedSharedCodexAppServerClient(client) : false;
2559
- }
2560
- /** Retries one config-loading request after moving its lease to the current owner. */
2561
- async function withLeasedCodexAppServerClientStartSelectionRetry(params) {
2562
- let client = params.lease.client;
2563
- if (!client) throw new Error("Codex app-server selection retry requires an active client lease");
2564
- const timeoutMs = params.options?.timeoutMs ?? 6e4;
2565
- const deadline = Date.now() + timeoutMs;
2566
- const signal = params.signal ?? params.options?.abandonSignal;
2567
- const requestOptions = () => {
2568
- if (signal?.aborted) throw new CodexAppServerStartupError("aborted", "Codex app-server selection retry aborted");
2569
- const remainingTimeoutMs = deadline - Date.now();
2570
- if (remainingTimeoutMs <= 0) throw new CodexAppServerStartupError("timed_out", "Codex app-server selection retry timed out");
2571
- return {
2572
- timeoutMs: remainingTimeoutMs,
2573
- ...signal ? { signal } : {}
2574
- };
2575
- };
2576
- for (let attempt = 0; attempt < 2; attempt += 1) try {
2577
- return await params.run(client, requestOptions());
2578
- } catch (error) {
2579
- if (!isCodexAppServerStartSelectionChangedError(error) || attempt > 0) throw error;
2580
- retireSharedCodexAppServerClientIfCurrent(client);
2581
- params.lease.client = void 0;
2582
- if (!releaseLeasedSharedCodexAppServerClient(client)) {
2583
- client.close();
2584
- throw new Error("Codex app-server selection retry requires a leased shared client", { cause: error });
2585
- }
2586
- const replacementOptions = requestOptions();
2587
- client = await getLeasedSharedCodexAppServerClient({
2588
- ...params.options,
2589
- timeoutMs: replacementOptions.timeoutMs,
2590
- ...signal ? { abandonSignal: signal } : {}
2591
- });
2592
- params.lease.client = client;
2593
- params.onClientChange(client);
2594
- }
2595
- throw new Error("Codex app-server selection retry loop exited unexpectedly");
2596
- }
2597
- async function acquireSharedCodexAppServerClient(options, leaseOptions) {
2598
- if (options?.abandonSignal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
2599
- const state = getSharedCodexAppServerClientState();
2600
- const warmIdentity = resolveWarmSharedCodexAppServerClientIdentity(options);
2601
- const warmClient = warmIdentity ? readWarmSharedCodexAppServerClient(state, warmIdentity) : void 0;
2602
- if (warmClient) {
2603
- options?.onStartedClient?.(warmClient.client);
2604
- const release = leaseOptions?.leased ? retainSharedClientEntry(warmClient.entry) : void 0;
2605
- return release ? {
2606
- client: warmClient.client,
2607
- release
2608
- } : { client: warmClient.client };
2609
- }
2610
- const acquireStartedAt = Date.now();
2611
- const timeoutMs = options?.timeoutMs ?? 0;
2612
- const { agentDir, usesNativeAuth, authProfileId, authProfileStore, preparedAuth, authRequirement, requestedStartOptions, startOptions } = await withCodexAppServerAcquireDeadline(timeoutMs, resolveCodexAppServerClientStartContext(options), options?.abandonSignal);
2613
- const remainingTimeoutMs = resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt);
2614
- const authIdentityCacheKey = preparedAuth?.kind === "api-key" ? resolveCodexAppServerPreparedApiKeyCacheKey(preparedAuth.apiKey) : preparedAuth?.snapshot.secretFreeCacheKey ?? (authRequirement === "api-key" && !authProfileId ? resolveCodexAppServerFallbackApiKeyCacheKey({ startOptions }) : void 0);
2615
- const baseKey = `${codexAppServerStartOptionsKey(startOptions, {
2616
- authProfileId,
2617
- authBindingFingerprint: options?.authBindingFingerprint,
2618
- agentDir: usesNativeAuth ? void 0 : agentDir,
2619
- fallbackApiKeyCacheKey: authIdentityCacheKey
2620
- })}\0auth-requirement:${authRequirement ?? "native"}`;
2621
- const runtimeArtifactMode = options?.runtimeArtifactMode ?? (options?.expectedRuntimeArtifact ? "capture" : void 0);
2622
- const expectedRuntimeArtifactKey = options?.expectedRuntimeArtifact ? createHash("sha256").update(options.expectedRuntimeArtifact.id).update("\0").update(options.expectedRuntimeArtifact.fingerprint).digest("hex") : "mint";
2623
- const key = runtimeArtifactMode ? `${baseKey}\0runtime-artifact:capture-v1:${expectedRuntimeArtifactKey}` : baseKey;
2624
- const entry = getOrCreateSharedClientEntry(state, key);
2625
- if (runtimeArtifactMode) entry.runtimeArtifactStartupAbort ??= new AbortController();
2626
- entry.closeWhenIdle = false;
2627
- const releasePendingAcquire = retainPendingSharedClientAcquire(entry);
2628
- const startedCallback = options?.onStartedClient;
2629
- if (startedCallback) {
2630
- entry.onStartedClientCallbacks.add(startedCallback);
2631
- if (entry.client) startedCallback(entry.client);
2632
- }
2633
- const stopStartedClientNotifications = () => {
2634
- if (startedCallback) entry.onStartedClientCallbacks.delete(startedCallback);
2635
- };
2636
- let cleanupAbandonSignal;
2637
- if (options?.abandonSignal) {
2638
- const abandon = () => {
2639
- stopStartedClientNotifications();
2640
- releasePendingAcquire();
2641
- retirePendingSharedClientEntryIfUnclaimed(key, entry);
2642
- };
2643
- options.abandonSignal.addEventListener("abort", abandon, { once: true });
2644
- cleanupAbandonSignal = () => options.abandonSignal?.removeEventListener("abort", abandon);
2645
- if (options.abandonSignal.aborted) abandon();
2646
- }
2647
- const startup = entry.startup ?? (entry.startup = createSharedCodexAppServerClientStartup({
2648
- entry,
2649
- key,
2650
- requestedStartOptions,
2651
- startOptions,
2652
- agentDir,
2653
- authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
2654
- authProfileStore,
2655
- preparedAuth,
2656
- authRequirement,
2657
- runtimeArtifactMode,
2658
- ...options?.expectedRuntimeArtifact ? { expectedRuntimeArtifact: options.expectedRuntimeArtifact } : {},
2659
- runtimeArtifactSignal: entry.runtimeArtifactStartupAbort?.signal,
2660
- config: options?.config
2661
- }));
2662
- try {
2663
- await withCodexAppServerAcquireDeadline(remainingTimeoutMs, startup.initialized, options?.abandonSignal, CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, () => buildCodexAppServerInitializeTimeoutError(entry.client));
2664
- const client = await withCodexAppServerAcquireDeadline(timeoutMs, startup.ready, options?.abandonSignal, "codex app-server authentication timed out");
2665
- if (entry.closeError) throw entry.closeError;
2666
- ensureCodexAppServerClientRuntime(client, {
2667
- agentDir,
2668
- authProfileId: usesNativeAuth ? void 0 : authProfileId,
2669
- ...authProfileStore ? { authProfileStore } : {},
2670
- authMode: preparedAuth?.kind === "api-key" ? "prepared-api-key" : "profile",
2671
- config: options?.config
2672
- });
2673
- const release = leaseOptions?.leased ? retainSharedClientEntry(entry) : void 0;
2674
- if (warmIdentity) rememberWarmSharedCodexAppServerClient(state, warmIdentity, {
2675
- key,
2676
- entry,
2677
- client
2678
- });
2679
- return release ? {
2680
- client,
2681
- release
2682
- } : { client };
2683
- } catch (error) {
2684
- releasePendingAcquire();
2685
- retirePendingSharedClientEntryIfUnclaimed(key, entry);
2686
- throw error;
2687
- } finally {
2688
- cleanupAbandonSignal?.();
2689
- stopStartedClientNotifications();
2690
- releasePendingAcquire();
2691
- }
2692
- }
2693
- async function withCodexAppServerAcquireDeadline(timeoutMs, promise, signal, timeoutMessage = CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, timeoutErrorFactory) {
2694
- if (signal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
2695
- const timed = withTimeout$1(promise, timeoutMs, timeoutMessage, () => timeoutErrorFactory?.() ?? new CodexAppServerStartupError("timed_out", timeoutMessage));
2696
- if (!signal) return await timed;
2697
- return await new Promise((resolve, reject) => {
2698
- const onAbort = () => reject(new CodexAppServerStartupError("aborted", "codex app-server initialize aborted"));
2699
- signal.addEventListener("abort", onAbort, { once: true });
2700
- timed.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2701
- });
2702
- }
2703
- function buildCodexAppServerInitializeTimeoutError(client) {
2704
- const stderr = client?.getStderrDiagnostic();
2705
- return new CodexAppServerStartupError("timed_out", stderr ? `${CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE}; stderr=${JSON.stringify(stderr)}` : CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE);
2706
- }
2707
- function resolveRemainingAcquireTimeout(timeoutMs, startedAt) {
2708
- if (!(timeoutMs > 0)) return timeoutMs;
2709
- const remaining = timeoutMs - (Date.now() - startedAt);
2710
- if (remaining <= 0) throw new CodexAppServerStartupError("timed_out", "codex app-server initialize timed out");
2711
- return remaining;
2712
- }
2713
- function createSharedCodexAppServerClientStartup(params) {
2714
- const initialized = createDeferred();
2715
- const ready = startInitializedCodexAppServerClient({
2716
- requestedStartOptions: params.requestedStartOptions,
2717
- startOptions: params.startOptions,
2718
- agentDir: params.agentDir,
2719
- authProfileId: params.authProfileId,
2720
- authProfileStore: params.authProfileStore,
2721
- preparedAuth: params.preparedAuth,
2722
- authRequirement: params.authRequirement,
2723
- runtimeArtifactMode: params.runtimeArtifactMode,
2724
- ...params.expectedRuntimeArtifact ? { expectedRuntimeArtifact: params.expectedRuntimeArtifact } : {},
2725
- runtimeArtifactSignal: params.runtimeArtifactSignal,
2726
- config: params.config,
2727
- onStartedClient: (startedClient) => {
2728
- params.entry.client = startedClient;
2729
- for (const callback of params.entry.onStartedClientCallbacks) callback(startedClient);
2730
- retirePendingSharedClientEntryIfUnclaimed(params.key, params.entry);
2731
- },
2732
- onInitializedClient: () => initialized.resolve()
2733
- }).then((client) => {
2734
- params.entry.client = client;
2735
- client.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(params.key, closedClient));
2736
- return client;
2737
- }, (error) => {
2738
- initialized.reject(error);
2739
- throw error;
2740
- });
2741
- ready.catch(() => void 0);
2742
- return {
2743
- initialized: initialized.promise,
2744
- ready
2745
- };
2746
- }
2747
- /** Starts a non-shared Codex app-server client owned entirely by the caller. */
2748
- async function createIsolatedCodexAppServerClient(options) {
2749
- if (options?.abandonSignal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
2750
- const acquireStartedAt = Date.now();
2751
- const timeoutMs = options?.timeoutMs ?? 0;
2752
- const { agentDir, usesNativeAuth, authProfileId, authProfileStore, preparedAuth, authRequirement, requestedStartOptions, startOptions } = await withCodexAppServerAcquireDeadline(timeoutMs, resolveCodexAppServerClientStartContext(options), options?.abandonSignal);
2753
- return await startInitializedCodexAppServerClient({
2754
- requestedStartOptions,
2755
- startOptions,
2756
- agentDir,
2757
- authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
2758
- authProfileStore,
2759
- preparedAuth,
2760
- authRequirement,
2761
- runtimeArtifactMode: options?.runtimeArtifactMode ?? (options?.expectedRuntimeArtifact ? "capture" : void 0),
2762
- ...options?.expectedRuntimeArtifact ? { expectedRuntimeArtifact: options.expectedRuntimeArtifact } : {},
2763
- runtimeArtifactSignal: options?.abandonSignal,
2764
- config: options?.config,
2765
- timeoutMs: resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt),
2766
- abandonSignal: options?.abandonSignal,
2767
- onStartedClient: options?.onStartedClient
2768
- });
2769
- }
2770
- async function startInitializedCodexAppServerClient(params) {
2771
- const acquireStartedAt = Date.now();
2772
- const timeoutMs = params.timeoutMs ?? 0;
2773
- const startOptionsCandidates = resolveManagedFallbackStartOptions(params.startOptions);
2774
- for (const [index, startOptions] of startOptionsCandidates.entries()) {
2775
- const runtimeArtifactModule = params.runtimeArtifactMode ? await import("./runtime-artifact-CmtG_t1L.js") : void 0;
2776
- const nativeCommandBeforeStart = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
2777
- const runtimeArtifactBeforeStart = runtimeArtifactModule ? await runtimeArtifactModule.captureCodexAppServerRuntimeArtifactBeforeStart({
2778
- startOptions,
2779
- spawnIdentity: resolveCodexAppServerSpawnIdentity(startOptions, nativeCommandBeforeStart),
2780
- signal: params.runtimeArtifactSignal
2781
- }) : void 0;
2782
- if (runtimeArtifactModule && runtimeArtifactBeforeStart && params.expectedRuntimeArtifact && !runtimeArtifactModule.validateCodexAppServerRuntimeArtifactCapture(params.expectedRuntimeArtifact, runtimeArtifactBeforeStart)) {
2783
- if (index + 1 < startOptionsCandidates.length) continue;
2784
- throw new Error("Codex app-server runtime artifact does not match verified inference");
2785
- }
2786
- const client = CodexAppServerClient.start(startOptions);
2787
- params.onStartedClient?.(client);
2788
- let initialize;
2789
- try {
2790
- await withCodexAppServerAcquireDeadline(resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt), initialize = client.initialize(), params.abandonSignal, CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, () => buildCodexAppServerInitializeTimeoutError(client));
2791
- } catch (error) {
2792
- client.close();
2793
- initialize?.catch(() => void 0);
2794
- if (shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates)) continue;
2795
- throw error;
2796
- }
2797
- params.onInitializedClient?.();
2798
- let runtimeArtifact;
2799
- try {
2800
- if (runtimeArtifactModule && runtimeArtifactBeforeStart) {
2801
- const nativeCommand = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
2802
- runtimeArtifact = await runtimeArtifactModule.finalizeCodexAppServerRuntimeArtifact({
2803
- before: runtimeArtifactBeforeStart,
2804
- startOptions,
2805
- spawnIdentity: resolveCodexAppServerSpawnIdentity(startOptions, nativeCommand),
2806
- runtimeIdentity: client.getRuntimeIdentity(),
2807
- signal: params.runtimeArtifactSignal
2808
- });
2809
- if (params.expectedRuntimeArtifact && (runtimeArtifact.id !== params.expectedRuntimeArtifact.id || runtimeArtifact.fingerprint !== params.expectedRuntimeArtifact.fingerprint)) throw new Error("Codex app-server runtime artifact does not match verified inference");
2810
- }
2811
- } catch (error) {
2812
- client.close();
2813
- throw error;
2814
- }
2815
- ensureCodexAppServerClientRuntime(client, {
2816
- agentDir: params.agentDir,
2817
- authProfileId: params.authProfileId ?? void 0,
2818
- authMode: params.preparedAuth?.kind === "api-key" ? "prepared-api-key" : "profile",
2819
- ...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {},
2820
- config: params.config
2821
- });
2822
- try {
2823
- await withCodexAppServerAcquireDeadline(resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt), applyCodexAppServerAuthProfile({
2824
- client,
2825
- agentDir: params.agentDir,
2826
- authProfileId: params.authProfileId,
2827
- preparedAuth: params.preparedAuth,
2828
- authRequirement: params.authRequirement,
2829
- startOptions,
2830
- config: params.config,
2831
- ...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {}
2832
- }), params.abandonSignal);
2833
- const nativeCommand = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
2834
- if (runtimeArtifactModule && runtimeArtifact) runtimeArtifactModule.bindCodexAppServerRuntimeArtifact(client, runtimeArtifact);
2835
- getCodexAppServerClientStartMetadata().set(client, {
2836
- requestedStartOptions: params.requestedStartOptions,
2837
- startOptions,
2838
- agentDir: params.agentDir,
2839
- ...nativeCommand ? { nativeCommand } : {}
2840
- });
2841
- const fenceKey = resolveCodexNativeConfigFenceKey({ client });
2842
- if (fenceKey) client.setThreadSessionRequestGuard(async (options) => {
2843
- const release = await acquireCodexNativeConfigFence(fenceKey, options);
2844
- try {
2845
- assertCodexAppServerClientStartSelectionCurrent({ client });
2846
- return release;
2847
- } catch (error) {
2848
- release();
2849
- throw error;
2850
- }
2851
- });
2852
- return client;
2853
- } catch (error) {
2854
- client.close();
2855
- throw error;
2856
- }
2857
- }
2858
- throw new Error("Managed Codex app-server fallback candidates were exhausted.");
2859
- }
2860
- function resolveManagedFallbackStartOptions(startOptions) {
2861
- const commands = [startOptions.command, ...startOptions.managedFallbackCommandPaths ?? []];
2862
- const candidates = [];
2863
- for (const [index, command] of commands.entries()) {
2864
- const managedFallbackCommandPaths = commands.slice(index + 1);
2865
- const candidate = {
2866
- ...startOptions,
2867
- command
2868
- };
2869
- if (managedFallbackCommandPaths.length === 0) delete candidate.managedFallbackCommandPaths;
2870
- else candidate.managedFallbackCommandPaths = managedFallbackCommandPaths;
2871
- candidates.push(candidate);
2872
- }
2873
- return candidates;
2874
- }
2875
- function shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates) {
2876
- return startOptions.commandSource === "resolved-managed" && index < startOptionsCandidates.length - 1 && isUnsupportedCodexAppServerVersionError(error);
2877
- }
2878
- /** Clears and closes the shared entry only if it still owns the supplied client. */
2879
- function clearSharedCodexAppServerClientIfCurrent(client) {
2880
- if (!client) return false;
2881
- const state = getSharedCodexAppServerClientState();
2882
- for (const [key, entry] of state.clients) if (entry.client === client) {
2883
- state.clients.delete(key);
2884
- client.close();
2885
- return true;
2886
- }
2887
- return false;
2888
- }
2889
- /** Retains the matching shared client and returns a release callback. */
2890
- function retainSharedCodexAppServerClientIfCurrent(client) {
2891
- if (!client) return;
2892
- const state = getSharedCodexAppServerClientState();
2893
- for (const entry of state.clients.values()) if (entry.client === client) return retainSharedClientEntry(entry);
2894
- }
2895
- /** Retains the live shared client whose initialized instance id matches a thread binding. */
2896
- function retainSharedCodexAppServerClientByInstanceId(clientId) {
2897
- const normalizedClientId = clientId?.trim();
2898
- if (!normalizedClientId) return;
2899
- for (const entry of getSharedCodexAppServerClientState().clients.values()) {
2900
- const client = entry.client;
2901
- if (client?.getInstanceId() !== normalizedClientId || entry.closeWhenIdle || entry.closeError) continue;
2902
- return {
2903
- client,
2904
- release: retainSharedClientEntry(entry)
2905
- };
2906
- }
2907
- }
2908
- /**
2909
- * Retires a matching shared client. Default is graceful: detach from the map
2910
- * (future acquisitions get a fresh client) and close once leases drain.
2911
- * `failActiveLeases` is for suspect clients only (timed-out turns): it closes
2912
- * the physical connection immediately so co-leased attempts hit the normal
2913
- * client-closed retry path, and pending acquires reject instead of leasing
2914
- * the poisoned process. Routine cleanup must NOT use it — it would abort
2915
- * healthy sibling turns on a working client.
2916
- */
2917
- function retireSharedCodexAppServerClientIfCurrent(client, opts) {
2918
- if (!client) return;
2919
- const state = getSharedCodexAppServerClientState();
2920
- for (const [key, entry] of state.clients) if (entry.client === client) {
2921
- state.clients.delete(key);
2922
- entry.closeWhenIdle = true;
2923
- if (opts?.failActiveLeases) {
2924
- entry.closeError = /* @__PURE__ */ new Error("codex app-server client is closed");
2925
- const closed = closeRetiredSharedClientEntry(entry);
2926
- if (closed) suspectClosedClients.add(client);
2927
- return {
2928
- activeLeases: entry.activeLeases,
2929
- closed
2930
- };
2931
- }
2932
- const closed = closeRetiredSharedClientEntryIfIdle(entry);
2933
- return {
2934
- activeLeases: entry.activeLeases,
2935
- closed
2936
- };
2937
- }
2938
- const activeLeases = state.leasedReleases.get(client)?.length ?? 0;
2939
- if (activeLeases > 0) {
2940
- if (opts?.failActiveLeases && !suspectClosedClients.has(client)) {
2941
- suspectClosedClients.add(client);
2942
- client.close();
2943
- return {
2944
- activeLeases,
2945
- closed: true
2946
- };
2947
- }
2948
- return {
2949
- activeLeases,
2950
- closed: false
2951
- };
2952
- }
2953
- }
2954
- /** Clears a matching shared client and waits for its process to exit. */
2955
- async function clearSharedCodexAppServerClientIfCurrentAndWait(client, options) {
2956
- if (!client) return false;
2957
- const state = getSharedCodexAppServerClientState();
2958
- for (const [key, entry] of state.clients) if (entry.client === client) {
2959
- state.clients.delete(key);
2960
- await client.closeAndWait(options);
2961
- return true;
2962
- }
2963
- return false;
2964
- }
2965
- /** Clears all shared clients and waits for their processes to exit. */
2966
- async function clearSharedCodexAppServerClientAndWait(options) {
2967
- const state = getSharedCodexAppServerClientState();
2968
- const clients = collectSharedClients(state);
2969
- state.clients.clear();
2970
- state.warmClientsByConfig = /* @__PURE__ */ new WeakMap();
2971
- await Promise.all(clients.map((client) => client.closeAndWait(options)));
2972
- }
2973
- globalThis[SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER] = clearSharedCodexAppServerClientAndWait;
2974
- function getOrCreateSharedClientEntry(state, key) {
2975
- let entry = state.clients.get(key);
2976
- if (!entry) {
2977
- entry = {
2978
- activeLeases: 0,
2979
- pendingAcquires: 0,
2980
- closeWhenIdle: false,
2981
- onStartedClientCallbacks: /* @__PURE__ */ new Set()
2982
- };
2983
- state.clients.set(key, entry);
2984
- }
2985
- return entry;
2986
- }
2987
- function clearSharedClientEntryIfCurrent(key, client) {
2988
- const state = getSharedCodexAppServerClientState();
2989
- if (state.clients.get(key)?.client === client) state.clients.delete(key);
2990
- }
2991
- /** Clears a matching shared client only when no lease or acquire currently claims it. */
2992
- function clearSharedCodexAppServerClientIfCurrentAndUnclaimed(client) {
2993
- if (!client) return {
2994
- found: false,
2995
- closed: false,
2996
- activeLeases: 0,
2997
- pendingAcquires: 0
2998
- };
2999
- const state = getSharedCodexAppServerClientState();
3000
- for (const [key, entry] of state.clients) if (entry.client === client) return {
3001
- found: true,
3002
- closed: closeSharedClientEntryIfUnclaimed(key, entry),
3003
- activeLeases: entry.activeLeases,
3004
- pendingAcquires: entry.pendingAcquires
3005
- };
3006
- return {
3007
- found: false,
3008
- closed: false,
3009
- activeLeases: 0,
3010
- pendingAcquires: 0
3011
- };
3012
- }
3013
- function retainPendingSharedClientAcquire(entry) {
3014
- let released = false;
3015
- entry.pendingAcquires += 1;
3016
- return () => {
3017
- if (released) return;
3018
- released = true;
3019
- entry.pendingAcquires = Math.max(0, entry.pendingAcquires - 1);
3020
- closeRetiredSharedClientEntryIfIdle(entry);
3021
- };
3022
- }
3023
- function retainSharedClientEntry(entry) {
3024
- let released = false;
3025
- entry.activeLeases += 1;
3026
- return () => {
3027
- if (released) return;
3028
- released = true;
3029
- entry.activeLeases = Math.max(0, entry.activeLeases - 1);
3030
- closeRetiredSharedClientEntryIfIdle(entry);
3031
- };
3032
- }
3033
- function closeRetiredSharedClientEntryIfIdle(entry) {
3034
- if (!entry.closeWhenIdle || entry.activeLeases > 0 || entry.pendingAcquires > 0 || !entry.client) return false;
3035
- const client = entry.client;
3036
- entry.closeWhenIdle = false;
3037
- entry.client = void 0;
3038
- client.close();
3039
- return true;
3040
- }
3041
- function closeRetiredSharedClientEntry(entry) {
3042
- const client = entry.client;
3043
- if (!client) return false;
3044
- entry.client = void 0;
3045
- client.close();
3046
- return true;
3047
- }
3048
- function closeSharedClientEntryIfUnclaimed(key, entry) {
3049
- if (entry.activeLeases > 0 || entry.pendingAcquires > 0) return false;
3050
- const state = getSharedCodexAppServerClientState();
3051
- if (state.clients.get(key) !== entry) return false;
3052
- state.clients.delete(key);
3053
- entry.client?.close();
3054
- return Boolean(entry.client);
3055
- }
3056
- function retirePendingSharedClientEntryIfUnclaimed(key, entry) {
3057
- if (entry.activeLeases > 0 || entry.pendingAcquires > 0) return;
3058
- entry.runtimeArtifactStartupAbort?.abort(/* @__PURE__ */ new Error("Codex runtime artifact startup was abandoned"));
3059
- entry.closeWhenIdle = true;
3060
- const state = getSharedCodexAppServerClientState();
3061
- if (state.clients.get(key) === entry) state.clients.delete(key);
3062
- if (!entry.client) return;
3063
- closeRetiredSharedClientEntry(entry);
3064
- }
3065
- function collectSharedClients(state) {
3066
- return [...new Set([...state.clients.values()].map((entry) => entry.client).filter((client) => Boolean(client)))];
3067
- }
3068
- //#endregion
3069
- export { resolveCodexTurnAssistantCompletionIdleTimeoutMs as $, retainCodexAppServerLiveThread as A, CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES as B, isCodexAppServerIndeterminateRequestCancellationError as C, resolveCodexAppServerClientInstanceId as D, isCodexAppServerRequestTimeoutError as E, resolveCodexAppServerAuthProfileId as F, resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath as G, CODEX_OPENCLAW_DIRECT_DYNAMIC_TOOL_NAMESPACE as H, resolveCodexAppServerAuthProfileIdForAgent as I, CodexAppServerStartupError as J, resolveCodexAppServerHomeDir as K, resolveCodexAppServerFallbackApiKeyCacheKey as L, readRecentCodexRateLimits as M, rememberCodexRateLimitsRead as N, consumeCodexAppServerLiveThread as O, resolveCodexAppServerAuthAccountCacheKey as P, resolveCodexStartupTimeoutMs as Q, resolveCodexAppServerPreparedApiKeyCacheKey as R, isCodexAppServerConnectionClosedError as S, isCodexAppServerPrewriteRequestCancellationError as T, flattenCodexDynamicToolFunctions as U, CODEX_INTERACTIVE_THREAD_SOURCE_KINDS as V, isJsonObject$1 as W, resolveCodexGatewayTimeoutWithGraceMs as X, isCodexAppServerStartupError as Y, resolveCodexPostToolRawAssistantCompletionIdleTimeoutMs as Z, acquireCodexNativeConfigFence as _, getLeasedSharedCodexAppServerClient as a, isCodexAppServerApprovalRequest as b, releaseCodexAppServerClientLease as c, retainSharedCodexAppServerClientByInstanceId as d, resolveCodexTurnCompletionIdleTimeoutMs as et, retainSharedCodexAppServerClientIfCurrent as f, withTimeout$1 as g, withLeasedCodexAppServerClientStartSelectionRetry as h, createIsolatedCodexAppServerClient as i, readCodexRateLimitsRevision as j, ensureCodexAppServerClientRuntime as k, releaseLeasedSharedCodexAppServerClient as l, shared_client_exports as m, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as n, withCodexStartupTimeout as nt, getSharedCodexAppServerClient as o, retireSharedCodexAppServerClientIfCurrent as p, CODEX_POST_REASONING_REPLY_IDLE_TIMEOUT_MS as q, clearSharedCodexAppServerClientIfCurrentAndWait as r, isCodexAppServerStartSelectionChangedError as s, clearSharedCodexAppServerClientIfCurrent as t, resolveCodexTurnTerminalIdleTimeoutMs as tt, resolveCodexNativeConfigFenceKey as u, CodexAppServerRpcError as v, isCodexAppServerIndeterminateTransportError as w, isCodexAppServerBrokenPipeError as x, getCodexAppServerClientInstanceId as y, resolveCodexAppServerPreparedAuthHandoff as z };