@openclaw/codex 2026.7.2-beta.5 → 2026.7.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -27
- package/dist/{command-formatters-ico4ZFnk.js → .setup/app-server-policy-C_qTMEMy.mjs} +51 -9
- package/dist/{attempt-notifications-CMR2_fmR.js → .setup/attempt-notifications-F8krwWL4.mjs} +6 -3
- package/dist/{command-handlers-CRmnwI2N.js → .setup/command-handlers-DSRFfor4.mjs} +1156 -1319
- package/dist/.setup/command-rpc-BvYsfQ7G.mjs +786 -0
- package/dist/{compact-dEN49UH6.js → .setup/compact-BNgh7I4t.mjs} +10 -40
- package/dist/.setup/computer-use-C3QkmSO3.mjs +377 -0
- package/dist/.setup/config-CYEDnLJ2.mjs +1138 -0
- package/dist/{conversation-binding-data-BHRpYbX3.js → .setup/conversation-binding-data-CrRxtDBu.mjs} +1 -1
- package/dist/{bounded-turn-FEbUXoYT.js → .setup/media-understanding-provider-EbJCyDqe.mjs} +193 -92
- package/dist/{models-BA01NEez.js → .setup/models-C_aZk03A.mjs} +11 -6
- package/dist/.setup/notification-correlation-iYs4WieS.mjs +35 -0
- package/dist/.setup/plugin-app-cache-key-DR8jV9oS.mjs +99 -0
- package/dist/.setup/protocol-2POPqAY4.mjs +13 -0
- package/dist/{protocol-validators-Dm4eXZmt.js → .setup/protocol-validators-dZQ-UTOa.mjs} +111 -334
- package/dist/{rate-limits-S_PXs0ul.js → .setup/provider-DGxDs6g8.mjs} +269 -13
- package/dist/{dynamic-tools-LIt9ojep.js → .setup/provider-capabilities-DS2N_zc1.mjs} +5465 -3399
- package/dist/.setup/request-DFR0JyoV.mjs +36 -0
- package/dist/.setup/run-attempt-C7xEKFVB.mjs +8180 -0
- package/dist/{sandbox-guard-D1Wky__S.js → .setup/sandbox-guard-DA2TQfZW.mjs} +1 -10
- package/dist/.setup/session-binding-DuihlMJc.mjs +628 -0
- package/dist/.setup/shared-client-B2KmLPRw.mjs +1854 -0
- package/dist/{side-question-CO12sHxo.js → .setup/side-question-Cv6JXWCS.mjs} +84 -159
- package/dist/{thread-lifecycle-DRg_FdzC.js → .setup/thread-lifecycle-u6CZdOOH.mjs} +1159 -1799
- package/dist/{web-search-provider.runtime-CaQMYDbp.js → .setup/web-search-provider.runtime-Ce2zOHxW.mjs} +3 -3
- package/dist/doctor-contract-api.js +122 -88
- package/dist/harness.js +20 -85
- package/dist/index.js +381 -1537
- package/dist/media-understanding-provider.js +1 -173
- package/dist/prompt-overlay.js +15 -0
- package/dist/provider-catalog.js +79 -0
- package/dist/provider-discovery.js +34 -0
- package/dist/provider.js +2 -0
- package/dist/web-search-contract-api.js +1 -1
- package/openclaw.plugin.json +178 -221
- package/package.json +8 -10
- package/dist/app-server-policy-BmDgseo_.js +0 -49
- package/dist/attempt-client-cleanup-Ia52yRWc.js +0 -127
- package/dist/auth-binding-B4FfbcCg.js +0 -62
- package/dist/capabilities-BHRSI6Cn.js +0 -36
- package/dist/cli-metadata.js +0 -20
- package/dist/computer-use-BjGylO-E.js +0 -695
- package/dist/conversation-control-DE7d9DOj.js +0 -287
- package/dist/event-projector-assistant-message-DTgnPPVF.js +0 -101
- package/dist/event-projector-usage-tvgb1NCX.js +0 -69
- package/dist/incognito-session-ET_ufDH-.js +0 -2
- package/dist/notification-correlation-Bj_Ak_jI.js +0 -67
- package/dist/plugin-app-cache-key-DSXX-rXO.js +0 -315
- package/dist/realtime-voice-api-BPcA1uN9.js +0 -494
- package/dist/realtime-voice-api.js +0 -2
- package/dist/request-CXpPennK.js +0 -157
- package/dist/run-attempt-C5GTPJOE.js +0 -11935
- package/dist/runtime-artifact-C2ITXdhM.js +0 -488
- package/dist/session-binding-DlVQ-Pxs.js +0 -2161
- package/dist/session-catalog-CP2oCcEb.js +0 -2444
- package/dist/session-cli-CqZ0Fp2a.js +0 -175
- package/dist/session-upstream-marker-QE-m5QFG.js +0 -82
- package/dist/settled-turn-finalizer-CA_2QXIE.js +0 -303
- package/dist/shared-client-BVKE40c-.js +0 -2952
- package/dist/transcript-mirror-uKA-A4tB.js +0 -550
- package/dist/transport-stdio-DXgGZ7Ib.js +0 -88
- package/dist/upstream-session-fork-_Vrz4WJr.js +0 -320
- package/dist/usage-UpVbdX5G.js +0 -25
- /package/dist/{rolldown-runtime-8H4AJuhK.js → .setup/rolldown-runtime-8H4AJuhK.mjs} +0 -0
- /package/dist/{session-binding-meta-B7aEMU7g.js → .setup/session-binding-meta-B7aEMU7g.mjs} +0 -0
- /package/dist/{web-search-provider.shared-BrZmlqyR.js → .setup/web-search-provider.shared-BrZmlqyR.mjs} +0 -0
|
@@ -1,2952 +0,0 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
|
|
2
|
-
import { d as codexAppServerStartOptionsKey, h as resolveCodexComputerUseConfig, m as resolveCodexAppServerStartOptionsForAgent, o as isCodexAppServerNativeAuthProfile, p as resolveCodexAppServerRuntimeOptions, x as resolveCodexAppServerUserHomeDir } from "./session-binding-DlVQ-Pxs.js";
|
|
3
|
-
import { n as resolveCodexAppServerSpawnEnv, t as createStdioTransport } from "./transport-stdio-DXgGZ7Ib.js";
|
|
4
|
-
import { createRequire } from "node:module";
|
|
5
|
-
import fs, { access } from "node:fs/promises";
|
|
6
|
-
import path from "node:path";
|
|
7
|
-
import { addTimerTimeoutGraceMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
8
|
-
import { AgentHarnessPreflightError, OPENCLAW_VERSION, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
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";
|
|
12
|
-
import fsSync, { constants, existsSync, readFileSync, realpathSync } from "node:fs";
|
|
13
|
-
import os from "node:os";
|
|
14
|
-
import { isDeepStrictEqual } from "node:util";
|
|
15
|
-
import { hasUsableOAuthCredential } from "openclaw/plugin-sdk/provider-auth";
|
|
16
|
-
import { runExec } from "openclaw/plugin-sdk/process-runtime";
|
|
17
|
-
import { createInterface } from "node:readline";
|
|
18
|
-
import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
19
|
-
import { parse } from "semver";
|
|
20
|
-
import { EventEmitter } from "node:events";
|
|
21
|
-
import net from "node:net";
|
|
22
|
-
import { PassThrough, Writable } from "node:stream";
|
|
23
|
-
import { StringDecoder } from "node:string_decoder";
|
|
24
|
-
import WebSocket from "ws";
|
|
25
|
-
import { fileURLToPath } from "node:url";
|
|
26
|
-
import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
|
|
27
|
-
import { withTimeout } from "openclaw/plugin-sdk/security-runtime";
|
|
28
|
-
//#region extensions/codex/src/app-server/attempt-timeouts.ts
|
|
29
|
-
/**
|
|
30
|
-
* Timeout defaults and normalizers for Codex app-server startup and turn
|
|
31
|
-
* liveness watches.
|
|
32
|
-
*/
|
|
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);
|
|
54
|
-
}
|
|
55
|
-
function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
|
|
56
|
-
return resolveTimerTimeoutMs(value, resolveTimerTimeoutMs(fallbackMs, 1));
|
|
57
|
-
}
|
|
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?.();
|
|
94
|
-
}
|
|
95
|
-
}
|
|
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);
|
|
101
|
-
}
|
|
102
|
-
/** Resolves the completion-idle timeout for an active turn. */
|
|
103
|
-
function resolveCodexTurnCompletionIdleTimeoutMs(value) {
|
|
104
|
-
return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS);
|
|
105
|
-
}
|
|
106
|
-
/** Resolves the short assistant-completion release timeout. */
|
|
107
|
-
function resolveCodexTurnAssistantCompletionIdleTimeoutMs(value) {
|
|
108
|
-
return resolvePositiveIntegerTimeoutMs(value, CODEX_TURN_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS);
|
|
109
|
-
}
|
|
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));
|
|
113
|
-
}
|
|
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));
|
|
118
|
-
}
|
|
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;
|
|
123
|
-
}
|
|
124
|
-
//#endregion
|
|
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
|
-
}
|
|
145
|
-
//#endregion
|
|
146
|
-
//#region extensions/codex/src/app-server/desktop-app-paths.ts
|
|
147
|
-
/** Shared path candidates for Codex's macOS desktop app bundle. */
|
|
148
|
-
const MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES = [{
|
|
149
|
-
appName: "ChatGPT.app",
|
|
150
|
-
appBundlePath: "/Applications/ChatGPT.app",
|
|
151
|
-
appServerCommandPath: "/Applications/ChatGPT.app/Contents/Resources/codex",
|
|
152
|
-
bundledMarketplacePath: "/Applications/ChatGPT.app/Contents/Resources/plugins/openai-bundled",
|
|
153
|
-
computerUseServiceAppPaths: ["/Applications/ChatGPT.app/Contents/Resources/cua_node/lib/node_modules/@oai/sky/Codex Computer Use.app", "/Applications/ChatGPT.app/Contents/Resources/plugins/openai-bundled/plugins/computer-use/Codex Computer Use.app"]
|
|
154
|
-
}, {
|
|
155
|
-
appName: "Codex.app",
|
|
156
|
-
appBundlePath: "/Applications/Codex.app",
|
|
157
|
-
appServerCommandPath: "/Applications/Codex.app/Contents/Resources/codex",
|
|
158
|
-
bundledMarketplacePath: "/Applications/Codex.app/Contents/Resources/plugins/openai-bundled",
|
|
159
|
-
computerUseServiceAppPaths: ["/Applications/Codex.app/Contents/Resources/plugins/openai-bundled/plugins/computer-use/Codex Computer Use.app", "/Applications/Codex.app/Contents/Resources/cua_node/lib/node_modules/@oai/sky/Codex Computer Use.app"]
|
|
160
|
-
}];
|
|
161
|
-
function resolveMacOSDesktopCodexBundledMarketplaceCandidates(platform = process.platform) {
|
|
162
|
-
return platform === "darwin" ? MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.map((candidate) => candidate.bundledMarketplacePath) : [];
|
|
163
|
-
}
|
|
164
|
-
function resolveMacOSDesktopCodexComputerUseServiceAppCandidates(platform = process.platform, appServerCommand) {
|
|
165
|
-
if (platform !== "darwin") return [];
|
|
166
|
-
const matchingCandidate = appServerCommand ? MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.find((candidate) => path.resolve(candidate.appServerCommandPath) === path.resolve(appServerCommand)) : void 0;
|
|
167
|
-
const orderedCandidates = matchingCandidate ? [matchingCandidate, ...MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES.filter((candidate) => candidate !== matchingCandidate)] : MACOS_DESKTOP_CODEX_APP_PATH_CANDIDATES;
|
|
168
|
-
return [...new Set(orderedCandidates.flatMap((candidate) => candidate.computerUseServiceAppPaths))];
|
|
169
|
-
}
|
|
170
|
-
function resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath(params = {}) {
|
|
171
|
-
const candidates = params.candidates ?? resolveMacOSDesktopCodexBundledMarketplaceCandidates(params.platform);
|
|
172
|
-
const pathExists = params.pathExists ?? existsSync;
|
|
173
|
-
return candidates.find((candidate) => pathExists(candidate));
|
|
174
|
-
}
|
|
175
|
-
//#endregion
|
|
176
|
-
//#region extensions/codex/src/app-server/computer-use-cache.ts
|
|
177
|
-
/** Shared Computer Use plugin cache reconciliation for isolated Codex homes. */
|
|
178
|
-
const DEFAULT_CODEX_COMPUTER_USE_BUNDLED_MARKETPLACE_PATH = resolveMacOSDesktopCodexBundledMarketplaceCandidates("darwin")[0] ?? "";
|
|
179
|
-
const DEFAULT_BUNDLED_MARKETPLACE_NAME = "openai-bundled";
|
|
180
|
-
async function ensureCodexComputerUseSharedPluginCache(params) {
|
|
181
|
-
if (!params.config.enabled) return skippedCacheResult("disabled", "Computer Use cache sharing skipped because it is disabled.");
|
|
182
|
-
if (params.config.pluginCacheMode === "independent") return skippedCacheResult("independent", "Computer Use cache sharing skipped because pluginCacheMode is independent.");
|
|
183
|
-
if (params.config.marketplaceName || params.config.marketplacePath) return skippedCacheResult("explicit_marketplace", "Computer Use cache sharing skipped because an explicit marketplace is configured.");
|
|
184
|
-
const bundledMarketplacePath = resolveComputerUseBundledMarketplacePath(params);
|
|
185
|
-
const sourcePluginRoot = path.join(bundledMarketplacePath, "plugins", params.config.pluginName);
|
|
186
|
-
const version = await readBundledPluginVersion(sourcePluginRoot);
|
|
187
|
-
if (!version) return skippedCacheResult("source_missing", `Computer Use bundled plugin source was not found at ${sourcePluginRoot}.`);
|
|
188
|
-
const marketplaceName = params.config.marketplaceName ?? DEFAULT_BUNDLED_MARKETPLACE_NAME;
|
|
189
|
-
const cacheRoot = path.join(params.codexHome, "plugins", "cache", marketplaceName, params.config.pluginName);
|
|
190
|
-
const cachePath = path.join(cacheRoot, version);
|
|
191
|
-
return {
|
|
192
|
-
status: "shared",
|
|
193
|
-
changed: await ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version),
|
|
194
|
-
cachePath,
|
|
195
|
-
targetPath: sourcePluginRoot,
|
|
196
|
-
version,
|
|
197
|
-
removedStaleVersions: [],
|
|
198
|
-
warnings: [],
|
|
199
|
-
message: `Computer Use plugin cache ${cachePath} contains bundled plugin ${sourcePluginRoot}.`
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
function resolveComputerUseBundledMarketplacePath(params) {
|
|
203
|
-
return params.bundledMarketplacePath ?? resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath({ candidates: params.bundledMarketplacePathCandidates }) ?? params.bundledMarketplacePathCandidates?.[0] ?? DEFAULT_CODEX_COMPUTER_USE_BUNDLED_MARKETPLACE_PATH;
|
|
204
|
-
}
|
|
205
|
-
async function readBundledPluginVersion(sourcePluginRoot) {
|
|
206
|
-
const pluginJsonPath = path.join(sourcePluginRoot, ".codex-plugin", "plugin.json");
|
|
207
|
-
let raw;
|
|
208
|
-
try {
|
|
209
|
-
raw = await fs.readFile(pluginJsonPath, "utf8");
|
|
210
|
-
} catch {
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
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;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
async function ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version) {
|
|
221
|
-
await fs.mkdir(path.dirname(cachePath), { recursive: true });
|
|
222
|
-
const stat = await fs.lstat(cachePath).catch(() => void 0);
|
|
223
|
-
if (stat?.isDirectory() && !stat.isSymbolicLink()) {
|
|
224
|
-
if (await readBundledPluginVersion(cachePath) === version) return false;
|
|
225
|
-
}
|
|
226
|
-
const cacheRoot = path.dirname(cachePath);
|
|
227
|
-
const cacheName = path.basename(cachePath);
|
|
228
|
-
const stagingRoot = await fs.mkdtemp(path.join(cacheRoot, `.${cacheName}.staging-`));
|
|
229
|
-
const stagedPath = path.join(stagingRoot, cacheName);
|
|
230
|
-
const backupPath = path.join(cacheRoot, `.${cacheName}.backup-${process.pid}-${Date.now()}`);
|
|
231
|
-
let backupCreated = false;
|
|
232
|
-
try {
|
|
233
|
-
await fs.cp(sourcePluginRoot, stagedPath, { recursive: true });
|
|
234
|
-
if (stat) {
|
|
235
|
-
await fs.rename(cachePath, backupPath);
|
|
236
|
-
backupCreated = true;
|
|
237
|
-
}
|
|
238
|
-
try {
|
|
239
|
-
await fs.rename(stagedPath, cachePath);
|
|
240
|
-
} catch (error) {
|
|
241
|
-
if (backupCreated) try {
|
|
242
|
-
await fs.rename(backupPath, cachePath);
|
|
243
|
-
backupCreated = false;
|
|
244
|
-
} catch (restoreError) {
|
|
245
|
-
throw new Error(`Failed to install Computer Use cache ${cachePath} and restore its prior copy: ${String(error)}`, { cause: restoreError });
|
|
246
|
-
}
|
|
247
|
-
throw error;
|
|
248
|
-
}
|
|
249
|
-
if (backupCreated) await fs.rm(backupPath, {
|
|
250
|
-
recursive: true,
|
|
251
|
-
force: true
|
|
252
|
-
});
|
|
253
|
-
return true;
|
|
254
|
-
} finally {
|
|
255
|
-
await fs.rm(stagingRoot, {
|
|
256
|
-
recursive: true,
|
|
257
|
-
force: true
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
function skippedCacheResult(status, message) {
|
|
262
|
-
return {
|
|
263
|
-
status,
|
|
264
|
-
changed: false,
|
|
265
|
-
message,
|
|
266
|
-
removedStaleVersions: [],
|
|
267
|
-
warnings: status === "source_missing" ? [message] : []
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
//#endregion
|
|
271
|
-
//#region extensions/codex/src/app-server/computer-use-service.ts
|
|
272
|
-
/** Native Computer Use service provisioning for isolated Codex homes. */
|
|
273
|
-
const SERVICE_APP_NAME = "Codex Computer Use.app";
|
|
274
|
-
const CLIENT_RELATIVE_PATH = path.join("Contents", "SharedSupport", "SkyComputerUseClient.app", "Contents", "MacOS", "SkyComputerUseClient");
|
|
275
|
-
const COPY_TIMEOUT_MS = 12e4;
|
|
276
|
-
const activeInstalls = /* @__PURE__ */ new Map();
|
|
277
|
-
/** Ensures the official native client exists beneath the CODEX_HOME used by its launcher. */
|
|
278
|
-
async function ensureCodexComputerUseServiceApp(params) {
|
|
279
|
-
const platform = params.platform ?? process.platform;
|
|
280
|
-
if (platform !== "darwin") return {
|
|
281
|
-
status: "unsupported",
|
|
282
|
-
changed: false
|
|
283
|
-
};
|
|
284
|
-
const targetPath = path.join(path.resolve(params.codexHome), "computer-use", SERVICE_APP_NAME);
|
|
285
|
-
const active = activeInstalls.get(targetPath);
|
|
286
|
-
if (active) return await active;
|
|
287
|
-
const install = ensureCodexComputerUseServiceAppOnce({
|
|
288
|
-
...params,
|
|
289
|
-
targetPath,
|
|
290
|
-
platform
|
|
291
|
-
});
|
|
292
|
-
activeInstalls.set(targetPath, install);
|
|
293
|
-
try {
|
|
294
|
-
return await install;
|
|
295
|
-
} finally {
|
|
296
|
-
if (activeInstalls.get(targetPath) === install) activeInstalls.delete(targetPath);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
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
|
-
}
|
|
377
|
-
}
|
|
378
|
-
async function pathExists$1(filePath) {
|
|
379
|
-
return await fs.lstat(filePath).then(() => true, () => false);
|
|
380
|
-
}
|
|
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) {
|
|
412
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
413
|
-
}
|
|
414
|
-
function isRpcResponse(message) {
|
|
415
|
-
return "id" in message && !("method" in message);
|
|
416
|
-
}
|
|
417
|
-
//#endregion
|
|
418
|
-
//#region extensions/codex/src/app-server/auth-bridge.ts
|
|
419
|
-
const CODEX_APP_SERVER_AUTH_PROVIDER = "openai";
|
|
420
|
-
const 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
|
-
}
|
|
542
|
-
};
|
|
543
|
-
}
|
|
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);
|
|
597
|
-
}
|
|
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);
|
|
605
|
-
}
|
|
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 });
|
|
666
|
-
}
|
|
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 } : {}
|
|
674
|
-
}
|
|
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;
|
|
691
|
-
}
|
|
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;
|
|
698
|
-
}
|
|
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.");
|
|
703
|
-
}
|
|
704
|
-
return;
|
|
705
|
-
}
|
|
706
|
-
let loginParams;
|
|
707
|
-
try {
|
|
708
|
-
loginParams = await resolveCodexAppServerAuthProfileLoginParams({
|
|
709
|
-
agentDir: params.agentDir,
|
|
710
|
-
authProfileId: params.authProfileId,
|
|
711
|
-
authProfileStore: params.authProfileStore,
|
|
712
|
-
config: params.config
|
|
713
|
-
});
|
|
714
|
-
} catch (error) {
|
|
715
|
-
if (params.authRequirement === "subscription" && error instanceof CodexAppServerAuthProfileUnavailableError) throw createCodexAppServerAuthError("Codex subscription auth profile could not produce login credentials.", error);
|
|
716
|
-
throw error;
|
|
717
|
-
}
|
|
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
|
|
727
|
-
});
|
|
728
|
-
if (fallbackLoginParams) await params.client.request("account/login/start", fallbackLoginParams);
|
|
729
|
-
return;
|
|
730
|
-
}
|
|
731
|
-
await params.client.request("account/login/start", loginParams);
|
|
732
|
-
}
|
|
733
|
-
function createCodexAppServerAuthError(message, cause) {
|
|
734
|
-
const error = cause === void 0 ? new Error(message) : new Error(message, { cause });
|
|
735
|
-
return Object.assign(error, { status: 401 });
|
|
736
|
-
}
|
|
737
|
-
var CodexAppServerAuthProfileUnavailableError = class extends Error {};
|
|
738
|
-
async function resolveCodexAppServerAuthProfileLoginParams(params) {
|
|
739
|
-
const store = resolveCodexAppServerAuthProfileStore(params);
|
|
740
|
-
const profileId = resolveCodexAppServerAuthProfileId({
|
|
741
|
-
authProfileId: params.authProfileId,
|
|
742
|
-
store,
|
|
743
|
-
config: params.config
|
|
744
|
-
});
|
|
745
|
-
const profile = profileId ? store.profiles[profileId] : void 0;
|
|
746
|
-
if (profileId && !profile) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" was not found.`);
|
|
747
|
-
if (profileId && profile && !isCodexAppServerAuthProfileCredential(profile, params.config)) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" must be OpenAI Codex auth or an OpenAI API-key backup.`);
|
|
748
|
-
return await resolveCodexAppServerAuthProfileLoginParamsInternal({
|
|
749
|
-
...params,
|
|
750
|
-
authProfileStore: store
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
async function refreshCodexAppServerAuthTokens(params) {
|
|
754
|
-
const loginParams = await resolveCodexAppServerAuthProfileLoginParamsInternal({
|
|
755
|
-
...params,
|
|
756
|
-
forceOAuthRefresh: true
|
|
757
|
-
});
|
|
758
|
-
if (!loginParams || loginParams.type !== "chatgptAuthTokens") throw new Error("Codex app-server ChatGPT token refresh requires an OAuth auth profile.");
|
|
759
|
-
return {
|
|
760
|
-
accessToken: loginParams.accessToken,
|
|
761
|
-
chatgptAccountId: loginParams.chatgptAccountId,
|
|
762
|
-
chatgptPlanType: loginParams.chatgptPlanType ?? null
|
|
763
|
-
};
|
|
764
|
-
}
|
|
765
|
-
async function resolveCodexAppServerAuthProfileLoginParamsInternal(params) {
|
|
766
|
-
const store = resolveCodexAppServerAuthProfileStore({
|
|
767
|
-
agentDir: params.agentDir,
|
|
768
|
-
authProfileId: params.authProfileId,
|
|
769
|
-
authProfileStore: params.authProfileStore,
|
|
770
|
-
config: params.config
|
|
771
|
-
});
|
|
772
|
-
const profileId = resolveCodexAppServerAuthProfileId({
|
|
773
|
-
authProfileId: params.authProfileId,
|
|
774
|
-
store,
|
|
775
|
-
config: params.config
|
|
776
|
-
});
|
|
777
|
-
if (!profileId) return;
|
|
778
|
-
const credential = store.profiles[profileId];
|
|
779
|
-
if (!credential) throw new Error(`Codex app-server auth profile "${profileId}" was not found.`);
|
|
780
|
-
if (!isCodexAppServerAuthProfileCredential(credential, params.config)) throw new Error(`Codex app-server auth profile "${profileId}" must be OpenAI Codex auth or an OpenAI API-key backup.`);
|
|
781
|
-
const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
|
|
782
|
-
agentDir: params.agentDir,
|
|
783
|
-
store,
|
|
784
|
-
preferStoreCredential: Boolean(params.authProfileStore?.profiles[profileId]),
|
|
785
|
-
forceOAuthRefresh: params.forceOAuthRefresh === true,
|
|
786
|
-
config: params.config
|
|
787
|
-
});
|
|
788
|
-
if (!loginParams) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" does not contain usable credentials.`);
|
|
789
|
-
return loginParams;
|
|
790
|
-
}
|
|
791
|
-
async function resolveCodexAppServerFallbackApiKeyLoginParams(params) {
|
|
792
|
-
const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS) ?? await readCodexCliAuthFileApiKey(params.codexCliAuthEnv);
|
|
793
|
-
if (!apiKey) return;
|
|
794
|
-
if ((await params.client.request("account/read", { refreshToken: false })).account) return;
|
|
795
|
-
return {
|
|
796
|
-
type: "apiKey",
|
|
797
|
-
apiKey
|
|
798
|
-
};
|
|
799
|
-
}
|
|
800
|
-
function resolveCodexCliAuthFilePath(env) {
|
|
801
|
-
const configuredCodexHome = env[CODEX_HOME_ENV_VAR]?.trim();
|
|
802
|
-
if (configuredCodexHome) return path.join(resolveHomeRelativePath(configuredCodexHome, env), CODEX_AUTH_JSON_FILENAME);
|
|
803
|
-
const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
|
|
804
|
-
return path.join(home, CODEX_HOME_DIRNAME, CODEX_AUTH_JSON_FILENAME);
|
|
805
|
-
}
|
|
806
|
-
function resolveHomeRelativePath(value, env) {
|
|
807
|
-
if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
|
|
808
|
-
const home = env[HOME_ENV_VAR]?.trim() || env.USERPROFILE?.trim() || os.homedir();
|
|
809
|
-
return path.join(home, value.slice(value === "~" ? 1 : 2));
|
|
810
|
-
}
|
|
811
|
-
return value;
|
|
812
|
-
}
|
|
813
|
-
function parseCodexCliAuthFileApiKey(raw) {
|
|
814
|
-
let parsed;
|
|
815
|
-
try {
|
|
816
|
-
parsed = JSON.parse(raw);
|
|
817
|
-
} catch {
|
|
818
|
-
return;
|
|
819
|
-
}
|
|
820
|
-
if (!parsed || typeof parsed !== "object") return;
|
|
821
|
-
const apiKey = parsed.OPENAI_API_KEY;
|
|
822
|
-
return typeof apiKey === "string" && apiKey.trim() ? apiKey.trim() : void 0;
|
|
823
|
-
}
|
|
824
|
-
async function readCodexCliAuthFileApiKey(env) {
|
|
825
|
-
try {
|
|
826
|
-
return parseCodexCliAuthFileApiKey(await fs.readFile(resolveCodexCliAuthFilePath(env), "utf8"));
|
|
827
|
-
} catch {
|
|
828
|
-
return;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
function resolveCodexCliAuthFileApiKeyCacheKey(env) {
|
|
832
|
-
try {
|
|
833
|
-
const apiKey = parseCodexCliAuthFileApiKey(fsSync.readFileSync(resolveCodexCliAuthFilePath(env), "utf8"));
|
|
834
|
-
return apiKey ? fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) : void 0;
|
|
835
|
-
} catch {
|
|
836
|
-
return;
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
async function resolveLoginParamsForCredential(profileId, credential, params) {
|
|
840
|
-
if (credential.type === "api_key") {
|
|
841
|
-
const apiKey = (await resolveApiKeyForProfile({
|
|
842
|
-
store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false }),
|
|
843
|
-
profileId,
|
|
844
|
-
agentDir: params.agentDir
|
|
845
|
-
}))?.apiKey?.trim();
|
|
846
|
-
return apiKey ? {
|
|
847
|
-
type: "apiKey",
|
|
848
|
-
apiKey
|
|
849
|
-
} : void 0;
|
|
850
|
-
}
|
|
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;
|
|
858
|
-
}
|
|
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;
|
|
905
|
-
}
|
|
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);
|
|
958
|
-
}
|
|
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
|
-
};
|
|
997
|
-
}
|
|
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;
|
|
1019
|
-
}
|
|
1020
|
-
return credential.email?.trim() || void 0;
|
|
1021
|
-
}
|
|
1022
|
-
//#endregion
|
|
1023
|
-
//#region extensions/codex/src/app-server/rate-limit-cache.ts
|
|
1024
|
-
const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 10 * 6e4;
|
|
1025
|
-
const SPARSE_ACCOUNT_METADATA_KEYS = [
|
|
1026
|
-
"credits",
|
|
1027
|
-
"individualLimit",
|
|
1028
|
-
"planType"
|
|
1029
|
-
];
|
|
1030
|
-
const rateLimitsByClient = /* @__PURE__ */ new WeakMap();
|
|
1031
|
-
/** Replaces one physical client's cache with an authoritative rate-limit read response. */
|
|
1032
|
-
function rememberCodexRateLimitsRead(client, value, nowMs = Date.now()) {
|
|
1033
|
-
if (value !== void 0) {
|
|
1034
|
-
const revisionsByLimitId = { ...rateLimitsByClient.get(client)?.revisionsByLimitId };
|
|
1035
|
-
for (const limitId of readRateLimitIds(value)) revisionsByLimitId[limitId] = (revisionsByLimitId[limitId] ?? 0) + 1;
|
|
1036
|
-
rateLimitsByClient.set(client, {
|
|
1037
|
-
value,
|
|
1038
|
-
updatedAtMs: nowMs,
|
|
1039
|
-
revisionsByLimitId
|
|
1040
|
-
});
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
/** Merges a sparse rolling notification into one physical client's latest read response. */
|
|
1044
|
-
function mergeCodexRateLimitsUpdate(client, value, nowMs = Date.now()) {
|
|
1045
|
-
const update = isJsonObject$1(value) && isJsonObject$1(value.rateLimits) ? value.rateLimits : void 0;
|
|
1046
|
-
if (!update) return;
|
|
1047
|
-
const currentState = rateLimitsByClient.get(client);
|
|
1048
|
-
const current = currentState?.value;
|
|
1049
|
-
const limitId = readLimitId(update);
|
|
1050
|
-
rateLimitsByClient.set(client, {
|
|
1051
|
-
value: mergeRateLimitUpdate(current, update),
|
|
1052
|
-
updatedAtMs: nowMs,
|
|
1053
|
-
revisionsByLimitId: {
|
|
1054
|
-
...currentState?.revisionsByLimitId,
|
|
1055
|
-
[limitId]: (currentState?.revisionsByLimitId[limitId] ?? 0) + 1
|
|
1056
|
-
}
|
|
1057
|
-
});
|
|
1058
|
-
}
|
|
1059
|
-
/** Per-limit marker used to trust only primary Codex updates from one turn startup. */
|
|
1060
|
-
function readCodexRateLimitsRevision(client, limitId = "codex") {
|
|
1061
|
-
return rateLimitsByClient.get(client)?.revisionsByLimitId[limitId] ?? 0;
|
|
1062
|
-
}
|
|
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
|
-
};
|
|
1089
|
-
return {
|
|
1090
|
-
...currentEnvelope,
|
|
1091
|
-
rateLimits: nextPrimary,
|
|
1092
|
-
...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
|
|
1093
|
-
};
|
|
1094
|
-
}
|
|
1095
|
-
function readRateLimitIds(value) {
|
|
1096
|
-
if (!isJsonObject$1(value)) return [];
|
|
1097
|
-
const ids = /* @__PURE__ */ new Set();
|
|
1098
|
-
if (isJsonObject$1(value.rateLimits)) ids.add(readLimitId(value.rateLimits));
|
|
1099
|
-
if (isJsonObject$1(value.rateLimitsByLimitId)) for (const [key, snapshot] of Object.entries(value.rateLimitsByLimitId)) {
|
|
1100
|
-
const snapshotLimitId = isJsonObject$1(snapshot) && typeof snapshot.limitId === "string" ? snapshot.limitId.trim() : "";
|
|
1101
|
-
ids.add(snapshotLimitId || key);
|
|
1102
|
-
}
|
|
1103
|
-
return [...ids];
|
|
1104
|
-
}
|
|
1105
|
-
function mergeSparseSnapshot(current, accountFallback, update, limitId) {
|
|
1106
|
-
const merged = {
|
|
1107
|
-
...update,
|
|
1108
|
-
limitId
|
|
1109
|
-
};
|
|
1110
|
-
for (const key of SPARSE_ACCOUNT_METADATA_KEYS) {
|
|
1111
|
-
const previous = current?.[key] ?? accountFallback?.[key];
|
|
1112
|
-
if (merged[key] == null && previous != null) merged[key] = previous;
|
|
1113
|
-
}
|
|
1114
|
-
return merged;
|
|
1115
|
-
}
|
|
1116
|
-
function readLimitId(snapshot) {
|
|
1117
|
-
const value = snapshot.limitId;
|
|
1118
|
-
return typeof value === "string" && value.trim() ? value.trim() : "codex";
|
|
1119
|
-
}
|
|
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);
|
|
1145
|
-
});
|
|
1146
|
-
}
|
|
1147
|
-
//#endregion
|
|
1148
|
-
//#region extensions/codex/src/app-server/transport-websocket.ts
|
|
1149
|
-
/**
|
|
1150
|
-
* Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
|
|
1151
|
-
* transport interface.
|
|
1152
|
-
*/
|
|
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
|
-
};
|
|
1230
|
-
}
|
|
1231
|
-
/** Opens the owner-scoped Codex control socket used by the WebSocket upgrade. */
|
|
1232
|
-
function connectCodexAppServerUnixSocket(socketPath) {
|
|
1233
|
-
return net.createConnection(socketPath);
|
|
1234
|
-
}
|
|
1235
|
-
/** Resolves the canonical or explicitly configured Codex control socket. */
|
|
1236
|
-
function resolveCodexAppServerUnixSocketPath(options) {
|
|
1237
|
-
if (options.transport !== "unix") {
|
|
1238
|
-
if (options.url?.startsWith("unix://")) throw new Error("codex app-server unix URL requires unix transport");
|
|
1239
|
-
return;
|
|
1240
|
-
}
|
|
1241
|
-
const url = options.url ?? "unix://";
|
|
1242
|
-
if (!url.startsWith("unix://")) throw new Error("codex app-server unix transport requires a unix:// URL");
|
|
1243
|
-
return url.slice(7) || path.join(resolveCodexAppServerUserHomeDir(options.env ?? process.env), "app-server-control", "app-server-control.sock");
|
|
1244
|
-
}
|
|
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");
|
|
1250
|
-
}
|
|
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?.();
|
|
1272
|
-
}
|
|
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);
|
|
1277
|
-
}
|
|
1278
|
-
function hasCodexAppServerTransportExited(child) {
|
|
1279
|
-
return child.exitCode !== null && child.exitCode !== void 0 ? true : child.signalCode !== null && child.signalCode !== void 0;
|
|
1280
|
-
}
|
|
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
|
-
});
|
|
1299
|
-
}
|
|
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);
|
|
1306
|
-
}
|
|
1307
|
-
//#endregion
|
|
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";
|
|
1318
|
-
//#endregion
|
|
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;
|
|
1342
|
-
}
|
|
1343
|
-
function resolveCodexAppServerClientInstanceId(client) {
|
|
1344
|
-
return client.getInstanceId?.call(client) ?? getCodexAppServerClientInstanceId(client);
|
|
1345
|
-
}
|
|
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;
|
|
1354
|
-
}
|
|
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";
|
|
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";
|
|
1367
|
-
}
|
|
1368
|
-
function isCodexAppServerBrokenPipeError(error) {
|
|
1369
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1370
|
-
let current = error;
|
|
1371
|
-
while (current && typeof current === "object" && !seen.has(current)) {
|
|
1372
|
-
seen.add(current);
|
|
1373
|
-
if ("code" in current && current.code === "EPIPE") return true;
|
|
1374
|
-
current = "cause" in current ? current.cause : void 0;
|
|
1375
|
-
}
|
|
1376
|
-
return false;
|
|
1377
|
-
}
|
|
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;
|
|
1389
|
-
}
|
|
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;
|
|
1393
|
-
}
|
|
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;
|
|
1397
|
-
}
|
|
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;
|
|
1402
|
-
}
|
|
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;
|
|
1410
|
-
}
|
|
1411
|
-
function isJsonObject(value) {
|
|
1412
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
1413
|
-
}
|
|
1414
|
-
/** Returns true for errors that mean the app-server transport is closed. */
|
|
1415
|
-
function isCodexAppServerConnectionClosedError(error) {
|
|
1416
|
-
if (!(error instanceof Error)) return false;
|
|
1417
|
-
if (isCodexAppServerIndeterminateTransportError(error)) return true;
|
|
1418
|
-
return error.message === "codex app-server client is closed" || error.message.startsWith("codex app-server exited:");
|
|
1419
|
-
}
|
|
1420
|
-
/** Stateful app-server JSON-RPC client over stdio or websocket transport. */
|
|
1421
|
-
var CodexAppServerClient = class CodexAppServerClient {
|
|
1422
|
-
constructor(child) {
|
|
1423
|
-
this.instanceId = randomUUID();
|
|
1424
|
-
this.pending = /* @__PURE__ */ new Map();
|
|
1425
|
-
this.requestHandlers = /* @__PURE__ */ new Set();
|
|
1426
|
-
this.notificationHandlers = /* @__PURE__ */ new Set();
|
|
1427
|
-
this.closeHandlers = /* @__PURE__ */ new Set();
|
|
1428
|
-
this.nextId = 1;
|
|
1429
|
-
this.initialized = false;
|
|
1430
|
-
this.closed = false;
|
|
1431
|
-
this.transportExited = false;
|
|
1432
|
-
this.stderrTail = "";
|
|
1433
|
-
this.child = child;
|
|
1434
|
-
this.lines = createInterface({ input: child.stdout });
|
|
1435
|
-
this.lines.on("line", (line) => this.handleLine(line));
|
|
1436
|
-
this.lines.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
|
|
1437
|
-
child.stdout.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
|
|
1438
|
-
child.stderr.setEncoding("utf8");
|
|
1439
|
-
child.stderr.on("data", (text) => {
|
|
1440
|
-
this.stderrTail = appendBoundedTail(this.stderrTail, text, CODEX_APP_SERVER_STDERR_TAIL_MAX);
|
|
1441
|
-
const trimmed = text.trim();
|
|
1442
|
-
if (trimmed) embeddedAgentLog.debug(`codex app-server stderr: ${trimmed}`);
|
|
1443
|
-
});
|
|
1444
|
-
child.stderr.on("error", (error) => {
|
|
1445
|
-
embeddedAgentLog.warn("codex app-server stderr stream failed", { error });
|
|
1446
|
-
});
|
|
1447
|
-
child.once("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
|
|
1448
|
-
child.once("exit", (code, signal) => {
|
|
1449
|
-
this.transportExited = true;
|
|
1450
|
-
this.closeWithError(buildCodexAppServerExitError(code, signal, this.stderrTail));
|
|
1451
|
-
});
|
|
1452
|
-
child.stdin.on?.("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
|
|
1453
|
-
}
|
|
1454
|
-
/** Starts a new app-server client using resolved runtime start options. */
|
|
1455
|
-
static start(options) {
|
|
1456
|
-
const defaults = resolveCodexAppServerRuntimeOptions().start;
|
|
1457
|
-
const startOptions = {
|
|
1458
|
-
...defaults,
|
|
1459
|
-
...options,
|
|
1460
|
-
headers: options?.headers ?? defaults.headers
|
|
1461
|
-
};
|
|
1462
|
-
if (startOptions.transport === "stdio" && startOptions.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
|
|
1463
|
-
if (startOptions.transport === "websocket" || startOptions.transport === "unix") return new CodexAppServerClient(createWebSocketTransport(startOptions));
|
|
1464
|
-
return new CodexAppServerClient(createStdioTransport(startOptions));
|
|
1465
|
-
}
|
|
1466
|
-
/** Builds a client around a fake transport for tests. */
|
|
1467
|
-
static fromTransportForTests(child) {
|
|
1468
|
-
return new CodexAppServerClient(child);
|
|
1469
|
-
}
|
|
1470
|
-
/** Performs the app-server initialize handshake and validates protocol version. */
|
|
1471
|
-
async initialize() {
|
|
1472
|
-
if (this.initialized) return;
|
|
1473
|
-
const response = await this.request("initialize", {
|
|
1474
|
-
clientInfo: {
|
|
1475
|
-
name: "openclaw",
|
|
1476
|
-
title: "OpenClaw",
|
|
1477
|
-
version: OPENCLAW_VERSION
|
|
1478
|
-
},
|
|
1479
|
-
capabilities: { experimentalApi: true }
|
|
1480
|
-
});
|
|
1481
|
-
this.serverVersion = assertSupportedCodexAppServerVersion(response);
|
|
1482
|
-
this.runtimeIdentity = buildCodexAppServerRuntimeIdentity(response, this.serverVersion);
|
|
1483
|
-
this.notify("initialized");
|
|
1484
|
-
this.initialized = true;
|
|
1485
|
-
}
|
|
1486
|
-
/** Returns the version detected during initialize. */
|
|
1487
|
-
getServerVersion() {
|
|
1488
|
-
return this.serverVersion;
|
|
1489
|
-
}
|
|
1490
|
-
/** Returns runtime metadata detected during initialize. */
|
|
1491
|
-
getRuntimeIdentity() {
|
|
1492
|
-
return this.runtimeIdentity ? { ...this.runtimeIdentity } : void 0;
|
|
1493
|
-
}
|
|
1494
|
-
/** Stable generation id for this exact physical client instance. */
|
|
1495
|
-
getInstanceId() {
|
|
1496
|
-
return this.instanceId;
|
|
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
|
-
})();
|
|
1559
|
-
}
|
|
1560
|
-
return this.requestWithoutThreadSessionGuard(method, params, options);
|
|
1561
|
-
}
|
|
1562
|
-
requestWithoutThreadSessionGuard(method, params, options, onWriteAttempt) {
|
|
1563
|
-
return this.requestWithOverloadRetry(method, params, options, onWriteAttempt);
|
|
1564
|
-
}
|
|
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
|
-
}
|
|
1581
|
-
}
|
|
1582
|
-
}
|
|
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
|
|
1672
|
-
});
|
|
1673
|
-
}
|
|
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
|
-
});
|
|
1722
|
-
}
|
|
1723
|
-
}
|
|
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
|
-
}
|
|
1737
|
-
});
|
|
1738
|
-
}
|
|
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);
|
|
1763
|
-
}
|
|
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);
|
|
1787
|
-
}
|
|
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
|
-
});
|
|
1808
|
-
}
|
|
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);
|
|
1818
|
-
}
|
|
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
|
-
}
|
|
1848
|
-
}
|
|
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
|
-
}
|
|
1870
|
-
}
|
|
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
|
-
}
|
|
1877
|
-
}
|
|
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
|
-
});
|
|
1882
|
-
}
|
|
1883
|
-
closeWithError(error) {
|
|
1884
|
-
if (this.markClosed(error)) closeCodexAppServerTransport(this.child);
|
|
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 {};
|
|
1919
|
-
}
|
|
1920
|
-
function stringifyCodexAppServerMessage(message) {
|
|
1921
|
-
return JSON.stringify(message, (_key, value) => typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value) ?? "null";
|
|
1922
|
-
}
|
|
1923
|
-
function timeoutServerRequestResponse(request) {
|
|
1924
|
-
if (request.method !== "item/tool/call") return;
|
|
1925
|
-
return {
|
|
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
|
|
1931
|
-
};
|
|
1932
|
-
}
|
|
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;
|
|
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;
|
|
1947
|
-
}
|
|
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);
|
|
1956
|
-
return {
|
|
1957
|
-
serverVersion,
|
|
1958
|
-
...userAgent ? { userAgent } : {},
|
|
1959
|
-
...codexHome ? { codexHome } : {},
|
|
1960
|
-
...platformFamily ? { platformFamily } : {},
|
|
1961
|
-
...platformOs ? { platformOs } : {}
|
|
1962
|
-
};
|
|
1963
|
-
}
|
|
1964
|
-
function readNonEmptyInitializeString(value) {
|
|
1965
|
-
const trimmed = value?.trim();
|
|
1966
|
-
return trimmed ? trimmed : void 0;
|
|
1967
|
-
}
|
|
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];
|
|
1971
|
-
}
|
|
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;
|
|
1975
|
-
}
|
|
1976
|
-
function appendBoundedTail(current, next, maxLength) {
|
|
1977
|
-
const combined = `${current}${next}`;
|
|
1978
|
-
return combined.length > maxLength ? sliceUtf16Safe(combined, -maxLength) : combined;
|
|
1979
|
-
}
|
|
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}`);
|
|
1984
|
-
}
|
|
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");
|
|
1989
|
-
}
|
|
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
|
-
});
|
|
2000
|
-
}
|
|
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);
|
|
2009
|
-
}
|
|
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";
|
|
2014
|
-
}
|
|
2015
|
-
//#endregion
|
|
2016
|
-
//#region extensions/codex/src/app-server/managed-binary.ts
|
|
2017
|
-
/**
|
|
2018
|
-
* Resolves the managed Codex app-server binary shipped with or installed beside
|
|
2019
|
-
* the Codex plugin before stdio startup.
|
|
2020
|
-
*/
|
|
2021
|
-
const CODEX_PLUGIN_ROOT = resolveDefaultCodexPluginRoot(path.dirname(fileURLToPath(import.meta.url)));
|
|
2022
|
-
const MACOS_DESKTOP_CODEX_APP_SERVER_COMMANDS = ["/Applications/ChatGPT.app/Contents/Resources/codex", "/Applications/Codex.app/Contents/Resources/codex"];
|
|
2023
|
-
/** Rewrites managed stdio start options to point at an executable Codex binary path. */
|
|
2024
|
-
async function resolveManagedCodexAppServerStartOptions(startOptions, options = {}) {
|
|
2025
|
-
if (startOptions.transport !== "stdio" || startOptions.commandSource !== "managed") return startOptions;
|
|
2026
|
-
const platform = options.platform ?? process.platform;
|
|
2027
|
-
const paths = resolveManagedCodexAppServerPaths({
|
|
2028
|
-
platform,
|
|
2029
|
-
pluginRoot: options.pluginRoot,
|
|
2030
|
-
managedCommandOrder: startOptions.managedCommandOrder
|
|
2031
|
-
});
|
|
2032
|
-
const pathExists = options.pathExists ?? commandPathExists;
|
|
2033
|
-
const commandPaths = await findManagedCodexAppServerCommandPaths({
|
|
2034
|
-
candidateCommandPaths: paths.candidateCommandPaths,
|
|
2035
|
-
pathExists,
|
|
2036
|
-
platform
|
|
2037
|
-
});
|
|
2038
|
-
const commandPath = expectDefined(commandPaths[0], "resolved managed Codex command path");
|
|
2039
|
-
const managedFallbackCommandPaths = commandPaths.slice(1);
|
|
2040
|
-
return {
|
|
2041
|
-
...startOptions,
|
|
2042
|
-
command: commandPath,
|
|
2043
|
-
commandSource: "resolved-managed",
|
|
2044
|
-
...managedFallbackCommandPaths.length > 0 ? { managedFallbackCommandPaths } : {}
|
|
2045
|
-
};
|
|
2046
|
-
}
|
|
2047
|
-
/** Resolves the native artifact behind a successful managed launcher selection. */
|
|
2048
|
-
function resolveManagedCodexNativeCommand(command, options = {}) {
|
|
2049
|
-
const platform = options.platform ?? process.platform;
|
|
2050
|
-
if (platform === "darwin" && MACOS_DESKTOP_CODEX_APP_SERVER_COMMANDS.some((candidate) => candidate === command)) return command;
|
|
2051
|
-
const target = resolveCodexNativeTarget(platform, options.arch ?? process.arch);
|
|
2052
|
-
if (!target) return;
|
|
2053
|
-
const packageRoot = resolveManagedCodexPackageRootForCommand(command, platform);
|
|
2054
|
-
if (!packageRoot) return;
|
|
2055
|
-
const resolvePackageJson = options.resolvePackageJson ?? resolvePackageJsonFromRoot;
|
|
2056
|
-
const pathExists = options.pathExists ?? existsSync;
|
|
2057
|
-
for (const packageName of [target.packageName, MANAGED_CODEX_APP_SERVER_PACKAGE]) {
|
|
2058
|
-
const packageJsonPath = resolvePackageJson(packageName, packageRoot);
|
|
2059
|
-
if (!packageJsonPath) continue;
|
|
2060
|
-
const candidate = path.join(path.dirname(packageJsonPath), "vendor", target.triple, "bin", platform === "win32" ? "codex.exe" : "codex");
|
|
2061
|
-
if (pathExists(candidate)) return candidate;
|
|
2062
|
-
}
|
|
2063
|
-
}
|
|
2064
|
-
function resolveManagedCodexPackageRootForCommand(command, platform) {
|
|
2065
|
-
const pathApi = pathForPlatform(platform);
|
|
2066
|
-
const commandPaths = [command];
|
|
2067
|
-
try {
|
|
2068
|
-
commandPaths.unshift(realpathSync(command));
|
|
2069
|
-
} catch {}
|
|
2070
|
-
for (const commandPath of commandPaths) {
|
|
2071
|
-
let current = pathApi.dirname(commandPath);
|
|
2072
|
-
while (true) {
|
|
2073
|
-
if (pathApi.basename(current) === "codex" && pathApi.basename(pathApi.dirname(current)) === "@openai") return current;
|
|
2074
|
-
if (pathApi.basename(current) === ".bin") return pathApi.join(pathApi.dirname(current), "@openai", "codex");
|
|
2075
|
-
const parent = pathApi.dirname(current);
|
|
2076
|
-
if (parent === current) break;
|
|
2077
|
-
current = parent;
|
|
2078
|
-
}
|
|
2079
|
-
}
|
|
2080
|
-
}
|
|
2081
|
-
function resolveCodexNativeTarget(platform, arch) {
|
|
2082
|
-
if ((platform === "linux" || platform === "android") && arch === "x64") return {
|
|
2083
|
-
packageName: "@openai/codex-linux-x64",
|
|
2084
|
-
triple: "x86_64-unknown-linux-musl"
|
|
2085
|
-
};
|
|
2086
|
-
if ((platform === "linux" || platform === "android") && arch === "arm64") return {
|
|
2087
|
-
packageName: "@openai/codex-linux-arm64",
|
|
2088
|
-
triple: "aarch64-unknown-linux-musl"
|
|
2089
|
-
};
|
|
2090
|
-
if (platform === "darwin" && arch === "x64") return {
|
|
2091
|
-
packageName: "@openai/codex-darwin-x64",
|
|
2092
|
-
triple: "x86_64-apple-darwin"
|
|
2093
|
-
};
|
|
2094
|
-
if (platform === "darwin" && arch === "arm64") return {
|
|
2095
|
-
packageName: "@openai/codex-darwin-arm64",
|
|
2096
|
-
triple: "aarch64-apple-darwin"
|
|
2097
|
-
};
|
|
2098
|
-
if (platform === "win32" && arch === "x64") return {
|
|
2099
|
-
packageName: "@openai/codex-win32-x64",
|
|
2100
|
-
triple: "x86_64-pc-windows-msvc"
|
|
2101
|
-
};
|
|
2102
|
-
if (platform === "win32" && arch === "arm64") return {
|
|
2103
|
-
packageName: "@openai/codex-win32-arm64",
|
|
2104
|
-
triple: "aarch64-pc-windows-msvc"
|
|
2105
|
-
};
|
|
2106
|
-
}
|
|
2107
|
-
function resolvePackageJsonFromRoot(packageName, root) {
|
|
2108
|
-
try {
|
|
2109
|
-
return createRequire(path.join(root, "package.json")).resolve(`${packageName}/package.json`);
|
|
2110
|
-
} catch {
|
|
2111
|
-
return;
|
|
2112
|
-
}
|
|
2113
|
-
}
|
|
2114
|
-
/** Returns the preferred and fallback managed Codex binary paths for a plugin root. */
|
|
2115
|
-
function resolveManagedCodexAppServerPaths(params) {
|
|
2116
|
-
const platform = params.platform ?? process.platform;
|
|
2117
|
-
const candidateCommandPaths = resolveManagedCodexAppServerCommandCandidates(params.pluginRoot ?? CODEX_PLUGIN_ROOT, platform, params.managedCommandOrder ?? "package-first");
|
|
2118
|
-
return {
|
|
2119
|
-
commandPath: candidateCommandPaths[0] ?? "",
|
|
2120
|
-
candidateCommandPaths
|
|
2121
|
-
};
|
|
2122
|
-
}
|
|
2123
|
-
function resolveManagedCodexAppServerCommandCandidates(pluginRoot, platform, managedCommandOrder) {
|
|
2124
|
-
const pathApi = pathForPlatform(platform);
|
|
2125
|
-
const commandName = platform === "win32" ? "codex.cmd" : "codex";
|
|
2126
|
-
const roots = resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform);
|
|
2127
|
-
const packageCommandPaths = [...roots.map((root) => pathApi.join(root, "node_modules", ".bin", commandName)), ...resolveManagedCodexPackageBinCandidates(roots, platform)];
|
|
2128
|
-
const desktopCommandPaths = resolveDesktopCodexAppServerCommandCandidates(platform);
|
|
2129
|
-
const orderedCommandPaths = managedCommandOrder === "desktop-first" ? [...desktopCommandPaths, ...packageCommandPaths] : [...packageCommandPaths, ...desktopCommandPaths];
|
|
2130
|
-
return [...new Set(orderedCommandPaths)];
|
|
2131
|
-
}
|
|
2132
|
-
function resolveDesktopCodexAppServerCommandCandidates(platform) {
|
|
2133
|
-
return platform === "darwin" ? [...MACOS_DESKTOP_CODEX_APP_SERVER_COMMANDS] : [];
|
|
2134
|
-
}
|
|
2135
|
-
function resolveDefaultCodexPluginRoot(moduleDir) {
|
|
2136
|
-
const moduleBaseName = path.basename(moduleDir);
|
|
2137
|
-
if (moduleBaseName === "dist" || moduleBaseName === "dist-runtime") return path.dirname(moduleDir);
|
|
2138
|
-
return path.resolve(moduleDir, "..", "..");
|
|
2139
|
-
}
|
|
2140
|
-
function resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform) {
|
|
2141
|
-
const pathApi = pathForPlatform(platform);
|
|
2142
|
-
const directRoots = [
|
|
2143
|
-
pluginRoot,
|
|
2144
|
-
pathApi.dirname(pluginRoot),
|
|
2145
|
-
pathApi.dirname(pathApi.dirname(pluginRoot)),
|
|
2146
|
-
isDistExtensionRoot(pluginRoot, platform) ? pathApi.dirname(pathApi.dirname(pathApi.dirname(pluginRoot))) : null
|
|
2147
|
-
].filter((root) => Boolean(root));
|
|
2148
|
-
return [.../* @__PURE__ */ new Set([...directRoots, ...resolveNearestNodeModulesProjectRoots(directRoots, platform)])];
|
|
2149
|
-
}
|
|
2150
|
-
function resolveNearestNodeModulesProjectRoots(roots, platform) {
|
|
2151
|
-
const pathApi = pathForPlatform(platform);
|
|
2152
|
-
const projectRoots = [];
|
|
2153
|
-
for (const root of roots) {
|
|
2154
|
-
let current = pathApi.resolve(root);
|
|
2155
|
-
while (true) {
|
|
2156
|
-
if (pathApi.basename(current) === "node_modules") {
|
|
2157
|
-
projectRoots.push(pathApi.dirname(current));
|
|
2158
|
-
break;
|
|
2159
|
-
}
|
|
2160
|
-
const parent = pathApi.dirname(current);
|
|
2161
|
-
if (parent === current) break;
|
|
2162
|
-
current = parent;
|
|
2163
|
-
}
|
|
2164
|
-
}
|
|
2165
|
-
return projectRoots;
|
|
2166
|
-
}
|
|
2167
|
-
function resolveManagedCodexPackageBinCandidates(roots, platform) {
|
|
2168
|
-
if (platform === "win32") return [];
|
|
2169
|
-
const candidates = [];
|
|
2170
|
-
for (const root of roots) {
|
|
2171
|
-
const candidate = resolveManagedCodexPackageBinCandidate(root);
|
|
2172
|
-
if (candidate) candidates.push(candidate);
|
|
2173
|
-
}
|
|
2174
|
-
return candidates;
|
|
2175
|
-
}
|
|
2176
|
-
function resolveManagedCodexPackageBinCandidate(root) {
|
|
2177
|
-
try {
|
|
2178
|
-
const packageJsonPath = createRequire(path.join(root, "package.json")).resolve(`${MANAGED_CODEX_APP_SERVER_PACKAGE}/package.json`);
|
|
2179
|
-
const packageRoot = path.dirname(packageJsonPath);
|
|
2180
|
-
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
|
2181
|
-
const binPath = typeof packageJson.bin === "string" ? packageJson.bin : isRecord(packageJson.bin) && typeof packageJson.bin.codex === "string" ? packageJson.bin.codex : null;
|
|
2182
|
-
return binPath ? path.resolve(packageRoot, binPath) : null;
|
|
2183
|
-
} catch {
|
|
2184
|
-
return null;
|
|
2185
|
-
}
|
|
2186
|
-
}
|
|
2187
|
-
function isRecord(value) {
|
|
2188
|
-
return typeof value === "object" && value !== null;
|
|
2189
|
-
}
|
|
2190
|
-
function isDistExtensionRoot(pluginRoot, platform) {
|
|
2191
|
-
const pathApi = pathForPlatform(platform);
|
|
2192
|
-
const extensionsDir = pathApi.dirname(pluginRoot);
|
|
2193
|
-
const distDir = pathApi.dirname(extensionsDir);
|
|
2194
|
-
return pathApi.basename(extensionsDir) === "extensions" && (pathApi.basename(distDir) === "dist" || pathApi.basename(distDir) === "dist-runtime");
|
|
2195
|
-
}
|
|
2196
|
-
function pathForPlatform(platform) {
|
|
2197
|
-
return platform === "win32" ? path.win32 : path.posix;
|
|
2198
|
-
}
|
|
2199
|
-
async function findManagedCodexAppServerCommandPaths(params) {
|
|
2200
|
-
const commandPaths = [];
|
|
2201
|
-
for (const commandPath of params.candidateCommandPaths) if (await params.pathExists(commandPath, params.platform)) commandPaths.push(commandPath);
|
|
2202
|
-
if (commandPaths.length > 0) return commandPaths;
|
|
2203
|
-
throw new Error([
|
|
2204
|
-
`Managed Codex app-server binary was not found for ${MANAGED_CODEX_APP_SERVER_PACKAGE}.`,
|
|
2205
|
-
"Reinstall or update OpenClaw, or run pnpm install in a source checkout.",
|
|
2206
|
-
"Set plugins.entries.codex.config.appServer.command or OPENCLAW_CODEX_APP_SERVER_BIN to use a custom Codex binary."
|
|
2207
|
-
].join(" "));
|
|
2208
|
-
}
|
|
2209
|
-
async function commandPathExists(filePath, platform) {
|
|
2210
|
-
try {
|
|
2211
|
-
await access(filePath, platform === "win32" ? constants.F_OK : constants.X_OK);
|
|
2212
|
-
return true;
|
|
2213
|
-
} catch {
|
|
2214
|
-
return false;
|
|
2215
|
-
}
|
|
2216
|
-
}
|
|
2217
|
-
//#endregion
|
|
2218
|
-
//#region extensions/codex/src/app-server/native-config-fence.ts
|
|
2219
|
-
const CODEX_NATIVE_CONFIG_FENCE_STATE = Symbol.for("openclaw.codexNativeConfigFenceState");
|
|
2220
|
-
function getFenceState() {
|
|
2221
|
-
const globalState = globalThis;
|
|
2222
|
-
globalState[CODEX_NATIVE_CONFIG_FENCE_STATE] ??= /* @__PURE__ */ new Map();
|
|
2223
|
-
return globalState[CODEX_NATIVE_CONFIG_FENCE_STATE];
|
|
2224
|
-
}
|
|
2225
|
-
/** Acquires the per-CODEX_HOME fence and returns an idempotent release. */
|
|
2226
|
-
async function acquireCodexNativeConfigFence(key, options = {}) {
|
|
2227
|
-
const state = getFenceState();
|
|
2228
|
-
const previous = state.get(key) ?? Promise.resolve();
|
|
2229
|
-
let resolveCurrent = () => void 0;
|
|
2230
|
-
const current = new Promise((resolve) => {
|
|
2231
|
-
resolveCurrent = resolve;
|
|
2232
|
-
});
|
|
2233
|
-
state.set(key, current);
|
|
2234
|
-
try {
|
|
2235
|
-
await waitForPreviousFence(previous, options);
|
|
2236
|
-
} catch (error) {
|
|
2237
|
-
previous.then(() => {
|
|
2238
|
-
resolveCurrent();
|
|
2239
|
-
if (state.get(key) === current) state.delete(key);
|
|
2240
|
-
});
|
|
2241
|
-
throw error;
|
|
2242
|
-
}
|
|
2243
|
-
let released = false;
|
|
2244
|
-
return () => {
|
|
2245
|
-
if (released) return;
|
|
2246
|
-
released = true;
|
|
2247
|
-
resolveCurrent();
|
|
2248
|
-
if (state.get(key) === current) state.delete(key);
|
|
2249
|
-
};
|
|
2250
|
-
}
|
|
2251
|
-
async function waitForPreviousFence(previous, options) {
|
|
2252
|
-
if (options.signal?.aborted) throw new Error(options.abortMessage ?? "Codex native config fence aborted");
|
|
2253
|
-
if (options.timeoutMs === void 0 && !options.signal) {
|
|
2254
|
-
await previous;
|
|
2255
|
-
return;
|
|
2256
|
-
}
|
|
2257
|
-
await new Promise((resolve, reject) => {
|
|
2258
|
-
let timeout;
|
|
2259
|
-
const cleanup = () => {
|
|
2260
|
-
if (timeout) {
|
|
2261
|
-
clearTimeout(timeout);
|
|
2262
|
-
timeout = void 0;
|
|
2263
|
-
}
|
|
2264
|
-
options.signal?.removeEventListener("abort", onAbort);
|
|
2265
|
-
};
|
|
2266
|
-
const settle = (run) => {
|
|
2267
|
-
cleanup();
|
|
2268
|
-
run();
|
|
2269
|
-
};
|
|
2270
|
-
const onAbort = () => settle(() => reject(new Error(options.abortMessage ?? "Codex native config fence aborted")));
|
|
2271
|
-
previous.then(() => settle(resolve));
|
|
2272
|
-
if (options.signal) options.signal.addEventListener("abort", onAbort, { once: true });
|
|
2273
|
-
if (options.timeoutMs !== void 0) {
|
|
2274
|
-
timeout = setTimeout(() => settle(() => reject(new Error(options.timeoutMessage ?? "Codex native config fence timed out"))), Math.max(1, options.timeoutMs));
|
|
2275
|
-
timeout.unref?.();
|
|
2276
|
-
}
|
|
2277
|
-
});
|
|
2278
|
-
}
|
|
2279
|
-
//#endregion
|
|
2280
|
-
//#region extensions/codex/src/app-server/timeout.ts
|
|
2281
|
-
/**
|
|
2282
|
-
* Thin Codex app-server timeout adapter around OpenClaw's shared security
|
|
2283
|
-
* runtime timeout helper.
|
|
2284
|
-
*/
|
|
2285
|
-
/** Awaits a promise with a Codex-specific timeout error message. */
|
|
2286
|
-
async function withTimeout$1(promise, timeoutMs, timeoutMessage, createError) {
|
|
2287
|
-
return await withTimeout(promise, timeoutMs, {
|
|
2288
|
-
message: timeoutMessage,
|
|
2289
|
-
...createError ? { createError } : {}
|
|
2290
|
-
});
|
|
2291
|
-
}
|
|
2292
|
-
//#endregion
|
|
2293
|
-
//#region extensions/codex/src/app-server/shared-client.ts
|
|
2294
|
-
/**
|
|
2295
|
-
* Owns shared and isolated Codex app-server client startup, auth application,
|
|
2296
|
-
* lease tracking, and teardown.
|
|
2297
|
-
*/
|
|
2298
|
-
var shared_client_exports = /* @__PURE__ */ __exportAll({
|
|
2299
|
-
assertCodexAppServerClientStartSelectionCurrent: () => assertCodexAppServerClientStartSelectionCurrent,
|
|
2300
|
-
clearSharedCodexAppServerClientAndWait: () => clearSharedCodexAppServerClientAndWait,
|
|
2301
|
-
clearSharedCodexAppServerClientIfCurrent: () => clearSharedCodexAppServerClientIfCurrent,
|
|
2302
|
-
clearSharedCodexAppServerClientIfCurrentAndUnclaimed: () => clearSharedCodexAppServerClientIfCurrentAndUnclaimed,
|
|
2303
|
-
clearSharedCodexAppServerClientIfCurrentAndWait: () => clearSharedCodexAppServerClientIfCurrentAndWait,
|
|
2304
|
-
createIsolatedCodexAppServerClient: () => createIsolatedCodexAppServerClient,
|
|
2305
|
-
getLeasedSharedCodexAppServerClient: () => getLeasedSharedCodexAppServerClient,
|
|
2306
|
-
getSharedCodexAppServerClient: () => getSharedCodexAppServerClient,
|
|
2307
|
-
isCodexAppServerStartSelectionChangedError: () => isCodexAppServerStartSelectionChangedError,
|
|
2308
|
-
releaseCodexAppServerClientLease: () => releaseCodexAppServerClientLease,
|
|
2309
|
-
releaseLeasedSharedCodexAppServerClient: () => releaseLeasedSharedCodexAppServerClient,
|
|
2310
|
-
resolveCodexAppServerSpawnIdentity: () => resolveCodexAppServerSpawnIdentity,
|
|
2311
|
-
resolveCodexNativeConfigFenceKey: () => resolveCodexNativeConfigFenceKey,
|
|
2312
|
-
retainSharedCodexAppServerClientIfCurrent: () => retainSharedCodexAppServerClientIfCurrent,
|
|
2313
|
-
retireSharedCodexAppServerClientIfCurrent: () => retireSharedCodexAppServerClientIfCurrent,
|
|
2314
|
-
withLeasedCodexAppServerClientStartSelectionRetry: () => withLeasedCodexAppServerClientStartSelectionRetry
|
|
2315
|
-
});
|
|
2316
|
-
const suspectClosedClients = /* @__PURE__ */ new WeakSet();
|
|
2317
|
-
const SHARED_CODEX_APP_SERVER_CLIENT_STATE = Symbol.for("openclaw.codexAppServerClientState");
|
|
2318
|
-
const SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER = Symbol.for("openclaw.codexAppServerClientDisposer");
|
|
2319
|
-
const CODEX_APP_SERVER_CLIENT_START_METADATA = Symbol.for("openclaw.codexAppServerClientStartMetadata");
|
|
2320
|
-
function getSharedCodexAppServerClientState() {
|
|
2321
|
-
const globalState = globalThis;
|
|
2322
|
-
globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] ??= {
|
|
2323
|
-
clients: /* @__PURE__ */ new Map(),
|
|
2324
|
-
leasedReleases: /* @__PURE__ */ new WeakMap()
|
|
2325
|
-
};
|
|
2326
|
-
return globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE];
|
|
2327
|
-
}
|
|
2328
|
-
function getCodexAppServerClientStartMetadata() {
|
|
2329
|
-
const globalState = globalThis;
|
|
2330
|
-
globalState[CODEX_APP_SERVER_CLIENT_START_METADATA] ??= /* @__PURE__ */ new WeakMap();
|
|
2331
|
-
return globalState[CODEX_APP_SERVER_CLIENT_START_METADATA];
|
|
2332
|
-
}
|
|
2333
|
-
/** Resolves non-secret spawn identity before startup; argv is represented only by its hash. */
|
|
2334
|
-
function resolveCodexAppServerSpawnIdentity(startOptions, resolvedNativeCommand) {
|
|
2335
|
-
const nativeCommand = resolvedNativeCommand ?? (startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0);
|
|
2336
|
-
return {
|
|
2337
|
-
command: startOptions.command,
|
|
2338
|
-
argsFingerprint: createHash("sha256").update(JSON.stringify(startOptions.args)).digest("hex"),
|
|
2339
|
-
...startOptions.commandSource ? { commandSource: startOptions.commandSource } : {},
|
|
2340
|
-
...startOptions.managedCommandOrder ? { managedCommandOrder: startOptions.managedCommandOrder } : {},
|
|
2341
|
-
...nativeCommand ? { nativeCommand } : {}
|
|
2342
|
-
};
|
|
2343
|
-
}
|
|
2344
|
-
var CodexAppServerStartSelectionChangedError = class extends Error {
|
|
2345
|
-
constructor() {
|
|
2346
|
-
super("Codex app-server managed executable selection changed during startup");
|
|
2347
|
-
this.code = "CODEX_APP_SERVER_START_SELECTION_CHANGED";
|
|
2348
|
-
this.name = "CodexAppServerStartSelectionChangedError";
|
|
2349
|
-
}
|
|
2350
|
-
};
|
|
2351
|
-
/** Cross-bundle-safe check for a managed executable selection retry. */
|
|
2352
|
-
function isCodexAppServerStartSelectionChangedError(error) {
|
|
2353
|
-
return error instanceof Error && "code" in error && error.code === "CODEX_APP_SERVER_START_SELECTION_CHANGED";
|
|
2354
|
-
}
|
|
2355
|
-
/**
|
|
2356
|
-
* Rechecks mutable Codex-owned plugin state immediately before thread start/resume.
|
|
2357
|
-
* The synchronous check prevents another gateway task from installing Computer
|
|
2358
|
-
* Use between the check and the JSON-RPC write on the same event loop turn.
|
|
2359
|
-
*/
|
|
2360
|
-
function assertCodexAppServerClientStartSelectionCurrent(params) {
|
|
2361
|
-
const metadata = getCodexAppServerClientStartMetadata().get(params.client);
|
|
2362
|
-
if (!metadata) return;
|
|
2363
|
-
const requestedStartOptions = params.startOptions ?? metadata.requestedStartOptions;
|
|
2364
|
-
if (requestedStartOptions.commandSource !== "managed") return;
|
|
2365
|
-
const current = resolveCodexAppServerStartOptionsForAgent({
|
|
2366
|
-
startOptions: requestedStartOptions,
|
|
2367
|
-
agentDir: params.agentDir ?? metadata.agentDir
|
|
2368
|
-
});
|
|
2369
|
-
if ((metadata.startOptions.managedCommandOrder ?? "package-first") !== (current.managedCommandOrder ?? "package-first")) throw new CodexAppServerStartSelectionChangedError();
|
|
2370
|
-
}
|
|
2371
|
-
/** Resolves the per-CODEX_HOME key used to serialize native config loading. */
|
|
2372
|
-
function resolveCodexNativeConfigFenceKey(params) {
|
|
2373
|
-
const metadata = params.client ? getCodexAppServerClientStartMetadata().get(params.client) : void 0;
|
|
2374
|
-
const startOptions = params.startOptions ?? metadata?.startOptions;
|
|
2375
|
-
if (!startOptions || startOptions.transport !== "stdio") return;
|
|
2376
|
-
const configuredHome = startOptions.env?.CODEX_HOME?.trim();
|
|
2377
|
-
const agentDir = params.agentDir ?? metadata?.agentDir ?? resolveDefaultAgentDir(params.config ?? {});
|
|
2378
|
-
const codexHome = configuredHome ? configuredHome : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir() : agentDir ? resolveCodexAppServerHomeDir(agentDir) : void 0;
|
|
2379
|
-
return codexHome ? `codex-home:${path.resolve(codexHome)}` : void 0;
|
|
2380
|
-
}
|
|
2381
|
-
function inferAuthRequirement(preparedAuth) {
|
|
2382
|
-
if (preparedAuth?.kind === "api-key") return "api-key";
|
|
2383
|
-
return preparedAuth?.kind === "profile" ? "subscription" : void 0;
|
|
2384
|
-
}
|
|
2385
|
-
async function resolveCodexAppServerClientStartContext(options) {
|
|
2386
|
-
const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
|
|
2387
|
-
const requestedStartOptions = options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start;
|
|
2388
|
-
const preparedAuth = options?.preparedAuth;
|
|
2389
|
-
const preparedApiKey = preparedAuth?.kind === "api-key" ? preparedAuth.apiKey.trim() : void 0;
|
|
2390
|
-
if (preparedAuth && options?.authProfileId !== void 0) throw new Error("Prepared Codex auth cannot also select a legacy auth profile.");
|
|
2391
|
-
if (preparedAuth?.kind === "profile" && !preparedAuth.store.profiles[preparedAuth.profileId]) throw new Error(`Prepared Codex auth profile "${preparedAuth.profileId}" was not found.`);
|
|
2392
|
-
if (preparedAuth?.kind === "api-key" && !preparedApiKey) throw new Error("Prepared Codex API-key auth is missing its resolved key.");
|
|
2393
|
-
if (preparedAuth && requestedStartOptions.homeScope === "user") throw new Error("Prepared Codex auth requires an isolated app-server home.");
|
|
2394
|
-
const preparedAuthRequirement = inferAuthRequirement(preparedAuth);
|
|
2395
|
-
if (options?.authRequirement && preparedAuthRequirement && options.authRequirement !== preparedAuthRequirement) throw new Error("Prepared Codex auth does not satisfy the requested auth requirement.");
|
|
2396
|
-
const authRequirement = options?.authRequirement ?? preparedAuthRequirement;
|
|
2397
|
-
const usesNativeAuth = !preparedAuth && (options?.authProfileId === null || requestedStartOptions.homeScope === "user");
|
|
2398
|
-
const requestedAuthProfileId = preparedAuth?.kind === "profile" ? preparedAuth.profileId : options?.authProfileId ?? void 0;
|
|
2399
|
-
const authProfileStore = preparedAuth?.kind === "profile" ? preparedAuth.store : !usesNativeAuth && options?.authProfileStore ? resolveCodexAppServerAuthProfileStore({
|
|
2400
|
-
agentDir,
|
|
2401
|
-
authProfileId: requestedAuthProfileId,
|
|
2402
|
-
authProfileStore: options.authProfileStore,
|
|
2403
|
-
config: options.config
|
|
2404
|
-
}) : options?.authProfileStore;
|
|
2405
|
-
const authProfileId = preparedAuth?.kind === "profile" ? preparedAuth.profileId : usesNativeAuth || preparedAuth?.kind === "api-key" ? void 0 : resolveCodexAppServerAuthProfileIdForAgent({
|
|
2406
|
-
authProfileId: requestedAuthProfileId,
|
|
2407
|
-
agentDir,
|
|
2408
|
-
config: options?.config,
|
|
2409
|
-
...authProfileStore ? { authProfileStore } : {}
|
|
2410
|
-
});
|
|
2411
|
-
const preparedAuthProfileSnapshot = preparedAuth?.kind === "profile" ? preparedAuth.snapshot ?? await resolveCodexAppServerPreparedAuthProfileSnapshot({
|
|
2412
|
-
authProfileId,
|
|
2413
|
-
authProfileStore,
|
|
2414
|
-
agentDir,
|
|
2415
|
-
config: options?.config
|
|
2416
|
-
}) : void 0;
|
|
2417
|
-
if (preparedAuth?.kind === "profile" && !preparedAuthProfileSnapshot) throw new Error(`Prepared Codex auth profile "${preparedAuth.profileId}" is unusable.`);
|
|
2418
|
-
const resolvedPreparedAuth = preparedAuth?.kind === "api-key" ? {
|
|
2419
|
-
kind: "api-key",
|
|
2420
|
-
apiKey: preparedApiKey
|
|
2421
|
-
} : preparedAuth?.kind === "profile" ? {
|
|
2422
|
-
...preparedAuth,
|
|
2423
|
-
snapshot: preparedAuthProfileSnapshot
|
|
2424
|
-
} : void 0;
|
|
2425
|
-
return {
|
|
2426
|
-
agentDir,
|
|
2427
|
-
usesNativeAuth,
|
|
2428
|
-
authProfileId,
|
|
2429
|
-
authProfileStore,
|
|
2430
|
-
requestedStartOptions,
|
|
2431
|
-
preparedAuth: resolvedPreparedAuth,
|
|
2432
|
-
authRequirement,
|
|
2433
|
-
startOptions: await bridgeCodexAppServerStartOptions({
|
|
2434
|
-
startOptions: await resolveManagedCodexAppServerStartOptions(resolveCodexAppServerStartOptionsForAgent({
|
|
2435
|
-
startOptions: requestedStartOptions,
|
|
2436
|
-
agentDir
|
|
2437
|
-
})),
|
|
2438
|
-
agentDir,
|
|
2439
|
-
authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
|
|
2440
|
-
...resolvedPreparedAuth ? { preparedAuth: resolvedPreparedAuth } : {},
|
|
2441
|
-
config: options?.config,
|
|
2442
|
-
pluginConfig: options?.pluginConfig,
|
|
2443
|
-
...authProfileStore ? { authProfileStore } : {}
|
|
2444
|
-
})
|
|
2445
|
-
};
|
|
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
|
-
}
|
|
2451
|
-
/** Gets or starts a shared Codex app-server client and records a release lease. */
|
|
2452
|
-
async function getLeasedSharedCodexAppServerClient(options) {
|
|
2453
|
-
const acquired = await acquireSharedCodexAppServerClient(options, { leased: true });
|
|
2454
|
-
const state = getSharedCodexAppServerClientState();
|
|
2455
|
-
const releases = state.leasedReleases.get(acquired.client) ?? [];
|
|
2456
|
-
releases.push(acquired.release);
|
|
2457
|
-
state.leasedReleases.set(acquired.client, releases);
|
|
2458
|
-
return acquired.client;
|
|
2459
|
-
}
|
|
2460
|
-
/** Releases one outstanding lease for a shared Codex app-server client. */
|
|
2461
|
-
function releaseLeasedSharedCodexAppServerClient(client) {
|
|
2462
|
-
const state = getSharedCodexAppServerClientState();
|
|
2463
|
-
const releases = state.leasedReleases.get(client);
|
|
2464
|
-
if (!releases) return false;
|
|
2465
|
-
const release = releases.pop();
|
|
2466
|
-
if (!release) return false;
|
|
2467
|
-
if (releases.length === 0) state.leasedReleases.delete(client);
|
|
2468
|
-
release();
|
|
2469
|
-
return true;
|
|
2470
|
-
}
|
|
2471
|
-
/** Releases the currently owned client exactly once. */
|
|
2472
|
-
function releaseCodexAppServerClientLease(lease) {
|
|
2473
|
-
const client = lease.client;
|
|
2474
|
-
lease.client = void 0;
|
|
2475
|
-
return client ? releaseLeasedSharedCodexAppServerClient(client) : false;
|
|
2476
|
-
}
|
|
2477
|
-
/** Retries one config-loading request after moving its lease to the current owner. */
|
|
2478
|
-
async function withLeasedCodexAppServerClientStartSelectionRetry(params) {
|
|
2479
|
-
let client = params.lease.client;
|
|
2480
|
-
if (!client) throw new Error("Codex app-server selection retry requires an active client lease");
|
|
2481
|
-
const timeoutMs = params.options?.timeoutMs ?? 6e4;
|
|
2482
|
-
const deadline = Date.now() + timeoutMs;
|
|
2483
|
-
const signal = params.signal ?? params.options?.abandonSignal;
|
|
2484
|
-
const requestOptions = () => {
|
|
2485
|
-
if (signal?.aborted) throw new CodexAppServerStartupError("aborted", "Codex app-server selection retry aborted");
|
|
2486
|
-
const remainingTimeoutMs = deadline - Date.now();
|
|
2487
|
-
if (remainingTimeoutMs <= 0) throw new CodexAppServerStartupError("timed_out", "Codex app-server selection retry timed out");
|
|
2488
|
-
return {
|
|
2489
|
-
timeoutMs: remainingTimeoutMs,
|
|
2490
|
-
...signal ? { signal } : {}
|
|
2491
|
-
};
|
|
2492
|
-
};
|
|
2493
|
-
for (let attempt = 0; attempt < 2; attempt += 1) try {
|
|
2494
|
-
return await params.run(client, requestOptions());
|
|
2495
|
-
} catch (error) {
|
|
2496
|
-
if (!isCodexAppServerStartSelectionChangedError(error) || attempt > 0) throw error;
|
|
2497
|
-
retireSharedCodexAppServerClientIfCurrent(client);
|
|
2498
|
-
params.lease.client = void 0;
|
|
2499
|
-
if (!releaseLeasedSharedCodexAppServerClient(client)) {
|
|
2500
|
-
client.close();
|
|
2501
|
-
throw new Error("Codex app-server selection retry requires a leased shared client", { cause: error });
|
|
2502
|
-
}
|
|
2503
|
-
const replacementOptions = requestOptions();
|
|
2504
|
-
client = await getLeasedSharedCodexAppServerClient({
|
|
2505
|
-
...params.options,
|
|
2506
|
-
timeoutMs: replacementOptions.timeoutMs,
|
|
2507
|
-
...signal ? { abandonSignal: signal } : {}
|
|
2508
|
-
});
|
|
2509
|
-
params.lease.client = client;
|
|
2510
|
-
params.onClientChange(client);
|
|
2511
|
-
}
|
|
2512
|
-
throw new Error("Codex app-server selection retry loop exited unexpectedly");
|
|
2513
|
-
}
|
|
2514
|
-
async function acquireSharedCodexAppServerClient(options, leaseOptions) {
|
|
2515
|
-
if (options?.abandonSignal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
|
|
2516
|
-
const acquireStartedAt = Date.now();
|
|
2517
|
-
const timeoutMs = options?.timeoutMs ?? 0;
|
|
2518
|
-
const { agentDir, usesNativeAuth, authProfileId, authProfileStore, preparedAuth, authRequirement, requestedStartOptions, startOptions } = await withCodexAppServerAcquireDeadline(timeoutMs, resolveCodexAppServerClientStartContext(options), options?.abandonSignal);
|
|
2519
|
-
const remainingTimeoutMs = resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt);
|
|
2520
|
-
const authIdentityCacheKey = preparedAuth?.kind === "api-key" ? resolveCodexAppServerPreparedApiKeyCacheKey(preparedAuth.apiKey) : preparedAuth?.snapshot.secretFreeCacheKey ?? (authRequirement === "api-key" && !authProfileId ? resolveCodexAppServerFallbackApiKeyCacheKey({ startOptions }) : void 0);
|
|
2521
|
-
const baseKey = `${codexAppServerStartOptionsKey(startOptions, {
|
|
2522
|
-
authProfileId,
|
|
2523
|
-
authBindingFingerprint: options?.authBindingFingerprint,
|
|
2524
|
-
agentDir: usesNativeAuth ? void 0 : agentDir,
|
|
2525
|
-
fallbackApiKeyCacheKey: authIdentityCacheKey
|
|
2526
|
-
})}\0auth-requirement:${authRequirement ?? "native"}`;
|
|
2527
|
-
const runtimeArtifactMode = options?.runtimeArtifactMode ?? (options?.expectedRuntimeArtifact ? "capture" : void 0);
|
|
2528
|
-
const expectedRuntimeArtifactKey = options?.expectedRuntimeArtifact ? createHash("sha256").update(options.expectedRuntimeArtifact.id).update("\0").update(options.expectedRuntimeArtifact.fingerprint).digest("hex") : "mint";
|
|
2529
|
-
const key = runtimeArtifactMode ? `${baseKey}\0runtime-artifact:capture-v1:${expectedRuntimeArtifactKey}` : baseKey;
|
|
2530
|
-
const entry = getOrCreateSharedClientEntry(getSharedCodexAppServerClientState(), key);
|
|
2531
|
-
if (runtimeArtifactMode) entry.runtimeArtifactStartupAbort ??= new AbortController();
|
|
2532
|
-
entry.closeWhenIdle = false;
|
|
2533
|
-
const releasePendingAcquire = retainPendingSharedClientAcquire(entry);
|
|
2534
|
-
const startedCallback = options?.onStartedClient;
|
|
2535
|
-
if (startedCallback) {
|
|
2536
|
-
entry.onStartedClientCallbacks.add(startedCallback);
|
|
2537
|
-
if (entry.client) startedCallback(entry.client);
|
|
2538
|
-
}
|
|
2539
|
-
const stopStartedClientNotifications = () => {
|
|
2540
|
-
if (startedCallback) entry.onStartedClientCallbacks.delete(startedCallback);
|
|
2541
|
-
};
|
|
2542
|
-
let cleanupAbandonSignal;
|
|
2543
|
-
if (options?.abandonSignal) {
|
|
2544
|
-
const abandon = () => {
|
|
2545
|
-
stopStartedClientNotifications();
|
|
2546
|
-
releasePendingAcquire();
|
|
2547
|
-
retirePendingSharedClientEntryIfUnclaimed(key, entry);
|
|
2548
|
-
};
|
|
2549
|
-
options.abandonSignal.addEventListener("abort", abandon, { once: true });
|
|
2550
|
-
cleanupAbandonSignal = () => options.abandonSignal?.removeEventListener("abort", abandon);
|
|
2551
|
-
if (options.abandonSignal.aborted) abandon();
|
|
2552
|
-
}
|
|
2553
|
-
const startup = entry.startup ?? (entry.startup = createSharedCodexAppServerClientStartup({
|
|
2554
|
-
entry,
|
|
2555
|
-
key,
|
|
2556
|
-
requestedStartOptions,
|
|
2557
|
-
startOptions,
|
|
2558
|
-
agentDir,
|
|
2559
|
-
authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
|
|
2560
|
-
authProfileStore,
|
|
2561
|
-
preparedAuth,
|
|
2562
|
-
authRequirement,
|
|
2563
|
-
runtimeArtifactMode,
|
|
2564
|
-
...options?.expectedRuntimeArtifact ? { expectedRuntimeArtifact: options.expectedRuntimeArtifact } : {},
|
|
2565
|
-
runtimeArtifactSignal: entry.runtimeArtifactStartupAbort?.signal,
|
|
2566
|
-
config: options?.config
|
|
2567
|
-
}));
|
|
2568
|
-
try {
|
|
2569
|
-
await withCodexAppServerAcquireDeadline(remainingTimeoutMs, startup.initialized, options?.abandonSignal);
|
|
2570
|
-
const client = await withCodexAppServerAcquireDeadline(timeoutMs, startup.ready, options?.abandonSignal, "codex app-server authentication timed out");
|
|
2571
|
-
if (entry.closeError) throw entry.closeError;
|
|
2572
|
-
ensureCodexAppServerClientRuntime(client, {
|
|
2573
|
-
agentDir,
|
|
2574
|
-
authProfileId: usesNativeAuth ? void 0 : authProfileId,
|
|
2575
|
-
...authProfileStore ? { authProfileStore } : {},
|
|
2576
|
-
authMode: preparedAuth?.kind === "api-key" ? "prepared-api-key" : "profile",
|
|
2577
|
-
config: options?.config
|
|
2578
|
-
});
|
|
2579
|
-
const release = leaseOptions?.leased ? retainSharedClientEntry(entry) : void 0;
|
|
2580
|
-
return release ? {
|
|
2581
|
-
client,
|
|
2582
|
-
release
|
|
2583
|
-
} : { client };
|
|
2584
|
-
} catch (error) {
|
|
2585
|
-
releasePendingAcquire();
|
|
2586
|
-
retirePendingSharedClientEntryIfUnclaimed(key, entry);
|
|
2587
|
-
throw error;
|
|
2588
|
-
} finally {
|
|
2589
|
-
cleanupAbandonSignal?.();
|
|
2590
|
-
stopStartedClientNotifications();
|
|
2591
|
-
releasePendingAcquire();
|
|
2592
|
-
}
|
|
2593
|
-
}
|
|
2594
|
-
async function withCodexAppServerAcquireDeadline(timeoutMs, promise, signal, timeoutMessage = "codex app-server initialize timed out") {
|
|
2595
|
-
if (signal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
|
|
2596
|
-
const timed = withTimeout$1(promise, timeoutMs, timeoutMessage, () => new CodexAppServerStartupError("timed_out", timeoutMessage));
|
|
2597
|
-
if (!signal) return await timed;
|
|
2598
|
-
return await new Promise((resolve, reject) => {
|
|
2599
|
-
const onAbort = () => reject(new CodexAppServerStartupError("aborted", "codex app-server initialize aborted"));
|
|
2600
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
2601
|
-
timed.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
2602
|
-
});
|
|
2603
|
-
}
|
|
2604
|
-
function resolveRemainingAcquireTimeout(timeoutMs, startedAt) {
|
|
2605
|
-
if (!(timeoutMs > 0)) return timeoutMs;
|
|
2606
|
-
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
2607
|
-
if (remaining <= 0) throw new CodexAppServerStartupError("timed_out", "codex app-server initialize timed out");
|
|
2608
|
-
return remaining;
|
|
2609
|
-
}
|
|
2610
|
-
function createSharedCodexAppServerClientStartup(params) {
|
|
2611
|
-
const initialized = createDeferred();
|
|
2612
|
-
const ready = startInitializedCodexAppServerClient({
|
|
2613
|
-
requestedStartOptions: params.requestedStartOptions,
|
|
2614
|
-
startOptions: params.startOptions,
|
|
2615
|
-
agentDir: params.agentDir,
|
|
2616
|
-
authProfileId: params.authProfileId,
|
|
2617
|
-
authProfileStore: params.authProfileStore,
|
|
2618
|
-
preparedAuth: params.preparedAuth,
|
|
2619
|
-
authRequirement: params.authRequirement,
|
|
2620
|
-
runtimeArtifactMode: params.runtimeArtifactMode,
|
|
2621
|
-
...params.expectedRuntimeArtifact ? { expectedRuntimeArtifact: params.expectedRuntimeArtifact } : {},
|
|
2622
|
-
runtimeArtifactSignal: params.runtimeArtifactSignal,
|
|
2623
|
-
config: params.config,
|
|
2624
|
-
onStartedClient: (startedClient) => {
|
|
2625
|
-
params.entry.client = startedClient;
|
|
2626
|
-
for (const callback of params.entry.onStartedClientCallbacks) callback(startedClient);
|
|
2627
|
-
retirePendingSharedClientEntryIfUnclaimed(params.key, params.entry);
|
|
2628
|
-
},
|
|
2629
|
-
onInitializedClient: () => initialized.resolve()
|
|
2630
|
-
}).then((client) => {
|
|
2631
|
-
params.entry.client = client;
|
|
2632
|
-
client.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(params.key, closedClient));
|
|
2633
|
-
return client;
|
|
2634
|
-
}, (error) => {
|
|
2635
|
-
initialized.reject(error);
|
|
2636
|
-
throw error;
|
|
2637
|
-
});
|
|
2638
|
-
ready.catch(() => void 0);
|
|
2639
|
-
return {
|
|
2640
|
-
initialized: initialized.promise,
|
|
2641
|
-
ready
|
|
2642
|
-
};
|
|
2643
|
-
}
|
|
2644
|
-
/** Starts a non-shared Codex app-server client owned entirely by the caller. */
|
|
2645
|
-
async function createIsolatedCodexAppServerClient(options) {
|
|
2646
|
-
if (options?.abandonSignal?.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
|
|
2647
|
-
const acquireStartedAt = Date.now();
|
|
2648
|
-
const timeoutMs = options?.timeoutMs ?? 0;
|
|
2649
|
-
const { agentDir, usesNativeAuth, authProfileId, authProfileStore, preparedAuth, authRequirement, requestedStartOptions, startOptions } = await withCodexAppServerAcquireDeadline(timeoutMs, resolveCodexAppServerClientStartContext(options), options?.abandonSignal);
|
|
2650
|
-
return await startInitializedCodexAppServerClient({
|
|
2651
|
-
requestedStartOptions,
|
|
2652
|
-
startOptions,
|
|
2653
|
-
agentDir,
|
|
2654
|
-
authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
|
|
2655
|
-
authProfileStore,
|
|
2656
|
-
preparedAuth,
|
|
2657
|
-
authRequirement,
|
|
2658
|
-
runtimeArtifactMode: options?.runtimeArtifactMode ?? (options?.expectedRuntimeArtifact ? "capture" : void 0),
|
|
2659
|
-
...options?.expectedRuntimeArtifact ? { expectedRuntimeArtifact: options.expectedRuntimeArtifact } : {},
|
|
2660
|
-
runtimeArtifactSignal: options?.abandonSignal,
|
|
2661
|
-
config: options?.config,
|
|
2662
|
-
timeoutMs: resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt),
|
|
2663
|
-
abandonSignal: options?.abandonSignal,
|
|
2664
|
-
onStartedClient: options?.onStartedClient
|
|
2665
|
-
});
|
|
2666
|
-
}
|
|
2667
|
-
async function startInitializedCodexAppServerClient(params) {
|
|
2668
|
-
const acquireStartedAt = Date.now();
|
|
2669
|
-
const timeoutMs = params.timeoutMs ?? 0;
|
|
2670
|
-
const startOptionsCandidates = resolveManagedFallbackStartOptions(params.startOptions);
|
|
2671
|
-
for (const [index, startOptions] of startOptionsCandidates.entries()) {
|
|
2672
|
-
const runtimeArtifactModule = params.runtimeArtifactMode ? await import("./runtime-artifact-C2ITXdhM.js") : void 0;
|
|
2673
|
-
const nativeCommandBeforeStart = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
|
|
2674
|
-
const runtimeArtifactBeforeStart = runtimeArtifactModule ? await runtimeArtifactModule.captureCodexAppServerRuntimeArtifactBeforeStart({
|
|
2675
|
-
startOptions,
|
|
2676
|
-
spawnIdentity: resolveCodexAppServerSpawnIdentity(startOptions, nativeCommandBeforeStart),
|
|
2677
|
-
signal: params.runtimeArtifactSignal
|
|
2678
|
-
}) : void 0;
|
|
2679
|
-
if (runtimeArtifactModule && runtimeArtifactBeforeStart && params.expectedRuntimeArtifact && !runtimeArtifactModule.validateCodexAppServerRuntimeArtifactCapture(params.expectedRuntimeArtifact, runtimeArtifactBeforeStart)) {
|
|
2680
|
-
if (index + 1 < startOptionsCandidates.length) continue;
|
|
2681
|
-
throw new Error("Codex app-server runtime artifact does not match verified inference");
|
|
2682
|
-
}
|
|
2683
|
-
const client = CodexAppServerClient.start(startOptions);
|
|
2684
|
-
params.onStartedClient?.(client);
|
|
2685
|
-
let initialize;
|
|
2686
|
-
try {
|
|
2687
|
-
await withCodexAppServerAcquireDeadline(resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt), initialize = client.initialize(), params.abandonSignal);
|
|
2688
|
-
} catch (error) {
|
|
2689
|
-
client.close();
|
|
2690
|
-
initialize?.catch(() => void 0);
|
|
2691
|
-
if (shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates)) continue;
|
|
2692
|
-
throw error;
|
|
2693
|
-
}
|
|
2694
|
-
params.onInitializedClient?.();
|
|
2695
|
-
let runtimeArtifact;
|
|
2696
|
-
try {
|
|
2697
|
-
if (runtimeArtifactModule && runtimeArtifactBeforeStart) {
|
|
2698
|
-
const nativeCommand = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
|
|
2699
|
-
runtimeArtifact = await runtimeArtifactModule.finalizeCodexAppServerRuntimeArtifact({
|
|
2700
|
-
before: runtimeArtifactBeforeStart,
|
|
2701
|
-
startOptions,
|
|
2702
|
-
spawnIdentity: resolveCodexAppServerSpawnIdentity(startOptions, nativeCommand),
|
|
2703
|
-
runtimeIdentity: client.getRuntimeIdentity(),
|
|
2704
|
-
signal: params.runtimeArtifactSignal
|
|
2705
|
-
});
|
|
2706
|
-
if (params.expectedRuntimeArtifact && (runtimeArtifact.id !== params.expectedRuntimeArtifact.id || runtimeArtifact.fingerprint !== params.expectedRuntimeArtifact.fingerprint)) throw new Error("Codex app-server runtime artifact does not match verified inference");
|
|
2707
|
-
}
|
|
2708
|
-
} catch (error) {
|
|
2709
|
-
client.close();
|
|
2710
|
-
throw error;
|
|
2711
|
-
}
|
|
2712
|
-
ensureCodexAppServerClientRuntime(client, {
|
|
2713
|
-
agentDir: params.agentDir,
|
|
2714
|
-
authProfileId: params.authProfileId ?? void 0,
|
|
2715
|
-
authMode: params.preparedAuth?.kind === "api-key" ? "prepared-api-key" : "profile",
|
|
2716
|
-
...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {},
|
|
2717
|
-
config: params.config
|
|
2718
|
-
});
|
|
2719
|
-
try {
|
|
2720
|
-
await withCodexAppServerAcquireDeadline(resolveRemainingAcquireTimeout(timeoutMs, acquireStartedAt), applyCodexAppServerAuthProfile({
|
|
2721
|
-
client,
|
|
2722
|
-
agentDir: params.agentDir,
|
|
2723
|
-
authProfileId: params.authProfileId,
|
|
2724
|
-
preparedAuth: params.preparedAuth,
|
|
2725
|
-
authRequirement: params.authRequirement,
|
|
2726
|
-
startOptions,
|
|
2727
|
-
config: params.config,
|
|
2728
|
-
...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {}
|
|
2729
|
-
}), params.abandonSignal);
|
|
2730
|
-
const nativeCommand = startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0;
|
|
2731
|
-
if (runtimeArtifactModule && runtimeArtifact) runtimeArtifactModule.bindCodexAppServerRuntimeArtifact(client, runtimeArtifact);
|
|
2732
|
-
getCodexAppServerClientStartMetadata().set(client, {
|
|
2733
|
-
requestedStartOptions: params.requestedStartOptions,
|
|
2734
|
-
startOptions,
|
|
2735
|
-
agentDir: params.agentDir,
|
|
2736
|
-
...nativeCommand ? { nativeCommand } : {}
|
|
2737
|
-
});
|
|
2738
|
-
const fenceKey = resolveCodexNativeConfigFenceKey({ client });
|
|
2739
|
-
if (fenceKey) client.setThreadSessionRequestGuard(async (options) => {
|
|
2740
|
-
const release = await acquireCodexNativeConfigFence(fenceKey, options);
|
|
2741
|
-
try {
|
|
2742
|
-
assertCodexAppServerClientStartSelectionCurrent({ client });
|
|
2743
|
-
return release;
|
|
2744
|
-
} catch (error) {
|
|
2745
|
-
release();
|
|
2746
|
-
throw error;
|
|
2747
|
-
}
|
|
2748
|
-
});
|
|
2749
|
-
return client;
|
|
2750
|
-
} catch (error) {
|
|
2751
|
-
client.close();
|
|
2752
|
-
throw error;
|
|
2753
|
-
}
|
|
2754
|
-
}
|
|
2755
|
-
throw new Error("Managed Codex app-server fallback candidates were exhausted.");
|
|
2756
|
-
}
|
|
2757
|
-
function resolveManagedFallbackStartOptions(startOptions) {
|
|
2758
|
-
const commands = [startOptions.command, ...startOptions.managedFallbackCommandPaths ?? []];
|
|
2759
|
-
const candidates = [];
|
|
2760
|
-
for (const [index, command] of commands.entries()) {
|
|
2761
|
-
const managedFallbackCommandPaths = commands.slice(index + 1);
|
|
2762
|
-
const candidate = {
|
|
2763
|
-
...startOptions,
|
|
2764
|
-
command
|
|
2765
|
-
};
|
|
2766
|
-
if (managedFallbackCommandPaths.length === 0) delete candidate.managedFallbackCommandPaths;
|
|
2767
|
-
else candidate.managedFallbackCommandPaths = managedFallbackCommandPaths;
|
|
2768
|
-
candidates.push(candidate);
|
|
2769
|
-
}
|
|
2770
|
-
return candidates;
|
|
2771
|
-
}
|
|
2772
|
-
function shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates) {
|
|
2773
|
-
return startOptions.commandSource === "resolved-managed" && index < startOptionsCandidates.length - 1 && isUnsupportedCodexAppServerVersionError(error);
|
|
2774
|
-
}
|
|
2775
|
-
/** Clears and closes the shared entry only if it still owns the supplied client. */
|
|
2776
|
-
function clearSharedCodexAppServerClientIfCurrent(client) {
|
|
2777
|
-
if (!client) return false;
|
|
2778
|
-
const state = getSharedCodexAppServerClientState();
|
|
2779
|
-
for (const [key, entry] of state.clients) if (entry.client === client) {
|
|
2780
|
-
state.clients.delete(key);
|
|
2781
|
-
client.close();
|
|
2782
|
-
return true;
|
|
2783
|
-
}
|
|
2784
|
-
return false;
|
|
2785
|
-
}
|
|
2786
|
-
/** Retains the matching shared client and returns a release callback. */
|
|
2787
|
-
function retainSharedCodexAppServerClientIfCurrent(client) {
|
|
2788
|
-
if (!client) return;
|
|
2789
|
-
const state = getSharedCodexAppServerClientState();
|
|
2790
|
-
for (const entry of state.clients.values()) if (entry.client === client) return retainSharedClientEntry(entry);
|
|
2791
|
-
}
|
|
2792
|
-
/**
|
|
2793
|
-
* Retires a matching shared client. Default is graceful: detach from the map
|
|
2794
|
-
* (future acquisitions get a fresh client) and close once leases drain.
|
|
2795
|
-
* `failActiveLeases` is for suspect clients only (timed-out turns): it closes
|
|
2796
|
-
* the physical connection immediately so co-leased attempts hit the normal
|
|
2797
|
-
* client-closed retry path, and pending acquires reject instead of leasing
|
|
2798
|
-
* the poisoned process. Routine cleanup must NOT use it — it would abort
|
|
2799
|
-
* healthy sibling turns on a working client.
|
|
2800
|
-
*/
|
|
2801
|
-
function retireSharedCodexAppServerClientIfCurrent(client, opts) {
|
|
2802
|
-
if (!client) return;
|
|
2803
|
-
const state = getSharedCodexAppServerClientState();
|
|
2804
|
-
for (const [key, entry] of state.clients) if (entry.client === client) {
|
|
2805
|
-
state.clients.delete(key);
|
|
2806
|
-
entry.closeWhenIdle = true;
|
|
2807
|
-
if (opts?.failActiveLeases) {
|
|
2808
|
-
entry.closeError = /* @__PURE__ */ new Error("codex app-server client is closed");
|
|
2809
|
-
const closed = closeRetiredSharedClientEntry(entry);
|
|
2810
|
-
if (closed) suspectClosedClients.add(client);
|
|
2811
|
-
return {
|
|
2812
|
-
activeLeases: entry.activeLeases,
|
|
2813
|
-
closed
|
|
2814
|
-
};
|
|
2815
|
-
}
|
|
2816
|
-
const closed = closeRetiredSharedClientEntryIfIdle(entry);
|
|
2817
|
-
return {
|
|
2818
|
-
activeLeases: entry.activeLeases,
|
|
2819
|
-
closed
|
|
2820
|
-
};
|
|
2821
|
-
}
|
|
2822
|
-
const activeLeases = state.leasedReleases.get(client)?.length ?? 0;
|
|
2823
|
-
if (activeLeases > 0) {
|
|
2824
|
-
if (opts?.failActiveLeases && !suspectClosedClients.has(client)) {
|
|
2825
|
-
suspectClosedClients.add(client);
|
|
2826
|
-
client.close();
|
|
2827
|
-
return {
|
|
2828
|
-
activeLeases,
|
|
2829
|
-
closed: true
|
|
2830
|
-
};
|
|
2831
|
-
}
|
|
2832
|
-
return {
|
|
2833
|
-
activeLeases,
|
|
2834
|
-
closed: false
|
|
2835
|
-
};
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
/** Clears a matching shared client and waits for its process to exit. */
|
|
2839
|
-
async function clearSharedCodexAppServerClientIfCurrentAndWait(client, options) {
|
|
2840
|
-
if (!client) return false;
|
|
2841
|
-
const state = getSharedCodexAppServerClientState();
|
|
2842
|
-
for (const [key, entry] of state.clients) if (entry.client === client) {
|
|
2843
|
-
state.clients.delete(key);
|
|
2844
|
-
await client.closeAndWait(options);
|
|
2845
|
-
return true;
|
|
2846
|
-
}
|
|
2847
|
-
return false;
|
|
2848
|
-
}
|
|
2849
|
-
/** Clears all shared clients and waits for their processes to exit. */
|
|
2850
|
-
async function clearSharedCodexAppServerClientAndWait(options) {
|
|
2851
|
-
const state = getSharedCodexAppServerClientState();
|
|
2852
|
-
const clients = collectSharedClients(state);
|
|
2853
|
-
state.clients.clear();
|
|
2854
|
-
await Promise.all(clients.map((client) => client.closeAndWait(options)));
|
|
2855
|
-
}
|
|
2856
|
-
globalThis[SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER] = clearSharedCodexAppServerClientAndWait;
|
|
2857
|
-
function getOrCreateSharedClientEntry(state, key) {
|
|
2858
|
-
let entry = state.clients.get(key);
|
|
2859
|
-
if (!entry) {
|
|
2860
|
-
entry = {
|
|
2861
|
-
activeLeases: 0,
|
|
2862
|
-
pendingAcquires: 0,
|
|
2863
|
-
closeWhenIdle: false,
|
|
2864
|
-
onStartedClientCallbacks: /* @__PURE__ */ new Set()
|
|
2865
|
-
};
|
|
2866
|
-
state.clients.set(key, entry);
|
|
2867
|
-
}
|
|
2868
|
-
return entry;
|
|
2869
|
-
}
|
|
2870
|
-
function clearSharedClientEntryIfCurrent(key, client) {
|
|
2871
|
-
const state = getSharedCodexAppServerClientState();
|
|
2872
|
-
if (state.clients.get(key)?.client === client) state.clients.delete(key);
|
|
2873
|
-
}
|
|
2874
|
-
/** Clears a matching shared client only when no lease or acquire currently claims it. */
|
|
2875
|
-
function clearSharedCodexAppServerClientIfCurrentAndUnclaimed(client) {
|
|
2876
|
-
if (!client) return {
|
|
2877
|
-
found: false,
|
|
2878
|
-
closed: false,
|
|
2879
|
-
activeLeases: 0,
|
|
2880
|
-
pendingAcquires: 0
|
|
2881
|
-
};
|
|
2882
|
-
const state = getSharedCodexAppServerClientState();
|
|
2883
|
-
for (const [key, entry] of state.clients) if (entry.client === client) return {
|
|
2884
|
-
found: true,
|
|
2885
|
-
closed: closeSharedClientEntryIfUnclaimed(key, entry),
|
|
2886
|
-
activeLeases: entry.activeLeases,
|
|
2887
|
-
pendingAcquires: entry.pendingAcquires
|
|
2888
|
-
};
|
|
2889
|
-
return {
|
|
2890
|
-
found: false,
|
|
2891
|
-
closed: false,
|
|
2892
|
-
activeLeases: 0,
|
|
2893
|
-
pendingAcquires: 0
|
|
2894
|
-
};
|
|
2895
|
-
}
|
|
2896
|
-
function retainPendingSharedClientAcquire(entry) {
|
|
2897
|
-
let released = false;
|
|
2898
|
-
entry.pendingAcquires += 1;
|
|
2899
|
-
return () => {
|
|
2900
|
-
if (released) return;
|
|
2901
|
-
released = true;
|
|
2902
|
-
entry.pendingAcquires = Math.max(0, entry.pendingAcquires - 1);
|
|
2903
|
-
closeRetiredSharedClientEntryIfIdle(entry);
|
|
2904
|
-
};
|
|
2905
|
-
}
|
|
2906
|
-
function retainSharedClientEntry(entry) {
|
|
2907
|
-
let released = false;
|
|
2908
|
-
entry.activeLeases += 1;
|
|
2909
|
-
return () => {
|
|
2910
|
-
if (released) return;
|
|
2911
|
-
released = true;
|
|
2912
|
-
entry.activeLeases = Math.max(0, entry.activeLeases - 1);
|
|
2913
|
-
closeRetiredSharedClientEntryIfIdle(entry);
|
|
2914
|
-
};
|
|
2915
|
-
}
|
|
2916
|
-
function closeRetiredSharedClientEntryIfIdle(entry) {
|
|
2917
|
-
if (!entry.closeWhenIdle || entry.activeLeases > 0 || entry.pendingAcquires > 0 || !entry.client) return false;
|
|
2918
|
-
const client = entry.client;
|
|
2919
|
-
entry.closeWhenIdle = false;
|
|
2920
|
-
entry.client = void 0;
|
|
2921
|
-
client.close();
|
|
2922
|
-
return true;
|
|
2923
|
-
}
|
|
2924
|
-
function closeRetiredSharedClientEntry(entry) {
|
|
2925
|
-
const client = entry.client;
|
|
2926
|
-
if (!client) return false;
|
|
2927
|
-
entry.client = void 0;
|
|
2928
|
-
client.close();
|
|
2929
|
-
return true;
|
|
2930
|
-
}
|
|
2931
|
-
function closeSharedClientEntryIfUnclaimed(key, entry) {
|
|
2932
|
-
if (entry.activeLeases > 0 || entry.pendingAcquires > 0) return false;
|
|
2933
|
-
const state = getSharedCodexAppServerClientState();
|
|
2934
|
-
if (state.clients.get(key) !== entry) return false;
|
|
2935
|
-
state.clients.delete(key);
|
|
2936
|
-
entry.client?.close();
|
|
2937
|
-
return Boolean(entry.client);
|
|
2938
|
-
}
|
|
2939
|
-
function retirePendingSharedClientEntryIfUnclaimed(key, entry) {
|
|
2940
|
-
if (entry.activeLeases > 0 || entry.pendingAcquires > 0) return;
|
|
2941
|
-
entry.runtimeArtifactStartupAbort?.abort(/* @__PURE__ */ new Error("Codex runtime artifact startup was abandoned"));
|
|
2942
|
-
entry.closeWhenIdle = true;
|
|
2943
|
-
const state = getSharedCodexAppServerClientState();
|
|
2944
|
-
if (state.clients.get(key) === entry) state.clients.delete(key);
|
|
2945
|
-
if (!entry.client) return;
|
|
2946
|
-
closeRetiredSharedClientEntry(entry);
|
|
2947
|
-
}
|
|
2948
|
-
function collectSharedClients(state) {
|
|
2949
|
-
return [...new Set([...state.clients.values()].map((entry) => entry.client).filter((client) => Boolean(client)))];
|
|
2950
|
-
}
|
|
2951
|
-
//#endregion
|
|
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 };
|