@openclaw/codex 2026.7.2-beta.4 → 2026.7.2-beta.7

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 (40) hide show
  1. package/dist/{app-server-policy-BO3jYBkv.js → app-server-policy-BSaO2JIT.js} +1 -1
  2. package/dist/{attempt-notifications-DdmnBMUp.js → attempt-notifications-AP-a-Q5k.js} +1 -1
  3. package/dist/{bounded-turn-CaQL96kg.js → bounded-turn-D2ZAgZVz.js} +54 -24
  4. package/dist/{capabilities-CLICvTxf.js → capabilities-BFDTVYr4.js} +1 -1
  5. package/dist/cli-metadata.js +1 -1
  6. package/dist/{command-formatters-DgADqnHa.js → command-formatters-C336eRVS.js} +2 -2
  7. package/dist/{command-handlers-l_lVPNlB.js → command-handlers-DAHUSry9.js} +1233 -1222
  8. package/dist/{compact-CC5KhBzX.js → compact-D_uvHurS.js} +8 -8
  9. package/dist/{computer-use-Ip1-QGa-.js → computer-use-CYEc8U3w.js} +123 -115
  10. package/dist/{conversation-control-sNPsbTCP.js → conversation-control-xsIeXbo4.js} +6 -6
  11. package/dist/doctor-contract-api.js +24 -86
  12. package/dist/{dynamic-tools-CQI3UwqY.js → dynamic-tools-D2gYkSBO.js} +482 -91
  13. package/dist/effective-mcp-catalog-Bbd98Inw.js +114 -0
  14. package/dist/{event-projector-usage-D6tE7_qD.js → event-projector-usage-Xp4AlR2k.js} +20 -3
  15. package/dist/harness.js +19 -14
  16. package/dist/index.js +292 -328
  17. package/dist/media-understanding-provider.js +6 -1
  18. package/dist/{models-BNeMlHgg.js → models-BBMKU4jA.js} +2 -2
  19. package/dist/{notification-correlation-BGLixv5_.js → notification-correlation-CU6_AnOb.js} +3 -3
  20. package/dist/{plugin-app-cache-key-CvzvmBRz.js → plugin-app-cache-key-DztPafOA.js} +135 -42
  21. package/dist/{rate-limits-D0IJT-a6.js → rate-limits-CU-gVCCS.js} +1 -1
  22. package/dist/{request-BTccUTD3.js → request-qKh331yu.js} +3 -3
  23. package/dist/{run-attempt--858NXDl.js → run-attempt-CY9WlDLc.js} +1060 -402
  24. package/dist/{runtime-artifact-C2ITXdhM.js → runtime-artifact-CmtG_t1L.js} +90 -24
  25. package/dist/{sandbox-guard-D1Wky__S.js → sandbox-guard-NuhpXmPB.js} +4 -0
  26. package/dist/{session-binding-ZSMX1omP.js → session-binding-BXpo9ymA.js} +1006 -891
  27. package/dist/{session-catalog-DsKaezgR.js → session-catalog-DyOgR4WH.js} +289 -56
  28. package/dist/{session-cli-CYJTfRLG.js → session-cli-2PZaFLRh.js} +2 -2
  29. package/dist/{session-upstream-marker-D7XlI9us.js → session-upstream-marker-B6U7tLw5.js} +1 -1
  30. package/dist/{settled-turn-finalizer-DHltNgtF.js → settled-turn-finalizer-CXY2Z9dT.js} +19 -6
  31. package/dist/{shared-client-wmgNFNYp.js → shared-client-DTbvH-XV.js} +1993 -1720
  32. package/dist/{side-question-BfFZCsJ-.js → side-question-_ulBk1AL.js} +12 -10
  33. package/dist/{thread-lifecycle-cqrOlJkq.js → thread-lifecycle-DF53ogiA.js} +980 -346
  34. package/dist/{transcript-mirror-2p7kl6e4.js → transcript-mirror-DzsdNCf5.js} +80 -41
  35. package/dist/{upstream-session-fork-vPjwkT1i.js → upstream-session-fork-Dy4Xvuoj.js} +3 -3
  36. package/dist/{usage-DM_I3mPT.js → usage-CQ6GhD5-.js} +3 -3
  37. package/dist/{web-search-provider.runtime-Bx6HAc_k.js → web-search-provider.runtime-CCFhg2z5.js} +3 -3
  38. package/package.json +6 -8
  39. package/npm-shrinkwrap.json +0 -202
  40. package/dist/{auth-binding-C1czuHPA.js → auth-binding-B4FfbcCg.js} +1 -1
@@ -1,1865 +1,2059 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { C as resolveCodexAppServerUserHomeDir, S as resolveCodexAppServerStartOptionsForAgent, h as codexAppServerStartOptionsKey, o as isCodexAppServerNativeAuthProfile, w as resolveCodexComputerUseConfig, x as resolveCodexAppServerRuntimeOptions } from "./session-binding-ZSMX1omP.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
3
  import { n as resolveCodexAppServerSpawnEnv, t as createStdioTransport } from "./transport-stdio-DXgGZ7Ib.js";
4
4
  import { createRequire } from "node:module";
5
5
  import fs, { access } from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { addTimerTimeoutGraceMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
8
- import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
8
+ import { AgentHarnessPreflightError, OPENCLAW_VERSION, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
9
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";
10
12
  import fsSync, { constants, existsSync, readFileSync, realpathSync } from "node:fs";
11
13
  import os from "node:os";
12
- import { ensureAuthProfileStore, findPersistedAuthProfileCredential, loadAuthProfileStoreForSecretsRuntime, refreshOAuthCredentialForRuntime, resolveApiKeyForProfile, resolveAuthProfileOrder, resolveDefaultAgentDir, resolvePersistedAuthProfileOwnerAgentDir, resolveProviderIdForAuth } from "openclaw/plugin-sdk/agent-runtime";
13
- import { OPENCLAW_VERSION, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
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";
14
18
  import { createInterface } from "node:readline";
15
- import { parse } from "semver";
19
+ import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
16
20
  import { EventEmitter } from "node:events";
17
21
  import net from "node:net";
18
22
  import { PassThrough, Writable } from "node:stream";
19
23
  import { StringDecoder } from "node:string_decoder";
20
24
  import WebSocket from "ws";
21
- import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
22
- import { isDeepStrictEqual } from "node:util";
23
- import { hasUsableOAuthCredential } from "openclaw/plugin-sdk/provider-auth";
24
25
  import { fileURLToPath } from "node:url";
25
26
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
26
27
  import { withTimeout } from "openclaw/plugin-sdk/security-runtime";
27
- //#region extensions/codex/src/app-server/protocol.ts
28
- /** Namespace Codex keeps directly model-visible without exposing it to Code Mode guests. */
29
- const CODEX_OPENCLAW_DIRECT_DYNAMIC_TOOL_NAMESPACE = "openclaw_direct";
30
- function flattenCodexDynamicToolFunctions(tools) {
31
- return (tools ?? []).flatMap((tool) => tool.type === "namespace" ? tool.tools : [tool]);
32
- }
33
- const CODEX_INTERACTIVE_THREAD_SOURCE_KINDS = ["cli", "vscode"];
34
- const CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES = ["atlas", "chatgpt"];
35
- function isJsonObject$1(value) {
36
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
37
- }
38
- function isRpcResponse(message) {
39
- return "id" in message && !("method" in message);
40
- }
41
- //#endregion
42
- //#region extensions/codex/src/app-server/transport-websocket.ts
28
+ //#region extensions/codex/src/app-server/attempt-timeouts.ts
43
29
  /**
44
- * Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
45
- * transport interface.
30
+ * Timeout defaults and normalizers for Codex app-server startup and turn
31
+ * liveness watches.
46
32
  */
47
- /** Opens a WebSocket app-server transport and maps newline-delimited frames to stdout/stdin. */
48
- function createWebSocketTransport(options) {
49
- if (!options.url) throw new Error("codex app-server websocket transport requires plugins.entries.codex.config.appServer.url");
50
- const events = new EventEmitter();
51
- const stdout = new PassThrough();
52
- const stderr = new PassThrough();
53
- const websocketOptions = {
54
- headers: {
55
- ...options.headers,
56
- ...options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}
57
- },
58
- perMessageDeflate: false
59
- };
60
- const unixSocketPath = resolveCodexAppServerUnixSocketPath(options);
61
- const socket = unixSocketPath ? new WebSocket("ws://localhost/", {
62
- ...websocketOptions,
63
- createConnection: () => connectCodexAppServerUnixSocket(unixSocketPath)
64
- }) : new WebSocket(options.url, websocketOptions);
65
- const pendingFrames = [];
66
- const stdinDecoder = new StringDecoder("utf8");
67
- let pendingLine = "";
68
- let killed = false;
69
- const sendFrame = (frame) => {
70
- const trimmed = frame.trim();
71
- if (!trimmed) return;
72
- if (socket.readyState === WebSocket.OPEN) {
73
- socket.send(trimmed);
74
- return;
75
- }
76
- pendingFrames.push(trimmed);
77
- };
78
- socket.once("open", () => {
79
- for (const frame of pendingFrames.splice(0)) socket.send(frame);
80
- });
81
- socket.once("error", (error) => events.emit("error", error));
82
- socket.once("close", (code, reason) => {
83
- killed = true;
84
- events.emit("exit", code, reason.toString("utf8"));
85
- });
86
- socket.on("message", (data) => {
87
- const text = websocketFrameToText(data);
88
- stdout.write(text.endsWith("\n") ? text : `${text}\n`);
89
- });
90
- const stdin = new Writable({
91
- write(chunk, _encoding, callback) {
92
- pendingLine += stdinDecoder.write(chunk);
93
- const lines = pendingLine.split("\n");
94
- pendingLine = lines.pop() ?? "";
95
- for (const frame of lines) sendFrame(frame);
96
- callback();
97
- },
98
- final(callback) {
99
- pendingLine += stdinDecoder.end();
100
- if (pendingLine) sendFrame(pendingLine);
101
- pendingLine = "";
102
- callback();
103
- }
104
- });
105
- const closeSocket = () => {
106
- if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
107
- socket.close();
108
- };
109
- stdin.once("finish", closeSocket);
110
- stdin.once("close", closeSocket);
111
- return {
112
- stdin,
113
- stdout,
114
- stderr,
115
- get killed() {
116
- return killed;
117
- },
118
- kill: () => {
119
- killed = true;
120
- socket.close();
121
- },
122
- once: (event, listener) => events.once(event, listener)
123
- };
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);
124
54
  }
125
- /** Opens the owner-scoped Codex control socket used by the WebSocket upgrade. */
126
- function connectCodexAppServerUnixSocket(socketPath) {
127
- return net.createConnection(socketPath);
55
+ function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
56
+ return resolveTimerTimeoutMs(value, resolveTimerTimeoutMs(fallbackMs, 1));
128
57
  }
129
- /** Resolves the canonical or explicitly configured Codex control socket. */
130
- function resolveCodexAppServerUnixSocketPath(options) {
131
- if (options.transport !== "unix") {
132
- if (options.url?.startsWith("unix://")) throw new Error("codex app-server unix URL requires unix transport");
133
- return;
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?.();
134
94
  }
135
- const url = options.url ?? "unix://";
136
- if (!url.startsWith("unix://")) throw new Error("codex app-server unix transport requires a unix:// URL");
137
- return url.slice(7) || path.join(resolveCodexAppServerUserHomeDir(options.env ?? process.env), "app-server-control", "app-server-control.sock");
138
95
  }
139
- function websocketFrameToText(data) {
140
- if (typeof data === "string") return data;
141
- if (Buffer.isBuffer(data)) return data.toString("utf8");
142
- if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
143
- return Buffer.from(data).toString("utf8");
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);
144
101
  }
145
- //#endregion
146
- //#region extensions/codex/src/app-server/transport.ts
147
- /** Starts graceful transport shutdown and schedules a force kill fallback. */
148
- function closeCodexAppServerTransport(child, options = {}) {
149
- child.stdin.end?.();
150
- child.stdin.destroy?.();
151
- const forceKillDelayMs = options.forceKillDelayMs ?? 1e3;
152
- const forceKill = setTimeout(() => {
153
- if (hasCodexAppServerTransportExited(child)) return;
154
- signalCodexAppServerTransport(child, "SIGKILL");
155
- }, Math.max(1, forceKillDelayMs));
156
- forceKill.unref?.();
157
- child.once("exit", () => {
158
- clearTimeout(forceKill);
159
- child.stdout.destroy?.();
160
- child.stderr.destroy?.();
161
- });
162
- child.unref?.();
163
- child.stdout.unref?.();
164
- child.stderr.unref?.();
165
- child.stdin.unref?.();
102
+ /** Resolves the completion-idle timeout for an active turn. */
103
+ function resolveCodexTurnCompletionIdleTimeoutMs(value) {
104
+ return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS);
166
105
  }
167
- /** Closes a transport and waits briefly for an exit event. */
168
- async function closeCodexAppServerTransportAndWait(child, options = {}) {
169
- if (!hasCodexAppServerTransportExited(child)) closeCodexAppServerTransport(child, options);
170
- return await waitForCodexAppServerTransportExit(child, options.exitTimeoutMs ?? 2e3);
106
+ /** Resolves the short assistant-completion release timeout. */
107
+ function resolveCodexTurnAssistantCompletionIdleTimeoutMs(value) {
108
+ return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS);
171
109
  }
172
- function hasCodexAppServerTransportExited(child) {
173
- return child.exitCode !== null && child.exitCode !== void 0 ? true : child.signalCode !== null && child.signalCode !== void 0;
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));
174
113
  }
175
- async function waitForCodexAppServerTransportExit(child, timeoutMs) {
176
- if (hasCodexAppServerTransportExited(child)) return true;
177
- return await new Promise((resolve) => {
178
- let settled = false;
179
- const onExit = () => {
180
- if (settled) return;
181
- settled = true;
182
- clearTimeout(timeout);
183
- resolve(true);
184
- };
185
- const timeout = setTimeout(() => {
186
- if (settled) return;
187
- settled = true;
188
- child.off?.("exit", onExit);
189
- resolve(false);
190
- }, Math.max(1, timeoutMs));
191
- child.once("exit", onExit);
192
- });
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));
193
118
  }
194
- function signalCodexAppServerTransport(child, signal) {
195
- if (child.pid && process.platform !== "win32") try {
196
- process.kill(-child.pid, signal);
197
- return;
198
- } catch {}
199
- child.kill?.(signal);
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;
200
123
  }
