@openclaw/codex 2026.7.1-beta.1 → 2026.7.1-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{app-server-policy-xi0ZmBGO.js → app-server-policy-BUk0GLMy.js} +5 -5
  2. package/dist/{attempt-notifications-l9LElGOU.js → attempt-notifications-BGsEIIDI.js} +5 -40
  3. package/dist/{command-handlers-vZy8xX5X.js → command-handlers-UVniG5Hl.js} +267 -232
  4. package/dist/command-rpc-BjgEPh19.js +784 -0
  5. package/dist/compact-CZzbcygx.js +603 -0
  6. package/dist/{computer-use-FPGG-mtX.js → computer-use-DDeySrnb.js} +3 -3
  7. package/dist/{config-C_whBx3M.js → config-CYEDnLJ2.js} +36 -15
  8. package/dist/conversation-binding-data-BHRpYbX3.js +121 -0
  9. package/dist/doctor-contract-api.js +439 -22
  10. package/dist/harness.js +29 -10
  11. package/dist/index.js +1119 -28
  12. package/dist/{media-understanding-provider-C5yYzx_6.js → media-understanding-provider-DgqRvU2_.js} +13 -8
  13. package/dist/media-understanding-provider.js +1 -1
  14. package/dist/{models-Ccy1_7nN.js → models-DDmO1zwd.js} +2 -2
  15. package/dist/notification-correlation-Bo7KB3ks.js +35 -0
  16. package/dist/{plugin-app-cache-key-CDioyur-.js → plugin-app-cache-key-o-AHbdaf.js} +8 -4
  17. package/dist/{protocol-dh-ETiNd.js → protocol-2POPqAY4.js} +2 -1
  18. package/dist/{protocol-validators-CB4mtyrs.js → protocol-validators-dZQ-UTOa.js} +117 -62
  19. package/dist/{provider-capabilities-CE5k8cmO.js → provider-capabilities-gTCwjfmh.js} +2920 -114
  20. package/dist/{provider-DosqwRb6.js → provider-cc_62eQE.js} +19 -10
  21. package/dist/provider.js +2 -2
  22. package/dist/{request-BQuSQF29.js → request-BcJyl8KL.js} +2 -2
  23. package/dist/{run-attempt-O3Zs32KI.js → run-attempt-8SPLiDlT.js} +1016 -2877
  24. package/dist/{sandbox-guard-pTY2COoC.js → sandbox-guard-DA2TQfZW.js} +3 -3
  25. package/dist/session-binding-Dc03iwRF.js +595 -0
  26. package/dist/session-binding-meta-B7aEMU7g.js +6 -0
  27. package/dist/{shared-client-rR6TDJA3.js → shared-client-4ICy3U6d.js} +892 -103
  28. package/dist/{side-question-DDVgFmpv.js → side-question-DkjXvYv7.js} +132 -140
  29. package/dist/{thread-lifecycle-DeSMZSXr.js → thread-lifecycle-BskXnNP-.js} +609 -444
  30. package/dist/{web-search-provider.runtime-Q89rQhsL.js → web-search-provider.runtime-B5F42P7x.js} +3 -3
  31. package/npm-shrinkwrap.json +34 -34
  32. package/openclaw.plugin.json +20 -0
  33. package/package.json +9 -6
  34. package/dist/client-IcTBKEqA.js +0 -732
  35. package/dist/client-factory-CwjdQQ4j.js +0 -18
  36. package/dist/compact-BzB9AqN1.js +0 -278
  37. package/dist/conversation-binding-CEE2UyYb.js +0 -1570
  38. package/dist/rate-limit-cache-C7qmZ0Jh.js +0 -26
  39. package/dist/session-binding-Cm0Gg7Z1.js +0 -339
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { d as resolveCodexAppServerRuntimeOptions, r as codexAppServerStartOptionsKey } from "./config-C_whBx3M.js";
3
- import { l as resolveCodexAppServerSpawnEnv, o as isUnsupportedCodexAppServerVersionError, s as MANAGED_CODEX_APP_SERVER_PACKAGE, t as CodexAppServerClient } from "./client-IcTBKEqA.js";
2
+ import { i as isRpcResponse, r as isJsonObject$1 } from "./protocol-2POPqAY4.js";
3
+ import { d as resolveCodexAppServerRuntimeOptions, f as resolveCodexAppServerUserHomeDir, r as codexAppServerStartOptionsKey } from "./config-CYEDnLJ2.js";
4
4
  import { createRequire } from "node:module";
5
5
  import fs, { access } from "node:fs/promises";
6
6
  import path from "node:path";
@@ -8,10 +8,101 @@ import { createHash } from "node:crypto";
8
8
  import fsSync, { constants, readFileSync } from "node:fs";
9
9
  import os from "node:os";
10
10
  import { ensureAuthProfileStore, findPersistedAuthProfileCredential, loadAuthProfileStoreForSecretsRuntime, refreshOAuthCredentialForRuntime, resolveApiKeyForProfile, resolveAuthProfileOrder, resolveDefaultAgentDir, resolvePersistedAuthProfileOwnerAgentDir, resolveProviderIdForAuth } from "openclaw/plugin-sdk/agent-runtime";
11
+ import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
12
+ import { OPENCLAW_VERSION, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
11
13
  import { isDeepStrictEqual } from "node:util";
12
14
  import { hasUsableOAuthCredential } from "openclaw/plugin-sdk/provider-auth";
15
+ import { spawn } from "node:child_process";
16
+ import { createInterface } from "node:readline";
17
+ import { EventEmitter } from "node:events";
18
+ import { PassThrough, Writable } from "node:stream";
19
+ import WebSocket from "ws";
13
20
  import { fileURLToPath } from "node:url";
14
21
  import { withTimeout } from "openclaw/plugin-sdk/security-runtime";
22
+ //#region extensions/codex/src/app-server/transport-stdio.ts
23
+ /**
24
+ * Creates and configures stdio-backed Codex app-server transports, including
25
+ * Windows spawn normalization and environment filtering.
26
+ */
27
+ const UNSAFE_ENVIRONMENT_KEYS = /* @__PURE__ */ new Set([
28
+ "__proto__",
29
+ "constructor",
30
+ "prototype"
31
+ ]);
32
+ const QA_PARENT_PID_ENV = "OPENCLAW_QA_PARENT_PID";
33
+ const DEFAULT_SPAWN_RUNTIME = {
34
+ platform: process.platform,
35
+ env: process.env,
36
+ execPath: process.execPath
37
+ };
38
+ /** Resolves the concrete command/argv/shell settings used to spawn Codex app-server. */
39
+ function resolveCodexAppServerSpawnInvocation(options, runtime = DEFAULT_SPAWN_RUNTIME) {
40
+ if (options.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
41
+ const resolved = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
42
+ command: options.command,
43
+ platform: runtime.platform,
44
+ env: runtime.env,
45
+ execPath: runtime.execPath,
46
+ packageName: "@openai/codex"
47
+ }), options.args);
48
+ return {
49
+ command: resolved.command,
50
+ args: resolved.argv,
51
+ shell: resolved.shell,
52
+ windowsHide: resolved.windowsHide
53
+ };
54
+ }
55
+ /** Merges app-server environment overrides while honoring clearEnv and unsafe key filtering. */
56
+ function resolveCodexAppServerSpawnEnv(options, baseEnv = process.env, platform = process.platform) {
57
+ const env = Object.create(null);
58
+ copySafeEnvironmentEntries(env, baseEnv);
59
+ copySafeEnvironmentEntries(env, options.env ?? {});
60
+ const keysToClear = normalizedEnvironmentKeys(options.clearEnv ?? []);
61
+ if (platform === "win32") {
62
+ const lowerCaseKeysToClear = new Set(keysToClear.map((key) => key.toLowerCase()));
63
+ for (const candidate of Object.keys(env)) if (lowerCaseKeysToClear.has(candidate.toLowerCase())) delete env[candidate];
64
+ } else for (const key of keysToClear) delete env[key];
65
+ return env;
66
+ }
67
+ /** Keeps QA-owned app-server processes inside the gateway process-group cleanup boundary. */
68
+ function resolveCodexAppServerDetachedMode(env, platform = process.platform) {
69
+ return platform !== "win32" && !env[QA_PARENT_PID_ENV]?.trim();
70
+ }
71
+ function normalizedEnvironmentKeys(rawKeys) {
72
+ const keys = [];
73
+ for (const rawKey of rawKeys) {
74
+ const key = rawKey.trim();
75
+ if (key.length > 0) keys.push(key);
76
+ }
77
+ return keys;
78
+ }
79
+ function copySafeEnvironmentEntries(target, source) {
80
+ for (const [key, value] of Object.entries(source)) {
81
+ if (UNSAFE_ENVIRONMENT_KEYS.has(key)) continue;
82
+ target[key] = value;
83
+ }
84
+ }
85
+ /** Spawns the Codex app-server process and returns the shared transport interface. */
86
+ function createStdioTransport(options) {
87
+ const env = resolveCodexAppServerSpawnEnv(options);
88
+ const invocation = resolveCodexAppServerSpawnInvocation(options, {
89
+ platform: process.platform,
90
+ env,
91
+ execPath: process.execPath
92
+ });
93
+ return spawn(invocation.command, invocation.args, {
94
+ env,
95
+ detached: resolveCodexAppServerDetachedMode(env),
96
+ shell: invocation.shell,
97
+ stdio: [
98
+ "pipe",
99
+ "pipe",
100
+ "pipe"
101
+ ],
102
+ windowsHide: invocation.windowsHide
103
+ });
104
+ }
105
+ //#endregion
15
106
  //#region extensions/codex/src/app-server/auth-bridge.ts
