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