@openclaw/codex 2026.9.4 → 2026.9.6

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 (160) hide show
  1. package/assets/activity.svg +30 -0
  2. package/assets/icon.png +0 -0
  3. package/dist/.setup/account-usage-runtime-Eem_WGqY.mjs +75 -0
  4. package/dist/{apply-CvT8tW5i.js → .setup/apply-DDOi8uNx.mjs} +24 -30
  5. package/dist/.setup/async-questions-DdhOCwGi.mjs +27 -0
  6. package/dist/{attempt-client-cleanup-DKHzbwt5.js → .setup/attempt-client-cleanup-CEv1cKwF.mjs} +79 -49
  7. package/dist/.setup/attempt-terminal-gZrxQ35N.mjs +5 -0
  8. package/dist/.setup/attempt-workspace-context-DUVEn_CS.mjs +331 -0
  9. package/dist/{auth-binding-CWlKVccJ.js → .setup/auth-binding-DhLWa_7K.mjs} +1 -1
  10. package/dist/{auth-cache-key-7orQae_j.js → .setup/auth-cache-key-B2mpaI9D.mjs} +9 -81
  11. package/dist/{auth-profile-CwzO4_RG.js → .setup/auth-profile-WqZtZfXN.mjs} +1 -1
  12. package/dist/.setup/auth-profile-health-oHizqgye.mjs +53 -0
  13. package/dist/.setup/auth-profile-recovery-BREezV0L.mjs +14 -0
  14. package/dist/.setup/binding-connection-ThoatDcb.mjs +50 -0
  15. package/dist/.setup/binding-connection.runtime-yoHrABt-.mjs +48 -0
  16. package/dist/{bounded-turn-C_Hneydj.js → .setup/bounded-turn-B2HScEgT.mjs} +143 -32
  17. package/dist/{build-state-BCmg9-5p.js → .setup/build-state-C7EnDVgr.mjs} +1 -1
  18. package/dist/{capabilities-8vx68WLH.js → .setup/capabilities-CDXOOFdZ.mjs} +1 -1
  19. package/dist/{client-B57KWPQx.js → .setup/client-Cs08OXVQ.mjs} +705 -512
  20. package/dist/.setup/client-catalog-response-BMgt_4q4.mjs +285 -0
  21. package/dist/{command-dispatch-BpduNGVf.js → .setup/command-dispatch-B4JuOsOk.mjs} +8 -4
  22. package/dist/{command-formatters-lxlkNZgU.js → .setup/command-formatters-Bmqvr9tO.mjs} +8 -4
  23. package/dist/{command-handlers-tiL9iWj7.js → .setup/command-handlers-DW7Lx9oH.mjs} +137 -186
  24. package/dist/{command-rpc-CR5EOEZX.js → .setup/command-rpc-DixIj3HW.mjs} +47 -23
  25. package/dist/{compact-B_H3AOd7.js → .setup/compact-Du5UvtxA.mjs} +29 -51
  26. package/dist/{config-oIORaQ5T.js → .setup/config-BoTP_mrL.mjs} +5 -4
  27. package/dist/{config-options-CXMq1T-C.js → .setup/config-options-BvaRs51b.mjs} +50 -446
  28. package/dist/{protocol-5bh1G-H7.js → .setup/config-parsing-CcB9iPoq.mjs} +9 -51
  29. package/dist/{config-runtime-D0zGNIHu.js → .setup/config-runtime-C8Rw1m1m.mjs} +2 -2
  30. package/dist/.setup/config-security-BEReZ6go.mjs +380 -0
  31. package/dist/{conversation-binding-DsB4-O7U.js → .setup/conversation-binding-DP-gMrBP.mjs} +29 -38
  32. package/dist/{conversation-binding-data-BiodpIzq.js → .setup/conversation-binding-data-CrcyZk6O.mjs} +1 -1
  33. package/dist/{conversation-control-CtUu1b3m.js → .setup/conversation-control-uK9Jomlc.mjs} +32 -67
  34. package/dist/.setup/cyber-failover-DYwbmf1o.mjs +123 -0
  35. package/dist/.setup/cyber-failover-notice-e9G3J9-e.mjs +17 -0
  36. package/dist/{dynamic-tools-CmN5RAip.js → .setup/dynamic-tools-BDXl-8Cw.mjs} +936 -620
  37. package/dist/{effective-mcp-catalog-Bd73bqA8.js → .setup/effective-mcp-catalog-CvnvnGIe.mjs} +3 -3
  38. package/dist/{ephemeral-turn-D78_VmzO.js → .setup/ephemeral-turn-poidXgek.mjs} +9 -7
  39. package/dist/{event-projector-assistant-message-BmBM4qBV.js → .setup/event-projector-assistant-message-BsruvNrH.mjs} +8 -7
  40. package/dist/{event-projector-items-5VhsECCO.js → .setup/event-projector-items-C6L_5ZiT.mjs} +42 -8
  41. package/dist/{attempt-notifications-C9XufG6l.js → .setup/event-projector-usage-CnBS8Wa3.mjs} +102 -9
  42. package/dist/{harness-C7rRa7bm.js → .setup/harness-a_MsE4-_.mjs} +81 -21
  43. package/dist/{inference-context-Dr_mzvk4.js → .setup/inference-context-D96l9-ew.mjs} +1 -1
  44. package/dist/.setup/inference-proxy-b-aJMSxm.mjs +601 -0
  45. package/dist/{isolated-completion-DWVb5U2J.js → .setup/isolated-completion-BIZFhTNG.mjs} +18 -11
  46. package/dist/.setup/launch-args-DbFCehO7.mjs +196 -0
  47. package/dist/{managed-binary-D22rNEcR.js → .setup/managed-binary-BnshlFag.mjs} +14 -3
  48. package/dist/{managed-thread-store-D1t5jh3G.js → .setup/managed-thread-store-BMqgThVL.mjs} +48 -14
  49. package/dist/{model-catalog-Dq2n8f_p.js → .setup/model-catalog-CfXJf9Ay.mjs} +36 -12
  50. package/dist/{models-PCKOim-h.js → .setup/models-KnqBv0hE.mjs} +3 -3
  51. package/dist/.setup/native-auth-rWbGbMn3.mjs +57 -0
  52. package/dist/{native-subagent-history-DjtPloaU.js → .setup/native-subagent-history-0nYYgo0k.mjs} +43 -35
  53. package/dist/.setup/native-subagent-monitor-D3filLY2.mjs +4859 -0
  54. package/dist/{native-subagent-task-ids-BzTdT0Uw.js → .setup/native-subagent-task-ids-wb8CKZGN.mjs} +98 -44
  55. package/dist/{node-cli-sessions-DKaOmVUh.js → .setup/node-cli-sessions-r3avj02l.mjs} +86 -68
  56. package/dist/.setup/node-exec-server.runtime-BDwWXVpK.mjs +247 -0
  57. package/dist/{plan-7uG-Fp36.js → .setup/plan-CN3VwfNU.mjs} +133 -119
  58. package/dist/{plugin-activation-BYQculil.js → .setup/plugin-activation-DT3MNtqj.mjs} +7 -16
  59. package/dist/{plugin-app-cache-key-d0eKxy7b.js → .setup/plugin-app-cache-key-B2CsSdnV.mjs} +32 -44
  60. package/dist/{plugin-approval-roundtrip-Bz3FT8W5.js → .setup/plugin-approval-roundtrip-C0MZzCuP.mjs} +1 -1
  61. package/dist/{plugin-inventory-oL4Na1ZG.js → .setup/plugin-inventory-BoRei8Z4.mjs} +21 -11
  62. package/dist/{plugin-marketplace-discovery-P-Vndfqq.js → .setup/plugin-marketplace-discovery-CDOi8IFs.mjs} +4 -1
  63. package/dist/{plugin-metadata-cache-ClPJpRio.js → .setup/plugin-metadata-cache-Ctmo83k_.mjs} +226 -141
  64. package/dist/.setup/protocol-CANUwXJ3.mjs +17 -0
  65. package/dist/{provider-MQ8PVkuE.js → .setup/provider-BOsxQHOM.mjs} +9 -5
  66. package/dist/{provider-capabilities-BvCUL69A.js → .setup/provider-capabilities-BfE88FZ5.mjs} +31 -3
  67. package/dist/{rate-limits-CBMmWBr9.js → .setup/rate-limits-CMU3DUD0.mjs} +174 -151
  68. package/dist/{request-B7hEkBGq.js → .setup/request-D2L0zMrq.mjs} +130 -42
  69. package/dist/{run-attempt-CvsAAGa0.js → .setup/run-attempt-BHu11r7h.mjs} +1628 -966
  70. package/dist/.setup/run-attempt-lifecycle-B7JbY4-F.mjs +71 -0
  71. package/dist/{runtime-artifact-BJ0rXBZ_.js → .setup/runtime-artifact-CLZ8udh-.mjs} +29 -45
  72. package/dist/{sandbox-guard-BxgyoM8M.js → .setup/sandbox-guard-C2sRMOEY.mjs} +3 -3
  73. package/dist/{session-binding-CI8UuilT.js → .setup/session-binding-Cm0apEbd.mjs} +36 -83
  74. package/dist/{session-binding-record-Bcvslnhf.js → .setup/session-binding-record-BGoz8wOK.mjs} +202 -5
  75. package/dist/.setup/session-binding-sidecars-BlB5EvIS.mjs +546 -0
  76. package/dist/.setup/session-catalog-Pno1xGcl.mjs +2764 -0
  77. package/dist/{session-catalog-adoption-tcZi1IfX.js → .setup/session-catalog-adoption-BI6UTDZT.mjs} +58 -26
  78. package/dist/{session-catalog-archive-CwKg8Xz2.js → .setup/session-catalog-archive-lHBqzhaO.mjs} +6 -6
  79. package/dist/.setup/session-catalog-events-Bj6j94E_.mjs +347 -0
  80. package/dist/.setup/session-catalog-index-B9_VQIUz.mjs +1170 -0
  81. package/dist/.setup/session-catalog-index-order-hcdz07yN.mjs +48 -0
  82. package/dist/.setup/session-catalog-index-state-Dgh8ORJm.mjs +183 -0
  83. package/dist/{thread-history-page-D0JIp48V.js → .setup/session-catalog-native-projection-DowriLid.mjs} +223 -95
  84. package/dist/{session-catalog-node-adoption-B1tgDW-m.js → .setup/session-catalog-node-adoption-ITddWx_X.mjs} +25 -13
  85. package/dist/{session-catalog-node-continue-Ci-DXyJP.js → .setup/session-catalog-node-continue-6g6qi4A9.mjs} +24 -15
  86. package/dist/.setup/session-catalog-projection-zK_PUsiE.mjs +422 -0
  87. package/dist/{session-cli-DNN_jhGc.js → .setup/session-cli-irrD-uo7.mjs} +3 -3
  88. package/dist/{session-history-Cz-tOOYj.js → .setup/session-history-BrqhSCf9.mjs} +19 -19
  89. package/dist/{session-history-import-DwyijFI6.js → .setup/session-history-import-D-3wAgOP.mjs} +4 -4
  90. package/dist/{session-history-read-cxPUxyVV.js → .setup/session-history-read-B3ZfSUbF.mjs} +2 -2
  91. package/dist/{session-history.worker-BeK1YOyT.js → .setup/session-history.worker-CaCh0xF_.mjs} +10 -24
  92. package/dist/{session-initialization-Ct0_Hzmg.js → .setup/session-initialization-rcgbZiid.mjs} +2 -2
  93. package/dist/{session-permission-policy-BBmXA8Eg.js → .setup/session-permission-policy-BI1QK_98.mjs} +2 -2
  94. package/dist/{session-retirement-B2YfbAAT.js → .setup/session-retirement-BH-S6qkJ.mjs} +26 -7
  95. package/dist/{settled-turn-context-Du6gdUDd.js → .setup/settled-turn-context-fmwouT5I.mjs} +2 -2
  96. package/dist/{settled-turn-finalizer-Dn91stmc.js → .setup/settled-turn-finalizer-DiAi6Kx6.mjs} +12 -12
  97. package/dist/{shared-client-CscigXXL.js → .setup/shared-client-DA4VR4Eb.mjs} +332 -221
  98. package/dist/{side-question-BGMJQf4U.js → .setup/side-question-BJ1wSDcB.mjs} +183 -230
  99. package/dist/{source-CElXU0Oy.js → .setup/source-CUzJq5WN.mjs} +11 -10
  100. package/dist/.setup/spawn-error-CL3n6MAa.mjs +57 -0
  101. package/dist/{thread-archive-guard-DfpBr-Sz.js → .setup/thread-archive-guard-C9frICzX.mjs} +10 -3
  102. package/dist/.setup/thread-history-page-DoVpnHim.mjs +83 -0
  103. package/dist/{thread-lifecycle-DXl1-I6b.js → .setup/thread-lifecycle-B3mfz1TG.mjs} +347 -2318
  104. package/dist/{thread-ownership-BsDRTsyp.js → .setup/thread-ownership-DcTtAcXj.mjs} +6 -4
  105. package/dist/{thread-policy-BuEQfE0g.js → .setup/thread-policy-DGuQsuFC.mjs} +19 -3
  106. package/dist/.setup/thread-requests-BLvGkP2R.mjs +2205 -0
  107. package/dist/{thread-resume-DsDOZpFg.js → .setup/thread-resume-DIBXwOpE.mjs} +8 -5
  108. package/dist/.setup/timeout-C910MdAB.mjs +80 -0
  109. package/dist/{transcript-history-projection-v17wXgdK.js → .setup/transcript-history-projection-ZZpkFkJ_.mjs} +96 -61
  110. package/dist/{transcript-mirror-C5CKgNy6.js → .setup/transcript-mirror-BtHDBp1G.mjs} +224 -195
  111. package/dist/{transcript-mirror-attestation-DibE0krH.js → .setup/transcript-mirror-attestation-CzM-94NC.mjs} +4 -1
  112. package/dist/{transport-stdio-BGjHoYLr.js → .setup/transport-stdio-h2VHOskC.mjs} +274 -89
  113. package/dist/{upstream-session-fork-BZerMte_.js → .setup/upstream-session-fork-BUr4OUbC.mjs} +51 -42
  114. package/dist/{usage-tCk-mg_x.js → .setup/usage-BML0r-ua.mjs} +5 -4
  115. package/dist/.setup/usage-limit-error-DUMbefVY.mjs +166 -0
  116. package/dist/{web-search-provider.runtime-B7bGbGWq.js → .setup/web-search-provider.runtime-CDKlN-Rv.mjs} +4 -3
  117. package/dist/api.js +23 -12
  118. package/dist/catalog-page-worker-entrypoint.js +12 -0
  119. package/dist/catalog-page.worker.js +9 -0
  120. package/dist/cli-metadata.js +1 -1
  121. package/dist/doctor-contract-api.js +8 -528
  122. package/dist/harness.js +1 -1
  123. package/dist/index.js +306 -215
  124. package/dist/media-understanding-provider.js +3 -3
  125. package/dist/migration-provider-api.js +1 -1
  126. package/dist/native-tool-policy.js +12 -0
  127. package/dist/provider-discovery.js +18 -0
  128. package/dist/session-history-worker-runtime.js +36 -35
  129. package/dist/session-history.worker.js +2 -2
  130. package/dist/web-search-contract-api.js +1 -1
  131. package/openclaw.plugin.json +354 -69
  132. package/package.json +14 -8
  133. package/dist/attempt-context-D44yeDII.js +0 -636
  134. package/dist/binding-connection-D3udKbIE.js +0 -60
  135. package/dist/event-projector-usage-BfXmpOec.js +0 -102
  136. package/dist/inference-proxy-HGXKUIre.js +0 -311
  137. package/dist/launch-args-RXQwn8zV.js +0 -90
  138. package/dist/native-subagent-history-owner-Pcp7JuVF.js +0 -34
  139. package/dist/native-subagent-monitor-fQ7eIXEf.js +0 -2978
  140. package/dist/node-exec-server.runtime-Cl2vapEi.js +0 -226
  141. package/dist/rpc-error-ttN_QjEm.js +0 -30
  142. package/dist/session-catalog-ct-AH01I.js +0 -1477
  143. package/dist/session-catalog-home-id-CwhLdC03.js +0 -18
  144. package/dist/session-catalog-provenance-D-dIfRAH.js +0 -96
  145. package/dist/timeout-BVw8aaM1.js +0 -33
  146. package/dist/version-omm6IPI3.js +0 -12
  147. /package/dist/{auth-profile-selection-DFu9e167.js → .setup/auth-profile-selection-DFu9e167.mjs} +0 -0
  148. /package/dist/{config-utils-DujwEnhg.js → .setup/config-utils-DujwEnhg.mjs} +0 -0
  149. /package/dist/{context-compaction-activity-CMla5FPJ.js → .setup/context-compaction-activity-CMla5FPJ.mjs} +0 -0
  150. /package/dist/{elicitation-input-DPoK8F7w.js → .setup/elicitation-input-DPoK8F7w.mjs} +0 -0
  151. /package/dist/{history-rejection-B4nOXNXF.js → .setup/history-rejection-B4nOXNXF.mjs} +0 -0
  152. /package/dist/{image-payload-sanitizer-tupAr-2o.js → .setup/image-payload-sanitizer-tupAr-2o.mjs} +0 -0
  153. /package/dist/{incognito-session-uhrBF6wJ.js → .setup/incognito-session-uhrBF6wJ.mjs} +0 -0
  154. /package/dist/{local-runtime-attribution-B_2mnqhb.js → .setup/local-runtime-attribution-B_2mnqhb.mjs} +0 -0
  155. /package/dist/{native-execution-policy-umd0tgh4.js → .setup/native-execution-policy-umd0tgh4.mjs} +0 -0
  156. /package/dist/{rolldown-runtime-8H4AJuhK.js → .setup/rolldown-runtime-8H4AJuhK.mjs} +0 -0
  157. /package/dist/{session-binding-meta-B7aEMU7g.js → .setup/session-binding-meta-B7aEMU7g.mjs} +0 -0
  158. /package/dist/{session-upstream-marker-D15C9NHp.js → .setup/session-upstream-marker-D15C9NHp.mjs} +0 -0
  159. /package/dist/{upstream-prompt-provenance-LphB8slG.js → .setup/upstream-prompt-provenance-LphB8slG.mjs} +0 -0
  160. /package/dist/{web-search-provider.shared-BrZmlqyR.js → .setup/web-search-provider.shared-BrZmlqyR.mjs} +0 -0