201
124
  //#endregion
202
- //#region extensions/codex/src/app-server/version.ts
203
- /**
204
- * Version and package pins for the managed Codex app-server runtime.
205
- */
206
- /** Minimum Codex app-server version supported by the OpenClaw Codex bridge. */
207
- const MIN_CODEX_APP_SERVER_VERSION = "0.143.0";
208
- /** Newest Codex app-server version validated by the OpenClaw Codex bridge. */
209
- const MAX_CODEX_APP_SERVER_VERSION = "0.145.0";
210
- /** npm package name for the managed Codex app-server binary. */
211
- const MANAGED_CODEX_APP_SERVER_PACKAGE = "@openai/codex";
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
+ }
212
145
  //#endregion
213
- //#region extensions/codex/src/app-server/client.ts
214
- /**
215
- * JSON-RPC client for Codex app-server transports, including request/response
216
- * routing, notification fanout, server request handlers, and version checks.
217
- */
218
- /** Minimum supported Codex app-server version exported for callers/tests. */
219
- const CODEX_APP_SERVER_PARSE_LOG_MAX = 500;
220
- const CODEX_APP_SERVER_PARSE_BUFFER_MAX = 8 * 1024 * 1024;
221
- const CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES = 1e3;
222
- const CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS = 66e4;
223
- const CODEX_APP_SERVER_STDERR_TAIL_MAX = 2e3;
224
- const CODEX_APP_SERVER_OVERLOADED_ERROR_CODE = -32001;
225
- const CODEX_APP_SERVER_OVERLOAD_MAX_RETRIES = 3;
226
- const CODEX_APP_SERVER_OVERLOAD_RETRY_BASE_MS = 50;
227
- const CODEX_APP_SERVER_CLIENT_INSTANCE_IDS = /* @__PURE__ */ new WeakMap();
228
- const UNPAIRED_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
229
- /** Process-local generation fence for bindings tied to one app-server client instance. */
230
- function getCodexAppServerClientInstanceId(client) {
231
- const current = CODEX_APP_SERVER_CLIENT_INSTANCE_IDS.get(client);
232
- if (current) return current;
233
- const created = randomUUID();
234
- CODEX_APP_SERVER_CLIENT_INSTANCE_IDS.set(client, created);
235
- return created;
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) : [];
236
163
  }
237
- function resolveCodexAppServerClientInstanceId(client) {
238
- return client.getInstanceId?.call(client) ?? getCodexAppServerClientInstanceId(client);
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))];
239
169
  }
240
- /** RPC error wrapper that preserves app-server error code and data. */
241
- var CodexAppServerRpcError = class extends Error {
242
- constructor(error, method) {
243
- super(formatCodexAppServerRpcErrorMessage(error, method));
244
- this.name = "CodexAppServerRpcError";
245
- this.code = error.code;
246
- this.data = error.data;
247
- this.method = method;
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;
248
212
  }
249
- };
250
- var CodexAppServerLocalRequestCancellationError = class extends Error {
251
- constructor(method, reason, mayHaveWritten) {
252
- super(`${method} ${reason}`);
253
- this.reason = reason;
254
- this.mayHaveWritten = mayHaveWritten;
255
- this.code = "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED";
256
- this.name = "CodexAppServerLocalRequestCancellationError";
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;
257
218
  }
258
- };
259
- function isCodexAppServerRequestTimeoutError(error) {
260
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED" && "reason" in error && error.reason === "timed out";
261
219
  }
262
- function isCodexAppServerBrokenPipeError(error) {
263
- const seen = /* @__PURE__ */ new Set();
264
- let current = error;
265
- while (current && typeof current === "object" && !seen.has(current)) {
266
- seen.add(current);
267
- if ("code" in current && current.code === "EPIPE") return true;
268
- current = "cause" in current ? current.cause : void 0;
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;
269
225
  }
270
- return false;
271
- }
272
- var CodexAppServerIndeterminateTransportError = class extends Error {
273
- constructor(method, cause) {
274
- super(`${method} transport failed after request write: ${cause.message}`, { cause });
275
- this.code = "CODEX_APP_SERVER_REQUEST_TRANSPORT_INDETERMINATE";
276
- this.mayHaveWritten = true;
277
- this.name = "CodexAppServerIndeterminateTransportError";
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
+ });
278
259
  }
279
- };
280
- /** True when a local cancellation can leave an app-server request in flight. */
281
- function isCodexAppServerIndeterminateRequestCancellationError(error) {
282
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED" && "mayHaveWritten" in error && error.mayHaveWritten === true;
283
260
  }
284
- /** True when local cancellation happened before a request write was attempted. */
285
- function isCodexAppServerPrewriteRequestCancellationError(error) {
286
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_LOCAL_REQUEST_CANCELLED" && "mayHaveWritten" in error && error.mayHaveWritten === false;
261
+ function skippedCacheResult(status, message) {
262
+ return {
263
+ status,
264
+ changed: false,
265
+ message,
266
+ removedStaleVersions: [],
267
+ warnings: status === "source_missing" ? [message] : []
268
+ };
287
269
  }
288
- /** True when transport failure cannot prove a written request stopped running. */
289
- function isCodexAppServerIndeterminateTransportError(error) {
290
- return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_REQUEST_TRANSPORT_INDETERMINATE" && "mayHaveWritten" in error && error.mayHaveWritten === true;
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
+ }
291
298
  }
292
- function formatCodexAppServerRpcErrorMessage(error, method) {
293
- const message = error.message || `${method} failed`;
294
- const detail = readCodexAppServerRpcReloginDetail(error.data);
295
- return detail && !message.includes(detail) ? `${message}: ${detail}` : message;
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
+ }
296
377
  }
