@openclaw/codex 2026.7.2-beta.3 → 2026.7.2-beta.5

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