@@ -1,32 +1,109 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { n as defineCodexBuildState, t as codexBuildSymbol } from "./build-state-BCmg9-5p.js";
3
- import { t as CODEX_APP_SERVER_AUTH_PROVIDER } from "./auth-profile-selection-DFu9e167.js";
4
- import { a as resolveCodexAppServerStartOptionsForAgent, g as readCodexEffectiveConfig, h as CODEX_SESSION_OVERRIDABLE_LAYER_TYPES, o as resolveCodexComputerUseConfig, t as codexAppServerStartOptionsKey } from "./config-options-CXMq1T-C.js";
5
- import { c as resolveCodexAppServerLocalHomeDir, l as resolveCodexAppServerUserHomeDir, o as isJsonObject, s as resolveCodexAppServerHomeDir, u as withEphemeralCodexAuthStore } from "./protocol-5bh1G-H7.js";
6
- import { t as isCodexAppServerProxyLaunch } from "./launch-args-RXQwn8zV.js";
7
- import { f as isUnsupportedCodexAppServerVersionError, t as CodexAppServerClient } from "./client-B57KWPQx.js";
8
- import { c as resolveMacOSDesktopCodexAppPathCandidates, i as resolveManagedCodexNativeCommand, l as resolveMacOSDesktopCodexBundledMarketplaceCandidates, r as resolveManagedCodexAppServerStartOptions, s as resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath, t as isManagedCodexDesktopCommand, u as resolveMacOSDesktopCodexComputerUseServiceAppCandidates } from "./managed-binary-D22rNEcR.js";
9
- import { _ as isCodexDesktopGenerationCurrent, a as readCodexCliAuthFileApiKey, c as resolveCodexAppServerPreparedApiKeyCacheKey, d as createCodexAppServerStartupLifetime, f as getCurrentSharedClientEntry, i as fingerprintTokenAuthProfileCacheKey, l as closeRetiredSharedClientEntry, m as retireSharedCodexAppServerClientIfCurrent, n as CODEX_AUTH_JSON_FILENAME, o as readFirstNonEmptyEnv, p as getSharedCodexAppServerClientState, r as fingerprintApiKeyAuthProfileCacheKey, s as resolveCodexAppServerFallbackApiKeyCacheKey, t as CODEX_APP_SERVER_API_KEY_ENV_VARS, u as closeRetiredSharedClientEntryIfIdle, v as waitForCodexDesktopGeneration } from "./auth-cache-key-7orQae_j.js";
10
- import { n as resolveCodexAppServerSpawnEnv } from "./transport-stdio-BGjHoYLr.js";
11
- import { n as withTimeout } from "./timeout-BVw8aaM1.js";
12
- import { n as readCodexSessionMeta } from "./session-catalog-provenance-D-dIfRAH.js";
13
- import { n as resolveCodexAppServerRuntimeOptions } from "./config-runtime-D0zGNIHu.js";
14
- import { a as resolveCodexAppServerAuthProfileStore, i as resolveCodexAppServerAuthProfileIdForAgent, r as resolveCodexAppServerAuthProfileId, t as isCodexAppServerNativeAuthProfile } from "./auth-profile-CwzO4_RG.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
+ import { n as defineCodexBuildState, t as codexBuildSymbol } from "./build-state-C7EnDVgr.mjs";
3
+ import { t as CODEX_APP_SERVER_AUTH_PROVIDER } from "./auth-profile-selection-DFu9e167.mjs";
4
+ import { d as resolveCodexAppServerHomeDir, f as resolveCodexAppServerLocalHomeDir, h as withEphemeralCodexAuthStore, m as withClearedEnvironmentVariables, p as resolveCodexAppServerUserHomeDir } from "./config-security-BEReZ6go.mjs";
5
+ import { n as isCodexAppServerProxyLaunch } from "./launch-args-DbFCehO7.mjs";
6
+ import { i as isJsonObject } from "./protocol-CANUwXJ3.mjs";
7
+ import { a as resolveCodexAppServerStartOptionsForAgent, d as readCodexEffectiveConfig, o as resolveCodexComputerUseConfig, t as codexAppServerStartOptionsKey, u as CODEX_SESSION_OVERRIDABLE_LAYER_TYPES } from "./config-options-BvaRs51b.mjs";
8
+ import { d as resolveMacOSDesktopCodexBundledMarketplaceCandidates, f as resolveMacOSDesktopCodexComputerUseServiceAppCandidates, i as resolveManagedCodexNativeCommand, l as resolveFirstExistingMacOSDesktopCodexBundledMarketplacePath, r as resolveManagedCodexAppServerStartOptions, t as isManagedCodexDesktopCommand, u as resolveMacOSDesktopCodexAppPathCandidates } from "./managed-binary-BnshlFag.mjs";
9
+ import { a as readCodexCliAuthFileApiKey, c as resolveCodexAppServerPreparedApiKeyCacheKey, d as waitForCodexDesktopGeneration, i as fingerprintTokenAuthProfileCacheKey, n as CODEX_AUTH_JSON_FILENAME, o as readFirstNonEmptyEnv, r as fingerprintApiKeyAuthProfileCacheKey, s as resolveCodexAppServerFallbackApiKeyCacheKey, t as CODEX_APP_SERVER_API_KEY_ENV_VARS, u as isCodexDesktopGenerationCurrent } from "./auth-cache-key-B2mpaI9D.mjs";
10
+ import { d as createCodexAppServerStartupLifetime, f as getCurrentSharedClientEntry, h as retireSharedCodexAppServerClientIfCurrent, l as closeRetiredSharedClientEntry, n as observeCodexCatalogClient, o as readCodexSessionMeta, p as getSharedCodexAppServerClientState, u as closeRetiredSharedClientEntryIfIdle } from "./session-catalog-events-Bj6j94E_.mjs";
11
+ import { n as resolveCodexAppServerSpawnEnv } from "./transport-stdio-h2VHOskC.mjs";
12
+ import { n as CodexAppServerAuthProfileUnavailableError, r as formatCodexAuthProfileUnavailableMessage } from "./auth-profile-recovery-BREezV0L.mjs";
13
+ import { i as withTimeout } from "./timeout-C910MdAB.mjs";
14
+ import { n as resolveCodexAppServerRuntimeOptions } from "./config-runtime-C8Rw1m1m.mjs";
15
+ import { a as resolveCodexAppServerAuthProfileStore, i as resolveCodexAppServerAuthProfileIdForAgent, r as resolveCodexAppServerAuthProfileId, t as isCodexAppServerNativeAuthProfile } from "./auth-profile-WqZtZfXN.mjs";
16
+ import { f as isUnsupportedCodexAppServerVersionError, t as CodexAppServerClient } from "./client-Cs08OXVQ.mjs";
15
17
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
16
18
  import { createHash } from "node:crypto";