297
- function readCodexAppServerRpcReloginDetail(data) {
298
- const record = isJsonObject(data) ? data : void 0;
299
- const nested = isJsonObject(record?.error) ? record.error : record;
300
- if (!nested) return;
301
- const isRelogin = nested.action === "relogin" || nested.reason === "cloudRequirements" && nested.errorCode === "Auth";
302
- const detail = typeof nested.detail === "string" ? nested.detail.trim() : "";
303
- return isRelogin && detail ? detail : void 0;
378
+ async function pathExists$1(filePath) {
379
+ return await fs.lstat(filePath).then(() => true, () => false);
304
380
  }
305
- function isJsonObject(value) {
306
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
381
+ async function findUsableServiceApp(candidates) {
382
+ for (const candidate of candidates) if (await hasExecutableClient(candidate)) return candidate;
307
383
  }
308
- /** Returns true for errors that mean the app-server transport is closed. */
309
- function isCodexAppServerConnectionClosedError(error) {
310
- if (!(error instanceof Error)) return false;
311
- if (isCodexAppServerIndeterminateTransportError(error)) return true;
312
- return error.message === "codex app-server client is closed" || error.message.startsWith("codex app-server exited:");
313
- }
314
- /** Stateful app-server JSON-RPC client over stdio or websocket transport. */
315
- var CodexAppServerClient = class CodexAppServerClient {
316
- constructor(child) {
317
- this.instanceId = randomUUID();
318
- this.pending = /* @__PURE__ */ new Map();
319
- this.requestHandlers = /* @__PURE__ */ new Set();
320
- this.notificationHandlers = /* @__PURE__ */ new Set();
321
- this.closeHandlers = /* @__PURE__ */ new Set();
322
- this.nextId = 1;
323
- this.initialized = false;
324
- this.closed = false;
325
- this.transportExited = false;
326
- this.stderrTail = "";
327
- this.child = child;
328
- this.lines = createInterface({ input: child.stdout });
329
- this.lines.on("line", (line) => this.handleLine(line));
330
- this.lines.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
331
- child.stdout.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
332
- child.stderr.setEncoding("utf8");
333
- child.stderr.on("data", (text) => {
334
- this.stderrTail = appendBoundedTail(this.stderrTail, text, CODEX_APP_SERVER_STDERR_TAIL_MAX);
335
- const trimmed = text.trim();
336
- if (trimmed) embeddedAgentLog.debug(`codex app-server stderr: ${trimmed}`);
337
- });
338
- child.stderr.on("error", (error) => {
339
- embeddedAgentLog.warn("codex app-server stderr stream failed", { error });
340
- });
341
- child.once("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
342
- child.once("exit", (code, signal) => {
343
- this.transportExited = true;
344
- this.closeWithError(buildCodexAppServerExitError(code, signal, this.stderrTail));
345
- });
346
- child.stdin.on?.("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
347
- }
348
- /** Starts a new app-server client using resolved runtime start options. */
349
- static start(options) {
350
- const defaults = resolveCodexAppServerRuntimeOptions().start;
351
- const startOptions = {
352
- ...defaults,
353
- ...options,
354
- headers: options?.headers ?? defaults.headers
355
- };
356
- if (startOptions.transport === "stdio" && startOptions.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
357
- if (startOptions.transport === "websocket" || startOptions.transport === "unix") return new CodexAppServerClient(createWebSocketTransport(startOptions));
358
- return new CodexAppServerClient(createStdioTransport(startOptions));
359
- }
360
- /** Builds a client around a fake transport for tests. */
361
- static fromTransportForTests(child) {
362
- return new CodexAppServerClient(child);
363
- }
364
- /** Performs the app-server initialize handshake and validates protocol version. */
365
- async initialize() {
366
- if (this.initialized) return;
367
- const response = await this.request("initialize", {
368
- clientInfo: {
369
- name: "openclaw",
370
- title: "OpenClaw",
371
- version: OPENCLAW_VERSION
372
- },
373
- capabilities: { experimentalApi: true }
374
- });
375
- this.serverVersion = assertSupportedCodexAppServerVersion(response);
376
- this.runtimeIdentity = buildCodexAppServerRuntimeIdentity(response, this.serverVersion);
377
- this.notify("initialized");
378
- this.initialized = true;
379
- }
380
- /** Returns the version detected during initialize. */
381
- getServerVersion() {
382
- return this.serverVersion;
383
- }
384
- /** Returns runtime metadata detected during initialize. */
385
- getRuntimeIdentity() {
386
- return this.runtimeIdentity ? { ...this.runtimeIdentity } : void 0;
387
- }
388
- /** Stable generation id for this exact physical client instance. */
389
- getInstanceId() {
390
- return this.instanceId;
391
- }
392
- /** Installs the spawn-owner check run before config-loading thread requests. */
393
- setThreadSessionRequestGuard(guard) {
394
- this.threadSessionRequestGuard = guard;
395
- }
396
- /** Returns the local transport PID for scoped child-process cleanup, when available. */
397
- getTransportPid() {
398
- return this.child.pid;
399
- }
400
- request(method, params, optionsInput) {
401
- let options = optionsInput;
402
- options ??= {};
403
- if (this.closed) return Promise.reject(this.closeError ?? /* @__PURE__ */ new Error("codex app-server client is closed"));
404
- if (options.signal?.aborted) return Promise.reject(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
405
- const guard = method === "thread/start" || method === "thread/resume" || method === "thread/fork" ? this.threadSessionRequestGuard : void 0;
406
- if (guard) {
407
- 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`));
408
- return (async () => {
409
- const guardStartedAt = Date.now();
410
- const timeoutMessage = `${method} timed out`;
411
- const abortMessage = `${method} aborted`;
412
- let releaseGuard;
413
- try {
414
- releaseGuard = await guard({
415
- signal: options.signal,
416
- timeoutMs: options.timeoutMs,
417
- timeoutMessage,
418
- abortMessage
419
- });
420
- } catch (error) {
421
- if (error instanceof Error && error.message === timeoutMessage) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
422
- if (error instanceof Error && error.message === abortMessage) throw new CodexAppServerLocalRequestCancellationError(method, "aborted", false);
423
- throw error;
424
- }
425
- let released = false;
426
- const release = () => {
427
- if (released) return;
428
- released = true;
429
- releaseGuard();
430
- };
431
- let releaseWhenRequestSettles = true;
432
- let requestMayHaveWritten = false;
433
- try {
434
- const elapsedMs = Date.now() - guardStartedAt;
435
- const remainingTimeoutMs = options.timeoutMs === void 0 ? void 0 : options.timeoutMs - elapsedMs;
436
- if (remainingTimeoutMs !== void 0 && remainingTimeoutMs <= 0) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
437
- return await this.requestWithoutThreadSessionGuard(method, params, {
438
- ...options,
439
- ...remainingTimeoutMs !== void 0 ? { timeoutMs: remainingTimeoutMs } : {}
440
- }, () => {
441
- requestMayHaveWritten = true;
442
- });
443
- } catch (error) {
444
- if (requestMayHaveWritten && !(error instanceof CodexAppServerRpcError)) {
445
- releaseWhenRequestSettles = false;
446
- await this.closeAndRunAfterExit(release, method);
447
- }
448
- throw error;
449
- } finally {
450
- if (releaseWhenRequestSettles) release();
451
- }
452
- })();
453
- }
454
- return this.requestWithoutThreadSessionGuard(method, params, options);
455
- }
456
- requestWithoutThreadSessionGuard(method, params, options, onWriteAttempt) {
457
- return this.requestWithOverloadRetry(method, params, options, onWriteAttempt);
458
- }
459
- async requestWithOverloadRetry(method, params, options, onWriteAttempt) {
460
- const deadline = options.timeoutMs !== void 0 && Number.isFinite(options.timeoutMs) ? Date.now() + options.timeoutMs : void 0;
461
- for (let retry = 0;; retry += 1) {
462
- if (options.signal?.aborted) throw new CodexAppServerLocalRequestCancellationError(method, "aborted", false);
463
- const remainingTimeoutMs = deadline === void 0 ? void 0 : deadline - Date.now();
464
- if (remainingTimeoutMs !== void 0 && remainingTimeoutMs <= 0) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
465
- try {
466
- return await this.requestOnce(method, params, {
467
- ...options,
468
- ...remainingTimeoutMs !== void 0 ? { timeoutMs: remainingTimeoutMs } : {}
469
- }, onWriteAttempt);
470
- } catch (error) {
471
- if (!(error instanceof CodexAppServerRpcError) || error.code !== CODEX_APP_SERVER_OVERLOADED_ERROR_CODE || retry >= CODEX_APP_SERVER_OVERLOAD_MAX_RETRIES) throw error;
472
- const backoffMs = Math.round(CODEX_APP_SERVER_OVERLOAD_RETRY_BASE_MS * 2 ** retry * (.75 + Math.random() * .5));
473
- await this.waitForOverloadRetry(method, backoffMs, deadline, options.signal);
474
- }
475
- }
476
- }
477
- async waitForOverloadRetry(method, backoffMs, deadline, signal) {
478
- if (signal?.aborted) throw new CodexAppServerLocalRequestCancellationError(method, "aborted", false);
479
- const remainingMs = deadline === void 0 ? void 0 : deadline - Date.now();
480
- if (remainingMs !== void 0 && remainingMs <= 0) throw new CodexAppServerLocalRequestCancellationError(method, "timed out", false);
481
- const delayMs = remainingMs === void 0 ? backoffMs : Math.min(backoffMs, remainingMs);
482
- await new Promise((resolve, reject) => {
483
- const timer = setTimeout(() => {
484
- cleanup();
485
- resolve();
486
- }, delayMs);
487
- timer.unref?.();
488
- const abortListener = () => {
489
- cleanup();
490
- reject(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
491
- };
492
- const cleanup = () => {
493
- clearTimeout(timer);
494
- signal?.removeEventListener("abort", abortListener);
495
- };
496
- signal?.addEventListener("abort", abortListener, { once: true });
497
- if (signal?.aborted) abortListener();
498
- });
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;
499
390
  }
500
- requestOnce(method, params, options, onWriteAttempt) {
501
- if (this.closed) return Promise.reject(this.closeError ?? /* @__PURE__ */ new Error("codex app-server client is closed"));
502
- if (options.signal?.aborted) return Promise.reject(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
503
- const id = this.nextId++;
504
- const message = {
505
- id,
506
- method,
507
- params
508
- };
509
- return new Promise((resolve, reject) => {
510
- let timeout;
511
- let cleanupAbort;
512
- let mayHaveWritten = false;
513
- const cleanup = () => {
514
- if (timeout) {
515
- clearTimeout(timeout);
516
- timeout = void 0;
517
- }
518
- cleanupAbort?.();
519
- cleanupAbort = void 0;
520
- };
521
- const rejectPending = (error) => {
522
- if (!this.pending.has(id)) return;
523
- this.pending.delete(id);
524
- cleanup();
525
- reject(mayHaveWritten && !(error instanceof CodexAppServerRpcError) && !isCodexAppServerIndeterminateRequestCancellationError(error) && !isCodexAppServerIndeterminateTransportError(error) ? new CodexAppServerIndeterminateTransportError(method, error) : error);
526
- };
527
- if (options.timeoutMs && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0) {
528
- timeout = setTimeout(() => rejectPending(new CodexAppServerLocalRequestCancellationError(method, "timed out", mayHaveWritten)), Math.max(100, options.timeoutMs));
529
- timeout.unref?.();
530
- }
531
- if (options.signal) {
532
- const abortListener = () => rejectPending(new CodexAppServerLocalRequestCancellationError(method, "aborted", mayHaveWritten));
533
- options.signal.addEventListener("abort", abortListener, { once: true });
534
- cleanupAbort = () => options.signal?.removeEventListener("abort", abortListener);
535
- }
536
- this.pending.set(id, {
537
- method,
538
- resolve: (value) => {
539
- cleanup();
540
- resolve(value);
541
- },
542
- reject: (error) => {
543
- cleanup();
544
- reject(mayHaveWritten && !(error instanceof CodexAppServerRpcError) && !isCodexAppServerIndeterminateRequestCancellationError(error) && !isCodexAppServerIndeterminateTransportError(error) ? new CodexAppServerIndeterminateTransportError(method, error) : error);
545
- },
546
- cleanup
547
- });
548
- if (options.signal?.aborted) {
549
- rejectPending(new CodexAppServerLocalRequestCancellationError(method, "aborted", false));
550
- return;
551
- }
552
- try {
553
- mayHaveWritten = true;
554
- onWriteAttempt?.();
555
- this.writeMessage(message, (error) => rejectPending(error));
556
- } catch (error) {
557
- rejectPending(error instanceof Error ? error : new Error(String(error)));
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
558
537
  }
559
- });
560
- }
561
- /** Sends a fire-and-forget JSON-RPC notification to the app-server. */
562
- notify(method, params) {
563
- this.writeMessage({
564
- method,
565
- params
566
- });
567
- }
568
- /** Registers a handler for app-server requests sent back to OpenClaw. */
569
- addRequestHandler(handler) {
570
- this.requestHandlers.add(handler);
571
- return () => this.requestHandlers.delete(handler);
572
- }
573
- /** Registers a notification handler and returns its disposer. */
574
- addNotificationHandler(handler) {
575
- this.notificationHandlers.add(handler);
576
- return () => this.notificationHandlers.delete(handler);
577
- }
578
- /** Registers a close handler and returns its disposer. */
579
- addCloseHandler(handler) {
580
- this.closeHandlers.add(handler);
581
- return () => this.closeHandlers.delete(handler);
582
- }
583
- /** Closes the transport without waiting for process/socket shutdown. */
584
- close() {
585
- if (!this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"))) return;
586
- closeCodexAppServerTransport(this.child);
587
- }
588
- /** Closes the transport and waits for shutdown according to transport policy. */
589
- async closeAndWait(options) {
590
- this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"));
591
- return await closeCodexAppServerTransportAndWait(this.child, options);
592
- }
593
- /** Closes this transport and runs cleanup only after physical process exit. */
594
- async closeAndRunAfterExit(onExit, operation) {
595
- let settled = false;
596
- const runOnExit = () => {
597
- if (settled) return;
598
- settled = true;
599
- onExit();
600
538
  };
601
- if (this.transportExited) {
602
- runOnExit();
603
- return;
604
- }
605
- this.child.once("exit", runOnExit);
606
- try {
607
- if (await this.closeAndWait()) {
608
- this.child.off?.("exit", runOnExit);
609
- runOnExit();
610
- }
611
- } catch (closeError) {
612
- embeddedAgentLog.warn("codex app-server shutdown after indeterminate request failed", {
613
- closeError,
614
- operation
615
- });
616
- }
617
- }
618
- writeMessage(message, onError) {
619
- if (this.closed) return;
620
- const id = "id" in message ? message.id : void 0;
621
- const method = "method" in message ? message.method : void 0;
622
- this.child.stdin.write(`${stringifyCodexAppServerMessage(message)}\n`, (error) => {
623
- if (error) {
624
- embeddedAgentLog.warn("codex app-server write failed", {
625
- error,
626
- id,
627
- method
628
- });
629
- onError?.(error);
630
- }
631
- });
632
539
  }
633
- handleLine(line) {
634
- const rawLine = line.endsWith("\r") ? line.slice(0, -1) : line;
635
- if (this.pendingParse) {
636
- this.handlePendingParseLine(rawLine);
637
- return;
638
- }
639
- const trimmed = rawLine.trim();
640
- if (!trimmed) return;
641
- let parsed;
642
- try {
643
- parsed = JSON.parse(trimmed);
644
- } catch (error) {
645
- if (shouldBufferCodexAppServerParseFailure(trimmed, error)) {
646
- this.pendingParse = {
647
- text: trimmed,
648
- lineCount: 1,
649
- firstError: error
650
- };
651
- return;
652
- }
653
- logCodexAppServerParseFailure(trimmed, error, 1);
654
- return;
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
655
567
  }
656
- this.handleParsedMessage(parsed);
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);
657
593
  }
658
- handlePendingParseLine(line) {
659
- const pending = this.pendingParse;
660
- if (!pending) return;
661
- const candidate = `${pending.text}\\n${line}`;
662
- let parsed;
663
- try {
664
- parsed = JSON.parse(candidate);
665
- } catch (error) {
666
- const lineCount = pending.lineCount + 1;
667
- if (shouldBufferCodexAppServerParseFailure(candidate.trim(), error) && candidate.length <= CODEX_APP_SERVER_PARSE_BUFFER_MAX && lineCount <= CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES) {
668
- this.pendingParse = {
669
- text: candidate,
670
- lineCount,
671
- firstError: pending.firstError
672
- };
673
- return;
674
- }
675
- this.pendingParse = void 0;
676
- logCodexAppServerParseFailure(candidate, error, lineCount);
677
- return;
678
- }
679
- this.pendingParse = void 0;
680
- this.handleParsedMessage(parsed);
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);
681
601
  }
682
- handleParsedMessage(parsed) {
683
- if (!parsed || typeof parsed !== "object") return;
684
- const message = parsed;
685
- if (isRpcResponse(message)) {
686
- this.handleResponse(message);
687
- return;
688
- }
689
- if (!("method" in message)) return;
690
- if ("id" in message && message.id !== void 0) {
691
- this.handleServerRequest({
692
- id: message.id,
693
- method: message.method,
694
- params: message.params
695
- });
696
- return;
697
- }
698
- this.handleNotification({
699
- method: message.method,
700
- params: message.params
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
701
659
  });
660
+ } catch (error) {
661
+ throw new AgentHarnessPreflightError("Codex Computer Use client provisioning failed.", { cause: error });
702
662
  }
703
- handleResponse(response) {
704
- const pending = this.pending.get(response.id);
705
- if (!pending) return;
706
- this.pending.delete(response.id);
707
- if (response.error) {
708
- pending.reject(new CodexAppServerRpcError(response.error, pending.method));
709
- return;
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 } : {}
710
670
  }
711
- pending.resolve(response.result);
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;
712
687
  }
713
- async handleServerRequest(request) {
714
- try {
715
- const result = await this.runServerRequestHandlers(request);
716
- if (result !== void 0) {
717
- this.writeMessage({
718
- id: request.id,
719
- result
720
- });
721
- return;
722
- }
723
- this.writeMessage({
724
- id: request.id,
725
- result: defaultServerRequestResponse(request)
726
- });
727
- } catch (error) {
728
- const message = error instanceof Error ? error.message : String(error);
729
- embeddedAgentLog.warn("codex app-server server request handler failed", {
730
- id: request.id,
731
- method: request.method,
732
- error
733
- });
734
- this.writeMessage({
735
- id: request.id,
736
- error: {
737
- code: -32603,
738
- message
739
- }
740
- });
741
- }
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;
742
694
  }
743
- async runServerRequestHandlers(request) {
744
- const controller = new AbortController();
745
- const timeoutResponse = timeoutServerRequestResponse(request);
746
- if (!timeoutResponse) return await this.runServerRequestHandlersWithoutTimeout(request, controller.signal);
747
- let timeout;
748
- try {
749
- return await Promise.race([this.runServerRequestHandlersWithoutTimeout(request, controller.signal), new Promise((resolve) => {
750
- timeout = setTimeout(() => {
751
- embeddedAgentLog.warn("codex app-server server request timed out", {
752
- id: request.id,
753
- method: request.method,
754
- timeoutMs: CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS
755
- });
756
- controller.abort(/* @__PURE__ */ new Error("codex app-server server request timed out"));
757
- resolve(timeoutResponse);
758
- }, CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS);
759
- timeout.unref?.();
760
- })]);
761
- } finally {
762
- if (timeout) clearTimeout(timeout);
763
- }
695
+ if (params.authProfileId === null) {
696
+ await assertNativeCodexAccountMatchesRoute(params.client, params.authRequirement);
697
+ return;
764
698
  }
765
- async runServerRequestHandlersWithoutTimeout(request, signal) {
766
- for (const handler of this.requestHandlers) {
767
- if (signal.aborted) return;
768
- const result = await handler(request, signal);
769
- if (result !== void 0) return result;
770
- }
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;
771
710
  }
772
- handleNotification(notification) {
773
- for (const handler of this.notificationHandlers) Promise.resolve(handler(notification)).catch((error) => {
774
- embeddedAgentLog.warn("codex app-server notification handler failed", { error });
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
775
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;
776
860
  }
777
- closeWithError(error) {
778
- if (this.markClosed(error)) closeCodexAppServerTransport(this.child);
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;
779
868
  }
780
- markClosed(error) {
781
- if (this.closed) return false;
782
- this.closed = true;
783
- this.closeError = error;
784
- this.lines.close();
785
- this.rejectPendingRequests(error);
786
- return true;
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;
787
915
  }
788
- rejectPendingRequests(error) {
789
- for (const pending of this.pending.values()) {
790
- pending.cleanup();
791
- pending.reject(error);
792
- }
793
- this.pending.clear();
794
- for (const handler of this.closeHandlers) handler(this);
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);
795
968
  }
796
- };
797
- function defaultServerRequestResponse(request) {
798
- if (request.method === "item/tool/call") return {
799
- contentItems: [{
800
- type: "inputText",
801
- text: "OpenClaw did not register a handler for this app-server tool call."
802
- }],
803
- success: false
804
- };
805
- if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return { decision: "decline" };
806
- if (request.method === "item/permissions/requestApproval") return {
807
- permissions: {},
808
- scope: "turn"
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]
809
991
  };
810
- if (request.method === "item/tool/requestUserInput") return { answers: {} };
811
- if (request.method === "mcpServer/elicitation/request") return { action: "decline" };
812
- return {};
813
992
  }
814
- function stringifyCodexAppServerMessage(message) {
815
- return JSON.stringify(message, (_key, value) => typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value) ?? "null";
993
+ function readFirstNonEmptyEnv(env, keys) {
994
+ return readFirstNonEmptyEnvEntry(env, keys)?.value;
816
995
  }
817
- function timeoutServerRequestResponse(request) {
818
- if (request.method !== "item/tool/call") return;
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) {
819
1006
  return {
820
- contentItems: [{
821
- type: "inputText",
822
- text: `OpenClaw dynamic tool call timed out after ${CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS}ms before sending a response to Codex.`
823
- }],
824
- success: false
1007
+ type: "chatgptAuthTokens",
1008
+ accessToken,
1009
+ chatgptAccountId: resolveChatgptAccountId(profileId, credential),
1010
+ chatgptPlanType: resolveChatgptPlanType(credential)
825
1011
  };
826
1012
  }
827
- /** Raised when the initialize handshake detects an unsupported app-server version. */
828
- var CodexAppServerVersionError = class extends Error {
829
- constructor(detectedVersion) {
830
- const detected = detectedVersion ? `detected ${detectedVersion}` : "OpenClaw could not determine the running Codex version";
831
- super(`A stable Codex app-server from ${MIN_CODEX_APP_SERVER_VERSION} through ${MAX_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.`);
832
- this.name = "CodexAppServerVersionError";
833
- this.detectedVersion = detectedVersion;
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;
834
1025
  }
835
- };
836
- function assertSupportedCodexAppServerVersion(response) {
837
- const detectedVersion = readCodexVersionFromUserAgent(response.userAgent);
838
- const parsedVersion = parse(detectedVersion ?? "");
839
- if (!detectedVersion || !parsedVersion || parsedVersion.compare("0.143.0") < 0 || parsedVersion.compare("0.145.0") > 0 || parsedVersion.prerelease.length > 0 || parsedVersion.build.length > 0) throw new CodexAppServerVersionError(detectedVersion);
840
- return detectedVersion;
1026
+ return credential.email?.trim() || void 0;
841
1027
  }
842
- function isUnsupportedCodexAppServerVersionError(error) {
843
- return error instanceof CodexAppServerVersionError;
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
+ }
844
1048
  }
845
- function buildCodexAppServerRuntimeIdentity(response, serverVersion) {
846
- const userAgent = readNonEmptyInitializeString(response.userAgent);
847
- const codexHome = readNonEmptyInitializeString(response.codexHome);
848
- const platformFamily = readNonEmptyInitializeString(response.platformFamily);
849
- const platformOs = readNonEmptyInitializeString(response.platformOs);
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
+ };
850
1095
  return {
851
- serverVersion,
852
- ...userAgent ? { userAgent } : {},
853
- ...codexHome ? { codexHome } : {},
854
- ...platformFamily ? { platformFamily } : {},
855
- ...platformOs ? { platformOs } : {}
1096
+ ...currentEnvelope,
1097
+ rateLimits: nextPrimary,
1098
+ ...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
856
1099
  };
857
1100
  }
858
- function readNonEmptyInitializeString(value) {
859
- const trimmed = value?.trim();
860
- return trimmed ? trimmed : void 0;
861
- }
862
- /** Extracts the Codex version from the app-server initialize user-agent field. */
863
- function readCodexVersionFromUserAgent(userAgent) {
864
- return (userAgent?.match(/^[^/]+\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:[\s(]|$)/))?.[1];
865
- }
866
- function redactCodexAppServerLinePreview(value) {
867
- 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");
868
- return redacted.length > CODEX_APP_SERVER_PARSE_LOG_MAX ? `${truncateUtf16Safe(redacted, CODEX_APP_SERVER_PARSE_LOG_MAX)}...` : redacted;
869
- }
870
- function appendBoundedTail(current, next, maxLength) {
871
- const combined = `${current}${next}`;
872
- return combined.length > maxLength ? sliceUtf16Safe(combined, -maxLength) : combined;
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];
873
1110
  }
874
- function buildCodexAppServerExitError(code, signal, stderrTail) {
875
- const stderrPreview = redactCodexAppServerLinePreview(stderrTail);
876
- const suffix = stderrPreview ? ` stderr=${JSON.stringify(stderrPreview)}` : "";
877
- return /* @__PURE__ */ new Error(`codex app-server exited: code=${formatExitValue(code)} signal=${formatExitValue(signal)}${suffix}`);
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;
878
1121
  }
879
- function shouldBufferCodexAppServerParseFailure(value, error) {
880
- if (!value.startsWith("{") && !value.startsWith("[")) return false;
881
- const message = error instanceof Error ? error.message : String(error);
882
- return message.includes("Unterminated string") || message.includes("Unexpected end of JSON input");
1122
+ function readLimitId(snapshot) {
1123
+ const value = snapshot.limitId;
1124
+ return typeof value === "string" && value.trim() ? value.trim() : "codex";
883
1125
  }
884
- function logCodexAppServerParseFailure(value, error, fragmentCount) {
885
- const linePreview = redactCodexAppServerLinePreview(value);
886
- const suffix = fragmentCount > 1 ? ` fragments=${fragmentCount}` : "";
887
- embeddedAgentLog.warn("failed to parse codex app-server message", {
888
- error,
889
- errorMessage: error instanceof Error ? error.message : String(error),
890
- fragmentCount,
891
- linePreview,
892
- consoleMessage: `failed to parse codex app-server message${suffix}: preview=${JSON.stringify(linePreview)}`
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);
893
1151
  });
894
1152
  }
895
- const CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS = /* @__PURE__ */ new Set([
896
- "item/commandExecution/requestApproval",
897
- "item/fileChange/requestApproval",
898
- "item/permissions/requestApproval"
899
- ]);
900
- /** Returns true for app-server approval request methods OpenClaw can answer. */
901
- function isCodexAppServerApprovalRequest(method) {
902
- return CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS.has(method);
903
- }
904
- function formatExitValue(value) {
905
- if (value === null || value === void 0) return "null";
906
- if (typeof value === "string" || typeof value === "number") return String(value);
907
- return "unknown";
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;
908
1185
  }
909
1186
  //#endregion
910
- //#region extensions/codex/src/app-server/attempt-timeouts.ts
1187
+ //#region extensions/codex/src/app-server/transport-websocket.ts
911
1188
  /**
912
- * Timeout defaults and normalizers for Codex app-server startup and turn
913
- * liveness watches.
1189
+ * Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
1190
+ * transport interface.
914
1191
  */
915
- /** Minimum startup timeout accepted by the Codex app-server harness. */
916
- const CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS = 100;
917
- /** Default idle timeout while waiting for app-server turn completion. */
918
- const CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS = 6e4;
919
- /** Short guard after apparent assistant completion. */
920
- const CODEX_TURN_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS = 1e4;
921
- const CODEX_POST_TOOL_RAW_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS = 5 * 6e4;
922
- /** Guard after reasoning/commentary progress when no tool handoff occurred. */
923
- const CODEX_POST_REASONING_REPLY_IDLE_TIMEOUT_MS = 5 * 6e4;
924
- /** Long terminal idle watch for app-server turns that never send completion. */
925
- const CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS = 30 * 6e4;
926
- var CodexAppServerStartupError = class extends Error {
927
- constructor(reason, message = reason === "timed_out" ? "codex app-server startup timed out" : "codex app-server startup aborted") {
928
- super(message);
929
- this.reason = reason;
930
- this.code = "CODEX_APP_SERVER_STARTUP_CANCELLED";
931
- this.name = "CodexAppServerStartupError";
932
- }
933
- };
934
- function isCodexAppServerStartupError(error, reason) {
935
- 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);
936
- }
937
- function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
938
- return resolveTimerTimeoutMs(value, resolveTimerTimeoutMs(fallbackMs, 1));
939
- }
940
- /** Runs startup work with abort and timeout handling plus optional cleanup. */
941
- async function withCodexStartupTimeout(params) {
942
- if (params.signal.aborted) throw new CodexAppServerStartupError("aborted");
943
- let timeout;
944
- let abortCleanup;
945
- let timeoutError;
946
- let timeoutCleanup;
947
- try {
948
- return await Promise.race([params.operation(), new Promise((_, reject) => {
949
- const rejectOnce = (error) => {
950
- if (timeout) {
951
- clearTimeout(timeout);
952
- timeout = void 0;
953
- }
954
- reject(error);
955
- };
956
- timeout = setTimeout(() => {
957
- timeoutError = new CodexAppServerStartupError("timed_out");
958
- timeoutCleanup = Promise.resolve(params.onTimeout?.()).then(() => void 0, () => void 0);
959
- timeoutCleanup.finally(() => {
960
- rejectOnce(timeoutError);
961
- });
962
- }, params.timeoutMs);
963
- const abortListener = () => rejectOnce(new CodexAppServerStartupError("aborted"));
964
- params.signal.addEventListener("abort", abortListener, { once: true });
965
- abortCleanup = () => params.signal.removeEventListener("abort", abortListener);
966
- })]);
967
- } catch (error) {
968
- if (timeoutError) {
969
- await timeoutCleanup;
970
- throw timeoutError;
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;
971
1220
  }
972
- throw error;
973
- } finally {
974
- if (timeout) clearTimeout(timeout);
975
- abortCleanup?.();
976
- }
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
+ };
977
1269
  }
978
- /** Resolves startup timeout while honoring the configured floor. */
979
- function resolveCodexStartupTimeoutMs(params) {
980
- const timeoutFloorMs = resolvePositiveIntegerTimeoutMs(params.timeoutFloorMs, CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS);
981
- const timeoutMs = resolvePositiveIntegerTimeoutMs(params.timeoutMs, timeoutFloorMs);
982
- return Math.max(timeoutFloorMs, timeoutMs);
1270
+ /** Opens the owner-scoped Codex control socket used by the WebSocket upgrade. */
1271
+ function connectCodexAppServerUnixSocket(socketPath) {
1272
+ return net.createConnection(socketPath);
983
1273
  }
984
- /** Resolves the completion-idle timeout for an active turn. */
985
- function resolveCodexTurnCompletionIdleTimeoutMs(value) {
986
- return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS);
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");
987
1283
  }
988
- /** Resolves the short assistant-completion release timeout. */
989
- function resolveCodexTurnAssistantCompletionIdleTimeoutMs(value) {
990
- return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS);
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");
991
1289
  }
992
- /** Resolves the conservative post-tool raw assistant guard timeout. */
993
- function resolveCodexPostToolRawAssistantCompletionIdleTimeoutMs(value, fallbackMs) {
994
- return resolvePositiveIntegerTimeoutMs(value, Math.max(resolvePositiveIntegerTimeoutMs(void 0, fallbackMs), CODEX_POST_TOOL_RAW_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS));
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?.();
995
1311
  }
996
- /** Resolves the long terminal turn idle timeout. */
997
- function resolveCodexTurnTerminalIdleTimeoutMs(value, runTimeoutOverrideMs) {
998
- const explicitRunBudgetMs = resolvePositiveIntegerTimeoutMs(runTimeoutOverrideMs, CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS);
999
- return resolvePositiveIntegerTimeoutMs(value, Math.max(CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS, explicitRunBudgetMs));
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);
1000
1316
  }
1001
- /** Adds gateway grace time to a caller timeout without overflowing invalid values. */
1002
- function resolveCodexGatewayTimeoutWithGraceMs(timeoutMs, graceMs = 1e4) {
1003
- const timeout = resolvePositiveIntegerTimeoutMs(timeoutMs, 1);
1004
- return addTimerTimeoutGraceMs(timeout, resolveTimerTimeoutMs(graceMs, 0, 0)) ?? timeout;
1317
+ function hasCodexAppServerTransportExited(child) {
1318
+ return child.exitCode !== null && child.exitCode !== void 0 ? true : child.signalCode !== null && child.signalCode !== void 0;
1005
1319
  }
1006
- //#endregion
1007
- //#region extensions/codex/src/app-server/auth-start-options.ts
1008
- const CODEX_APP_SERVER_HOME_DIRNAME = "codex-home";
1009
- const CODEX_EPHEMERAL_AUTH_STORE_OVERRIDE = "cli_auth_credentials_store=\"ephemeral\"";
1010
- function resolveCodexAppServerHomeDir(agentDir) {
1011
- return path.join(path.resolve(agentDir), CODEX_APP_SERVER_HOME_DIRNAME);
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
+ });
1012
1338
  }
1013
- /** Forces OpenClaw-owned Codex auth to remain process-local. */
1014
- function withEphemeralCodexAuthStore(params) {
1015
- const { startOptions } = params;
1016
- if (!(startOptions.commandSource === "managed" || startOptions.commandSource === "resolved-managed") || !params.preparedAuth && params.authProfileId === null) return startOptions;
1017
- if (startOptions.args.at(-2) === "-c" && startOptions.args.at(-1) === CODEX_EPHEMERAL_AUTH_STORE_OVERRIDE) return startOptions;
1018
- return {
1019
- ...startOptions,
1020
- args: [
1021
- ...startOptions.args,
1022
- "-c",
1023
- CODEX_EPHEMERAL_AUTH_STORE_OVERRIDE
1024
- ]
1025
- };
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);
1026
1345
  }
1027
1346
  //#endregion
1028
- //#region extensions/codex/src/app-server/desktop-app-paths.ts
1029
- /** Shared path candidates for Codex's macOS desktop app bundle. */
1030
- const MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES = [{
1031
- appName: "ChatGPT.app",
1032
- appBundlePath: "/Applications/ChatGPT.app",
1033
- appServerCommandPath: "/Applications/ChatGPT.app/Contents/Resources/codex",
1034
- bundledMarketplacePath: "/Applications/ChatGPT.app/Contents/Resources/plugins/openai-bundled"
1035
- }, {
1036
- appName: "Codex.app",
1037
- appBundlePath: "/Applications/Codex.app",
1038
- appServerCommandPath: "/Applications/Codex.app/Contents/Resources/codex",
1039
- bundledMarketplacePath: "/Applications/Codex.app/Contents/Resources/plugins/openai-bundled"
1040
- }];
1041
- function resolveMacOSDesktopCodexBundledMarketplaceCandidates(platform = process.platform) {
1042
- return platform === "darwin" ? MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.map((candidate) => candidate.bundledMarketplacePath) : [];
1043
- }
1044
- function resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath(params = {}) {
1045
- const candidates = params.candidates ?? resolveMacOSDesktopCodexBundledMarketplaceCandidates(params.platform);
1046
- const pathExists = params.pathExists ?? existsSync;
1047
- return candidates.find((candidate) => pathExists(candidate));
1048
- }
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";
1049
1355
  //#endregion
1050
- //#region extensions/codex/src/app-server/computer-use-cache.ts
1051
- /** Shared Computer Use plugin cache reconciliation for isolated Codex homes. */
1052
- const DEFAULT_CODEX_COMPUTER_USE_BUNDLED_MARKETPLACE_PATH = resolveMacOSDesktopCodexBundledMarketplaceCandidates("darwin")[0] ?? "";
1053
- const DEFAULT_BUNDLED_MARKETPLACE_NAME = "openai-bundled";
1054
- async function ensureCodexComputerUseSharedPluginCache(params) {
1055
- if (!params.config.enabled) return skippedCacheResult("disabled", "Computer Use cache sharing skipped because it is disabled.");
1056
- if (params.config.pluginCacheMode === "independent") return skippedCacheResult("independent", "Computer Use cache sharing skipped because pluginCacheMode is independent.");
1057
- if (params.config.marketplaceName || params.config.marketplacePath) return skippedCacheResult("explicit_marketplace", "Computer Use cache sharing skipped because an explicit marketplace is configured.");
1058
- const bundledMarketplacePath = resolveComputerUseBundledMarketplacePath(params);
1059
- const sourcePluginRoot = path.join(bundledMarketplacePath, "plugins", params.config.pluginName);
1060
- const version = await readBundledPluginVersion(sourcePluginRoot);
1061
- if (!version) return skippedCacheResult("source_missing", `Computer Use bundled plugin source was not found at ${sourcePluginRoot}.`);
1062
- const marketplaceName = params.config.marketplaceName ?? DEFAULT_BUNDLED_MARKETPLACE_NAME;
1063
- const cacheRoot = path.join(params.codexHome, "plugins", "cache", marketplaceName, params.config.pluginName);
1064
- const cachePath = path.join(cacheRoot, version);
1065
- return {
1066
- status: "shared",
1067
- changed: await ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version),
1068
- cachePath,
1069
- targetPath: sourcePluginRoot,
1070
- version,
1071
- removedStaleVersions: [],
1072
- warnings: [],
1073
- message: `Computer Use plugin cache ${cachePath} contains bundled plugin ${sourcePluginRoot}.`
1074
- };
1075
- }
1076
- function resolveComputerUseBundledMarketplacePath(params) {
1077
- return params.bundledMarketplacePath ?? resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath({ candidates: params.bundledMarketplacePathCandidates }) ?? params.bundledMarketplacePathCandidates?.[0] ?? DEFAULT_CODEX_COMPUTER_USE_BUNDLED_MARKETPLACE_PATH;
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;
1078
1378
  }
1079
- async function readBundledPluginVersion(sourcePluginRoot) {
1080
- const pluginJsonPath = path.join(sourcePluginRoot, ".codex-plugin", "plugin.json");
1081
- let raw;
1082
- try {
1083
- raw = await fs.readFile(pluginJsonPath, "utf8");
1084
- } catch {
1085
- return;
1086
- }
1087
- try {
1088
- const parsed = JSON.parse(raw);
1089
- return typeof parsed.version === "string" && parsed.version.trim() ? parsed.version.trim() : void 0;
1090
- } catch {
1091
- return;
1092
- }
1379
+ function resolveCodexAppServerClientInstanceId(client) {
1380
+ return client.getInstanceId?.call(client) ?? getCodexAppServerClientInstanceId(client);
1093
1381
  }
1094
- async function ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version) {
1095
- await fs.mkdir(path.dirname(cachePath), { recursive: true });
1096
- const stat = await fs.lstat(cachePath).catch(() => void 0);
1097
- if (stat?.isDirectory() && !stat.isSymbolicLink()) {
1098
- if (await readBundledPluginVersion(cachePath) === version) return false;
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;
1099
1390
  }
1100
- const cacheRoot = path.dirname(cachePath);
1101
- const cacheName = path.basename(cachePath);
1102
- const stagingRoot = await fs.mkdtemp(path.join(cacheRoot, `.${cacheName}.staging-`));
1103
- const stagedPath = path.join(stagingRoot, cacheName);
1104
- const backupPath = path.join(cacheRoot, `.${cacheName}.backup-${process.pid}-${Date.now()}`);
1105
- let backupCreated = false;
1106
- try {
1107
- await fs.cp(sourcePluginRoot, stagedPath, { recursive: true });
1108
- if (stat) {
1109
- await fs.rename(cachePath, backupPath);
1110
- backupCreated = true;
1111
- }
1112
- try {
1113
- await fs.rename(stagedPath, cachePath);
1114
- } catch (error) {
1115
- if (backupCreated) try {
1116
- await fs.rename(backupPath, cachePath);
1117
- backupCreated = false;
1118
- } catch (restoreError) {
1119
- throw new Error(`Failed to install Computer Use cache ${cachePath} and restore its prior copy: ${String(error)}`, { cause: restoreError });
1120
- }
1121
- throw error;
1122
- }
1123
- if (backupCreated) await fs.rm(backupPath, {
1124
- recursive: true,
1125
- force: true
1126
- });
1127
- return true;
1128
- } finally {
1129
- await fs.rm(stagingRoot, {
1130
- recursive: true,
1131
- force: true
1132
- });
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";
1133
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";
1134
1403
  }
1135
- function skippedCacheResult(status, message) {
1136
- return {
1137
- status,
1138
- changed: false,
1139
- message,
1140
- removedStaleVersions: [],
1141
- warnings: status === "source_missing" ? [message] : []
1142
- };
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;
1143
1413
  }
1144
- //#endregion
1145
- //#region extensions/codex/src/app-server/auth-bridge.ts
1146
- const CODEX_APP_SERVER_AUTH_PROVIDER = "openai";
1147
- const OPENAI_CODEX_APP_SERVER_AUTH_PROVIDER = "openai-codex";
1148
- const LEGACY_CODEX_APP_SERVER_AUTH_PROVIDER = "codex-cli";
1149
- const CODEX_APP_SERVER_EXTERNAL_CLI_PROVIDER_IDS = [CODEX_APP_SERVER_AUTH_PROVIDER, LEGACY_CODEX_APP_SERVER_AUTH_PROVIDER];
1150
- const OPENAI_PROVIDER = "openai";
1151
- const OPENAI_CODEX_DEFAULT_PROFILE_ID = "openai:default";
1152
- const CODEX_HOME_ENV_VAR = "CODEX_HOME";
1153
- const HOME_ENV_VAR = "HOME";
1154
- const CODEX_API_KEY_ENV_VAR = "CODEX_API_KEY";
1155
- const OPENAI_API_KEY_ENV_VAR = "OPENAI_API_KEY";
1156
- const CODEX_ACCESS_TOKEN_ENV_VAR = "CODEX_ACCESS_TOKEN";
1157
- const CODEX_APP_SERVER_API_KEY_ENV_VARS = [CODEX_API_KEY_ENV_VAR, OPENAI_API_KEY_ENV_VAR];
1158
- const CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS = [
1159
- CODEX_API_KEY_ENV_VAR,
1160
- OPENAI_API_KEY_ENV_VAR,
1161
- CODEX_ACCESS_TOKEN_ENV_VAR
1162
- ];
1163
- const CODEX_APP_SERVER_HOME_ENV_VARS = [CODEX_HOME_ENV_VAR, HOME_ENV_VAR];
1164
- const CODEX_AUTH_JSON_FILENAME = "auth.json";
1165
- const CODEX_HOME_DIRNAME = ".codex";
1166
- const scopedOAuthRefreshQueues = /* @__PURE__ */ new WeakMap();
1167
- async function bridgeCodexAppServerStartOptions(params) {
1168
- if (params.startOptions.transport !== "stdio") return params.startOptions;
1169
- const scopedStartOptions = await withCodexHomeEnvironment(withEphemeralCodexAuthStore(params), params.agentDir, params.pluginConfig);
1170
- if (params.preparedAuth) return withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS);
1171
- if (params.authProfileId === null) return scopedStartOptions;
1172
- const store = resolveCodexAppServerAuthProfileStore({
1173
- agentDir: params.agentDir,
1174
- authProfileId: params.authProfileId,
1175
- authProfileStore: params.authProfileStore,
1176
- config: params.config
1177
- });
1178
- return shouldClearOpenAiApiKeyForCodexAuthProfile({
1179
- store,
1180
- authProfileId: resolveCodexAppServerAuthProfileId({
1181
- authProfileId: params.authProfileId,
1182
- store,
1183
- config: params.config
1184
- }),
1185
- config: params.config
1186
- }) ? withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS) : scopedStartOptions;
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;
1187
1425
  }
1188
- function resolveCodexAppServerAuthProfileId(params) {
1189
- const requested = params.authProfileId?.trim();
1190
- if (requested) return requested;
1191
- return resolveAuthProfileOrder({
1192
- cfg: params.config,
1193
- store: params.store,
1194
- provider: CODEX_APP_SERVER_AUTH_PROVIDER
1195
- })[0]?.trim();
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;
1196
1429
  }
1197
- function resolveCodexAppServerAuthProfileIdForAgent(params) {
1198
- const store = resolveCodexAppServerAuthProfileStore({
1199
- agentDir: params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {}),
1200
- authProfileId: params.authProfileId,
1201
- authProfileStore: params.authProfileStore,
1202
- config: params.config
1203
- });
1204
- return resolveCodexAppServerAuthProfileId({
1205
- authProfileId: params.authProfileId,
1206
- store,
1207
- config: params.config
1208
- });
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;
1209
1433
  }
1210
- function ensureCodexAppServerAuthProfileStore(params) {
1211
- return ensureAuthProfileStore(params.agentDir, {
1212
- allowKeychainPrompt: false,
1213
- config: params.config,
1214
- externalCliProviderIds: CODEX_APP_SERVER_EXTERNAL_CLI_PROVIDER_IDS,
1215
- ...params.authProfileId ? { externalCliProfileIds: [params.authProfileId] } : {}
1216
- });
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;
1217
1438
  }
1218
- function resolveCodexAppServerAuthProfileStore(params) {
1219
- if (params.authProfileStore) return params.authProfileStore;
1220
- return ensureCodexAppServerAuthProfileStore({
1221
- agentDir: params.agentDir,
1222
- authProfileId: params.authProfileId,
1223
- config: params.config
1224
- });
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;
1225
1446
  }
1226
- /** Resolves prepared profile login material once so cache identity and RPC login cannot drift. */
1227
- async function resolveCodexAppServerPreparedAuthProfileSnapshot(params) {
1228
- const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
1229
- const store = resolveCodexAppServerAuthProfileStore({
1230
- agentDir,
1231
- authProfileId: params.authProfileId,
1232
- authProfileStore: params.authProfileStore,
1233
- config: params.config
1234
- });
1235
- const profileId = resolveCodexAppServerAuthProfileId({
1236
- authProfileId: params.authProfileId,
1237
- store,
1238
- config: params.config
1239
- });
1240
- if (!profileId) return;
1241
- const credential = store.profiles[profileId];
1242
- if (!credential || !isCodexAppServerAuthProfileCredential(credential, params.config)) return;
1243
- const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
1244
- agentDir,
1245
- authProfileId: profileId,
1246
- authProfileStore: store,
1247
- config: params.config
1248
- });
1249
- if (!loginParams) return;
1250
- const accountId = loginParams.type === "chatgptAuthTokens" ? loginParams.chatgptAccountId : resolveChatgptAccountId(profileId, credential);
1251
- const stableChatgptAccountId = resolveStableChatgptAccountId(credential);
1252
- return {
1253
- loginParams,
1254
- secretFreeCacheKey: credential.type === "api_key" && loginParams.type === "apiKey" ? `${accountId}:${fingerprintApiKeyAuthProfileCacheKey(loginParams.apiKey)}` : loginParams.type === "chatgptAuthTokens" && (credential.type === "token" || !stableChatgptAccountId) ? `${accountId}:${fingerprintTokenAuthProfileCacheKey(loginParams.accessToken)}` : accountId
1255
- };
1447
+ function isJsonObject(value) {
1448
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
1256
1449
  }
1257
- /** Maps one prepared route to one mutually exclusive app-server auth handoff. */
1258
- async function resolveCodexAppServerPreparedAuthHandoff(params) {
1259
- if (params.authRequirement === "api-key") {
1260
- const apiKey = params.resolvedApiKey?.trim();
1261
- if (!apiKey) throw new Error("Prepared Codex API-key route is missing its resolved API key.");
1262
- return {
1263
- nativeAuthProfile: false,
1264
- preparedAuth: {
1265
- kind: "api-key",
1266
- apiKey
1267
- }
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
1268
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;
1269
1545
  }
1270
- const authProfileId = params.authProfileId?.trim() || void 0;
1271
- const nativeAuthProfile = isCodexAppServerNativeAuthProfile({
1272
- authProfileId,
1273
- authProfileStore: params.authProfileStore,
1274
- agentDir: params.agentDir,
1275
- config: params.config
1276
- });
1277
- if (params.authRequirement !== "subscription") return {
1278
- authProfileId,
1279
- nativeAuthProfile
1280
- };
1281
- if (!authProfileId || !nativeAuthProfile) throw createCodexAppServerAuthError(params.subscriptionProfileRequiredError);
1282
- const snapshot = await resolveCodexAppServerPreparedAuthProfileSnapshot({
1283
- authProfileId,
1284
- authProfileStore: params.authProfileStore,
1285
- agentDir: params.agentDir,
1286
- config: params.config
1287
- });
1288
- if (!snapshot) throw createCodexAppServerAuthError(params.subscriptionProfileUnusableError);
1289
- return {
1290
- authProfileId,
1291
- nativeAuthProfile,
1292
- preparedAuth: {
1293
- kind: "profile",
1294
- profileId: authProfileId,
1295
- store: params.authProfileStore,
1296
- snapshot
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
+ })();
1297
1599
  }
1298
- };
1299
- }
1300
- async function resolveCodexAppServerAuthAccountCacheKey(params) {
1301
- const agentDir = params.agentDir?.trim() || resolveDefaultAgentDir(params.config ?? {});
1302
- const store = resolveCodexAppServerAuthProfileStore({
1303
- agentDir,
1304
- authProfileId: params.authProfileId,
1305
- authProfileStore: params.authProfileStore,
1306
- config: params.config
1307
- });
1308
- const profileId = resolveCodexAppServerAuthProfileId({
1309
- authProfileId: params.authProfileId,
1310
- store,
1311
- config: params.config
1312
- });
1313
- if (!profileId) return;
1314
- const credential = store.profiles[profileId];
1315
- if (!credential || !isCodexAppServerAuthProfileCredential(credential, params.config)) return;
1316
- if (credential.type === "api_key") {
1317
- const apiKey = (await resolveApiKeyForProfile({
1318
- store,
1319
- profileId,
1320
- agentDir
1321
- }))?.apiKey?.trim();
1322
- return apiKey ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintApiKeyAuthProfileCacheKey(apiKey)}` : resolveChatgptAccountId(profileId, credential);
1600
+ return this.requestWithoutThreadSessionGuard(method, params, options);
1323
1601
  }
1324
- if (credential.type === "token") {
1325
- const accessToken = (await resolveApiKeyForProfile({
1326
- store,
1327
- profileId,
1328
- agentDir
1329
- }))?.apiKey?.trim();
1330
- return accessToken ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintTokenAuthProfileCacheKey(accessToken)}` : resolveChatgptAccountId(profileId, credential);
1602
+ requestWithoutThreadSessionGuard(method, params, options, onWriteAttempt) {
1603
+ return this.requestWithOverloadRetry(method, params, options, onWriteAttempt);
1331
1604
  }
1332
- return resolveChatgptAccountId(profileId, credential);
1333
- }
1334
- function resolveCodexAppServerEnvApiKeyCacheKey(params) {
1335
- if (params.startOptions.transport !== "stdio") return;
1336
- const apiKey = readFirstNonEmptyEnvEntry(resolveCodexAppServerSpawnEnv(params.startOptions, params.baseEnv ?? process.env, params.platform ?? process.platform), CODEX_APP_SERVER_API_KEY_ENV_VARS);
1337
- if (!apiKey) return;
1338
- const hash = createHash("sha256");
1339
- hash.update("openclaw:codex:app-server-env-api-key:v1");
1340
- hash.update("\0");
1341
- hash.update(apiKey.key);
1342
- hash.update("\0");
1343
- hash.update(apiKey.value);
1344
- return `${apiKey.key}:sha256:${hash.digest("hex")}`;
1345
- }
1346
- function resolveCodexAppServerFallbackApiKeyCacheKey(params) {
1347
- if (params.startOptions.transport !== "stdio") return;
1348
- return resolveCodexAppServerEnvApiKeyCacheKey(params) ?? resolveCodexCliAuthFileApiKeyCacheKey(params.baseEnv ?? process.env);
1349
- }
1350
- /** Secret-free cache identity for an API key already resolved by the runtime plan. */
1351
- function resolveCodexAppServerPreparedApiKeyCacheKey(apiKey) {
1352
- const resolved = apiKey?.trim();
1353
- return resolved ? fingerprintApiKeyAuthProfileCacheKey(resolved) : void 0;
1354
- }
1355
- function fingerprintApiKeyAuthProfileCacheKey(apiKey) {
1356
- const hash = createHash("sha256");
1357
- hash.update("openclaw:codex:app-server-auth-profile-api-key:v1");
1358
- hash.update("\0");
1359
- hash.update(apiKey);
1360
- return `api_key:sha256:${hash.digest("hex")}`;
1361
- }
1362
- function fingerprintTokenAuthProfileCacheKey(accessToken) {
1363
- const hash = createHash("sha256");
1364
- hash.update("openclaw:codex:app-server-auth-profile-token:v1");
1365
- hash.update("\0");
1366
- hash.update(accessToken);
1367
- return `token:sha256:${hash.digest("hex")}`;
1368
- }
1369
- function fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) {
1370
- const hash = createHash("sha256");
1371
- hash.update("openclaw:codex:app-server-cli-auth-json-api-key:v1");
1372
- hash.update("\0");
1373
- hash.update(apiKey);
1374
- return `CODEX_AUTH_JSON:sha256:${hash.digest("hex")}`;
1375
- }
1376
- async function withCodexHomeEnvironment(startOptions, agentDir, pluginConfig) {
1377
- const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim() ? startOptions.env[CODEX_HOME_ENV_VAR] : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir(process.env) : resolveCodexAppServerHomeDir(agentDir);
1378
- const nativeHome = startOptions.env?.[HOME_ENV_VAR]?.trim() ? startOptions.env[HOME_ENV_VAR] : void 0;
1379
- await fs.mkdir(codexHome, { recursive: true });
1380
- await ensureCodexComputerUseSharedPluginCache({
1381
- codexHome,
1382
- config: resolveCodexComputerUseConfig({ pluginConfig })
1383
- });
1384
- if (nativeHome) await fs.mkdir(nativeHome, { recursive: true });
1385
- const nextStartOptions = {
1386
- ...startOptions,
1387
- env: {
1388
- ...startOptions.env,
1389
- [CODEX_HOME_ENV_VAR]: codexHome,
1390
- ...nativeHome ? { [HOME_ENV_VAR]: nativeHome } : {}
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
+ }
1391
1621
  }
1392
- };
1393
- const clearEnv = withoutClearedCodexHomeEnv(startOptions.clearEnv);
1394
- if (clearEnv) nextStartOptions.clearEnv = clearEnv;
1395
- else delete nextStartOptions.clearEnv;
1396
- return nextStartOptions;
1397
- }
1398
- function withoutClearedCodexHomeEnv(clearEnv) {
1399
- if (!clearEnv) return;
1400
- const reserved = new Set(CODEX_APP_SERVER_HOME_ENV_VARS);
1401
- const filtered = clearEnv.filter((envVar) => !reserved.has(envVar.trim().toUpperCase()));
1402
- return filtered.length === clearEnv.length ? clearEnv : filtered;
1403
- }
1404
- async function applyCodexAppServerAuthProfile(params) {
1405
- if (params.preparedAuth?.kind === "profile") {
1406
- await params.client.request("account/login/start", params.preparedAuth.snapshot.loginParams);
1407
- return;
1408
1622
  }
1409
- if (params.preparedAuth?.kind === "api-key") {
1410
- await params.client.request("account/login/start", {
1411
- type: "apiKey",
1412
- apiKey: params.preparedAuth.apiKey
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
1413
1712
  });
1414
- return;
1415
1713
  }
1416
- if (params.authProfileId === null) {
1417
- if (params.authRequirement === "subscription") {
1418
- const response = await params.client.request("account/read", { refreshToken: false });
1419
- if (!isJsonObject$1(response.account) || response.account.type !== "chatgpt") throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.");
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
+ });
1420
1762
  }
1421
- return;
1422
1763
  }
1423
- let loginParams;
1424
- try {
1425
- loginParams = await resolveCodexAppServerAuthProfileLoginParams({
1426
- agentDir: params.agentDir,
1427
- authProfileId: params.authProfileId,
1428
- authProfileStore: params.authProfileStore,
1429
- config: params.config
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
+ }
1430
1777
  });
1431
- } catch (error) {
1432
- if (params.authRequirement === "subscription" && error instanceof CodexAppServerAuthProfileUnavailableError) throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.", error);
1433
- throw error;
1434
1778
  }
1435
- if (params.authRequirement === "subscription" && loginParams?.type !== "chatgptAuthTokens") throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.");
1436
- if (!loginParams) {
1437
- if (params.authRequirement === "subscription") throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.");
1438
- if (params.authRequirement !== "api-key" || params.startOptions?.transport !== "stdio") return;
1439
- const env = resolveCodexAppServerSpawnEnv(params.startOptions, process.env);
1440
- const fallbackLoginParams = await resolveCodexAppServerFallbackApiKeyLoginParams({
1441
- client: params.client,
1442
- env,
1443
- codexCliAuthEnv: process.env
1444
- });
1445
- if (fallbackLoginParams) await params.client.request("account/login/start", fallbackLoginParams);
1446
- return;
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);
1447
1803
  }
1448
- await params.client.request("account/login/start", loginParams);
1449
- }
1450
- function createCodexAppServerAuthError(message, cause) {
1451
- const error = cause === void 0 ? new Error(message) : new Error(message, { cause });
1452
- return Object.assign(error, { status: 401 });
1453
- }
1454
- var CodexAppServerAuthProfileUnavailableError = class extends Error {};
1455
- async function resolveCodexAppServerAuthProfileLoginParams(params) {
1456
- const store = resolveCodexAppServerAuthProfileStore(params);
1457
- const profileId = resolveCodexAppServerAuthProfileId({
1458
- authProfileId: params.authProfileId,
1459
- store,
1460
- config: params.config
1461
- });
1462
- const profile = profileId ? store.profiles[profileId] : void 0;
1463
- if (profileId && !profile) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" was not found.`);
1464
- if (profileId && profile && !isCodexAppServerAuthProfileCredential(profile, params.config)) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" must be OpenAI Codex auth or an OpenAI API-key backup.`);
1465
- return await resolveCodexAppServerAuthProfileLoginParamsInternal({
1466
- ...params,
1467
- authProfileStore: store
1468
- });
1469
- }
1470
- async function refreshCodexAppServerAuthTokens(params) {
1471
- const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
1472
- ...params,
1473
- forceOAuthRefresh: true
1474
- });
1475
- if (!loginParams || loginParams.type !== "chatgptAuthTokens") throw new Error("Codex app-server ChatGPT token refresh requires an OAuth auth profile.");
1476
- return {
1477
- accessToken: loginParams.accessToken,
1478
- chatgptAccountId: loginParams.chatgptAccountId,
1479
- chatgptPlanType: loginParams.chatgptPlanType ?? null
1480
- };
1481
- }
1482
- async function resolveCodexAppServerAuthProfileLoginParamsInternal(params) {
1483
- const store = resolveCodexAppServerAuthProfileStore({
1484
- agentDir: params.agentDir,
1485
- authProfileId: params.authProfileId,
1486
- authProfileStore: params.authProfileStore,
1487
- config: params.config
1488
- });
1489
- const profileId = resolveCodexAppServerAuthProfileId({
1490
- authProfileId: params.authProfileId,
1491
- store,
1492
- config: params.config
1493
- });
1494
- if (!profileId) return;
1495
- const credential = store.profiles[profileId];
1496
- if (!credential) throw new Error(`Codex app-server auth profile "${profileId}" was not found.`);
1497
- if (!isCodexAppServerAuthProfileCredential(credential, params.config)) throw new Error(`Codex app-server auth profile "${profileId}" must be OpenAI Codex auth or an OpenAI API-key backup.`);
1498
- const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
1499
- agentDir: params.agentDir,
1500
- store,
1501
- preferStoreCredential: Boolean(params.authProfileStore?.profiles[profileId]),
1502
- forceOAuthRefresh: params.forceOAuthRefresh === true,
1503
- config: params.config
1504
- });
1505
- if (!loginParams) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" does not contain usable credentials.`);
1506
- return loginParams;
1507
- }
1508
- async function resolveCodexAppServerFallbackApiKeyLoginParams(params) {
1509
- const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS) ?? await readCodexCliAuthFileApiKey(params.codexCliAuthEnv);
1510
- if (!apiKey) return;
1511
- if ((await params.client.request("account/read", { refreshToken: false })).account) return;
1512
- return {
1513
- type: "apiKey",
1514
- apiKey
1515
- };
1516
- }
1517
- function resolveCodexCliAuthFilePath(env) {
1518
- const configuredCodexHome = env[CODEX_HOME_ENV_VAR]?.trim();
1519
- if (configuredCodexHome) return path.join(resolveHomeRelativePath(configuredCodexHome, env), CODEX_AUTH_JSON_FILENAME);
1520
- const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
1521
- return path.join(home, CODEX_HOME_DIRNAME, CODEX_AUTH_JSON_FILENAME);
1522
- }
1523
- function resolveHomeRelativePath(value, env) {
1524
- if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
1525
- const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
1526
- return path.join(home, value.slice(value === "~" ? 1 : 2));
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
+ });
1527
1848
  }