16
107
  const CODEX_APP_SERVER_AUTH_PROVIDER = "openai";
17
108
  const OPENAI_CODEX_APP_SERVER_AUTH_PROVIDER = "openai-codex";
@@ -29,8 +120,8 @@ const CODEX_HOME_DIRNAME = ".codex";
29
120
  const scopedOAuthRefreshQueues = /* @__PURE__ */ new WeakMap();
30
121
  async function bridgeCodexAppServerStartOptions(params) {
31
122
  if (params.startOptions.transport !== "stdio") return params.startOptions;
32
- const isolatedStartOptions = await withAgentCodexHomeEnvironment(params.startOptions, params.agentDir);
33
- if (params.authProfileId === null) return isolatedStartOptions;
123
+ const scopedStartOptions = await withCodexHomeEnvironment(params.startOptions, params.agentDir);
124
+ if (params.authProfileId === null) return scopedStartOptions;
34
125
  const store = resolveCodexAppServerAuthProfileStore({
35
126
  agentDir: params.agentDir,
36
127
  authProfileId: params.authProfileId,
@@ -45,7 +136,7 @@ async function bridgeCodexAppServerStartOptions(params) {
45
136
  config: params.config
46
137
  }),
47
138
  config: params.config
48
- }) ? withClearedEnvironmentVariables(isolatedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS) : isolatedStartOptions;
139
+ }) ? withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS) : scopedStartOptions;
49
140
  }
