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