19
+ import { isDeepStrictEqual } from "node:util";
17
20
  import { AgentHarnessPreflightError, resolveDefaultAgentDir } from "openclaw/plugin-sdk/agent-harness-registration";
18
21
  import { addTimerTimeoutGraceMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
19
22
  import { runExec } from "openclaw/plugin-sdk/process-runtime";
20
23
  import fs, { constants } from "node:fs";
21
24
  import path from "node:path";
22
25
  import fs$1 from "node:fs/promises";
23
- import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
24
26
  import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
25
27
  import { ensureAuthProfileStore, findPersistedAuthProfileCredential, refreshOAuthCredentialForRuntime, resolveApiKeyForProfile, resolvePersistedAuthProfileOwnerAgentDir } from "openclaw/plugin-sdk/agent-runtime";
26
28
  import { AgentHarnessPreflightError as AgentHarnessPreflightError$1, embeddedAgentLog as embeddedAgentLog$1, formatErrorMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
27
- import { isDeepStrictEqual } from "node:util";
28
- import { assertNoSymlinkParents } from "openclaw/plugin-sdk/security-runtime";
29
29
  import { hasUsableOAuthCredential, resolveOpenAICodexAuthIdentity } from "openclaw/plugin-sdk/provider-auth";
30
+ import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
31
+ import { assertNoSymlinkParents } from "openclaw/plugin-sdk/security-runtime";
32
+ //#region extensions/codex/src/app-server/attempt-timeouts.ts
33
+ /**
34
+ * Timeout defaults and normalizers for Codex app-server startup and turn
35
+ * liveness watches.
36
+ */
37
+ /** Minimum startup timeout accepted by the Codex app-server harness. */
38
+ const CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS = 100;
39
+ const TURN_TERMINAL_SETTLEMENT_TIMEOUT_MS = 12e4;
40
+ const TURN_FINALIZE_DRAIN_ABORT_GRACE_MS = 5e3;
41
+ var CodexAppServerStartupError = class extends Error {
42
+ constructor(reason, message = reason === "timed_out" ? "codex app-server startup timed out" : "codex app-server startup aborted") {
43
+ super(message);
44
+ this.reason = reason;
45
+ this.code = "CODEX_APP_SERVER_STARTUP_CANCELLED";
46
+ this.name = "CodexAppServerStartupError";
47
+ }
48
+ };
49
+ function isCodexAppServerStartupError(error, reason) {
50
+ 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);
51
+ }
52
+ function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
53
+ const fallback = resolveTimerTimeoutMs(fallbackMs, 1);
54
+ return resolveTimerTimeoutMs(value, fallback);
55
+ }
56
+ /** Runs startup work with abort and timeout handling plus optional cleanup. */
57
+ async function withCodexStartupTimeout(params) {
58
+ if (params.signal.aborted) throw new CodexAppServerStartupError("aborted");
59
+ let timeout;
60
+ let abortCleanup;
61
+ let timeoutError;
62
+ let timeoutCleanup;
63
+ try {
64
+ return await Promise.race([params.operation(), new Promise((_, reject) => {
65
+ const rejectOnce = (error) => {
66
+ if (timeout) {
67
+ clearTimeout(timeout);
68
+ timeout = void 0;
69
+ }
70
+ reject(error);
71
+ };
72
+ timeout = setTimeout(() => {
73
+ timeoutError = new CodexAppServerStartupError("timed_out");
74
+ timeoutCleanup = Promise.resolve(params.onTimeout?.()).then(() => void 0, () => void 0);
75
+ timeoutCleanup.finally(() => {
76
+ rejectOnce(timeoutError);
77
+ });
78
+ }, params.timeoutMs);
79
+ const abortListener = () => rejectOnce(new CodexAppServerStartupError("aborted"));
80
+ params.signal.addEventListener("abort", abortListener, { once: true });
81
+ abortCleanup = () => params.signal.removeEventListener("abort", abortListener);
82
+ })]);
83
+ } catch (error) {
84
+ if (timeoutError) {
85
+ await timeoutCleanup;
86
+ throw timeoutError;
87
+ }
88
+ throw error;
89
+ } finally {
90
+ if (timeout) clearTimeout(timeout);
91
+ abortCleanup?.();
92
+ }
93
+ }
94
+ /** Resolves startup timeout while honoring the configured floor. */
95
+ function resolveCodexStartupTimeoutMs(params) {
96
+ const timeoutFloorMs = resolvePositiveIntegerTimeoutMs(params.timeoutFloorMs, CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS);
97
+ const timeoutMs = resolvePositiveIntegerTimeoutMs(params.timeoutMs, timeoutFloorMs);
98
+ return Math.max(timeoutFloorMs, timeoutMs);
99
+ }
100
+ /** Adds gateway grace time to a caller timeout without overflowing invalid values. */
101
+ function resolveCodexGatewayTimeoutWithGraceMs(timeoutMs, graceMs = 1e4) {
102
+ const timeout = resolvePositiveIntegerTimeoutMs(timeoutMs, 1);
103
+ const grace = resolveTimerTimeoutMs(graceMs, 0, 0);
104
+ return addTimerTimeoutGraceMs(timeout, grace) ?? timeout;
105
+ }
106
+ //#endregion
30
107
  //#region extensions/codex/src/app-server/computer-use-service-path.ts
31
108
  /** Filesystem ownership guards for isolated Computer Use service provisioning. */