1528
- return value;
1529
- }
1530
- function parseCodexCliAuthFileApiKey(raw) {
1531
- let parsed;
1532
- try {
1533
- parsed = JSON.parse(raw);
1534
- } catch {
1535
- return;
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);
1536
1858
  }
1537
- if (!parsed || typeof parsed !== "object") return;
1538
- const apiKey = parsed.OPENAI_API_KEY;
1539
- return typeof apiKey === "string" && apiKey.trim() ? apiKey.trim() : void 0;
1540
- }
1541
- async function readCodexCliAuthFileApiKey(env) {
1542
- try {
1543
- return parseCodexCliAuthFileApiKey(await fs.readFile(resolveCodexCliAuthFilePath(env), "utf8"));
1544
- } catch {
1545
- return;
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
+ }
1546
1888
  }
1547
- }
1548
- function resolveCodexCliAuthFileApiKeyCacheKey(env) {
1549
- try {
1550
- const apiKey = parseCodexCliAuthFileApiKey(fsSync.readFileSync(resolveCodexCliAuthFilePath(env), "utf8"));
1551
- return apiKey ? fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) : void 0;
1552
- } catch {
1553
- return;
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
+ }
1554
1910
  }
1555
- }
1556
- async function resolveLoginParamsForCredential(profileId, credential, params) {
1557
- if (credential.type === "api_key") {
1558
- const apiKey = (await resolveApiKeyForProfile({
1559
- store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
1560
- profileId,
1561
- agentDir: params.agentDir
1562
- }))?.apiKey?.trim();
1563
- return apiKey ? {
1564
- type: "apiKey",
1565
- apiKey
1566
- } : void 0;
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
+ }
1567
1917
  }