50
141
  function resolveCodexAppServerAuthProfileId(params) {
51
142
  const requested = params.authProfileId?.trim();
@@ -190,8 +281,8 @@ function fingerprintCodexCliAuthFileApiKeyCacheKey(apiKey) {
190
281
  function resolveCodexAppServerHomeDir(agentDir) {
191
282
  return path.join(path.resolve(agentDir), CODEX_APP_SERVER_HOME_DIRNAME);
192
283
  }
193
- async function withAgentCodexHomeEnvironment(startOptions, agentDir) {
194
- const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim() ? startOptions.env[CODEX_HOME_ENV_VAR] : resolveCodexAppServerHomeDir(agentDir);
284
+ async function withCodexHomeEnvironment(startOptions, agentDir) {
285
+ const codexHome = startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim() ? startOptions.env[CODEX_HOME_ENV_VAR] : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir(process.env) : resolveCodexAppServerHomeDir(agentDir);
195
286
  const nativeHome = startOptions.env?.[HOME_ENV_VAR]?.trim() ? startOptions.env[HOME_ENV_VAR] : void 0;
196
287
  await fs.mkdir(codexHome, { recursive: true });
197
288
  if (nativeHome) await fs.mkdir(nativeHome, { recursive: true });
@@ -505,6 +596,781 @@ function resolveChatgptAccountId(profileId, credential) {
505
596
  return credential.email?.trim() || profileId;
506
597
  }
507
598
  //#endregion
599
+ //#region extensions/codex/src/app-server/rate-limit-cache.ts
600
+ const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 10 * 6e4;
601
+ const SPARSE_ACCOUNT_METADATA_KEYS = [
602
+ "credits",
603
+ "individualLimit",
604
+ "planType"
605
+ ];
606
+ const rateLimitsByClient = /* @__PURE__ */ new WeakMap();
607
+ /** Replaces one physical client's cache with an authoritative rate-limit read response. */
608
+ function rememberCodexRateLimitsRead(client, value, nowMs = Date.now()) {
609
+ if (value !== void 0) {
610
+ const revisionsByLimitId = { ...rateLimitsByClient.get(client)?.revisionsByLimitId };
611
+ for (const limitId of readRateLimitIds(value)) revisionsByLimitId[limitId] = (revisionsByLimitId[limitId] ?? 0) + 1;
612
+ rateLimitsByClient.set(client, {
613
+ value,
614
+ updatedAtMs: nowMs,
615
+ revisionsByLimitId
616
+ });
617
+ }
618
+ }
619
+ /** Merges a sparse rolling notification into one physical client's latest read response. */
620
+ function mergeCodexRateLimitsUpdate(client, value, nowMs = Date.now()) {
621
+ const update = isJsonObject$1(value) && isJsonObject$1(value.rateLimits) ? value.rateLimits : void 0;
622
+ if (!update) return;
623
+ const currentState = rateLimitsByClient.get(client);
624
+ const current = currentState?.value;
625
+ const limitId = readLimitId(update);
626
+ rateLimitsByClient.set(client, {
627
+ value: mergeRateLimitUpdate(current, update),
628
+ updatedAtMs: nowMs,
629
+ revisionsByLimitId: {
630
+ ...currentState?.revisionsByLimitId,
631
+ [limitId]: (currentState?.revisionsByLimitId[limitId] ?? 0) + 1
632
+ }
633
+ });
634
+ }
635
+ /** Per-limit marker used to trust only primary Codex updates from one turn startup. */
636
+ function readCodexRateLimitsRevision(client, limitId = "codex") {
637
+ return rateLimitsByClient.get(client)?.revisionsByLimitId[limitId] ?? 0;
638
+ }
639
+ /** Reads one physical client's cached rate-limit payload within the max-age window. */
640
+ function readRecentCodexRateLimits(client, options) {
641
+ const state = rateLimitsByClient.get(client);
642
+ if (!state) return;
643
+ const nowMs = options?.nowMs ?? Date.now();
644
+ const maxAgeMs = options?.maxAgeMs ?? DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS;
645
+ return maxAgeMs >= 0 && nowMs - state.updatedAtMs > maxAgeMs ? void 0 : state.value;
646
+ }
647
+ function mergeRateLimitUpdate(current, update) {
648
+ const currentEnvelope = isJsonObject$1(current) ? current : void 0;
649
+ const currentPrimary = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimits) ? currentEnvelope.rateLimits : void 0;
650
+ const currentByLimitId = currentEnvelope && isJsonObject$1(currentEnvelope.rateLimitsByLimitId) ? currentEnvelope.rateLimitsByLimitId : void 0;
651
+ const limitId = readLimitId(update);
652
+ const currentPrimaryLimitId = currentPrimary ? readLimitId(currentPrimary) : void 0;
653
+ const currentForLimit = (currentByLimitId && isJsonObject$1(currentByLimitId[limitId]) ? currentByLimitId[limitId] : void 0) ?? (currentPrimaryLimitId === limitId ? currentPrimary : void 0);
654
+ const merged = mergeSparseSnapshot(isJsonObject$1(currentForLimit) ? currentForLimit : void 0, currentPrimary, update, limitId);
655
+ const nextPrimary = !currentPrimary || currentPrimaryLimitId === limitId ? merged : currentPrimary;
656
+ let nextByLimitId;
657
+ if (currentByLimitId) nextByLimitId = {
658
+ ...currentByLimitId,
659
+ [limitId]: merged
660
+ };
661
+ else if (currentPrimary && currentPrimaryLimitId && currentPrimaryLimitId !== limitId) nextByLimitId = {
662
+ [currentPrimaryLimitId]: currentPrimary,
663
+ [limitId]: merged
664
+ };
665
+ return {
666
+ ...currentEnvelope,
667
+ rateLimits: nextPrimary,
668
+ ...nextByLimitId ? { rateLimitsByLimitId: nextByLimitId } : {}
669
+ };
670
+ }
671
+ function readRateLimitIds(value) {
672
+ if (!isJsonObject$1(value)) return [];
673
+ const ids = /* @__PURE__ */ new Set();
674
+ if (isJsonObject$1(value.rateLimits)) ids.add(readLimitId(value.rateLimits));
675
+ if (isJsonObject$1(value.rateLimitsByLimitId)) for (const [key, snapshot] of Object.entries(value.rateLimitsByLimitId)) {
676
+ const snapshotLimitId = isJsonObject$1(snapshot) && typeof snapshot.limitId === "string" ? snapshot.limitId.trim() : "";
677
+ ids.add(snapshotLimitId || key);
678
+ }
679
+ return [...ids];
680
+ }
681
+ function mergeSparseSnapshot(current, accountFallback, update, limitId) {
682
+ const merged = {
683
+ ...update,
684
+ limitId
685
+ };
686
+ for (const key of SPARSE_ACCOUNT_METADATA_KEYS) {
687
+ const previous = current?.[key] ?? accountFallback?.[key];
688
+ if (merged[key] == null && previous != null) merged[key] = previous;
689
+ }
690
+ return merged;
691
+ }
692
+ function readLimitId(snapshot) {
693
+ const value = snapshot.limitId;
694
+ return typeof value === "string" && value.trim() ? value.trim() : "codex";
695
+ }
696
+ //#endregion
697
+ //#region extensions/codex/src/app-server/client-runtime.ts
698
+ /** Client-scoped Codex auth and account observers. */
699
+ const configuredClients = /* @__PURE__ */ new WeakMap();
700
+ /** Installs one auth-refresh handler and one rate-limit observer per physical client. */
701
+ function ensureCodexAppServerClientRuntime(client, context) {
702
+ const existing = configuredClients.get(client);
703
+ if (existing) {
704
+ existing.context = context;
705
+ return;
706
+ }
707
+ const runtime = { context };
708
+ configuredClients.set(client, runtime);
709
+ client.addRequestHandler(async (request) => {
710
+ if (request.method !== "account/chatgptAuthTokens/refresh") return;
711
+ return await refreshCodexAppServerAuthTokens({
712
+ agentDir: runtime.context.agentDir,
713
+ authProfileId: runtime.context.authProfileId,
714
+ ...runtime.context.authProfileStore ? { authProfileStore: runtime.context.authProfileStore } : {},
715
+ config: runtime.context.config
716
+ });
717
+ });
718
+ client.addNotificationHandler((notification) => {
719
+ if (notification.method === "account/rateLimits/updated") mergeCodexRateLimitsUpdate(client, notification.params);
720
+ });
721
+ }
722
+ //#endregion
723
+ //#region extensions/codex/src/app-server/transport-websocket.ts
724
+ /**
725
+ * Adapts a remote Codex app-server WebSocket endpoint to the shared stdio-like
726
+ * transport interface.
727
+ */
728
+ /** Opens a WebSocket app-server transport and maps newline-delimited frames to stdout/stdin. */
729
+ function createWebSocketTransport(options) {
730
+ if (!options.url) throw new Error("codex app-server websocket transport requires plugins.entries.codex.config.appServer.url");
731
+ const events = new EventEmitter();
732
+ const stdout = new PassThrough();
733
+ const stderr = new PassThrough();
734
+ const headers = {
735
+ ...options.headers,
736
+ ...options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}
737
+ };
738
+ const socket = new WebSocket(options.url, { headers });
739
+ const pendingFrames = [];
740
+ let killed = false;
741
+ const sendFrame = (frame) => {
742
+ const trimmed = frame.trim();
743
+ if (!trimmed) return;
744
+ if (socket.readyState === WebSocket.OPEN) {
745
+ socket.send(trimmed);
746
+ return;
747
+ }
748
+ pendingFrames.push(trimmed);
749
+ };
750
+ socket.once("open", () => {
751
+ for (const frame of pendingFrames.splice(0)) socket.send(frame);
752
+ });
753
+ socket.once("error", (error) => events.emit("error", error));
754
+ socket.once("close", (code, reason) => {
755
+ killed = true;
756
+ events.emit("exit", code, reason.toString("utf8"));
757
+ });
758
+ socket.on("message", (data) => {
759
+ const text = websocketFrameToText(data);
760
+ stdout.write(text.endsWith("\n") ? text : `${text}\n`);
761
+ });
762
+ const stdin = new Writable({ write(chunk, _encoding, callback) {
763
+ for (const frame of chunk.toString("utf8").split("\n")) sendFrame(frame);
764
+ callback();
765
+ } });
766
+ const closeSocket = () => {
767
+ if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
768
+ socket.close();
769
+ };
770
+ stdin.once("finish", closeSocket);
771
+ stdin.once("close", closeSocket);
772
+ return {
773
+ stdin,
774
+ stdout,
775
+ stderr,
776
+ get killed() {
777
+ return killed;
778
+ },
779
+ kill: () => {
780
+ killed = true;
781
+ socket.close();
782
+ },
783
+ once: (event, listener) => events.once(event, listener)
784
+ };
785
+ }
786
+ function websocketFrameToText(data) {
787
+ if (typeof data === "string") return data;
788
+ if (Buffer.isBuffer(data)) return data.toString("utf8");
789
+ if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
790
+ return Buffer.from(data).toString("utf8");
791
+ }
792
+ //#endregion
793
+ //#region extensions/codex/src/app-server/transport.ts
794
+ /** Starts graceful transport shutdown and schedules a force kill fallback. */
795
+ function closeCodexAppServerTransport(child, options = {}) {
796
+ child.stdin.end?.();
797
+ child.stdin.destroy?.();
798
+ const forceKillDelayMs = options.forceKillDelayMs ?? 1e3;
799
+ const forceKill = setTimeout(() => {
800
+ if (hasCodexAppServerTransportExited(child)) return;
801
+ signalCodexAppServerTransport(child, "SIGKILL");
802
+ }, Math.max(1, forceKillDelayMs));
803
+ forceKill.unref?.();
804
+ child.once("exit", () => {
805
+ clearTimeout(forceKill);
806
+ child.stdout.destroy?.();
807
+ child.stderr.destroy?.();
808
+ });
809
+ child.unref?.();
810
+ child.stdout.unref?.();
811
+ child.stderr.unref?.();
812
+ child.stdin.unref?.();
813
+ }
814
+ /** Closes a transport and waits briefly for an exit event. */
815
+ async function closeCodexAppServerTransportAndWait(child, options = {}) {
816
+ if (!hasCodexAppServerTransportExited(child)) closeCodexAppServerTransport(child, options);
817
+ return await waitForCodexAppServerTransportExit(child, options.exitTimeoutMs ?? 2e3);
818
+ }
819
+ function hasCodexAppServerTransportExited(child) {
820
+ return child.exitCode !== null && child.exitCode !== void 0 ? true : child.signalCode !== null && child.signalCode !== void 0;
821
+ }
822
+ async function waitForCodexAppServerTransportExit(child, timeoutMs) {
823
+ if (hasCodexAppServerTransportExited(child)) return true;
824
+ return await new Promise((resolve) => {
825
+ let settled = false;
826
+ const onExit = () => {
827
+ if (settled) return;
828
+ settled = true;
829
+ clearTimeout(timeout);
830
+ resolve(true);
831
+ };
832
+ const timeout = setTimeout(() => {
833
+ if (settled) return;
834
+ settled = true;
835
+ child.off?.("exit", onExit);
836
+ resolve(false);
837
+ }, Math.max(1, timeoutMs));
838
+ child.once("exit", onExit);
839
+ });
840
+ }
841
+ function signalCodexAppServerTransport(child, signal) {
842
+ if (child.pid && process.platform !== "win32") try {
843
+ process.kill(-child.pid, signal);
844
+ return;
845
+ } catch {}
846
+ child.kill?.(signal);
847
+ }
848
+ //#endregion
849
+ //#region extensions/codex/src/app-server/version.ts
850
+ /**
851
+ * Version and package pins for the managed Codex app-server runtime.
852
+ */
853
+ /** Minimum Codex app-server version supported by the OpenClaw Codex bridge. */
854
+ const MIN_CODEX_APP_SERVER_VERSION = "0.143.0";
855
+ /** npm package name for the managed Codex app-server binary. */
856
+ const MANAGED_CODEX_APP_SERVER_PACKAGE = "@openai/codex";
857
+ //#endregion
858
+ //#region extensions/codex/src/app-server/client.ts
859
+ /**
860
+ * JSON-RPC client for Codex app-server transports, including request/response
861
+ * routing, notification fanout, server request handlers, and version checks.
862
+ */
863
+ const CODEX_APP_SERVER_PARSE_LOG_MAX = 500;
864
+ const CODEX_APP_SERVER_PARSE_BUFFER_MAX = 1e6;
865
+ const CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES = 1e3;
866
+ const CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS = 6e5;
867
+ const CODEX_APP_SERVER_STDERR_TAIL_MAX = 2e3;
868
+ const UNPAIRED_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
869
+ /** RPC error wrapper that preserves app-server error code and data. */
870
+ var CodexAppServerRpcError = class extends Error {
871
+ constructor(error, method) {
872
+ super(formatCodexAppServerRpcErrorMessage(error, method));
873
+ this.name = "CodexAppServerRpcError";
874
+ this.code = error.code;
875
+ this.data = error.data;
876
+ }
877
+ };
878
+ function formatCodexAppServerRpcErrorMessage(error, method) {
879
+ const message = error.message || `${method} failed`;
880
+ const detail = readCodexAppServerRpcReloginDetail(error.data);
881
+ return detail && !message.includes(detail) ? `${message}: ${detail}` : message;
882
+ }
883
+ function readCodexAppServerRpcReloginDetail(data) {
884
+ const record = isJsonObject(data) ? data : void 0;
885
+ const nested = isJsonObject(record?.error) ? record.error : record;
886
+ if (!nested) return;
887
+ const isRelogin = nested.action === "relogin" || nested.reason === "cloudRequirements" && nested.errorCode === "Auth";
888
+ const detail = typeof nested.detail === "string" ? nested.detail.trim() : "";
889
+ return isRelogin && detail ? detail : void 0;
890
+ }
891
+ function isJsonObject(value) {
892
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
893
+ }
894
+ /** Returns true for errors that mean the app-server transport is closed. */
895
+ function isCodexAppServerConnectionClosedError(error) {
896
+ if (!(error instanceof Error)) return false;
897
+ return error.message === "codex app-server client is closed" || error.message.startsWith("codex app-server exited:");
898
+ }
899
+ /** Stateful app-server JSON-RPC client over stdio or websocket transport. */
900
+ var CodexAppServerClient = class CodexAppServerClient {
901
+ constructor(child) {
902
+ this.pending = /* @__PURE__ */ new Map();
903
+ this.requestHandlers = /* @__PURE__ */ new Set();
904
+ this.notificationHandlers = /* @__PURE__ */ new Set();
905
+ this.closeHandlers = /* @__PURE__ */ new Set();
906
+ this.nextId = 1;
907
+ this.initialized = false;
908
+ this.closed = false;
909
+ this.stderrTail = "";
910
+ this.child = child;
911
+ this.lines = createInterface({ input: child.stdout });
912
+ this.lines.on("line", (line) => this.handleLine(line));
913
+ this.lines.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
914
+ child.stdout.on("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
915
+ child.stderr.on("data", (chunk) => {
916
+ const text = chunk.toString("utf8");
917
+ this.stderrTail = appendBoundedTail(this.stderrTail, text, CODEX_APP_SERVER_STDERR_TAIL_MAX);
918
+ const trimmed = text.trim();
919
+ if (trimmed) embeddedAgentLog.debug(`codex app-server stderr: ${trimmed}`);
920
+ });
921
+ child.stderr.on("error", (error) => {
922
+ embeddedAgentLog.warn("codex app-server stderr stream failed", { error });
923
+ });
924
+ child.once("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
925
+ child.once("exit", (code, signal) => {
926
+ this.closeWithError(buildCodexAppServerExitError(code, signal, this.stderrTail));
927
+ });
928
+ child.stdin.on?.("error", (error) => this.closeWithError(error instanceof Error ? error : new Error(String(error))));
929
+ }
930
+ /** Starts a new app-server client using resolved runtime start options. */
931
+ static start(options) {
932
+ const defaults = resolveCodexAppServerRuntimeOptions().start;
933
+ const startOptions = {
934
+ ...defaults,
935
+ ...options,
936
+ headers: options?.headers ?? defaults.headers
937
+ };
938
+ if (startOptions.transport === "stdio" && startOptions.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
939
+ if (startOptions.transport === "websocket") return new CodexAppServerClient(createWebSocketTransport(startOptions));
940
+ return new CodexAppServerClient(createStdioTransport(startOptions));
941
+ }
942
+ /** Builds a client around a fake transport for tests. */
943
+ static fromTransportForTests(child) {
944
+ return new CodexAppServerClient(child);
945
+ }
946
+ /** Performs the app-server initialize handshake and validates protocol version. */
947
+ async initialize() {
948
+ if (this.initialized) return;
949
+ const response = await this.request("initialize", {
950
+ clientInfo: {
951
+ name: "openclaw",
952
+ title: "OpenClaw",
953
+ version: OPENCLAW_VERSION
954
+ },
955
+ capabilities: { experimentalApi: true }
956
+ });
957
+ this.serverVersion = assertSupportedCodexAppServerVersion(response);
958
+ this.runtimeIdentity = buildCodexAppServerRuntimeIdentity(response, this.serverVersion);
959
+ this.notify("initialized");
960
+ this.initialized = true;
961
+ }
962
+ /** Returns the version detected during initialize. */
963
+ getServerVersion() {
964
+ return this.serverVersion;
965
+ }
966
+ /** Returns runtime metadata detected during initialize. */
967
+ getRuntimeIdentity() {
968
+ return this.runtimeIdentity ? { ...this.runtimeIdentity } : void 0;
969
+ }
970
+ request(method, params, optionsInput) {
971
+ let options = optionsInput;
972
+ options ??= {};
973
+ if (this.closed) return Promise.reject(this.closeError ?? /* @__PURE__ */ new Error("codex app-server client is closed"));
974
+ if (options.signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(`${method} aborted`));
975
+ const id = this.nextId++;
976
+ const message = {
977
+ id,
978
+ method,
979
+ params
980
+ };
981
+ return new Promise((resolve, reject) => {
982
+ let timeout;
983
+ let cleanupAbort;
984
+ const cleanup = () => {
985
+ if (timeout) {
986
+ clearTimeout(timeout);
987
+ timeout = void 0;
988
+ }
989
+ cleanupAbort?.();
990
+ cleanupAbort = void 0;
991
+ };
992
+ const rejectPending = (error) => {
993
+ if (!this.pending.has(id)) return;
994
+ this.pending.delete(id);
995
+ cleanup();
996
+ reject(error);
997
+ };
998
+ if (options.timeoutMs && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0) {
999
+ timeout = setTimeout(() => rejectPending(/* @__PURE__ */ new Error(`${method} timed out`)), Math.max(100, options.timeoutMs));
1000
+ timeout.unref?.();
1001
+ }
1002
+ if (options.signal) {
1003
+ const abortListener = () => rejectPending(/* @__PURE__ */ new Error(`${method} aborted`));
1004
+ options.signal.addEventListener("abort", abortListener, { once: true });
1005
+ cleanupAbort = () => options.signal?.removeEventListener("abort", abortListener);
1006
+ }
1007
+ this.pending.set(id, {
1008
+ method,
1009
+ resolve: (value) => {
1010
+ cleanup();
1011
+ resolve(value);
1012
+ },
1013
+ reject: (error) => {
1014
+ cleanup();
1015
+ reject(error);
1016
+ },
1017
+ cleanup
1018
+ });
1019
+ if (options.signal?.aborted) {
1020
+ rejectPending(/* @__PURE__ */ new Error(`${method} aborted`));
1021
+ return;
1022
+ }
1023
+ try {
1024
+ this.writeMessage(message, (error) => rejectPending(error));
1025
+ } catch (error) {
1026
+ rejectPending(error instanceof Error ? error : new Error(String(error)));
1027
+ }
1028
+ });
1029
+ }
1030
+ /** Sends a fire-and-forget JSON-RPC notification to the app-server. */
1031
+ notify(method, params) {
1032
+ this.writeMessage({
1033
+ method,
1034
+ params
1035
+ });
1036
+ }
1037
+ /** Registers a handler for app-server requests sent back to OpenClaw. */
1038
+ addRequestHandler(handler) {
1039
+ this.requestHandlers.add(handler);
1040
+ return () => this.requestHandlers.delete(handler);
1041
+ }
1042
+ /** Registers a notification handler and returns its disposer. */
1043
+ addNotificationHandler(handler) {
1044
+ this.notificationHandlers.add(handler);
1045
+ return () => this.notificationHandlers.delete(handler);
1046
+ }
1047
+ /** Registers a close handler and returns its disposer. */
1048
+ addCloseHandler(handler) {
1049
+ this.closeHandlers.add(handler);
1050
+ return () => this.closeHandlers.delete(handler);
1051
+ }
1052
+ /** Closes the transport without waiting for process/socket shutdown. */
1053
+ close() {
1054
+ if (!this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"))) return;
1055
+ closeCodexAppServerTransport(this.child);
1056
+ }
1057
+ /** Closes the transport and waits for shutdown according to transport policy. */
1058
+ async closeAndWait(options) {
1059
+ this.markClosed(/* @__PURE__ */ new Error("codex app-server client is closed"));
1060
+ return await closeCodexAppServerTransportAndWait(this.child, options);
1061
+ }
1062
+ writeMessage(message, onError) {
1063
+ if (this.closed) return;
1064
+ const id = "id" in message ? message.id : void 0;
1065
+ const method = "method" in message ? message.method : void 0;
1066
+ this.child.stdin.write(`${stringifyCodexAppServerMessage(message)}\n`, (error) => {
1067
+ if (error) {
1068
+ embeddedAgentLog.warn("codex app-server write failed", {
1069
+ error,
1070
+ id,
1071
+ method
1072
+ });
1073
+ onError?.(error);
1074
+ }
1075
+ });
1076
+ }
1077
+ handleLine(line) {
1078
+ const rawLine = line.endsWith("\r") ? line.slice(0, -1) : line;
1079
+ if (this.pendingParse) {
1080
+ this.handlePendingParseLine(rawLine);
1081
+ return;
1082
+ }
1083
+ const trimmed = rawLine.trim();
1084
+ if (!trimmed) return;
1085
+ let parsed;
1086
+ try {
1087
+ parsed = JSON.parse(trimmed);
1088
+ } catch (error) {
1089
+ if (shouldBufferCodexAppServerParseFailure(trimmed, error)) {
1090
+ this.pendingParse = {
1091
+ text: trimmed,
1092
+ lineCount: 1,
1093
+ firstError: error
1094
+ };
1095
+ return;
1096
+ }
1097
+ logCodexAppServerParseFailure(trimmed, error, 1);
1098
+ return;
1099
+ }
1100
+ this.handleParsedMessage(parsed);
1101
+ }
1102
+ handlePendingParseLine(line) {
1103
+ const pending = this.pendingParse;
1104
+ if (!pending) return;
1105
+ const candidate = `${pending.text}\\n${line}`;
1106
+ let parsed;
1107
+ try {
1108
+ parsed = JSON.parse(candidate);
1109
+ } catch (error) {
1110
+ const lineCount = pending.lineCount + 1;
1111
+ if (shouldBufferCodexAppServerParseFailure(candidate.trim(), error) && candidate.length <= CODEX_APP_SERVER_PARSE_BUFFER_MAX && lineCount <= CODEX_APP_SERVER_PARSE_BUFFER_MAX_LINES) {
1112
+ this.pendingParse = {
1113
+ text: candidate,
1114
+ lineCount,
1115
+ firstError: pending.firstError
1116
+ };
1117
+ return;
1118
+ }
1119
+ this.pendingParse = void 0;
1120
+ logCodexAppServerParseFailure(candidate, error, lineCount);
1121
+ return;
1122
+ }
1123
+ this.pendingParse = void 0;
1124
+ this.handleParsedMessage(parsed);
1125
+ }
1126
+ handleParsedMessage(parsed) {
1127
+ if (!parsed || typeof parsed !== "object") return;
1128
+ const message = parsed;
1129
+ if (isRpcResponse(message)) {
1130
+ this.handleResponse(message);
1131
+ return;
1132
+ }
1133
+ if (!("method" in message)) return;
1134
+ if ("id" in message && message.id !== void 0) {
1135
+ this.handleServerRequest({
1136
+ id: message.id,
1137
+ method: message.method,
1138
+ params: message.params
1139
+ });
1140
+ return;
1141
+ }
1142
+ this.handleNotification({
1143
+ method: message.method,
1144
+ params: message.params
1145
+ });
1146
+ }
1147
+ handleResponse(response) {
1148
+ const pending = this.pending.get(response.id);
1149
+ if (!pending) return;
1150
+ this.pending.delete(response.id);
1151
+ if (response.error) {
1152
+ pending.reject(new CodexAppServerRpcError(response.error, pending.method));
1153
+ return;
1154
+ }
1155
+ pending.resolve(response.result);
1156
+ }
1157
+ async handleServerRequest(request) {
1158
+ try {
1159
+ const result = await this.runServerRequestHandlers(request);
1160
+ if (result !== void 0) {
1161
+ this.writeMessage({
1162
+ id: request.id,
1163
+ result
1164
+ });
1165
+ return;
1166
+ }
1167
+ this.writeMessage({
1168
+ id: request.id,
1169
+ result: defaultServerRequestResponse(request)
1170
+ });
1171
+ } catch (error) {
1172
+ const message = error instanceof Error ? error.message : String(error);
1173
+ embeddedAgentLog.warn("codex app-server server request handler failed", {
1174
+ id: request.id,
1175
+ method: request.method,
1176
+ error
1177
+ });
1178
+ this.writeMessage({
1179
+ id: request.id,
1180
+ error: {
1181
+ code: -32603,
1182
+ message
1183
+ }
1184
+ });
1185
+ }
1186
+ }
1187
+ async runServerRequestHandlers(request) {
1188
+ const timeoutResponse = timeoutServerRequestResponse(request);
1189
+ if (!timeoutResponse) return await this.runServerRequestHandlersWithoutTimeout(request);
1190
+ let timeout;
1191
+ try {
1192
+ return await Promise.race([this.runServerRequestHandlersWithoutTimeout(request), new Promise((resolve) => {
1193
+ timeout = setTimeout(() => {
1194
+ embeddedAgentLog.warn("codex app-server server request timed out", {
1195
+ id: request.id,
1196
+ method: request.method,
1197
+ timeoutMs: CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS
1198
+ });
1199
+ resolve(timeoutResponse);
1200
+ }, CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS);
1201
+ timeout.unref?.();
1202
+ })]);
1203
+ } finally {
1204
+ if (timeout) clearTimeout(timeout);
1205
+ }
1206
+ }
1207
+ async runServerRequestHandlersWithoutTimeout(request) {
1208
+ for (const handler of this.requestHandlers) {
1209
+ const result = await handler(request);
1210
+ if (result !== void 0) return result;
1211
+ }
1212
+ }
1213
+ handleNotification(notification) {
1214
+ for (const handler of this.notificationHandlers) Promise.resolve(handler(notification)).catch((error) => {
1215
+ embeddedAgentLog.warn("codex app-server notification handler failed", { error });
1216
+ });
1217
+ }
1218
+ closeWithError(error) {
1219
+ if (this.markClosed(error)) closeCodexAppServerTransport(this.child);
1220
+ }
1221
+ markClosed(error) {
1222
+ if (this.closed) return false;
1223
+ this.closed = true;
1224
+ this.closeError = error;
1225
+ this.lines.close();
1226
+ this.rejectPendingRequests(error);
1227
+ return true;
1228
+ }
1229
+ rejectPendingRequests(error) {
1230
+ for (const pending of this.pending.values()) {
1231
+ pending.cleanup();
1232
+ pending.reject(error);
1233
+ }
1234
+ this.pending.clear();
1235
+ for (const handler of this.closeHandlers) handler(this);
1236
+ }
1237
+ };
1238
+ function defaultServerRequestResponse(request) {
1239
+ if (request.method === "item/tool/call") return {
1240
+ contentItems: [{
1241
+ type: "inputText",
1242
+ text: "OpenClaw did not register a handler for this app-server tool call."
1243
+ }],
1244
+ success: false
1245
+ };
1246
+ if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return { decision: "decline" };
1247
+ if (request.method === "item/permissions/requestApproval") return {
1248
+ permissions: {},
1249
+ scope: "turn"
1250
+ };
1251
+ if (request.method === "item/tool/requestUserInput") return { answers: {} };
1252
+ if (request.method === "mcpServer/elicitation/request") return { action: "decline" };
1253
+ return {};
1254
+ }
1255
+ function stringifyCodexAppServerMessage(message) {
1256
+ return JSON.stringify(message, (_key, value) => typeof value === "string" ? value.replace(UNPAIRED_SURROGATE_RE, "") : value) ?? "null";
1257
+ }
1258
+ function timeoutServerRequestResponse(request) {
1259
+ if (request.method !== "item/tool/call") return;
1260
+ return {
1261
+ contentItems: [{
1262
+ type: "inputText",
1263
+ text: `OpenClaw dynamic tool call timed out after ${CODEX_DYNAMIC_TOOL_SERVER_REQUEST_TIMEOUT_MS}ms before sending a response to Codex.`
1264
+ }],
1265
+ success: false
1266
+ };
1267
+ }
1268
+ /** Raised when the initialize handshake detects an unsupported app-server version. */
1269
+ var CodexAppServerVersionError = class extends Error {
1270
+ constructor(detectedVersion) {
1271
+ const detected = detectedVersion ? `detected ${detectedVersion}` : "OpenClaw could not determine the running Codex version";
1272
+ super(`Codex app-server ${MIN_CODEX_APP_SERVER_VERSION} or newer is required, but ${detected}. Update the configured Codex app-server binary, or remove custom command overrides to use the managed binary.`);
1273
+ this.name = "CodexAppServerVersionError";
1274
+ this.detectedVersion = detectedVersion;
1275
+ }
1276
+ };
1277
+ function assertSupportedCodexAppServerVersion(response) {
1278
+ const detectedVersion = readCodexVersionFromUserAgent(response.userAgent);
1279
+ if (!detectedVersion || compareCodexAppServerVersions(detectedVersion, "0.143.0") < 0) throw new CodexAppServerVersionError(detectedVersion);
1280
+ return detectedVersion;
1281
+ }
1282
+ function isUnsupportedCodexAppServerVersionError(error) {
1283
+ return error instanceof CodexAppServerVersionError;
1284
+ }
1285
+ function buildCodexAppServerRuntimeIdentity(response, serverVersion) {
1286
+ const userAgent = readNonEmptyInitializeString(response.userAgent);
1287
+ const codexHome = readNonEmptyInitializeString(response.codexHome);
1288
+ const platformFamily = readNonEmptyInitializeString(response.platformFamily);
1289
+ const platformOs = readNonEmptyInitializeString(response.platformOs);
1290
+ return {
1291
+ serverVersion,
1292
+ ...userAgent ? { userAgent } : {},
1293
+ ...codexHome ? { codexHome } : {},
1294
+ ...platformFamily ? { platformFamily } : {},
1295
+ ...platformOs ? { platformOs } : {}
1296
+ };
1297
+ }
1298
+ function readNonEmptyInitializeString(value) {
1299
+ const trimmed = value?.trim();
1300
+ return trimmed ? trimmed : void 0;
1301
+ }
1302
+ /** Extracts the Codex version from the app-server initialize user-agent field. */
1303
+ function readCodexVersionFromUserAgent(userAgent) {
1304
+ return (userAgent?.match(/^[^/]+\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:[\s(]|$)/))?.[1];
1305
+ }
1306
+ /** Compares stable Codex app-server versions for protocol floor checks. */
1307
+ function compareCodexAppServerVersions(left, right) {
1308
+ const leftVersion = parseVersionForComparison(left);
1309
+ const rightVersion = parseVersionForComparison(right);
1310
+ const leftParts = leftVersion.parts;
1311
+ const rightParts = rightVersion.parts;
1312
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
1313
+ const leftPart = leftParts[index] ?? 0;
1314
+ const rightPart = rightParts[index] ?? 0;
1315
+ if (leftPart !== rightPart) return leftPart < rightPart ? -1 : 1;
1316
+ }
1317
+ if (leftVersion.unstableSuffix && !rightVersion.unstableSuffix) return -1;
1318
+ if (!leftVersion.unstableSuffix && rightVersion.unstableSuffix) return 1;
1319
+ return 0;
1320
+ }
1321
+ function parseVersionForComparison(version) {
1322
+ const hasBuildMetadata = version.includes("+");
1323
+ const [withoutBuild = version] = version.split("+", 1);
1324
+ const prereleaseIndex = withoutBuild.indexOf("-");
1325
+ return {
1326
+ parts: (prereleaseIndex >= 0 ? withoutBuild.slice(0, prereleaseIndex) : withoutBuild).split(".").map((part) => Number.parseInt(part, 10)).map((part) => Number.isFinite(part) ? part : 0),
1327
+ unstableSuffix: prereleaseIndex >= 0 || hasBuildMetadata
1328
+ };
1329
+ }
1330
+ function redactCodexAppServerLinePreview(value) {
1331
+ 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");
1332
+ return redacted.length > CODEX_APP_SERVER_PARSE_LOG_MAX ? `${redacted.slice(0, CODEX_APP_SERVER_PARSE_LOG_MAX)}...` : redacted;
1333
+ }
1334
+ function appendBoundedTail(current, next, maxLength) {
1335
+ const combined = `${current}${next}`;
1336
+ return combined.length > maxLength ? combined.slice(combined.length - maxLength) : combined;
1337
+ }
1338
+ function buildCodexAppServerExitError(code, signal, stderrTail) {
1339
+ const stderrPreview = redactCodexAppServerLinePreview(stderrTail);
1340
+ const suffix = stderrPreview ? ` stderr=${JSON.stringify(stderrPreview)}` : "";
1341
+ return /* @__PURE__ */ new Error(`codex app-server exited: code=${formatExitValue(code)} signal=${formatExitValue(signal)}${suffix}`);
1342
+ }
1343
+ function shouldBufferCodexAppServerParseFailure(value, error) {
1344
+ if (!value.startsWith("{") && !value.startsWith("[")) return false;
1345
+ const message = error instanceof Error ? error.message : String(error);
1346
+ return message.includes("Unterminated string") || message.includes("Unexpected end of JSON input");
1347
+ }
1348
+ function logCodexAppServerParseFailure(value, error, fragmentCount) {
1349
+ const linePreview = redactCodexAppServerLinePreview(value);
1350
+ const suffix = fragmentCount > 1 ? ` fragments=${fragmentCount}` : "";
1351
+ embeddedAgentLog.warn("failed to parse codex app-server message", {
1352
+ error,
1353
+ errorMessage: error instanceof Error ? error.message : String(error),
1354
+ fragmentCount,
1355
+ linePreview,
1356
+ consoleMessage: `failed to parse codex app-server message${suffix}: preview=${JSON.stringify(linePreview)}`
1357
+ });
1358
+ }
1359
+ const CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS = /* @__PURE__ */ new Set([
1360
+ "item/commandExecution/requestApproval",
1361
+ "item/fileChange/requestApproval",
1362
+ "item/permissions/requestApproval"
1363
+ ]);
1364
+ /** Returns true for app-server approval request methods OpenClaw can answer. */
1365
+ function isCodexAppServerApprovalRequest(method) {
1366
+ return CODEX_APP_SERVER_APPROVAL_REQUEST_METHODS.has(method);
1367
+ }
1368
+ function formatExitValue(value) {
1369
+ if (value === null || value === void 0) return "null";
1370
+ if (typeof value === "string" || typeof value === "number") return String(value);
1371
+ return "unknown";
1372
+ }
1373
+ //#endregion
508
1374
  //#region extensions/codex/src/app-server/managed-binary.ts
509
1375
  /**
510
1376
  * Resolves the managed Codex app-server binary shipped with or installed beside
@@ -548,7 +1414,7 @@ function resolveManagedCodexAppServerCommandCandidates(pluginRoot, platform) {
548
1414
  const pathApi = pathForPlatform(platform);
549
1415
  const commandName = platform === "win32" ? "codex.cmd" : "codex";
550
1416
  const roots = resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform);
551
- return [...new Set([
1417
+ return [.../* @__PURE__ */ new Set([
552
1418
  ...resolveDesktopCodexAppServerCommandCandidates(platform),
553
1419
  ...roots.map((root) => pathApi.join(root, "node_modules", ".bin", commandName)),
554
1420
  ...resolveManagedCodexPackageBinCandidates(roots, platform)
@@ -570,7 +1436,7 @@ function resolveManagedCodexAppServerCandidateRoots(pluginRoot, platform) {
570
1436
  pathApi.dirname(pathApi.dirname(pluginRoot)),
571
1437
  isDistExtensionRoot(pluginRoot, platform) ? pathApi.dirname(pathApi.dirname(pathApi.dirname(pluginRoot))) : null
572
1438
  ].filter((root) => Boolean(root));
573
- return [...new Set([...directRoots, ...resolveNearestNodeModulesProjectRoots(directRoots, platform)])];
1439
+ return [.../* @__PURE__ */ new Set([...directRoots, ...resolveNearestNodeModulesProjectRoots(directRoots, platform)])];
574
1440
  }
575
1441
  function resolveNearestNodeModulesProjectRoots(roots, platform) {
576
1442
  const pathApi = pathForPlatform(platform);
@@ -656,69 +1522,28 @@ async function withTimeout$1(promise, timeoutMs, timeoutMessage) {
656
1522
  * lease tracking, and teardown.
657
1523
  */
658
1524
  var shared_client_exports = /* @__PURE__ */ __exportAll({
659
- clearSharedCodexAppServerClient: () => clearSharedCodexAppServerClient,
660
1525
  clearSharedCodexAppServerClientAndWait: () => clearSharedCodexAppServerClientAndWait,
661
1526
  clearSharedCodexAppServerClientIfCurrent: () => clearSharedCodexAppServerClientIfCurrent,
662
1527
  clearSharedCodexAppServerClientIfCurrentAndUnclaimed: () => clearSharedCodexAppServerClientIfCurrentAndUnclaimed,
663
1528
  clearSharedCodexAppServerClientIfCurrentAndWait: () => clearSharedCodexAppServerClientIfCurrentAndWait,
664
1529
  createIsolatedCodexAppServerClient: () => createIsolatedCodexAppServerClient,
665
- detachSharedCodexAppServerClientIfCurrent: () => detachSharedCodexAppServerClientIfCurrent,
666
1530
  getLeasedSharedCodexAppServerClient: () => getLeasedSharedCodexAppServerClient,
667
- getSharedCodexAppServerClient: () => getSharedCodexAppServerClient,
668
1531
  releaseLeasedSharedCodexAppServerClient: () => releaseLeasedSharedCodexAppServerClient,
669
- resetSharedCodexAppServerClientForTests: () => resetSharedCodexAppServerClientForTests,
670
- retainSharedCodexAppServerClientIfCurrent: () => retainSharedCodexAppServerClientIfCurrent,
671
1532
  retireSharedCodexAppServerClientIfCurrent: () => retireSharedCodexAppServerClientIfCurrent
672
1533
  });
673
1534
  const SHARED_CODEX_APP_SERVER_CLIENT_STATE = Symbol.for("openclaw.codexAppServerClientState");
674
1535
  function getSharedCodexAppServerClientState() {
675
1536
  const globalState = globalThis;
676
- const state = globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE];
677
- const keyedState = readKeyedSharedCodexAppServerClientState(state);
678
- if (keyedState) {
679
- const clients = keyedState.clients;
680
- for (const entry of clients.values()) {
681
- entry.activeLeases ??= 0;
682
- entry.pendingAcquires ??= 0;
683
- entry.closeWhenIdle ??= false;
684
- }
685
- const nextState = {
686
- clients,
687
- leasedReleases: keyedState.leasedReleases instanceof WeakMap ? keyedState.leasedReleases : /* @__PURE__ */ new WeakMap()
688
- };
689
- globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] = nextState;
690
- return nextState;
691
- }
692
- const legacyState = readLegacySharedCodexAppServerClientState(state);
693
- const clients = /* @__PURE__ */ new Map();
694
- if (legacyState?.key && (legacyState.client || legacyState.promise)) {
695
- const legacyKey = legacyState.key;
696
- clients.set(legacyKey, {
697
- client: legacyState.client,
698
- promise: legacyState.promise,
699
- activeLeases: 0,
700
- pendingAcquires: 0,
701
- closeWhenIdle: false
702
- });
703
- legacyState.client?.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(legacyKey, closedClient));
704
- }
705
- const nextState = {
706
- clients,
1537
+ globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] ??= {
1538
+ clients: /* @__PURE__ */ new Map(),
707
1539
  leasedReleases: /* @__PURE__ */ new WeakMap()
708
1540
  };
709
- globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE] = nextState;
710
- return nextState;
711
- }
712
- function readKeyedSharedCodexAppServerClientState(value) {
713
- return value !== null && typeof value === "object" && value.clients instanceof Map ? value : void 0;
714
- }
715
- function readLegacySharedCodexAppServerClientState(value) {
716
- if (value === null || typeof value !== "object") return;
717
- return value;
1541
+ return globalState[SHARED_CODEX_APP_SERVER_CLIENT_STATE];
718
1542
  }
719
1543
  async function resolveCodexAppServerClientStartContext(options) {
720
1544
  const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
721
- const usesNativeAuth = options?.authProfileId === null;
1545
+ const requestedStartOptions = options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start;
1546
+ const usesNativeAuth = options?.authProfileId === null || requestedStartOptions.homeScope === "user";
722
1547
  const requestedAuthProfileId = options?.authProfileId === null ? void 0 : options?.authProfileId;
723
1548
  const authProfileStore = !usesNativeAuth && options?.authProfileStore ? resolveCodexAppServerAuthProfileStore({
724
1549
  agentDir,
@@ -738,7 +1563,7 @@ async function resolveCodexAppServerClientStartContext(options) {
738
1563
  authProfileId,
739
1564
  authProfileStore,
740
1565
  startOptions: await bridgeCodexAppServerStartOptions({
741
- startOptions: await resolveManagedCodexAppServerStartOptions(options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start),
1566
+ startOptions: await resolveManagedCodexAppServerStartOptions(requestedStartOptions),
742
1567
  agentDir,
743
1568
  authProfileId: usesNativeAuth ? null : authProfileId,
744
1569
  config: options?.config,
@@ -746,10 +1571,6 @@ async function resolveCodexAppServerClientStartContext(options) {
746
1571
  })
747
1572
  };
748
1573
  }
749
- /** Gets or starts a shared Codex app-server client without retaining a lease. */
750
- async function getSharedCodexAppServerClient(options) {
751
- return (await acquireSharedCodexAppServerClient(options)).client;
752
- }
753
1574
  /** Gets or starts a shared Codex app-server client and records a release lease. */
754
1575
  async function getLeasedSharedCodexAppServerClient(options) {
755
1576
  const acquired = await acquireSharedCodexAppServerClient(options, { leased: true });
@@ -799,18 +1620,20 @@ async function acquireSharedCodexAppServerClient(options, leaseOptions) {
799
1620
  config: options?.config,
800
1621
  onStartedClient: (startedClient) => {
801
1622
  entry.client = startedClient;
802
- startedClient.setActiveSharedLeaseCountProviderForUnscopedNotifications(() => entry.activeLeases);
803
1623
  options?.onStartedClient?.(startedClient);
804
1624
  }
805
1625
  });
806
1626
  entry.client = client;
807
- client.setActiveSharedLeaseCountProviderForUnscopedNotifications(() => entry.activeLeases);
808
1627
  client.addCloseHandler((closedClient) => clearSharedClientEntryIfCurrent(key, closedClient));
809
1628
  return client;
810
1629
  })());
811
1630
  try {
812
1631
  const client = await withTimeout$1(sharedPromise, options?.timeoutMs ?? 0, "codex app-server initialize timed out");
813
- client.setActiveSharedLeaseCountProviderForUnscopedNotifications(() => entry.activeLeases);
1632
+ ensureCodexAppServerClientRuntime(client, {
1633
+ agentDir,
1634
+ authProfileId: usesNativeAuth ? void 0 : authProfileId,
1635
+ config: options?.config
1636
+ });
814
1637
  const release = leaseOptions?.leased ? retainSharedClientEntry(entry) : void 0;
815
1638
  return release ? {
816
1639
  client,
@@ -853,14 +1676,11 @@ async function startInitializedCodexAppServerClient(params) {
853
1676
  if (shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates)) continue;
854
1677
  throw error;
855
1678
  }
856
- if (params.authProfileId) client.addRequestHandler(async (request) => {
857
- if (request.method !== "account/chatgptAuthTokens/refresh") return;
858
- return await refreshCodexAppServerAuthTokens({
859
- agentDir: params.agentDir,
860
- authProfileId: params.authProfileId,
861
- ...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {},
862
- config: params.config
863
- });
1679
+ ensureCodexAppServerClientRuntime(client, {
1680
+ agentDir: params.agentDir,
1681
+ authProfileId: params.authProfileId ?? void 0,
1682
+ ...params.authProfileStore ? { authProfileStore: params.authProfileStore } : {},
1683
+ config: params.config
864
1684
  });
865
1685
  try {
866
1686
  await applyCodexAppServerAuthProfile({
@@ -898,21 +1718,6 @@ function resolveManagedFallbackStartOptions(startOptions) {
898
1718
  function shouldTryManagedFallbackStartOption(error, startOptions, index, startOptionsCandidates) {
899
1719
  return startOptions.commandSource === "resolved-managed" && index < startOptionsCandidates.length - 1 && isUnsupportedCodexAppServerVersionError(error);
900
1720
  }
901
- /** Clears and closes all shared clients for deterministic tests. */
902
- function resetSharedCodexAppServerClientForTests() {
903
- const state = getSharedCodexAppServerClientState();
904
- const clients = collectSharedClients(state);
905
- state.clients.clear();
906
- state.leasedReleases = /* @__PURE__ */ new WeakMap();
907
- for (const client of clients) client.close();
908
- }
909
- /** Clears and closes all shared clients. */
910
- function clearSharedCodexAppServerClient() {
911
- const state = getSharedCodexAppServerClientState();
912
- const clients = collectSharedClients(state);
913
- state.clients.clear();
914
- for (const client of clients) client.close();
915
- }
916
1721
  /** Clears and closes the shared entry only if it still owns the supplied client. */
917
1722
  function clearSharedCodexAppServerClientIfCurrent(client) {
918
1723
  if (!client) return false;
@@ -924,22 +1729,6 @@ function clearSharedCodexAppServerClientIfCurrent(client) {
924
1729
  }
925
1730
  return false;
926
1731
  }
927
- /** Detaches the shared entry without closing the client when it still matches. */
928
- function detachSharedCodexAppServerClientIfCurrent(client) {
929
- if (!client) return false;
930
- const state = getSharedCodexAppServerClientState();
931
- for (const [key, entry] of state.clients) if (entry.client === client) {
932
- state.clients.delete(key);
933
- return true;
934
- }
935
- return false;
936
- }
937
- /** Retains the matching shared client and returns a release callback. */
938
- function retainSharedCodexAppServerClientIfCurrent(client) {
939
- if (!client) return;
940
- const state = getSharedCodexAppServerClientState();
941
- for (const entry of state.clients.values()) if (entry.client === client) return retainSharedClientEntry(entry);
942
- }
943
1732
  /** Marks a matching shared client to close after active leases/acquires drain. */
944
1733
  function retireSharedCodexAppServerClientIfCurrent(client) {
945
1734
  if (!client) return;
@@ -1061,4 +1850,4 @@ function collectSharedClients(state) {
1061
1850
  return [...new Set([...state.clients.values()].map((entry) => entry.client).filter((client) => Boolean(client)))];
1062
1851
  }
1063
1852
  //#endregion
1064
- export { getLeasedSharedCodexAppServerClient as a, shared_client_exports as c, resolveCodexAppServerAuthAccountCacheKey as d, resolveCodexAppServerAuthProfileId as f, resolveCodexAppServerHomeDir as h, createIsolatedCodexAppServerClient as i, withTimeout$1 as l, resolveCodexAppServerFallbackApiKeyCacheKey as m, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as n, releaseLeasedSharedCodexAppServerClient as o, resolveCodexAppServerAuthProfileIdForAgent as p, clearSharedCodexAppServerClientIfCurrentAndWait as r, retireSharedCodexAppServerClientIfCurrent as s, clearSharedCodexAppServerClientIfCurrent as t, refreshCodexAppServerAuthTokens as u };
1853
+ export { resolveCodexAppServerAuthAccountCacheKey as _, getLeasedSharedCodexAppServerClient as a, resolveCodexAppServerFallbackApiKeyCacheKey as b, shared_client_exports as c, isCodexAppServerApprovalRequest as d, isCodexAppServerConnectionClosedError as f, rememberCodexRateLimitsRead as g, readRecentCodexRateLimits as h, createIsolatedCodexAppServerClient as i, withTimeout$1 as l, readCodexRateLimitsRevision as m, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as n, releaseLeasedSharedCodexAppServerClient as o, ensureCodexAppServerClientRuntime as p, clearSharedCodexAppServerClientIfCurrentAndWait as r, retireSharedCodexAppServerClientIfCurrent as s, clearSharedCodexAppServerClientIfCurrent as t, CodexAppServerRpcError as u, resolveCodexAppServerAuthProfileId as v, resolveCodexAppServerHomeDir as x, resolveCodexAppServerAuthProfileIdForAgent as y };