32
109
  async function assertOwnedServicePath(params) {
@@ -238,6 +315,7 @@ async function ensureRealDirectoryCopy(cachePath, sourcePluginRoot, version, bou
238
315
  let backupCreated = false;
239
316
  try {
240
317
  await fs$1.cp(sourcePluginRoot, stagedPath, { recursive: true });
318
+ await waitForCodexDesktopGeneration();
241
319
  if (ownedParent) await assertDirectoryIdentityStable(ownedParent, "Computer Use plugin cache parent");
242
320
  if (stat) {
243
321
  boundary.assertCurrent?.();
@@ -523,7 +601,9 @@ async function ensureCodexComputerUseServiceAppOnce(params) {
523
601
  if (!stagedIdentity || !identitiesMatch(stagedIdentity, sourceIdentity)) throw new Error(`Copied Computer Use service app at ${stagedPath} does not match its selected signed source.`);
524
602
  const stagedSnapshot = await readServiceAppSnapshot(stagedPath, inspectServiceApp);
525
603
  const currentSourceIdentity = await inspectServiceApp(sourcePath);
604
+ await waitForCodexDesktopGeneration();
526
605
  await assertOwnedServiceParentStable(ownedParent);
606
+ await assertDirectoryIdentityStable(stagingRootIdentity, "Computer Use service staging directory");
527
607
  if (!currentSourceIdentity || !identitiesMatch(currentSourceIdentity, sourceIdentity)) throw new Error("Selected Computer Use service source changed during refresh.");
528
608
  await assertNotSymlink(operationTargetPath, "Computer Use service target");
529
609
  if (await pathExists$1(operationTargetPath)) {
@@ -802,7 +882,10 @@ const scopedOAuthRefreshQueues = /* @__PURE__ */ new WeakMap();
802
882
  async function bridgeCodexAppServerStartOptions(params) {
803
883
  if (params.startOptions.transport !== "stdio") return params.startOptions;
804
884
  const scopeStartOptions = () => withCodexHomeEnvironment(withEphemeralCodexAuthStore(params), params.agentDir);
805
- if (params.preparedAuth) return withClearedEnvironmentVariables(await scopeStartOptions(), CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS);
885
+ if (params.preparedAuth) {
886
+ const scopedStartOptions = await scopeStartOptions();
887
+ return withClearedEnvironmentVariables(scopedStartOptions, CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS);
888
+ }
806
889
  if (params.authProfileId === null) return scopeStartOptions();
807
890
  const store = resolveCodexAppServerAuthProfileStore({
808
891
  agentDir: params.agentDir,
@@ -886,6 +969,7 @@ async function resolveCodexAppServerPreparedAuthHandoff(params) {
886
969
  };
887
970
  }
888
971
  const authProfileId = params.authProfileId?.trim() || void 0;
972
+ if (authProfileId && !params.authProfileStore.profiles[authProfileId]) throw new CodexAppServerAuthProfileUnavailableError(formatCodexAuthProfileUnavailableMessage(authProfileId));
889
973
  const nativeAuthProfile = isCodexAppServerNativeAuthProfile({
890
974
  authProfileId,
891
975
  authProfileStore: params.authProfileStore,
@@ -931,23 +1015,16 @@ async function resolveCodexAppServerAuthAccountCacheKey(params) {
931
1015
  if (!profileId) return;
932
1016
  const credential = store.profiles[profileId];
933
1017
  if (!credential || !isCodexAppServerAuthProfileCredential(credential)) return;
934
- if (credential.type === "api_key") {
935
- const apiKey = (await resolveApiKeyForProfile({
936
- store,
937
- profileId,
938
- agentDir
939
- }))?.apiKey?.trim();
940
- return apiKey ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintApiKeyAuthProfileCacheKey(apiKey)}` : resolveChatgptAccountId(profileId, credential);
941
- }
942
- if (credential.type === "token") {
943
- const accessToken = (await resolveApiKeyForProfile({
944
- store,
945
- profileId,
946
- agentDir
947
- }))?.apiKey?.trim();
948
- return accessToken ? `${resolveChatgptAccountId(profileId, credential)}:${fingerprintTokenAuthProfileCacheKey(accessToken)}` : resolveChatgptAccountId(profileId, credential);
949
- }
950
- return resolveChatgptAccountId(profileId, credential);
1018
+ const accountId = resolveChatgptAccountId(profileId, credential);
1019
+ if (credential.type === "oauth") return accountId;
1020
+ const value = (await resolveApiKeyForProfile({
1021
+ cfg: params.config,
1022
+ store,
1023
+ profileId,
1024
+ agentDir
1025
+ }))?.apiKey?.trim();
1026
+ if (!value) return accountId;
1027
+ return `${accountId}:${credential.type === "api_key" ? fingerprintApiKeyAuthProfileCacheKey(value) : fingerprintTokenAuthProfileCacheKey(value)}`;
951
1028
  }
952
1029
  async function withCodexHomeEnvironment(startOptions, agentDir) {
953
1030
  const codexHome = resolveCodexAppServerLocalHomeDir(startOptions, agentDir);
@@ -1016,7 +1093,9 @@ async function reconcileCodexComputerUseStartArtifactsOnce(params) {
1016
1093
  const computerUseConfig = resolveCodexComputerUseConfig({ pluginConfig: params.pluginConfig });
1017
1094
  const ownsIsolatedCodexHome = params.ownsIsolatedCodexHome ?? (params.startOptions.homeScope !== "user" && !params.startOptions.env?.[CODEX_HOME_ENV_VAR]?.trim());
1018
1095
  const shouldProvisionComputerUse = computerUseConfig.enabled && computerUseConfig.autoInstall && ownsIsolatedCodexHome;
1019
- if (shouldProvisionComputerUse) await ensureOwnedCodexHome(codexHome, params.agentDir);
1096
+ const provisioningAgentDir = shouldProvisionComputerUse ? params.agentDir : void 0;
1097
+ if (shouldProvisionComputerUse && !provisioningAgentDir) throw new Error("Managed Codex Computer Use requires an OpenClaw agent directory");
1098
+ if (provisioningAgentDir) await ensureOwnedCodexHome(codexHome, provisioningAgentDir);
1020
1099
  else await fs$1.mkdir(codexHome, { recursive: true });
1021
1100
  const desktopCandidates = resolveMacOSDesktopCodexAppPathCandidates();
1022
1101
  const exactDesktopCandidate = desktopCandidates.find((candidate) => path.resolve(candidate.appServerCommandPath) === path.resolve(params.startOptions.command));
@@ -1027,12 +1106,12 @@ async function reconcileCodexComputerUseStartArtifactsOnce(params) {
1027
1106
  needsBundledMarketplace
1028
1107
  }) : exactDesktopCandidate;
1029
1108
  params.assertCurrent();
1030
- if (shouldProvisionComputerUse) {
1109
+ if (provisioningAgentDir) {
1031
1110
  if (desktopCandidates.length > 0 && !artifactCandidate) throw new CodexComputerUseCandidateArtifactsUnavailableError();
1032
1111
  try {
1033
1112
  const marketplacePath = usesManagedBundledMarketplace ? await ensureCodexManagedBundledMarketplace({
1034
1113
  codexHome,
1035
- ownershipRoot: params.agentDir,
1114
+ ownershipRoot: provisioningAgentDir,
1036
1115
  ...artifactCandidate ? {
1037
1116
  appServerCommand: artifactCandidate.appServerCommandPath,
1038
1117
  candidates: [artifactCandidate],
@@ -1111,11 +1190,12 @@ async function applyCodexAppServerAuthProfile(params) {
1111
1190
  await assertNativeCodexAccountMatchesRoute(params.client, params.authRequirement, params.assertCurrent);
1112
1191
  return;
1113
1192
  }
1193
+ const agentDir = params.agentDir ?? resolveDefaultAgentDir(params.config ?? {});
1114
1194
  let loginParams = params.preparedAuth?.kind === "profile" ? params.preparedAuth.snapshot.loginParams : params.preparedAuth?.kind === "api-key" ? {
1115
1195
  type: "apiKey",
1116
1196
  apiKey: params.preparedAuth.apiKey
1117
1197
  } : await resolveCodexAppServerAuthProfileLoginParams({
1118
- agentDir: params.agentDir,
1198
+ agentDir,
1119
1199
  authProfileId: params.authProfileId ?? void 0,
1120
1200
  authProfileStore: params.authProfileStore,
1121
1201
  config: params.config
@@ -1150,8 +1230,7 @@ async function applyCodexAppServerAuthProfile(params) {
1150
1230
  */
1151
1231
  async function assertNativeCodexAccountMatchesRoute(client, authRequirement, assertCurrent) {
1152
1232
  if (!authRequirement) return;
1153
- const response = await client.request("account/read", { refreshToken: false }, { assertCurrent });
1154
- const accountType = isJsonObject(response.account) ? response.account.type : void 0;
1233
+ const accountType = (await client.request("account/read", { refreshToken: false }, { assertCurrent })).account?.type;
1155
1234
  if (authRequirement === "subscription") {
1156
1235
  if (accountType !== "chatgpt") throw createCodexAppServerAuthError("Codex subscription route requires ChatGPT auth in the native Codex home. Run `codex login` for that home, or use appServer.homeScope=\"agent\" with an OpenClaw OAuth profile, then retry.");
1157
1236
  return;
@@ -1162,23 +1241,8 @@ function createCodexAppServerAuthError(message, cause) {
1162
1241
  const error = cause === void 0 ? new Error(message) : new Error(message, { cause });
1163
1242
  return Object.assign(error, { status: 401 });
1164
1243
  }
1165
- var CodexAppServerAuthProfileUnavailableError = class extends Error {
1166
- constructor(..._args) {
1167
- super(..._args);
1168
- this.status = 401;
1169
- this.code = "selected_auth_profile_unavailable";
1170
- }
1171
- };
1172
1244
  async function resolveCodexAppServerAuthProfileLoginParams(params) {
1173
1245
  const store = resolveCodexAppServerAuthProfileStore(params);
1174
- const profileId = resolveCodexAppServerAuthProfileId({
1175
- authProfileId: params.authProfileId,
1176
- store,
1177
- config: params.config
1178
- });
1179
- const profile = profileId ? store.profiles[profileId] : void 0;
1180
- if (profileId && !profile) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" was not found. Select an existing OpenAI profile or sign in again with OpenClaw, then retry.`);
1181
- if (profileId && profile && !isCodexAppServerAuthProfileCredential(profile)) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" must use the canonical OpenAI auth provider; run "openclaw doctor --fix" to migrate legacy provider IDs.`);
1182
1246
  return await resolveCodexAppServerAuthProfileLoginParamsInternal({
1183
1247
  ...params,
1184
1248
  authProfileStore: store
@@ -1226,7 +1290,7 @@ async function resolveCodexAppServerAuthProfileLoginParamsInternal(params) {
1226
1290
  });
1227
1291
  if (!profileId) return;
1228
1292
  const credential = store.profiles[profileId];
1229
- if (!credential) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" was not found. Select an existing OpenAI profile or sign in again with OpenClaw, then retry.`);
1293
+ if (!credential) throw new CodexAppServerAuthProfileUnavailableError(formatCodexAuthProfileUnavailableMessage(profileId));
1230
1294
  if (!isCodexAppServerAuthProfileCredential(credential)) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" must use the canonical OpenAI auth provider; run "openclaw doctor --fix" to migrate legacy provider IDs.`);
1231
1295
  const loginParams = await resolveLoginParamsForCredential(profileId, credential, {
1232
1296
  agentDir: params.agentDir,
@@ -1250,30 +1314,22 @@ async function resolveCodexAppServerFallbackApiKeyLoginParams(params) {
1250
1314
  };
1251
1315
  }
1252
1316
  async function resolveLoginParamsForCredential(profileId, credential, params) {
1253
- if (credential.type === "api_key") {
1254
- const apiKey = (await resolveApiKeyForProfile({
1317
+ if (credential.type === "api_key" || credential.type === "token") {
1318
+ const value = (await resolveApiKeyForProfile({
1319
+ cfg: params.config,
1255
1320
  store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, {
1256
1321
  allowKeychainPrompt: false,
1257
- profileId
1322
+ profileId,
1323
+ config: params.config
1258
1324
  }),
1259
1325
  profileId,
1260
1326
  agentDir: params.agentDir
1261
1327
  }))?.apiKey?.trim();
1262
- return apiKey ? {
1328
+ if (!value) return;
1329
+ return credential.type === "api_key" ? {
1263
1330
  type: "apiKey",
1264
- apiKey
1265
- } : void 0;
1266
- }
1267
- if (credential.type === "token") {
1268
- const accessToken = (await resolveApiKeyForProfile({
1269
- store: params.preferStoreCredential ? params.store : ensureAuthProfileStore(params.agentDir, {
1270
- allowKeychainPrompt: false,
1271
- profileId
1272
- }),
1273
- profileId,
1274
- agentDir: params.agentDir
1275
- }))?.apiKey?.trim();
1276
- return accessToken ? buildChatgptAuthTokensParams(profileId, credential, accessToken) : void 0;
1331
+ apiKey: value
1332
+ } : buildChatgptAuthTokensParams(profileId, credential, value);
1277
1333
  }
1278
1334
  if (credential.type !== "oauth") return;
1279
1335
  const resolvedCredential = await resolveOAuthCredentialForCodexAppServer(profileId, credential, {
@@ -1303,7 +1359,7 @@ async function resolveOAuthCredentialForCodexAppServer(profileId, credential, pa
1303
1359
  persistedCredential,
1304
1360
  suppliedCredential: credential
1305
1361
  });
1306
- if (params.preferStoreCredential && params.store.runtimePersistedProfileIds?.includes(profileId) && (persistedCredential?.type !== "oauth" || !isCodexAppServerAuthProvider(persistedCredential.provider))) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" is no longer available. Sign in again with OpenClaw, then retry.`);
1362
+ if (params.preferStoreCredential && params.store.runtimePersistedProfileIds?.includes(profileId) && (persistedCredential?.type !== "oauth" || !isCodexAppServerAuthProvider(persistedCredential.provider))) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" is no longer an OpenAI OAuth credential in its persisted OpenClaw store. Run "openclaw doctor" to inspect credential ownership, or select an existing OpenAI profile.`);
1307
1363
  const store = useScopedCredential ? params.store : resolveCodexAppServerAuthProfileStore({
1308
1364
  agentDir: ownerAgentDir,
1309
1365
  authProfileId: profileId,
@@ -1327,17 +1383,22 @@ async function resolveOAuthCredentialForCodexAppServer(profileId, credential, pa
1327
1383
  profileId,
1328
1384
  credential: overlaidOAuthCredential,
1329
1385
  forceRefresh: params.forceRefresh && !reuseCompletedRotation,
1330
- expectedAccountId
1386
+ expectedAccountId,
1387
+ config: params.config
1331
1388
  });
1332
1389
  if (params.forceRefresh && !persistedOAuthCredential && overlaidOAuthCredential) {
1333
1390
  if (reuseCompletedRotation) return overlaidOAuthCredential;
1334
- const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({ credential: overlaidOAuthCredential });
1391
+ const refreshedRuntimeCredential = await refreshOAuthCredentialForRuntime({
1392
+ credential: overlaidOAuthCredential,
1393
+ cfg: params.config
1394
+ });
1335
1395
  if (!refreshedRuntimeCredential?.access?.trim()) throw new Error(`Codex app-server auth profile "${profileId}" could not refresh. Sign in again with OpenClaw, then retry.`);
1336
1396
  assertCodexOAuthRefreshWorkspace(profileId, refreshedRuntimeCredential, expectedAccountId);
1337
1397
  store.profiles[profileId] = refreshedRuntimeCredential;
1338
1398
  return refreshedRuntimeCredential;
1339
1399
  }
1340
1400
  const resolved = await resolveApiKeyForProfile({
1401
+ cfg: params.config,
1341
1402
  store,
1342
1403
  profileId,
1343
1404
  agentDir: ownerAgentDir,
@@ -1345,7 +1406,7 @@ async function resolveOAuthCredentialForCodexAppServer(profileId, credential, pa
1345
1406
  allowProfileFallback: false,
1346
1407
  ...expectedAccountId ? { validateOAuthCredential: (candidate) => assertCodexOAuthRefreshWorkspace(profileId, candidate, expectedAccountId) } : {}
1347
1408
  });
1348
- if (!resolved || resolved.credential?.type !== "oauth" || !isCodexAppServerAuthProvider(resolved.credential.provider) || !resolved.apiKey.trim()) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" is no longer available. Sign in again with OpenClaw, then retry.`);
1409
+ if (!resolved || resolved.credential?.type !== "oauth" || !isCodexAppServerAuthProvider(resolved.credential.provider) || !resolved.apiKey.trim()) throw new CodexAppServerAuthProfileUnavailableError(`Codex app-server auth profile "${profileId}" could not resolve usable OAuth credentials from its OpenClaw credential store. Run "openclaw doctor" to inspect credential ownership, or select an existing OpenAI profile.`);
1349
1410
  const candidate = {
1350
1411
  ...resolved.credential,
1351
1412
  access: resolved.apiKey
@@ -1389,7 +1450,10 @@ async function resolveScopedOAuthCredential(params) {
1389
1450
  const current = params.store.profiles[params.profileId];
1390
1451
  const credential = current?.type === "oauth" ? current : params.credential;
1391
1452
  if (!params.forceRefresh && hasUsableOAuthCredential(credential)) return credential;
1392
- const refreshed = await refreshOAuthCredentialForRuntime({ credential });
1453
+ const refreshed = await refreshOAuthCredentialForRuntime({
1454
+ credential,
1455
+ cfg: params.config
1456
+ });
1393
1457
  if (!refreshed?.access?.trim()) throw new Error(`Codex app-server auth profile "${params.profileId}" could not refresh. Sign in again with OpenClaw, then retry.`);
1394
1458
  assertCodexOAuthRefreshWorkspace(params.profileId, refreshed, params.expectedAccountId);
1395
1459
  if (!isDeepStrictEqual(params.store.profiles[params.profileId], credential)) throw new Error(`Codex app-server auth profile "${params.profileId}" changed while refreshing. Retry with the newly selected OpenAI profile.`);
@@ -1422,15 +1486,6 @@ function isCodexSubscriptionCredential(credential) {
1422
1486
  if (!credential || !isCodexAppServerAuthProvider(credential.provider)) return false;
1423
1487
  return credential.type === "oauth" || credential.type === "token";
1424
1488
  }
1425
- function withClearedEnvironmentVariables(startOptions, envVars) {
1426
- const clearEnv = startOptions.clearEnv ?? [];
1427
- const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
1428
- if (missingEnvVars.length === 0) return startOptions;
1429
- return {
1430
- ...startOptions,
1431
- clearEnv: [...clearEnv, ...missingEnvVars]
1432
- };
1433
- }
1434
1489
  function buildChatgptAuthTokensParams(profileId, credential, accessToken) {
1435
1490
  const storedAccountId = resolveExplicitChatgptAccountId(credential);
1436
1491
  const tokenAccountId = resolveOpenAICodexAuthIdentity({ access: accessToken }).accountId;
@@ -1462,6 +1517,65 @@ function resolveExplicitChatgptAccountId(credential) {
1462
1517
  }
1463
1518
  }
1464
1519
  //#endregion
1520
+ //#region extensions/codex/src/app-server/client-thread-owner.ts
1521
+ function createThreadOwnerToken(threadId, onInvalidated) {
1522
+ const owner = {
1523
+ invalidated: false,
1524
+ invalidate: () => {
1525
+ if (owner.invalidated) return;
1526
+ owner.invalidated = true;
1527
+ try {
1528
+ onInvalidated?.();
1529
+ } catch (error) {
1530
+ embeddedAgentLog$1.warn("codex thread ownership invalidation failed", {
1531
+ threadId,
1532
+ reason: formatErrorMessage(error)
1533
+ });
1534
+ }
1535
+ }
1536
+ };
1537
+ return owner;
1538
+ }
1539
+ function hasThreadOwnership(runtime, threadId) {
1540
+ return runtime !== void 0 && !runtime.closed && (runtime.retainedThreads.get(threadId) !== void 0 || runtime.releasingThreads.get(threadId) !== void 0 || runtime.claimedThreads.get(threadId) !== void 0);
1541
+ }
1542
+ function hasSiblingThreadWork(runtime, threadId) {
1543
+ if (!runtime || runtime.closed) return false;
1544
+ if (runtime.protectedThreads.size > 0) return true;
1545
+ for (const [retainedThreadId, retained] of runtime.retainedThreads) if (retainedThreadId !== threadId && retained.ephemeralPolicy !== void 0) return true;
1546
+ for (const claimedThreadId of runtime.claimedThreads.keys()) if (claimedThreadId !== threadId) return true;
1547
+ return false;
1548
+ }
1549
+ function invalidateThreadOwnership(runtime, threadId) {
1550
+ const retainedOwner = runtime.retainedThreads.get(threadId)?.ownerToken;
1551
+ const claimedOwner = runtime.claimedThreads.get(threadId);
1552
+ const releasing = runtime.releasingThreads.get(threadId);
1553
+ if (releasing) releasing.invalidated = true;
1554
+ runtime.retainedThreads.delete(threadId);
1555
+ runtime.claimedThreads.delete(threadId);
1556
+ retainedOwner?.invalidate();
1557
+ claimedOwner?.invalidate();
1558
+ releasing?.retainedOwnerToken?.invalidate();
1559
+ }
1560
+ function forgetThreadOwnership(runtime, threadId, owner) {
1561
+ let forgotten = false;
1562
+ if (runtime.claimedThreads.get(threadId) === owner) {
1563
+ runtime.claimedThreads.delete(threadId);
1564
+ forgotten = true;
1565
+ }
1566
+ if (runtime.retainedThreads.get(threadId)?.ownerToken === owner) {
1567
+ runtime.retainedThreads.delete(threadId);
1568
+ forgotten = true;
1569
+ }
1570
+ const releasing = runtime.releasingThreads.get(threadId);
1571
+ if (releasing?.retainedOwnerToken === owner) {
1572
+ releasing.invalidated = true;
1573
+ forgotten = true;
1574
+ }
1575
+ if (forgotten) owner.invalidate();
1576
+ return forgotten;
1577
+ }
1578
+ //#endregion
1465
1579
  //#region extensions/codex/src/app-server/rate-limit-cache.ts
1466
1580
  const DEFAULT_CODEX_RATE_LIMIT_CACHE_MAX_AGE_MS = 6e5;
1467
1581
  const SPARSE_ACCOUNT_METADATA_KEYS = [
@@ -1655,8 +1769,11 @@ function ensureCodexAppServerClientRuntime(client, context) {
1655
1769
  clearTimeout(runtime.evictionTimer);
1656
1770
  runtime.evictionTimer = void 0;
1657
1771
  }
1658
- runtime.retainedThreads.clear();
1659
- runtime.claimedThreads.clear();
1772
+ for (const threadId of /* @__PURE__ */ new Set([
1773
+ ...runtime.retainedThreads.keys(),
1774
+ ...runtime.claimedThreads.keys(),
1775
+ ...runtime.releasingThreads.keys()
1776
+ ])) invalidateThreadOwnership(runtime, threadId);
1660
1777
  runtime.protectedThreads.clear();
1661
1778
  runtime.sessionMetadata.clear();
1662
1779
  runtime.workspaceReferences.clear();
@@ -1664,6 +1781,7 @@ function ensureCodexAppServerClientRuntime(client, context) {
1664
1781
  client.addRequestHandler(async (request) => {
1665
1782
  if (request.method !== "account/chatgptAuthTokens/refresh") return;
1666
1783
  if (runtime.context.authMode === "prepared-api-key") throw new Error("ChatGPT token refresh is unavailable for prepared Codex API-key auth.");
1784
+ if (!runtime.context.agentDir) throw new Error("ChatGPT token refresh requires an OpenClaw-owned auth profile.");
1667
1785
  const previousAccountId = isJsonObject(request.params) && typeof request.params.previousAccountId === "string" ? request.params.previousAccountId.trim() || void 0 : void 0;
1668
1786
  const authHandoff = runtime.authHandoff;
1669
1787
  try {
@@ -1703,10 +1821,7 @@ function ensureCodexAppServerClientRuntime(client, context) {
1703
1821
  if (notification.method === "thread/archived" || notification.method === "thread/deleted" || notification.method === "thread/closed") {
1704
1822
  const threadId = notification.params?.threadId;
1705
1823
  if (typeof threadId === "string") {
1706
- const releasing = runtime.releasingThreads.get(threadId);
1707
- if (releasing) releasing.invalidated = true;
1708
- runtime.retainedThreads.delete(threadId);
1709
- runtime.claimedThreads.delete(threadId);
1824
+ invalidateThreadOwnership(runtime, threadId);
1710
1825
  runtime.sessionMetadata.delete(threadId);
1711
1826
  runtime.workspaceReferences.delete(threadId);
1712
1827
  scheduleRetainedThreadEviction(client, runtime);
@@ -1747,14 +1862,18 @@ async function releaseRetainedThread(client, runtime, threadId, assertCurrent) {
1747
1862
  }
1748
1863
  runtime.retainedThreads.delete(threadId);
1749
1864
  scheduleRetainedThreadEviction(client, runtime);
1750
- const transition = { completion: Promise.resolve().then(() => {
1751
- assertCurrent?.();
1752
- return assertCurrent ? retained.release(threadId, assertCurrent) : retained.release(threadId);
1753
- }) };
1865
+ const transition = {
1866
+ retainedOwnerToken: retained.ownerToken,
1867
+ completion: Promise.resolve().then(() => {
1868
+ assertCurrent?.();
1869
+ return assertCurrent ? retained.release(threadId, assertCurrent) : retained.release(threadId);
1870
+ })
1871
+ };
1754
1872
  runtime.releasingThreads.set(threadId, transition);
1755
1873
  try {
1756
1874
  await transition.completion;
1757
1875
  runtime.workspaceReferences.delete(threadId);
1876
+ retained.ownerToken?.invalidate();
1758
1877
  return true;
1759
1878
  } catch (error) {
1760
1879
  if (!runtime.closed && !transition.invalidated && runtime.releasingThreads.get(threadId) === transition && !runtime.retainedThreads.has(threadId) && !runtime.claimedThreads.has(threadId)) {
@@ -1788,14 +1907,17 @@ async function retainCodexAppServerLiveThread(client, threadId, releaseThread, c
1788
1907
  const runtime = configuredClients.get(client);
1789
1908
  if (!runtime || runtime.closed) return false;
1790
1909
  const claimed = runtime.claimedThreads.get(threadId);
1791
- if (claimed !== void 0 && (releaseThread === void 0 || claimedThreadReleaseTokens.get(releaseThread) !== claimed)) return false;
1910
+ const ownerToken = releaseThread ? claimedThreadReleaseTokens.get(releaseThread) : void 0;
1911
+ if (claimed !== ownerToken || ownerToken?.invalidated) return false;
1792
1912
  const pendingRelease = runtime.releasingThreads.get(threadId);
1793
1913
  if (pendingRelease) {
1794
1914
  await pendingRelease.completion;
1795
1915
  return false;
1796
1916
  }
1917
+ const previousOwner = runtime.retainedThreads.get(threadId)?.ownerToken;
1797
1918
  runtime.retainedThreads.delete(threadId);
1798
1919
  const retained = {
1920
+ ownerToken,
1799
1921
  configFingerprint,
1800
1922
  ephemeralPolicy,
1801
1923
  serviceTier,
@@ -1805,6 +1927,7 @@ async function retainCodexAppServerLiveThread(client, threadId, releaseThread, c
1805
1927
  })
1806
1928
  };
1807
1929
  runtime.retainedThreads.set(threadId, retained);
1930
+ if (previousOwner !== ownerToken) previousOwner?.invalidate();
1808
1931
  try {
1809
1932
  await evictExcessIdleThreads(client, runtime);
1810
1933
  } catch (error) {
@@ -1834,8 +1957,8 @@ async function consumeCodexAppServerLiveThread(client, threadId, configFingerpri
1834
1957
  if (!retained || configFingerprint !== void 0 && retained.configFingerprint !== configFingerprint) return;
1835
1958
  return claimCodexAppServerThreadOwnership(client, runtime, threadId, retained);
1836
1959
  }
1837
- /** Claims an observed Codex auto-subscription without exposing a temporarily idle owner. */
1838
- async function claimCodexAppServerLiveThread(client, threadId) {
1960
+ /** Claims an auto-subscription; invalidation ends the handle after replacement or release. */
1961
+ async function claimCodexAppServerLiveThread(client, threadId, onInvalidated) {
1839
1962
  const runtime = configuredClients.get(client);
1840
1963
  if (!runtime || runtime.closed || runtime.claimedThreads.has(threadId)) return;
1841
1964
  const pendingRelease = runtime.releasingThreads.get(threadId);
@@ -1848,21 +1971,33 @@ async function claimCodexAppServerLiveThread(client, threadId) {
1848
1971
  release: async (releasedThreadId, assertCurrent) => {
1849
1972
  await unsubscribeCodexAppServerLiveThread(client, releasedThreadId, 5e3, assertCurrent);
1850
1973
  }
1851
- });
1974
+ }, onInvalidated);
1852
1975
  }
1853
- function claimCodexAppServerThreadOwnership(client, runtime, threadId, retained) {
1976
+ function claimCodexAppServerThreadOwnership(client, runtime, threadId, retained, onInvalidated) {
1977
+ const previousClaim = runtime.claimedThreads.get(threadId);
1854
1978
  runtime.retainedThreads.delete(threadId);
1855
- const claimed = Symbol(threadId);
1979
+ const claimed = createThreadOwnerToken(threadId, onInvalidated);
1856
1980
  runtime.claimedThreads.set(threadId, claimed);
1981
+ previousClaim?.invalidate();
1982
+ retained.ownerToken?.invalidate();
1857
1983
  scheduleRetainedThreadEviction(client, runtime);
1858
1984
  const assertCurrent = () => {
1859
- if (runtime.closed || runtime.claimedThreads.get(threadId) !== claimed) throw new Error(`Codex thread subscription ownership changed: ${threadId}`);
1985
+ if (claimed.invalidated || runtime.closed || runtime.claimedThreads.get(threadId) !== claimed) throw new Error(`Codex thread subscription ownership changed: ${threadId}`);
1860
1986
  };
1861
1987
  const release = async (releasedThreadId, assertReleaseCurrent) => {
1862
- if (releasedThreadId !== threadId || runtime.claimedThreads.get(threadId) !== claimed) {
1988
+ if (releasedThreadId !== threadId || claimed.invalidated) {
1863
1989
  assertReleaseCurrent?.();
1864
1990
  return;
1865
1991
  }
1992
+ if (runtime.claimedThreads.get(threadId) !== claimed) {
1993
+ if (runtime.retainedThreads.get(threadId)?.ownerToken === claimed) await releaseRetainedThread(client, runtime, threadId, assertReleaseCurrent);
1994
+ else {
1995
+ const pendingRelease = runtime.releasingThreads.get(threadId);
1996
+ if (pendingRelease?.retainedOwnerToken === claimed) await pendingRelease.completion;
1997
+ assertReleaseCurrent?.();
1998
+ }
1999
+ return;
2000
+ }
1866
2001
  const pendingRelease = runtime.releasingThreads.get(threadId);
1867
2002
  if (pendingRelease) {
1868
2003
  await pendingRelease.completion;
@@ -1882,6 +2017,7 @@ function claimCodexAppServerThreadOwnership(client, runtime, threadId, retained)
1882
2017
  if (runtime.claimedThreads.get(threadId) === claimed) {
1883
2018
  runtime.claimedThreads.delete(threadId);
1884
2019
  runtime.workspaceReferences.delete(threadId);
2020
+ claimed.invalidate();
1885
2021
  }
1886
2022
  } finally {
1887
2023
  if (runtime.releasingThreads.get(threadId) === transition) runtime.releasingThreads.delete(threadId);
@@ -1894,18 +2030,26 @@ function claimCodexAppServerThreadOwnership(client, runtime, threadId, retained)
1894
2030
  configFingerprint: retained.configFingerprint,
1895
2031
  ephemeralPolicy: retained.ephemeralPolicy,
1896
2032
  serviceTier: retained.serviceTier,
1897
- release
2033
+ release,
2034
+ forget: () => {
2035
+ if (forgetThreadOwnership(runtime, threadId, claimed)) {
2036
+ runtime.workspaceReferences.delete(threadId);
2037
+ scheduleRetainedThreadEviction(client, runtime);
2038
+ }
2039
+ }
1898
2040
  };
1899
2041
  }
1900
2042
  /** Distinguish active claimed ownership from an already-evicted idle subscription. */
1901
2043
  function hasCodexAppServerLiveThread(client, threadId) {
1902
- const runtime = configuredClients.get(client);
1903
- return runtime !== void 0 && !runtime.closed && (runtime.retainedThreads.has(threadId) || runtime.releasingThreads.has(threadId) || runtime.claimedThreads.has(threadId));
2044
+ return hasThreadOwnership(configuredClients.get(client), threadId);
1904
2045
  }
1905
2046
  function isCodexAppServerLiveThreadClaimed(client, threadId) {
1906
2047
  const runtime = configuredClients.get(client);
1907
2048
  return runtime !== void 0 && !runtime.closed && runtime.claimedThreads.has(threadId);
1908
2049
  }
2050
+ function hasCodexAppServerSiblingThreadWork(client, threadId) {
2051
+ return hasSiblingThreadWork(configuredClients.get(client), threadId);
2052
+ }
1909
2053
  /** Release the exact physical subscription and finish only its observed ownership generation. */
1910
2054
  async function unsubscribeCodexAppServerLiveThread(client, threadId, timeoutMs, assertCurrent) {
1911
2055
  const runtime = configuredClients.get(client);
@@ -1943,9 +2087,13 @@ async function unsubscribeCodexAppServerLiveThread(client, threadId, timeoutMs,
1943
2087
  await physicalRelease;
1944
2088
  if (retained !== void 0 && runtime?.retainedThreads.get(threadId) === retained) {
1945
2089
  runtime.retainedThreads.delete(threadId);
2090
+ retained.ownerToken?.invalidate();
1946
2091
  scheduleRetainedThreadEviction(client, runtime);
1947
2092
  }
1948
- if (claimed !== void 0 && runtime?.claimedThreads.get(threadId) === claimed) runtime.claimedThreads.delete(threadId);
2093
+ if (claimed !== void 0 && runtime?.claimedThreads.get(threadId) === claimed) {
2094
+ runtime.claimedThreads.delete(threadId);
2095
+ claimed.invalidate();
2096
+ }
1949
2097
  } finally {
1950
2098
  if (ownsTransition && runtime.releasingThreads.get(threadId) === transition) runtime.releasingThreads.delete(threadId);
1951
2099
  }
@@ -1986,81 +2134,6 @@ function protectCodexAppServerLiveThread(client, threadId) {
1986
2134
  };
1987
2135
  }
1988
2136
  //#endregion
1989
- //#region extensions/codex/src/app-server/attempt-timeouts.ts
1990
- /**
1991
- * Timeout defaults and normalizers for Codex app-server startup and turn
1992
- * liveness watches.
1993
- */
1994
- /** Minimum startup timeout accepted by the Codex app-server harness. */
1995
- const CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS = 100;
1996
- const TURN_TERMINAL_SETTLEMENT_TIMEOUT_MS = 12e4;
1997
- const TURN_FINALIZE_DRAIN_ABORT_GRACE_MS = 5e3;
1998
- var CodexAppServerStartupError = class extends Error {
1999
- constructor(reason, message = reason === "timed_out" ? "codex app-server startup timed out" : "codex app-server startup aborted") {
2000
- super(message);
2001
- this.reason = reason;
2002
- this.code = "CODEX_APP_SERVER_STARTUP_CANCELLED";
2003
- this.name = "CodexAppServerStartupError";
2004
- }
2005
- };
2006
- function isCodexAppServerStartupError(error, reason) {
2007
- 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);
2008
- }
2009
- function resolvePositiveIntegerTimeoutMs(value, fallbackMs) {
2010
- const fallback = resolveTimerTimeoutMs(fallbackMs, 1);
2011
- return resolveTimerTimeoutMs(value, fallback);
2012
- }
2013
- /** Runs startup work with abort and timeout handling plus optional cleanup. */
2014
- async function withCodexStartupTimeout(params) {
2015
- if (params.signal.aborted) throw new CodexAppServerStartupError("aborted");
2016
- let timeout;
2017
- let abortCleanup;
2018
- let timeoutError;
2019
- let timeoutCleanup;
2020
- try {
2021
- return await Promise.race([params.operation(), new Promise((_, reject) => {
2022
- const rejectOnce = (error) => {
2023
- if (timeout) {
2024
- clearTimeout(timeout);
2025
- timeout = void 0;
2026
- }
2027
- reject(error);
2028
- };
2029
- timeout = setTimeout(() => {
2030
- timeoutError = new CodexAppServerStartupError("timed_out");
2031
- timeoutCleanup = Promise.resolve(params.onTimeout?.()).then(() => void 0, () => void 0);
2032
- timeoutCleanup.finally(() => {
2033
- rejectOnce(timeoutError);
2034
- });
2035
- }, params.timeoutMs);
2036
- const abortListener = () => rejectOnce(new CodexAppServerStartupError("aborted"));
2037
- params.signal.addEventListener("abort", abortListener, { once: true });
2038
- abortCleanup = () => params.signal.removeEventListener("abort", abortListener);
2039
- })]);
2040
- } catch (error) {
2041
- if (timeoutError) {
2042
- await timeoutCleanup;
2043
- throw timeoutError;
2044
- }
2045
- throw error;
2046
- } finally {
2047
- if (timeout) clearTimeout(timeout);
2048
- abortCleanup?.();
2049
- }
2050
- }
2051
- /** Resolves startup timeout while honoring the configured floor. */
2052
- function resolveCodexStartupTimeoutMs(params) {
2053
- const timeoutFloorMs = resolvePositiveIntegerTimeoutMs(params.timeoutFloorMs, CODEX_APP_SERVER_STARTUP_TIMEOUT_FLOOR_MS);
2054
- const timeoutMs = resolvePositiveIntegerTimeoutMs(params.timeoutMs, timeoutFloorMs);
2055
- return Math.max(timeoutFloorMs, timeoutMs);
2056
- }
2057
- /** Adds gateway grace time to a caller timeout without overflowing invalid values. */
2058
- function resolveCodexGatewayTimeoutWithGraceMs(timeoutMs, graceMs = 1e4) {
2059
- const timeout = resolvePositiveIntegerTimeoutMs(timeoutMs, 1);
2060
- const grace = resolveTimerTimeoutMs(graceMs, 0, 0);
2061
- return addTimerTimeoutGraceMs(timeout, grace) ?? timeout;
2062
- }
2063
- //#endregion
2064
2137
  //#region extensions/codex/src/app-server/inference-routing.ts
2065
2138
  const owners = defineCodexBuildState("openclaw.codexAppServerInferenceOwners", () => /* @__PURE__ */ new WeakMap())();
2066
2139
  const MAX_ROUTES = 8;
@@ -2125,7 +2198,7 @@ async function prepareCodexInferenceRoute(params) {
2125
2198
  assertCurrent
2126
2199
  });
2127
2200
  assertCurrent();
2128
- const type = isJsonObject(account.account) ? account.account.type : void 0;
2201
+ const type = account.account?.type;
2129
2202
  if (type !== "apiKey" && type !== "chatgpt") return;
2130
2203
  if (owner.authRoute && owner.authRoute !== type) throw new Error("Codex native account route changed; reconnect before retrying");
2131
2204
  owner.authRoute = type;
@@ -2134,7 +2207,7 @@ async function prepareCodexInferenceRoute(params) {
2134
2207
  let pending = owner.routes.get(key);
2135
2208
  if (!pending) {
2136
2209
  if (owner.routes.size >= MAX_ROUTES) throw new Error("Codex inference route limit reached");
2137
- pending = import("./inference-proxy-HGXKUIre.js").then(({ createCodexInferenceProxy }) => {
2210
+ pending = import("./inference-proxy-b-aJMSxm.mjs").then(({ createCodexInferenceProxy }) => {
2138
2211
  assertClient();
2139
2212
  return createCodexInferenceProxy({
2140
2213
  upstream: target,
@@ -2263,6 +2336,50 @@ async function waitForPreviousFence(previous, options) {
2263
2336
  });
2264
2337
  }
2265
2338
  //#endregion
2339
+ //#region extensions/codex/src/app-server/native-hook-relay-state.ts
2340
+ const pending = /* @__PURE__ */ new Set();
2341
+ const closing = /* @__PURE__ */ new Set();
2342
+ /** Owns delayed hook-relay cleanup across runtime scheduling and test teardown. */
2343
+ const nativeHookRelayUnregisterQueue = {
2344
+ add(entry) {
2345
+ pending.add(entry);
2346
+ },
2347
+ delete(entry) {
2348
+ return pending.delete(entry);
2349
+ },
2350
+ track(operation) {
2351
+ closing.add(operation);
2352
+ operation.then(() => closing.delete(operation), () => closing.delete(operation));
2353
+ },
2354
+ async flush() {
2355
+ while (pending.size > 0) {
2356
+ const entry = pending.values().next().value;
2357
+ if (!entry) break;
2358
+ clearTimeout(entry.timeout);
2359
+ entry.unregister();
2360
+ }
2361
+ while (closing.size > 0) await Promise.allSettled(closing);
2362
+ },
2363
+ async clear() {
2364
+ for (const entry of pending) clearTimeout(entry.timeout);
2365
+ pending.clear();
2366
+ while (closing.size > 0) await Promise.allSettled(closing);
2367
+ }
2368
+ };
2369
+ //#endregion
2370
+ //#region extensions/codex/src/app-server/spawn-identity.ts
2371
+ /** Resolves non-secret spawn identity before startup; argv is represented only by its hash. */
2372
+ function resolveCodexAppServerSpawnIdentity(startOptions, resolvedNativeCommand) {
2373
+ const nativeCommand = resolvedNativeCommand ?? (startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0);
2374
+ return {
2375
+ command: startOptions.command,
2376
+ argsFingerprint: createHash("sha256").update(JSON.stringify(startOptions.args)).digest("hex"),
2377
+ ...startOptions.commandSource ? { commandSource: startOptions.commandSource } : {},
2378
+ ...startOptions.managedCommandOrder ? { managedCommandOrder: startOptions.managedCommandOrder } : {},
2379
+ ...nativeCommand ? { nativeCommand } : {}
2380
+ };
2381
+ }
2382
+ //#endregion
2266
2383
  //#region extensions/codex/src/app-server/thread-lifecycle-errors.ts
2267
2384
  var CodexThreadStartRequestError = class extends Error {
2268
2385
  constructor(cause) {
@@ -2270,6 +2387,12 @@ var CodexThreadStartRequestError = class extends Error {
2270
2387
  this.name = "CodexThreadStartRequestError";
2271
2388
  }
2272
2389
  };
2390
+ var CodexThreadClientReplacementError = class extends AgentHarnessPreflightError$1 {
2391
+ constructor() {
2392
+ super("Codex did not confirm unloading its previous configuration after a settled failure; a fresh client is required.");
2393
+ this.name = "CodexThreadClientReplacementError";
2394
+ }
2395
+ };
2273
2396
  var CodexThreadBindingConflictError = class extends Error {
2274
2397
  constructor(threadId, operation) {
2275
2398
  super(`Codex thread binding changed while ${operation}: ${threadId}`);
@@ -2305,7 +2428,6 @@ var shared_client_exports = /* @__PURE__ */ __exportAll({
2305
2428
  readCodexAppServerClientProcessIdentity: () => readCodexAppServerClientProcessIdentity,
2306
2429
  releaseCodexAppServerClientLease: () => releaseCodexAppServerClientLease,
2307
2430
  releaseLeasedSharedCodexAppServerClient: () => releaseLeasedSharedCodexAppServerClient,
2308
- resolveCodexAppServerSpawnIdentity: () => resolveCodexAppServerSpawnIdentity,
2309
2431
  resolveCodexNativeConfigFenceKey: () => resolveCodexNativeConfigFenceKey,
2310
2432
  retainSharedCodexAppServerClientByInstanceId: () => retainSharedCodexAppServerClientByInstanceId,
2311
2433
  retainSharedCodexAppServerClientIfCurrent: () => retainSharedCodexAppServerClientIfCurrent,
@@ -2328,7 +2450,7 @@ async function prepareCodexAppServerClient(options) {
2328
2450
  if (abandonSignal.aborted) throw new CodexAppServerStartupError("aborted", "codex app-server initialize aborted");
2329
2451
  };
2330
2452
  assertCurrent();
2331
- const startedAt = Date.now();
2453
+ const startedAt = performance.now();
2332
2454
  return {
2333
2455
  context: await withCodexAppServerAcquireDeadline(options?.timeoutMs ?? 0, ownCodexStartup(lifetime, resolveCodexAppServerClientStartContext(options)), abandonSignal),
2334
2456
  lifetime,
@@ -2372,17 +2494,6 @@ async function waitForCodexAppServerClientDesktopGenerationDrain(params) {
2372
2494
  drain.cancel();
2373
2495
  }
2374
2496
  }
2375
- /** Resolves non-secret spawn identity before startup; argv is represented only by its hash. */
2376
- function resolveCodexAppServerSpawnIdentity(startOptions, resolvedNativeCommand) {
2377
- const nativeCommand = resolvedNativeCommand ?? (startOptions.commandSource === "resolved-managed" ? resolveManagedCodexNativeCommand(startOptions.command) : void 0);
2378
- return {
2379
- command: startOptions.command,
2380
- argsFingerprint: createHash("sha256").update(JSON.stringify(startOptions.args)).digest("hex"),
2381
- ...startOptions.commandSource ? { commandSource: startOptions.commandSource } : {},
2382
- ...startOptions.managedCommandOrder ? { managedCommandOrder: startOptions.managedCommandOrder } : {},
2383
- ...nativeCommand ? { nativeCommand } : {}
2384
- };
2385
- }
2386
2497
  var CodexAppServerStartSelectionChangedError = class extends Error {
2387
2498
  constructor() {
2388
2499
  super("Codex app-server managed executable selection changed during startup");
@@ -2416,26 +2527,21 @@ function resolveCodexNativeConfigFenceKey(params) {
2416
2527
  const metadata = params.client ? getSharedCodexAppServerClientState().startMetadata.get(params.client) : void 0;
2417
2528
  const startOptions = metadata?.startOptions ?? params.startOptions;
2418
2529
  if (!startOptions || startOptions.transport !== "stdio") return;
2419
- const configuredHome = startOptions.env?.CODEX_HOME?.trim();
2420
- const agentDir = params.agentDir ?? metadata?.agentDir ?? resolveDefaultAgentDir(params.config ?? {});
2421
- const codexHome = configuredHome ? configuredHome : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir() : agentDir ? resolveCodexAppServerHomeDir(agentDir) : void 0;
2530
+ const configuredHome = startOptions.codexHome ?? startOptions.env?.CODEX_HOME?.trim();
2531
+ const codexHome = configuredHome ? configuredHome : startOptions.homeScope === "user" ? resolveCodexAppServerUserHomeDir() : resolveCodexAppServerHomeDir(params.agentDir ?? metadata?.agentDir ?? resolveDefaultAgentDir(params.config ?? {}));
2422
2532
  return codexHome ? `codex-home:${path.resolve(codexHome)}` : void 0;
2423
2533
  }
2424
- function inferAuthRequirement(preparedAuth) {
2425
- if (preparedAuth?.kind === "api-key") return "api-key";
2426
- return preparedAuth?.kind === "profile" ? "subscription" : void 0;
2427
- }
2428
2534
  async function resolveCodexAppServerClientStartContext(options) {
2429
- const agentDir = options?.agentDir ?? resolveDefaultAgentDir(options?.config ?? {});
2430
- const requestedStartOptions = options?.startOptions ?? resolveCodexAppServerRuntimeOptions().start;
2535
+ const requestedStartOptions = options?.startOptions ?? resolveCodexAppServerRuntimeOptions({ pluginConfig: options?.pluginConfig }).start;
2536
+ const agentDir = options?.agentDir ?? (requestedStartOptions.homeScope === "user" ? void 0 : resolveDefaultAgentDir(options?.config ?? {}));
2431
2537
  const desktopGeneration = shouldTrackDesktopGeneration(requestedStartOptions, options?.pluginConfig) ? await waitForCodexDesktopGeneration() : void 0;
2432
2538
  const preparedAuth = options?.preparedAuth;
2433
2539
  const preparedApiKey = preparedAuth?.kind === "api-key" ? preparedAuth.apiKey.trim() : void 0;
2434
2540
  if (preparedAuth && options?.authProfileId !== void 0) throw new Error("Prepared Codex auth cannot also select a legacy auth profile.");
2435
- if (preparedAuth?.kind === "profile" && !preparedAuth.store.profiles[preparedAuth.profileId]) throw new Error(`Prepared Codex auth profile "${preparedAuth.profileId}" was not found. Select an existing OpenAI profile or sign in again with OpenClaw, then retry.`);
2541
+ if (preparedAuth?.kind === "profile" && !preparedAuth.store.profiles[preparedAuth.profileId]) throw new CodexAppServerAuthProfileUnavailableError(formatCodexAuthProfileUnavailableMessage(preparedAuth.profileId));
2436
2542
  if (preparedAuth?.kind === "api-key" && !preparedApiKey) throw new Error("Prepared Codex API-key auth is missing its resolved key.");
2437
2543
  if (preparedAuth && requestedStartOptions.homeScope === "user") throw new Error("Prepared Codex auth requires an isolated app-server home.");
2438
- const preparedAuthRequirement = inferAuthRequirement(preparedAuth);
2544
+ const preparedAuthRequirement = preparedAuth && (preparedAuth.kind === "api-key" ? "api-key" : "subscription");
2439
2545
  if (options?.authRequirement && preparedAuthRequirement && options.authRequirement !== preparedAuthRequirement) throw new Error("Prepared Codex auth does not satisfy the requested auth requirement.");
2440
2546
  const authRequirement = options?.authRequirement ?? preparedAuthRequirement;
2441
2547
  const usesNativeAuth = !preparedAuth && (options?.authProfileId === null || requestedStartOptions.homeScope === "user");
@@ -2458,7 +2564,7 @@ async function resolveCodexAppServerClientStartContext(options) {
2458
2564
  agentDir,
2459
2565
  config: options?.config
2460
2566
  }) : void 0;
2461
- if (preparedAuth?.kind === "profile" && !preparedAuthProfileSnapshot) throw new Error(`Prepared Codex auth profile "${preparedAuth.profileId}" is unusable. Repair or replace the selected OpenAI profile, then retry.`);
2567
+ if (preparedAuth?.kind === "profile" && !preparedAuthProfileSnapshot) throw new CodexAppServerAuthProfileUnavailableError(`Prepared Codex auth profile "${preparedAuth.profileId}" is unusable. Repair or replace the selected OpenAI profile, then retry.`);
2462
2568
  const resolvedPreparedAuth = preparedAuth?.kind === "api-key" ? {
2463
2569
  kind: "api-key",
2464
2570
  apiKey: preparedApiKey
@@ -2527,11 +2633,11 @@ async function withLeasedCodexAppServerClientStartSelectionRetry(params) {
2527
2633
  let client = params.lease.client;
2528
2634
  if (!client) throw new Error("Codex app-server selection retry requires an active client lease");
2529
2635
  const timeoutMs = params.options?.timeoutMs ?? 6e4;
2530
- const deadline = Date.now() + timeoutMs;
2636
+ const deadline = performance.now() + timeoutMs;
2531
2637
  const signal = params.signal ?? params.options?.abandonSignal;
2532
2638
  const requestOptions = () => {
2533
2639
  if (signal?.aborted) throw new CodexAppServerStartupError("aborted", "Codex app-server selection retry aborted");
2534
- const remainingTimeoutMs = deadline - Date.now();
2640
+ const remainingTimeoutMs = deadline - performance.now();
2535
2641
  if (remainingTimeoutMs <= 0) throw new CodexAppServerStartupError("timed_out", "Codex app-server selection retry timed out");
2536
2642
  return {
2537
2643
  timeoutMs: remainingTimeoutMs,
@@ -2680,7 +2786,7 @@ function buildCodexAppServerInitializeTimeoutError(client) {
2680
2786
  }
2681
2787
  function resolveRemainingAcquireTimeout(timeoutMs, startedAt) {
2682
2788
  if (!(timeoutMs > 0)) return timeoutMs;
2683
- const remaining = timeoutMs - (Date.now() - startedAt);
2789
+ const remaining = timeoutMs - (performance.now() - startedAt);
2684
2790
  if (remaining <= 0) throw new CodexAppServerStartupError("timed_out", "codex app-server initialize timed out");
2685
2791
  return remaining;
2686
2792
  }
@@ -2760,7 +2866,7 @@ function trackIsolatedCodexAppServerClient(client) {
2760
2866
  });
2761
2867
  }
2762
2868
  async function startInitializedCodexAppServerClient(params) {
2763
- const acquireStartedAt = Date.now();
2869
+ const acquireStartedAt = performance.now();
2764
2870
  const timeoutMs = params.timeoutMs ?? 0;
2765
2871
  const abandonSignal = params.abandonSignal ? AbortSignal.any([params.lifetime.controller.signal, params.abandonSignal]) : params.lifetime.controller.signal;
2766
2872
  const waitForStartup = (operation, timeoutMessage = CODEX_APP_SERVER_INITIALIZE_TIMEOUT_MESSAGE, timeoutErrorFactory) => {
@@ -2805,7 +2911,7 @@ async function startInitializedCodexAppServerClient(params) {
2805
2911
  } finally {
2806
2912
  artifactDrain?.cancel();
2807
2913
  }
2808
- const runtimeArtifactModule = params.runtimeArtifactMode ? await import("./runtime-artifact-BJ0rXBZ_.js") : void 0;
2914
+ const runtimeArtifactModule = params.runtimeArtifactMode ? await import("./runtime-artifact-CLZ8udh-.mjs") : void 0;
2809
2915
  const runtimeArtifactBeforeStart = runtimeArtifactModule ? await runtimeArtifactModule.captureCodexAppServerRuntimeArtifactBeforeStart({
2810
2916
  startOptions,
2811
2917
  spawnIdentity: resolveCodexAppServerSpawnIdentity(startOptions),
@@ -2847,6 +2953,10 @@ async function startInitializedCodexAppServerClient(params) {
2847
2953
  }
2848
2954
  assertStartupCurrent();
2849
2955
  params.onInitializedClient?.();
2956
+ await waitForStartup(() => observeCodexCatalogClient(client, {
2957
+ startOptions: params.requestedStartOptions,
2958
+ agentDir: params.agentDir
2959
+ }));
2850
2960
  let runtimeArtifact;
2851
2961
  if (runtimeArtifactModule && runtimeArtifactBeforeStart) {
2852
2962
  runtimeArtifact = await runtimeArtifactModule.finalizeCodexAppServerRuntimeArtifact({
@@ -2892,7 +3002,7 @@ async function startInitializedCodexAppServerClient(params) {
2892
3002
  release();
2893
3003
  throw error;
2894
3004
  }
2895
- });
3005
+ }, () => Boolean(retireSharedCodexAppServerClientIfCurrent(client)));
2896
3006
  ready = true;
2897
3007
  return client;
2898
3008
  } finally {
@@ -2967,8 +3077,8 @@ function retainSharedCodexAppServerClientByInstanceId(clientId) {
2967
3077
  function captureCodexAppServerClientLifetime(client, requiredOwnership) {
2968
3078
  const state = getSharedCodexAppServerClientState();
2969
3079
  const start = state.startMetadata.get(client)?.startOptions;
2970
- if (requiredOwnership === "native-process" && (start?.transport !== "stdio" || isCodexAppServerProxyLaunch(start.args))) throw new AgentHarnessPreflightError("Codex ordinary configuration refresh requires an OpenClaw-managed local stdio process, not an external socket or app-server proxy. No turn was sent; reconnect through managed local stdio before continuing.");
2971
- const isCurrent = requiredOwnership === "native-process" && state.isolatedClients.has(client) ? () => state.isolatedClients.has(client) && !client.getCloseError() : captureSharedClientRegistration(client);
3080
+ if (requiredOwnership === "native-process" && (start?.transport !== "stdio" || isCodexAppServerProxyLaunch(start.args))) throw new AgentHarnessPreflightError("Codex manual thread adoption requires an OpenClaw-managed local stdio process, not an external socket or app-server proxy. No turn was sent; reconnect through managed local stdio before continuing.");
3081
+ const isCurrent = requiredOwnership !== "connection" && state.isolatedClients.has(client) ? () => state.isolatedClients.has(client) && !client.getCloseError() : captureSharedClientRegistration(client);
2972
3082
  const assertCurrent = () => {
2973
3083
  if (!isCurrent()) throw new CodexAdoptedThreadActiveError("Codex app-server connection changed during thread preparation; reconnect before continuing");
2974
3084
  assertCodexAppServerClientStartSelectionCurrent({ client });
@@ -3044,6 +3154,7 @@ async function clearSharedCodexAppServerClientAndWait(options) {
3044
3154
  try {
3045
3155
  while (lifetime.pending.size > 0) await Promise.allSettled(lifetime.pending);
3046
3156
  await closing;
3157
+ await nativeHookRelayUnregisterQueue.flush();
3047
3158
  } finally {
3048
3159
  if (state.startup === lifetime) state.startup = createCodexAppServerStartupLifetime();
3049
3160
  }
@@ -3106,4 +3217,4 @@ function retirePendingSharedClientEntryIfUnclaimed(entry) {
3106
3217
  closeRetiredSharedClientEntry(entry);
3107
3218
  }
3108
3219
  //#endregion
3109
- export { reconcileCodexComputerUseStartArtifacts as $, CodexAppServerStartupError as A, forgetCodexWorkspaceReferences as B, CodexThreadBindingConflictError as C, bindCodexInferenceThread as D, assertCodexInferenceRouteConfig as E, resolveCodexStartupTimeoutMs as F, protectCodexAppServerLiveThread as G, isCodexAppServerClientRuntimeLive as H, withCodexStartupTimeout as I, retainCodexAppServerLiveThread as J, readCodexClientSessionMeta as K, claimCodexAppServerLiveThread as L, TURN_TERMINAL_SETTLEMENT_TIMEOUT_MS as M, isCodexAppServerStartupError as N, getCodexInferenceThread as O, resolveCodexGatewayTimeoutWithGraceMs as P, rememberCodexRateLimitsRead as Q, consumeCodexAppServerLiveThread as R, CodexAdoptedThreadActiveError as S, acquireCodexNativeConfigFence as T, isCodexAppServerLiveThreadClaimed as U, hasCodexAppServerLiveThread as V, prepareCodexWorkspaceReferences as W, readCodexRateLimitsRevision as X, unsubscribeCodexAppServerLiveThread as Y, readRecentCodexRateLimits as Z, retainSharedCodexAppServerClientByInstanceId as _, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as a, waitForCodexAppServerClientDesktopGenerationDrain as b, getLeasedSharedCodexAppServerClient as c, readCodexAppServerClientDesktopGeneration as d, resolveCodexAppServerAuthAccountCacheKey as et, readCodexAppServerClientDesktopGenerationFingerprint as f, resolveCodexNativeConfigFenceKey as g, releaseLeasedSharedCodexAppServerClient as h, clearSharedCodexAppServerClientIfCurrent as i, TURN_FINALIZE_DRAIN_ABORT_GRACE_MS as j, prepareCodexInferenceThreadConfig as k, getSharedCodexAppServerClient as l, releaseCodexAppServerClientLease as m, captureCodexAppServerClientLifetime as n, resolveCodexManagedBundledMarketplacePath as nt, clearSharedCodexAppServerClientIfCurrentAndWait as o, readCodexAppServerClientProcessIdentity as p, releaseCodexAppServerLiveThread as q, captureSharedCodexAppServerCatalogLifetime as r, assertNotSymlink as rt, createIsolatedCodexAppServerClient as s, assertCodexAppServerClientStartSelectionCurrent as t, resolveCodexAppServerPreparedAuthHandoff as tt, isCodexAppServerStartSelectionChangedError as u, retainSharedCodexAppServerClientIfCurrent as v, CodexThreadStartRequestError as w, withLeasedCodexAppServerClientStartSelectionRetry as x, shared_client_exports as y, ensureCodexAppServerClientRuntime as z };
3220
+ export { assertNotSymlink as $, getCodexInferenceThread as A, prepareCodexWorkspaceReferences as B, CodexThreadBindingConflictError as C, acquireCodexNativeConfigFence as D, nativeHookRelayUnregisterQueue as E, forgetCodexWorkspaceReferences as F, unsubscribeCodexAppServerLiveThread as G, readCodexClientSessionMeta as H, hasCodexAppServerLiveThread as I, rememberCodexRateLimitsRead as J, readCodexRateLimitsRevision as K, hasCodexAppServerSiblingThreadWork as L, claimCodexAppServerLiveThread as M, consumeCodexAppServerLiveThread as N, assertCodexInferenceRouteConfig as O, ensureCodexAppServerClientRuntime as P, resolveCodexManagedBundledMarketplacePath as Q, isCodexAppServerClientRuntimeLive as R, CodexAdoptedThreadActiveError as S, CodexThreadStartRequestError as T, releaseCodexAppServerLiveThread as U, protectCodexAppServerLiveThread as V, retainCodexAppServerLiveThread as W, resolveCodexAppServerAuthAccountCacheKey as X, reconcileCodexComputerUseStartArtifacts as Y, resolveCodexAppServerPreparedAuthHandoff as Z, retainSharedCodexAppServerClientByInstanceId as _, clearSharedCodexAppServerClientIfCurrentAndUnclaimed as a, resolveCodexStartupTimeoutMs as at, waitForCodexAppServerClientDesktopGenerationDrain as b, getLeasedSharedCodexAppServerClient as c, readCodexAppServerClientDesktopGeneration as d, CodexAppServerStartupError as et, readCodexAppServerClientDesktopGenerationFingerprint as f, resolveCodexNativeConfigFenceKey as g, releaseLeasedSharedCodexAppServerClient as h, clearSharedCodexAppServerClientIfCurrent as i, resolveCodexGatewayTimeoutWithGraceMs as it, prepareCodexInferenceThreadConfig as j, bindCodexInferenceThread as k, getSharedCodexAppServerClient as l, releaseCodexAppServerClientLease as m, captureCodexAppServerClientLifetime as n, TURN_TERMINAL_SETTLEMENT_TIMEOUT_MS as nt, clearSharedCodexAppServerClientIfCurrentAndWait as o, withCodexStartupTimeout as ot, readCodexAppServerClientProcessIdentity as p, readRecentCodexRateLimits as q, captureSharedCodexAppServerCatalogLifetime as r, isCodexAppServerStartupError as rt, createIsolatedCodexAppServerClient as s, assertCodexAppServerClientStartSelectionCurrent as t, TURN_FINALIZE_DRAIN_ABORT_GRACE_MS as tt, isCodexAppServerStartSelectionChangedError as u, retainSharedCodexAppServerClientIfCurrent as v, CodexThreadClientReplacementError as w, withLeasedCodexAppServerClientStartSelectionRetry as x, shared_client_exports as y, isCodexAppServerLiveThreadClaimed as z };