1568
- if (credential.type === "token") {
1569
- const accessToken = (await resolveApiKeyForProfile({
1570
- store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
1571
- profileId,
1572
- agentDir: params.agentDir
1573
- }))?.apiKey?.trim();
1574
- return accessToken ? buildChatgptAuthTokensParams(profileId, credential, accessToken) : void 0;
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
+ }
1575
1926
  }
1576
- if (credential.type !== "oauth") return;
1577
- const resolvedCredential = await resolveOAuthCredentialForCodexAppServer(profileId, credential, {
1578
- agentDir: params.agentDir,
1579
- store: params.store,
1580
- preferStoreCredential: params.preferStoreCredential,
1581
- forceRefresh: params.forceOAuthRefresh,
1582
- config: params.config
1583
- });
1584
- const accessToken = resolvedCredential.access?.trim();
1585
- return accessToken ? buildChatgptAuthTokensParams(profileId, resolvedCredential, accessToken) : void 0;
1586
- }
1587
- async function resolveOAuthCredentialForCodexAppServer(profileId, credential, params) {
1588
- const ownerAgentDir = resolvePersistedAuthProfileOwnerAgentDir({
1589
- agentDir: params.agentDir,
1590
- profileId
1591
- });
1592
- const persistedCredential = findPersistedAuthProfileCredential({
1593
- agentDir: ownerAgentDir,
1594
- profileId
1595
- });
1596
- const useScopedCredential = params.preferStoreCredential && shouldUseScopedOAuthCredential({
1597
- store: params.store,
1598
- profileId,
1599
- persistedCredential,
1600
- suppliedCredential: credential,
1601
- config: params.config
1602
- });
1603
- const store = useScopedCredential ? params.store : ensureCodexAppServerAuthProfileStore({
1604
- agentDir: ownerAgentDir,
1605
- authProfileId: profileId,
1606
- config: params.config
1607
- });
1608
- const persistedOAuthCredential = !useScopedCredential && persistedCredential?.type === "oauth" && isCodexAppServerAuthProvider(persistedCredential.provider, params.config) ? persistedCredential : void 0;
1609
- const ownerCredential = store.profiles[profileId];
1610
- const overlaidOAuthCredential = ownerCredential?.type === "oauth" && isCodexAppServerAuthProvider(ownerCredential.provider, params.config) ? ownerCredential : void 0;
1611
- if (useScopedCredential && overlaidOAuthCredential) return await resolveScopedOAuthCredential({
1612
- store,
1613
- profileId,
1614
- credential: overlaidOAuthCredential,
1615
- forceRefresh: params.forceRefresh
1616
- });
1617
- if (params.forceRefresh && !persistedOAuthCredential && overlaidOAuthCredential) {
1618
- const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({ credential: overlaidOAuthCredential });
1619
- if (!refreshedRuntimeCredential?.access?.trim()) throw new Error(`Codex app-server auth profile "${profileId}" could not refresh.`);
1620
- store.profiles[profileId] = refreshedRuntimeCredential;
1621
- return refreshedRuntimeCredential;
1927
+ closeWithError(error) {
1928
+ if (this.markClosed(error)) closeCodexAppServerTransport(this.child);
1622
1929
  }
1623
- const resolved = await resolveApiKeyForProfile({
1624
- store,
1625
- profileId,
1626
- agentDir: ownerAgentDir,
1627
- forceRefresh: params.forceRefresh && Boolean(persistedOAuthCredential)
1628
- });
1629
- const refreshed = useScopedCredential ? void 0 : loadAuthProfileStoreForSecretsRuntime(ownerAgentDir).profiles[profileId];
1630
- const refreshedOAuthCredential = refreshed?.type === "oauth" && isCodexAppServerAuthProvider(refreshed.provider, params.config) ? refreshed : void 0;
1631
- if (refreshedOAuthCredential && isDeepStrictEqual(params.store.profiles[profileId], credential)) params.store.profiles[profileId] = refreshedOAuthCredential;
1632
- const storedCredential = store.profiles[profileId];
1633
- const candidate = refreshedOAuthCredential ? refreshedOAuthCredential : storedCredential?.type === "oauth" && isCodexAppServerAuthProvider(storedCredential.provider, params.config) ? storedCredential : credential;
1634
- return resolved?.apiKey ? {
1635
- ...candidate,
1636
- access: resolved.apiKey
1637
- } : candidate;
1638
- }
1639
- function shouldUseScopedOAuthCredential(params) {
1640
- if (!params.store.runtimePersistedProfileIds?.includes(params.profileId)) return true;
1641
- const persisted = params.persistedCredential;
1642
- if (persisted?.type !== "oauth") return true;
1643
- if (resolveProviderIdForAuth(persisted.provider, { config: params.config }) !== resolveProviderIdForAuth(params.suppliedCredential.provider, { config: params.config })) return true;
1644
- return !isDeepStrictEqual(persisted, params.suppliedCredential) && !hasMatchingOAuthIdentity(persisted, params.suppliedCredential);
1645
- }
1646
- function hasMatchingOAuthIdentity(persisted, supplied) {
1647
- const persistedAccountId = persisted.accountId?.trim();
1648
- const suppliedAccountId = supplied.accountId?.trim();
1649
- if (persistedAccountId && suppliedAccountId) return persistedAccountId === suppliedAccountId;
1650
- const persistedEmail = persisted.email?.trim().toLowerCase();
1651
- const suppliedEmail = supplied.email?.trim().toLowerCase();
1652
- return Boolean(persistedEmail && suppliedEmail && persistedEmail === suppliedEmail);
1653
- }
1654
- async function resolveScopedOAuthCredential(params) {
1655
- const existingRefresh = scopedOAuthRefreshQueues.get(params.store)?.get(params.profileId);
1656
- if (existingRefresh) return await existingRefresh;
1657
- if (!params.forceRefresh && hasUsableOAuthCredential(params.credential)) return params.credential;
1658
- const storeRefreshes = scopedOAuthRefreshQueues.get(params.store) ?? /* @__PURE__ */ new Map();
1659
- scopedOAuthRefreshQueues.set(params.store, storeRefreshes);
1660
- const refresh = (async () => {
1661
- const current = params.store.profiles[params.profileId];
1662
- const credential = current?.type === "oauth" ? current : params.credential;
1663
- if (!params.forceRefresh && hasUsableOAuthCredential(credential)) return credential;
1664
- const refreshed = await refreshOAuthCredentialForRuntime({ credential });
1665
- if (!refreshed?.access?.trim()) throw new Error(`Codex app-server auth profile "${params.profileId}" could not refresh.`);
1666
- if (!isDeepStrictEqual(params.store.profiles[params.profileId], credential)) throw new Error(`Codex app-server auth profile "${params.profileId}" changed while refreshing.`);
1667
- params.store.profiles[params.profileId] = refreshed;
1668
- return refreshed;
1669
- })();
1670
- storeRefreshes.set(params.profileId, refresh);
1671
- try {
1672
- return await refresh;
1673
- } finally {
1674
- if (storeRefreshes.get(params.profileId) === refresh) storeRefreshes.delete(params.profileId);
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;
1675
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 {};
1676
1963
  }
1677
- function isCodexAppServerAuthProvider(provider, config) {
1678
- const resolvedProvider = resolveProviderIdForAuth(provider, { config });
1679
- return resolvedProvider === CODEX_APP_SERVER_AUTH_PROVIDER || resolvedProvider === OPENAI_CODEX_APP_SERVER_AUTH_PROVIDER || resolvedProvider === LEGACY_CODEX_APP_SERVER_AUTH_PROVIDER;
1680
- }
1681
- function isOpenAIApiKeyBackupCredential(credential, config) {
1682
- return credential.type === "api_key" && resolveProviderIdForAuth(credential.provider, { config }) === OPENAI_PROVIDER;
1683
- }
1684
- function isCodexAppServerAuthProfileCredential(credential, config) {
1685
- return isCodexAppServerAuthProvider(credential.provider, config) || isOpenAIApiKeyBackupCredential(credential, config);
1686
- }
1687
- function shouldClearOpenAiApiKeyForCodexAuthProfile(params) {
1688
- const profileId = params.authProfileId?.trim();
1689
- return isCodexSubscriptionCredential(profileId ? params.store.profiles[profileId] : params.store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID], params.config);
1690
- }
1691
- function isCodexSubscriptionCredential(credential, config) {
1692
- if (!credential || !isCodexAppServerAuthProvider(credential.provider, config)) return false;
1693
- return credential.type === "oauth" || credential.type === "token";
1964
+ function stringifyCodexAppServerMessage(message) {
1965
+ return JSON.stringify(message, (_key, value) => typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value) ?? "null";
1694
1966
  }
1695
- function withClearedEnvironmentVariables(startOptions, envVars) {
1696
- const clearEnv = startOptions.clearEnv ?? [];
1697
- const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
1698
- if (missingEnvVars.length === 0) return startOptions;
1967
+ function timeoutServerRequestResponse(request) {
1968
+ if (request.method !== "item/tool/call") return;
1699
1969
  return {
1700
- ...startOptions,
1701
- clearEnv: [...clearEnv, ...missingEnvVars]
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
1702
1975
  };
1703
1976
  }
1704
- function readFirstNonEmptyEnv(env, keys) {
1705
- return readFirstNonEmptyEnvEntry(env, keys)?.value;
1706
- }
1707
- function readFirstNonEmptyEnvEntry(env, keys) {
1708
- for (const key of keys) {
1709
- const value = env[key]?.trim();
1710
- if (value) return {
1711
- key,
1712
- value
1713
- };
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;
1714
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;
1715
1990
  }
1716
- function buildChatgptAuthTokensParams(profileId, credential, accessToken) {
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);
1717
1999
  return {
1718
- type: "chatgptAuthTokens",
1719
- accessToken,
1720
- chatgptAccountId: resolveChatgptAccountId(profileId, credential),
1721
- chatgptPlanType: resolveChatgptPlanType(credential)
2000
+ serverVersion,
2001
+ ...userAgent ? { userAgent } : {},
2002
+ ...codexHome ? { codexHome } : {},
2003
+ ...platformFamily ? { platformFamily } : {},
2004
+ ...platformOs ? { platformOs } : {}
1722
2005
  };
1723
2006
  }
1724
- function resolveChatgptPlanType(credential) {
1725
- const record = credential;
1726
- const planType = record.chatgptPlanType ?? record.planType;
1727
- return typeof planType === "string" && planType.trim() ? planType.trim() : null;
1728
- }
1729
- function resolveChatgptAccountId(profileId, credential) {
1730
- return resolveStableChatgptAccountId(credential) ?? profileId;
1731
- }
1732
- function resolveStableChatgptAccountId(credential) {
1733
- if ("accountId" in credential && typeof credential.accountId === "string") {
1734
- const accountId = credential.accountId.trim();
1735
- if (accountId) return accountId;
1736
- }
1737
- return credential.email?.trim() || void 0;
1738
- }
1739
- //#endregion
1740
- //#region extensions/codex/src/app-server/rate-limit-cache.ts
1741
- const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 10 * 6e4;
1742
- const SPARSE_ACCOUNT_METADATA_KEYS = [
1743
- "credits",
1744
- "individualLimit",
1745
- "planType"
1746
- ];
1747
- const rateLimitsByClient = /* @__PURE__ */ new WeakMap();
1748
- /** Replaces one physical client's cache with an authoritative rate-limit read response. */
1749
- function rememberCodexRateLimitsRead(client, value, nowMs = Date.now()) {
1750
- if (value !== void 0) {
1751
- const revisionsByLimitId = { ...rateLimitsByClient.get(client)?.revisionsByLimitId };
1752
- for (const limitId of readRateLimitIds(value)) revisionsByLimitId[limitId] = (revisionsByLimitId[limitId] ?? 0) + 1;
1753
- rateLimitsByClient.set(client, {
1754
- value,
1755
- updatedAtMs: nowMs,
1756
- revisionsByLimitId
1757
- });
1758
- }
2007
+ function readNonEmptyInitializeString(value) {
2008
+ const trimmed = value?.trim();
2009
+ return trimmed ? trimmed : void 0;
1759
2010
  }
1760
- /** Merges a sparse rolling notification into one physical client's latest read response. */
1761
- function mergeCodexRateLimitsUpdate(client, value, nowMs = Date.now()) {
1762
- const update = isJsonObject$1(value) && isJsonObject$1(value.rateLimits) ? value.rateLimits : void 0;
1763
- if (!update) return;
1764
- const currentState = rateLimitsByClient.get(client);
1765
- const current = currentState?.value;
1766
- const limitId = readLimitId(update);
1767
- rateLimitsByClient.set(client, {
1768
- value: mergeRateLimitUpdate(current, update),
1769
- updatedAtMs: nowMs,
1770
- revisionsByLimitId: {
1771
- ...currentState?.revisionsByLimitId,
1772
- [limitId]: (currentState?.revisionsByLimitId[limitId] ?? 0) + 1
1773
- }
1774
- });
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];
1775
2014
  }
1776
- /** Per-limit marker used to trust only primary Codex updates from one turn startup. */
1777
- function readCodexRateLimitsRevision(client, limitId = "codex") {
1778
- return rateLimitsByClient.get(client)?.revisionsByLimitId[limitId] ?? 0;
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;
1779
2018
  }
1780
- /** Reads one physical client's cached rate-limit payload within the max-age window. */
1781
- function readRecentCodexRateLimits(client, options) {
1782
- const state = rateLimitsByClient.get(client);
1783
- if (!state) return;
1784
- const nowMs = options?.nowMs ?? Date.now();
1785
- const maxAgeMs = options?.maxAgeMs ?? DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS;
1786
- return maxAgeMs >= 0 && nowMs - state.updatedAtMs > maxAgeMs ? void 0 : state.value;
2019
+ function appendBoundedTail(current, next, maxLength) {
2020
+ const combined = `${current}${next}`;
2021
+ return combined.length > maxLength ? sliceUtf16Safe(combined, -maxLength) : combined;
1787
2022
  }
1788
- function mergeRateLimitUpdate(current, update) {
1789
- const currentEnvelope = isJsonObject$1(current) ? current : void 0;
1790
- const currentPrimary = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimits) ? currentEnvelope.rateLimits : void 0;
1791
- const currentByLimitId = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimitsByLimitId) ? currentEnvelope.rateLimitsByLimitId : void 0;
1792
- const limitId = readLimitId(update);
1793
- const currentPrimaryLimitId = currentPrimary ? readLimitId(currentPrimary) : void 0;
1794
- const currentForLimit = (currentByLimitId && isJsonObject$1(currentByLimitId[limitId]) ? currentByLimitId[limitId] : void 0) ?? (currentPrimaryLimitId === limitId ? currentPrimary : void 0);
1795
- const merged = mergeSparseSnapshot(isJsonObject$1(currentForLimit) ? currentForLimit : void 0, currentPrimary, update, limitId);
1796
- const nextPrimary = !currentPrimary || currentPrimaryLimitId === limitId ? merged : currentPrimary;
1797
- let nextByLimitId;
1798
- if (currentByLimitId) nextByLimitId = {
1799
- ...currentByLimitId,
1800
- [limitId]: merged
1801
- };
1802
- else if (currentPrimary && currentPrimaryLimitId && currentPrimaryLimitId !== limitId) nextByLimitId = {
1803
- [currentPrimaryLimitId]: currentPrimary,
1804
- [limitId]: merged
1805
- };
1806
- return {
1807
- ...currentEnvelope,
1808
- rateLimits: nextPrimary,
1809
- ...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
1810
- };
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}`);
1811
2027
  }
1812
- function readRateLimitIds(value) {
1813
- if (!isJsonObject$1(value)) return [];
1814
- const ids = /* @__PURE__ */ new Set();
1815
- if (isJsonObject$1(value.rateLimits)) ids.add(readLimitId(value.rateLimits));
1816
- if (isJsonObject$1(value.rateLimitsByLimitId)) for (const [key, snapshot] of Object.entries(value.rateLimitsByLimitId)) {
1817
- const snapshotLimitId = isJsonObject$1(snapshot) && typeof snapshot.limitId === "string" ? snapshot.limitId.trim() : "";
1818
- ids.add(snapshotLimitId || key);
1819
- }
1820
- return [...ids];
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");
1821
2032
  }
1822
- function mergeSparseSnapshot(current, accountFallback, update, limitId) {
1823
- const merged = {
1824
- ...update,
1825
- limitId
1826
- };
1827
- for (const key of SPARSE_ACCOUNT_METADATA_KEYS) {
1828
- const previous = current?.[key] ?? accountFallback?.[key];
1829
- if (merged[key] == null && previous != null) merged[key] = previous;
1830
- }
1831
- return merged;
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
+ });
1832
2043
  }
1833
- function readLimitId(snapshot) {
1834
- const value = snapshot.limitId;
1835
- return typeof value === "string" && value.trim() ? value.trim() : "codex";
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);
1836
2052
  }
1837
- //#endregion
1838
- //#region extensions/codex/src/app-server/client-runtime.ts
1839
- /** Client-scoped Codex auth and account observers. */
1840
- const configuredClients = /* @__PURE__ */ new WeakMap();
1841
- /** Installs one auth-refresh handler and one rate-limit observer per physical client. */
1842
- function ensureCodexAppServerClientRuntime(client, context) {
1843
- const existing = configuredClients.get(client);
1844
- if (existing) {
1845
- existing.context = context;
1846
- return;
1847
- }
1848
- const runtime = { context };
1849
- configuredClients.set(client, runtime);
1850
- client.addRequestHandler(async (request) => {
1851
- if (request.method !== "account/chatgptAuthTokens/refresh") return;
1852
- if (runtime.context.authMode === "prepared-api-key") throw new Error("ChatGPT token refresh is unavailable for prepared Codex API-key auth.");
1853
- return await refreshCodexAppServerAuthTokens({
1854
- agentDir: runtime.context.agentDir,
1855
- authProfileId: runtime.context.authProfileId,
1856
- ...runtime.context.authProfileStore ? { authProfileStore: runtime.context.authProfileStore } : {},
1857
- config: runtime.context.config
1858
- });
1859
- });
1860
- client.addNotificationHandler((notification) => {
1861
- if (notification.method === "account/rateLimits/updated") mergeCodexRateLimitsUpdate(client, notification.params);
1862
- });
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";
1863
2057
  }
1864
2058
  //#endregion
1865
2059
  //#region extensions/codex/src/app-server/managed-binary.ts
@@ -2152,15 +2346,18 @@ var shared_client_exports = /* @__PURE__ */ __exportAll({
2152
2346
  clearSharedCodexAppServerClientIfCurrentAndWait: () => clearSharedCodexAppServerClientIfCurrentAndWait,
2153
2347
  createIsolatedCodexAppServerClient: () => createIsolatedCodexAppServerClient,
2154
2348
  getLeasedSharedCodexAppServerClient: () => getLeasedSharedCodexAppServerClient,
2349
+ getSharedCodexAppServerClient: () => getSharedCodexAppServerClient,
2155
2350
  isCodexAppServerStartSelectionChangedError: () => isCodexAppServerStartSelectionChangedError,
2156
2351
  releaseCodexAppServerClientLease: () => releaseCodexAppServerClientLease,
2157
2352
  releaseLeasedSharedCodexAppServerClient: () => releaseLeasedSharedCodexAppServerClient,
2158
2353
  resolveCodexAppServerSpawnIdentity: () => resolveCodexAppServerSpawnIdentity,
2159
2354
  resolveCodexNativeConfigFenceKey: () => resolveCodexNativeConfigFenceKey,
2355
+ retainSharedCodexAppServerClientByInstanceId: () => retainSharedCodexAppServerClientByInstanceId,
2160
2356
  retainSharedCodexAppServerClientIfCurrent: () => retainSharedCodexAppServerClientIfCurrent,
2161
2357
  retireSharedCodexAppServerClientIfCurrent: () => retireSharedCodexAppServerClientIfCurrent,
2162
2358
  withLeasedCodexAppServerClientStartSelectionRetry: () => withLeasedCodexAppServerClientStartSelectionRetry
2163
2359
  });
2360
+ const CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE = "codex app-server initialize timed out";
2164
2361
  const suspectClosedClients = /* @__PURE__ */ new WeakSet();
2165
2362
  const SHARED_CODEX_APP_SERVER_CLIENT_STATE = Symbol.for("openclaw.codexAppServerClientState");
2166
2363
  const SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER = Symbol.for("openclaw.codexAppServerClientDisposer");
@@ -2292,6 +2489,48 @@ async function resolveCodexAppServerClientStartContext(options) {
2292
2489
  })
2293
2490
  };
2294
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
+ }
2295
2534
  /** Gets or starts a shared Codex app-server client and records a release lease. */
2296
2535
  async function getLeasedSharedCodexAppServerClient(options) {
2297
2536
  const acquired = await acquireSharedCodexAppServerClient(options, { leased: true });
@@ -2357,6 +2596,17 @@ async function withLeasedCodexAppServerClientStartSelectionRetry(params) {
2357
2596
  }
2358
2597
  async function acquireSharedCodexAppServerClient(options, leaseOptions) {
2359
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
+ }
2360
2610
  const acquireStartedAt = Date.now();
2361
2611
  const timeoutMs = options?.timeoutMs ?? 0;
2362
2612
  const { agentDir, usesNativeAuth, authProfileId, authProfileStore, preparedAuth, authRequirement, requestedStartOptions, startOptions } = await withCodexAppServerAcquireDeadline(timeoutMs, resolveCodexAppServerClientStartContext(options), options?.abandonSignal);
@@ -2371,7 +2621,7 @@ async function acquireSharedCodexAppServerClient(options, leaseOptions) {
2371
2621
  const runtimeArtifactMode = options?.runtimeArtifactMode ?? (options?.expectedRuntimeArtifact ? "capture" : void 0);
2372
2622
  const expectedRuntimeArtifactKey = options?.expectedRuntimeArtifact ? createHash("sha256").update(options.expectedRuntimeArtifact.id).update("\0").update(options.expectedRuntimeArtifact.fingerprint).digest("hex") : "mint";
2373
2623
  const key = runtimeArtifactMode ? `${baseKey}\0runtime-artifact:capture-v1:${expectedRuntimeArtifactKey}` : baseKey;
2374
- const entry = getOrCreateSharedClientEntry(getSharedCodexAppServerClientState(), key);
2624
+ const entry = getOrCreateSharedClientEntry(state, key);
2375
2625
  if (runtimeArtifactMode) entry.runtimeArtifactStartupAbort ??= new AbortController();
2376
2626
  entry.closeWhenIdle = false;
2377
2627
  const releasePendingAcquire = retainPendingSharedClientAcquire(entry);
@@ -2410,7 +2660,7 @@ async function acquireSharedCodexAppServerClient(options, leaseOptions) {
2410
2660
  config: options?.config
2411
2661
  }));
2412
2662
  try {
2413
- await withCodexAppServerAcquireDeadline(remainingTimeoutMs, startup.initialized, options?.abandonSignal);
2663
+ await withCodexAppServerAcquireDeadline(remainingTimeoutMs, startup.initialized, options?.abandonSignal, CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, () => buildCodexAppServerInitializeTimeoutError(entry.client));
2414
2664
  const client = await withCodexAppServerAcquireDeadline(timeoutMs, startup.ready, options?.abandonSignal, "codex app-server authentication timed out");
2415
2665
  if (entry.closeError) throw entry.closeError;
2416
2666
  ensureCodexAppServerClientRuntime(client, {
@@ -2421,6 +2671,11 @@ async function acquireSharedCodexAppServerClient(options, leaseOptions) {
2421
2671
  config: options?.config
2422
2672
  });
2423
2673
  const release = leaseOptions?.leased ? retainSharedClientEntry(entry) : void 0;
2674
+ if (warmIdentity) rememberWarmSharedCodexAppServerClient(state, warmIdentity, {
2675
+ key,
2676
+ entry,
2677
+ client
2678
+ });
2424
2679
  return release ? {
2425
2680
  client,
2426
2681
  release
@@ -2435,9 +2690,9 @@ async function acquireSharedCodexAppServerClient(options, leaseOptions) {
2435
2690
  releasePendingAcquire();
2436
2691
  }
2437
2692
  }
2438
- async function withCodexAppServerAcquireDeadline(timeoutMs, promise, signal, timeoutMessage = "codex app-server initialize timed out") {
2693
+ async function withCodexAppServerAcquireDeadline(timeoutMs, promise, signal, timeoutMessage = CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, timeoutErrorFactory) {
2439
2694
  if (signal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
2440
- const timed = withTimeout$1(promise, timeoutMs, timeoutMessage, () => new CodexAppServerStartupError("timed_out", timeoutMessage));
2695
+ const timed = withTimeout$1(promise, timeoutMs, timeoutMessage, () => timeoutErrorFactory?.() ?? new CodexAppServerStartupError("timed_out", timeoutMessage));
2441
2696
  if (!signal) return await timed;
2442
2697
  return await new Promise((resolve, reject) => {
2443
2698
  const onAbort = () => reject(new CodexAppServerStartupError("aborted", "codex app-server initialize aborted"));
@@ -2445,6 +2700,10 @@ async function withCodexAppServerAcquireDeadline(timeoutMs, promise, signal, tim
2445
2700
  timed.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2446
2701
  });
2447
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
+ }
2448
2707
  function resolveRemainingAcquireTimeout(timeoutMs, startedAt) {
2449
2708
  if (!(timeoutMs > 0)) return timeoutMs;
2450
2709
  const remaining = timeoutMs - (Date.now() - startedAt);
@@ -2513,7 +2772,7 @@ async function startInitializedCodexAppServerClient(params) {
2513
2772
  const timeoutMs = params.timeoutMs ?? 0;
2514
2773
  const startOptionsCandidates = resolveManagedFallbackStartOptions(params.startOptions);
2515
2774
  for (const [index, startOptions] of startOptionsCandidates.entries()) {
2516
- const runtimeArtifactModule = params.runtimeArtifactMode ? await import("./runtime-artifact-C2ITXdhM.js") : void 0;
2775
+ const runtimeArtifactModule = params.runtimeArtifactMode ? await import("./runtime-artifact-CmtG_t1L.js") : void 0;
2517
2776
  const nativeCommandBeforeStart = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
2518
2777
  const runtimeArtifactBeforeStart = runtimeArtifactModule ? await runtimeArtifactModule.captureCodexAppServerRuntimeArtifactBeforeStart({
2519
2778
  startOptions,
@@ -2528,7 +2787,7 @@ async function startInitializedCodexAppServerClient(params) {
2528
2787
  params.onStartedClient?.(client);
2529
2788
  let initialize;
2530
2789
  try {
2531
- await withCodexAppServerAcquireDeadline(resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt), initialize = client.initialize(), params.abandonSignal);
2790
+ await withCodexAppServerAcquireDeadline(resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt), initialize = client.initialize(), params.abandonSignal, CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, () => buildCodexAppServerInitializeTimeoutError(client));
2532
2791
  } catch (error) {
2533
2792
  client.close();
2534
2793
  initialize?.catch(() => void 0);
@@ -2633,6 +2892,19 @@ function retainSharedCodexAppServerClientIfCurrent(client) {
2633
2892
  const state = getSharedCodexAppServerClientState();
2634
2893
  for (const entry of state.clients.values()) if (entry.client === client) return retainSharedClientEntry(entry);
2635
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
+ }
2636
2908
  /**
2637
2909
  * Retires a matching shared client. Default is graceful: detach from the map
2638
2910
  * (future acquisitions get a fresh client) and close once leases drain.
@@ -2695,6 +2967,7 @@ async function clearSharedCodexAppServerClientAndWait(options) {
2695
2967
  const state = getSharedCodexAppServerClientState();
2696
2968
  const clients = collectSharedClients(state);
2697
2969
  state.clients.clear();
2970
+ state.warmClientsByConfig = /* @__PURE__ */ new WeakMap();
2698
2971
  await Promise.all(clients.map((client) => client.closeAndWait(options)));
2699
2972
  }
2700
2973
  globalThis[SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER] = clearSharedCodexAppServerClientAndWait;
@@ -2793,4 +3066,4 @@ function collectSharedClients(state) {
2793
3066
  return [...new Set([...state.clients.values()].map((entry) => entry.client).filter((client) => Boolean(client)))];
2794
3067
  }
2795
3068
  //#endregion
2796
- export { isCodexAppServerStartupError as A, isCodexAppServerApprovalRequest as B, resolveCodexAppServerFallbackApiKeyCacheKey as C, resolveCodexAppServerHomeDir as D, resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath as E, resolveCodexTurnCompletionIdleTimeoutMs as F, isCodexAppServerPrewriteRequestCancellationError as G, isCodexAppServerConnectionClosedError as H, resolveCodexTurnTerminalIdleTimeoutMs as I, CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES as J, isCodexAppServerRequestTimeoutError as K, withCodexStartupTimeout as L, resolveCodexPostToolRawAssistantCompletionIdleTimeoutMs as M, resolveCodexStartupTimeoutMs as N, CODEX_POST_REASONING_REPLY_IDLE_TIMEOUT_MS as O, resolveCodexTurnAssistantCompletionIdleTimeoutMs as P, isJsonObject$1 as Q, CodexAppServerRpcError as R, resolveCodexAppServerAuthProfileIdForAgent as S, resolveCodexAppServerPreparedAuthHandoff as T, isCodexAppServerIndeterminateRequestCancellationError as U, isCodexAppServerBrokenPipeError as V, isCodexAppServerIndeterminateTransportError as W, CODEX_OPENCLAW_DIRECT_DYNAMIC_TOOL_NAMESPACE as X, CODEX_INTERACTIVE_THREAD_SOURCE_KINDS as Y, flattenCodexDynamicToolFunctions as Z, readCodexRateLimitsRevision as _, getLeasedSharedCodexAppServerClient as a, resolveCodexAppServerAuthAccountCacheKey as b, releaseLeasedSharedCodexAppServerClient as c, retireSharedCodexAppServerClientIfCurrent as d, shared_client_exports as f, ensureCodexAppServerClientRuntime as g, acquireCodexNativeConfigFence as h, createIsolatedCodexAppServerClient as i, resolveCodexGatewayTimeoutWithGraceMs as j, CodexAppServerStartupError as k, resolveCodexNativeConfigFenceKey as l, withTimeout$1 as m, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as n, isCodexAppServerStartSelectionChangedError as o, withLeasedCodexAppServerClientStartSelectionRetry as p, resolveCodexAppServerClientInstanceId as q, clearSharedCodexAppServerClientIfCurrentAndWait as r, releaseCodexAppServerClientLease as s, clearSharedCodexAppServerClientIfCurrent as t, retainSharedCodexAppServerClientIfCurrent as u, readRecentCodexRateLimits as v, resolveCodexAppServerPreparedApiKeyCacheKey as w, resolveCodexAppServerAuthProfileId as x, rememberCodexRateLimitsRead as y, getCodexAppServerClientInstanceId as z };
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 };