@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.
- package/dist/{app-server-policy-DUMF2Xyr.js → app-server-policy-BmDgseo_.js} +1 -1
- package/dist/attempt-client-cleanup-Ia52yRWc.js +127 -0
- package/dist/{attempt-notifications-Ecjyzufe.js → attempt-notifications-CMR2_fmR.js} +1 -1
- package/dist/{media-understanding-provider-IPNNQre6.js → bounded-turn-FEbUXoYT.js} +71 -188
- package/dist/capabilities-BHRSI6Cn.js +36 -0
- package/dist/cli-metadata.js +1 -1
- package/dist/{command-formatters-NCTL7A2q.js → command-formatters-ico4ZFnk.js} +3 -37
- package/dist/{command-handlers-DtFbZiba.js → command-handlers-CRmnwI2N.js} +1233 -1221
- package/dist/{compact-Kgy26gIM.js → compact-dEN49UH6.js} +8 -7
- package/dist/{computer-use-C7x4ZaqR.js → computer-use-BjGylO-E.js} +16 -6
- package/dist/{conversation-control-B0s3aIjT.js → conversation-control-DE7d9DOj.js} +6 -5
- package/dist/doctor-contract-api.js +24 -86
- package/dist/{dynamic-tools-D_vSVmv9.js → dynamic-tools-LIt9ojep.js} +135 -2696
- package/dist/event-projector-assistant-message-DTgnPPVF.js +101 -0
- package/dist/event-projector-usage-tvgb1NCX.js +69 -0
- package/dist/harness.js +31 -11
- package/dist/incognito-session-ET_ufDH-.js +2 -0
- package/dist/index.js +250 -275
- package/dist/media-understanding-provider.js +173 -1
- package/dist/{models-DD5zBdX5.js → models-BA01NEez.js} +2 -2
- package/dist/{notification-correlation-C8DVQ_Bq.js → notification-correlation-Bj_Ak_jI.js} +3 -3
- package/dist/{plugin-app-cache-key-DJbhLYSK.js → plugin-app-cache-key-DSXX-rXO.js} +5 -5
- package/dist/{transcript-mirror-D9rTxx2P.js → protocol-validators-Dm4eXZmt.js} +335 -595
- package/dist/{rate-limits-CqhWQ2R9.js → rate-limits-S_PXs0ul.js} +1 -1
- package/dist/realtime-voice-api-BPcA1uN9.js +494 -0
- package/dist/realtime-voice-api.js +2 -0
- package/dist/{request-9yf9pZjf.js → request-CXpPennK.js} +1 -1
- package/dist/{run-attempt-BIoO8ISr.js → run-attempt-C5GTPJOE.js} +3111 -387
- package/dist/{session-binding-Bmt20HfB.js → session-binding-DlVQ-Pxs.js} +957 -890
- package/dist/{session-catalog-CA7R-hX2.js → session-catalog-CP2oCcEb.js} +98 -87
- package/dist/{session-cli-Bxk3-Wqz.js → session-cli-CqZ0Fp2a.js} +2 -2
- package/dist/session-upstream-marker-QE-m5QFG.js +82 -0
- package/dist/settled-turn-finalizer-CA_2QXIE.js +303 -0
- package/dist/{shared-client-CSXLtCLE.js → shared-client-BVKE40c-.js} +1870 -1694
- package/dist/{side-question-DtzquMOb.js → side-question-CO12sHxo.js} +24 -16
- package/dist/{thread-lifecycle-CQ_9mAa1.js → thread-lifecycle-DRg_FdzC.js} +127 -153
- package/dist/transcript-mirror-uKA-A4tB.js +550 -0
- package/dist/upstream-session-fork-_Vrz4WJr.js +320 -0
- package/dist/{usage-CuPpFgTc.js → usage-UpVbdX5G.js} +3 -3
- package/dist/{web-search-provider.runtime-_x5XTeqh.js → web-search-provider.runtime-CaQMYDbp.js} +3 -3
- package/package.json +7 -8
- package/npm-shrinkwrap.json +0 -202
- 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 {
|
|
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 {
|
|
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 {
|
|
13
|
-
import {
|
|
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/
|
|
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
|
-
*
|
|
44
|
-
*
|
|
30
|
+
* Timeout defaults and normalizers for Codex app-server startup and turn
|
|
31
|
+
* liveness watches.
|
|
45
32
|
*/
|
|
46
|
-
/**
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
|
|
112
|
-
|
|
113
|
-
return net.createConnection(socketPath);
|
|
55
|
+
function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
|
|
56
|
+
return resolveTimerTimeoutMs(value, resolveTimerTimeoutMs(fallbackMs, 1));
|
|
114
57
|
}
|
|
115
|
-
/**
|
|
116
|
-
function
|
|
117
|
-
if (
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
return
|
|
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
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
/**
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
|
|
159
|
-
|
|
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
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
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/
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
-
/**
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
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
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
+
function skippedCacheResult(status, message) {
|
|
262
|
+
return {
|
|
263
|
+
status,
|
|
264
|
+
changed: false,
|
|
265
|
+
message,
|
|
266
|
+
removedStaleVersions: [],
|
|
267
|
+
warnings: status === "source_missing" ? [message] : []
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
//#endregion
|
|
271
|
+
//#region extensions/codex/src/app-server/computer-use-service.ts
|
|
272
|
+
/** Native Computer Use service provisioning for isolated Codex homes. */
|
|
273
|
+
const SERVICE_APP_NAME = "Codex Computer Use.app";
|
|
274
|
+
const CLIENT_RELATIVE_PATH = path.join("Contents", "SharedSupport", "SkyComputerUseClient.app", "Contents", "MacOS", "SkyComputerUseClient");
|
|
275
|
+
const COPY_TIMEOUT_MS = 12e4;
|
|
276
|
+
const activeInstalls = /* @__PURE__ */ new Map();
|
|
277
|
+
/** Ensures the official native client exists beneath the CODEX_HOME used by its launcher. */
|
|
278
|
+
async function ensureCodexComputerUseServiceApp(params) {
|
|
279
|
+
const platform = params.platform ?? process.platform;
|
|
280
|
+
if (platform !== "darwin") return {
|
|
281
|
+
status: "unsupported",
|
|
282
|
+
changed: false
|
|
283
|
+
};
|
|
284
|
+
const targetPath = path.join(path.resolve(params.codexHome), "computer-use", SERVICE_APP_NAME);
|
|
285
|
+
const active = activeInstalls.get(targetPath);
|
|
286
|
+
if (active) return await active;
|
|
287
|
+
const install = ensureCodexComputerUseServiceAppOnce({
|
|
288
|
+
...params,
|
|
289
|
+
targetPath,
|
|
290
|
+
platform
|
|
291
|
+
});
|
|
292
|
+
activeInstalls.set(targetPath, install);
|
|
293
|
+
try {
|
|
294
|
+
return await install;
|
|
295
|
+
} finally {
|
|
296
|
+
if (activeInstalls.get(targetPath) === install) activeInstalls.delete(targetPath);
|
|
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
|
-
|
|
268
|
-
|
|
269
|
-
|
|
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
|
-
|
|
272
|
-
|
|
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
|
|
276
|
-
const
|
|
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
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
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
|
|
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
|
-
|
|
292
|
-
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
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
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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
|
-
|
|
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
|
-
|
|
642
|
-
const
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
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
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
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
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
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
|
-
|
|
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
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
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
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
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
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
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
|
-
|
|
753
|
-
|
|
754
|
-
|
|
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
|
-
|
|
758
|
-
|
|
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
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
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
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
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
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
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
|
|
795
|
-
return
|
|
987
|
+
function readFirstNonEmptyEnv(env, keys) {
|
|
988
|
+
return readFirstNonEmptyEnvEntry(env, keys)?.value;
|
|
796
989
|
}
|
|
797
|
-
function
|
|
798
|
-
|
|
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
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
success: false
|
|
1001
|
+
type: "chatgptAuthTokens",
|
|
1002
|
+
accessToken,
|
|
1003
|
+
chatgptAccountId: resolveChatgptAccountId(profileId, credential),
|
|
1004
|
+
chatgptPlanType: resolveChatgptPlanType(credential)
|
|
805
1005
|
};
|
|
806
1006
|
}
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
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
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
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
|
-
|
|
823
|
-
|
|
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
|
|
826
|
-
const
|
|
827
|
-
const
|
|
828
|
-
const
|
|
829
|
-
const
|
|
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
|
-
|
|
832
|
-
|
|
833
|
-
...
|
|
834
|
-
...platformFamily ? { platformFamily } : {},
|
|
835
|
-
...platformOs ? { platformOs } : {}
|
|
1090
|
+
...currentEnvelope,
|
|
1091
|
+
rateLimits: nextPrimary,
|
|
1092
|
+
...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
|
|
836
1093
|
};
|
|
837
1094
|
}
|
|
838
|
-
function
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
}
|
|
846
|
-
|
|
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
|
|
855
|
-
const
|
|
856
|
-
|
|
857
|
-
|
|
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
|
|
860
|
-
|
|
861
|
-
|
|
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
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
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/
|
|
1148
|
+
//#region extensions/codex/src/app-server/transport-websocket.ts
|
|
891
1149
|
/**
|
|
892
|
-
*
|
|
893
|
-
*
|
|
1150
|
+
* Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
|
|
1151
|
+
* transport interface.
|
|
894
1152
|
*/
|
|
895
|
-
/**
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
const
|
|
899
|
-
|
|
900
|
-
const
|
|
901
|
-
const
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
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
|
-
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
|
|
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
|
-
/**
|
|
959
|
-
function
|
|
960
|
-
|
|
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
|
|
965
|
-
function
|
|
966
|
-
|
|
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
|
-
|
|
969
|
-
|
|
970
|
-
return
|
|
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
|
-
|
|
973
|
-
|
|
974
|
-
|
|
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
|
-
/**
|
|
977
|
-
function
|
|
978
|
-
|
|
979
|
-
return
|
|
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
|
-
|
|
982
|
-
|
|
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
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
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
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
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/
|
|
1009
|
-
/**
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
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/
|
|
1031
|
-
/**
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
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
|
-
|
|
1060
|
-
|
|
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
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
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
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
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
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
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
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
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
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
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
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
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
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
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
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
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
|
-
|
|
1207
|
-
|
|
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
|
-
/**
|
|
1238
|
-
|
|
1239
|
-
if (
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
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
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
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
|
-
|
|
1305
|
-
|
|
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
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
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
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
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
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
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
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
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
|
-
|
|
1416
|
-
|
|
1417
|
-
if (
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
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
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
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
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
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
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
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
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
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
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
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
|
-
|
|
1549
|
-
const
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
}
|
|
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
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
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
|
-
|
|
1604
|
-
|
|
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
|
|
1658
|
-
|
|
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
|
|
1676
|
-
|
|
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
|
-
|
|
1681
|
-
|
|
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
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
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
|
|
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
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1957
|
+
serverVersion,
|
|
1958
|
+
...userAgent ? { userAgent } : {},
|
|
1959
|
+
...codexHome ? { codexHome } : {},
|
|
1960
|
+
...platformFamily ? { platformFamily } : {},
|
|
1961
|
+
...platformOs ? { platformOs } : {}
|
|
1702
1962
|
};
|
|
1703
1963
|
}
|
|
1704
|
-
function
|
|
1705
|
-
const
|
|
1706
|
-
|
|
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
|
-
/**
|
|
1741
|
-
function
|
|
1742
|
-
|
|
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
|
-
|
|
1757
|
-
|
|
1758
|
-
return
|
|
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
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
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
|
|
1769
|
-
const
|
|
1770
|
-
const
|
|
1771
|
-
|
|
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
|
|
1793
|
-
if (!
|
|
1794
|
-
const
|
|
1795
|
-
|
|
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
|
|
1803
|
-
const
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
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
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
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
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
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 {
|
|
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 };
|