@openclaw/codex 2026.10.1 → 2026.10.5-beta.1

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 (161) hide show
  1. package/dist/.setup/{account-usage-runtime-B7Vg4rmy.mjs → account-usage-runtime-QBZsvZS8.mjs} +8 -7
  2. package/dist/.setup/{app-server-policy-Bg4FZw1f.mjs → app-server-policy-D_zv8J7V.mjs} +3 -4
  3. package/dist/.setup/{apply-BzlIkqSz.mjs → apply-CBMV8LN0.mjs} +40 -51
  4. package/dist/.setup/{attempt-client-cleanup-HXQxfMc1.mjs → attempt-client-cleanup-t-kd_1ys.mjs} +6 -6
  5. package/dist/.setup/attempt-terminal-jO5IMj9K.mjs +2 -0
  6. package/dist/.setup/{attempt-workspace-context-BmCutoyg.mjs → attempt-workspace-context-CcwP3DA3.mjs} +21 -18
  7. package/dist/.setup/{auth-binding-BoMwpuPN.mjs → auth-binding-BaxlhaNx.mjs} +2 -2
  8. package/dist/.setup/{auth-cache-key-BCCQHWdc.mjs → auth-cache-key-DyfUvsSa.mjs} +30 -41
  9. package/dist/.setup/{binding-connection-C-08ez1w.mjs → binding-connection-B7HAAZSI.mjs} +2 -2
  10. package/dist/.setup/{binding-connection.runtime-Dn2p-fdy.mjs → binding-connection.runtime-DAXn7iFl.mjs} +6 -5
  11. package/dist/.setup/{bounded-turn-Cv4uIEzz.mjs → bounded-turn-CyQVQwGe.mjs} +21 -17
  12. package/dist/.setup/{bounded-turn-isolation-DklXNk3k.mjs → bounded-turn-isolation-BfDAo-qZ.mjs} +4 -4
  13. package/dist/.setup/{build-state-BwxNfFEB.mjs → build-state-CzLMy1S9.mjs} +1 -1
  14. package/dist/.setup/{capabilities-kQntafj_.mjs → capabilities-DbOzOglY.mjs} +1 -1
  15. package/dist/.setup/{client-catalog-response-BNFDYAKh.mjs → client-catalog-response-DsbEAtpd.mjs} +25 -32
  16. package/dist/.setup/{client-BIRVBXXb.mjs → client-y7nO6X9c.mjs} +198 -247
  17. package/dist/.setup/{command-dispatch-D3_ypl-R.mjs → command-dispatch-uA9lz2Kf.mjs} +3 -4
  18. package/dist/.setup/{command-formatters-DV3DHhdr.mjs → command-formatters-xW9KpoSZ.mjs} +16 -26
  19. package/dist/.setup/{command-handlers-KPit4G0p.mjs → command-handlers-VBaJnpZo.mjs} +270 -360
  20. package/dist/.setup/{command-rpc-CmQDOxY9.mjs → command-rpc-C9VxOLuG.mjs} +19 -18
  21. package/dist/.setup/{compact-CLLteFIY.mjs → compact-CD8xJxXS.mjs} +41 -61
  22. package/dist/.setup/{computer-use-BVxocZZc.mjs → computer-use-CiToXF5C.mjs} +109 -147
  23. package/dist/.setup/{config-0Gxk3_eq.mjs → config-C1YVVLEA.mjs} +32 -59
  24. package/dist/.setup/config-contracts.shared-D85SGEuq.mjs +4 -0
  25. package/dist/.setup/{config-options-HG_Rr3W_.mjs → config-options-DDzeNQ8m.mjs} +52 -90
  26. package/dist/.setup/{config-parsing-BQq-CHTF.mjs → config-parsing-DsWSCPHO.mjs} +19 -55
  27. package/dist/.setup/{config-runtime-cUYrqu_a.mjs → config-runtime-DWzK-k0n.mjs} +2 -2
  28. package/dist/.setup/{config-security-KAPScztc.mjs → config-security-clxAZYWX.mjs} +35 -39
  29. package/dist/.setup/config-utils-DN_YT7dE.mjs +47 -0
  30. package/dist/.setup/{context-engine-projection-CsgYSQhW.mjs → context-engine-projection-ps-yn_ci.mjs} +10 -22
  31. package/dist/.setup/{conversation-binding-DJ_288rC.mjs → conversation-binding-CTSLDM9S.mjs} +85 -119
  32. package/dist/.setup/{conversation-binding-data-DJ4ix-W5.mjs → conversation-binding-data-UgLuTSQT.mjs} +9 -8
  33. package/dist/.setup/{conversation-control-CuiZ_pDL.mjs → conversation-control-GXM3unE4.mjs} +7 -10
  34. package/dist/.setup/{cyber-failover-Bb1J6hS1.mjs → cyber-failover-D4dgNfFf.mjs} +2 -5
  35. package/dist/.setup/{cyber-failover-notice-XR03ef31.mjs → cyber-failover-notice-ljgGGL0s.mjs} +1 -1
  36. package/dist/.setup/{doctor-start-options-DPW9JxIE.mjs → doctor-start-options-JjTAl-q_.mjs} +5 -5
  37. package/dist/.setup/{dynamic-tool-build-DgWZMfAQ.mjs → dynamic-tool-build-D731PCdv.mjs} +57 -69
  38. package/dist/.setup/{dynamic-tools-Ct6GKAFr.mjs → dynamic-tools-D0pYbxHH.mjs} +689 -710
  39. package/dist/.setup/{effective-mcp-catalog-DmCSc8TS.mjs → effective-mcp-catalog-1hWFKghy.mjs} +11 -20
  40. package/dist/.setup/{elicitation-input-r9axtppm.mjs → elicitation-input-DXG_qaXr.mjs} +14 -20
  41. package/dist/.setup/{ephemeral-turn-_cBMKCFb.mjs → ephemeral-turn-Cphy5Qr_.mjs} +3 -3
  42. package/dist/.setup/{event-projector-assistant-message-C3Tpt370.mjs → event-projector-assistant-message-CLMKN4x-.mjs} +2 -2
  43. package/dist/.setup/{event-projector-usage-03R0I2dM.mjs → event-projector-usage-BpKfdoTm.mjs} +20 -33
  44. package/dist/.setup/{event-projector-values-DTqZHizf.mjs → event-projector-values-CLvG1Hil.mjs} +4 -5
  45. package/dist/.setup/history-rejection-B4nOXNXF.mjs +13 -0
  46. package/dist/.setup/{inference-context-D-9gWlTR.mjs → inference-context-DNlGwzwy.mjs} +10 -11
  47. package/dist/.setup/{inference-dispatch-B5UKEUyC.mjs → inference-dispatch-CO6tTs4q.mjs} +5 -4
  48. package/dist/.setup/{inference-metadata-CgIf7sOx.mjs → inference-metadata-DCvcG_N_.mjs} +36 -41
  49. package/dist/.setup/{inference-proxy-DUO5E2QQ.mjs → inference-proxy-BDWV0djM.mjs} +10 -14
  50. package/dist/.setup/{isolated-completion-CjrQEeke.mjs → isolated-completion-Bhqd2yBq.mjs} +8 -8
  51. package/dist/.setup/local-runtime-attribution-CZz2DJ4q.mjs +15 -0
  52. package/dist/.setup/{managed-binary-C1VFoVPf.mjs → managed-binary-BtIjV7yN.mjs} +16 -36
  53. package/dist/.setup/{mcp-app-session-preparation-D0yRoreX.mjs → mcp-app-session-preparation-DqSvxFqc.mjs} +24 -25
  54. package/dist/.setup/{mcp-tool-metadata-j10HhfTC.mjs → mcp-tool-metadata-DW41snf3.mjs} +1 -1
  55. package/dist/.setup/{model-catalog--G4arndd.mjs → model-catalog-B227ST3D.mjs} +6 -6
  56. package/dist/.setup/{models-BYbLQPnj.mjs → models-DdRyi93L.mjs} +6 -10
  57. package/dist/.setup/{native-auth-Cjb9y7IZ.mjs → native-auth-esN5MdIv.mjs} +5 -5
  58. package/dist/.setup/{native-execution-policy-ClzpdG3D.mjs → native-execution-policy-MXEe7PB3.mjs} +11 -28
  59. package/dist/.setup/native-hook-relay-BUWIOrSr.mjs +561 -0
  60. package/dist/.setup/{native-mcp-app-5i5eRCwO.mjs → native-mcp-app-CjxJQ4F7.mjs} +6 -6
  61. package/dist/.setup/native-skill-isolation-UMVoNjZz.mjs +391 -0
  62. package/dist/.setup/{native-subagent-monitor-B2C8D_N0.mjs → native-subagent-monitor-iHc8oLg5.mjs} +505 -639
  63. package/dist/.setup/{native-subagent-pending-assignments-BDqhOdJp.mjs → native-subagent-pending-assignments-DmVhedNs.mjs} +11 -23
  64. package/dist/.setup/{native-task-assignments-C6KVqiN1.mjs → native-task-assignments-DimsQ9Qa.mjs} +73 -27
  65. package/dist/.setup/{node-cli-sessions-B5oNDkUS.mjs → node-cli-sessions-CzKg2nGq.mjs} +18 -26
  66. package/dist/.setup/{node-exec-server.runtime-0xSEjKYt.mjs → node-exec-server.runtime-BWkULhBM.mjs} +5 -8
  67. package/dist/.setup/{plan-B5bDIEuQ.mjs → plan-C_F3aio0.mjs} +40 -50
  68. package/dist/.setup/{plugin-activation-BcyBv8PG.mjs → plugin-activation-D7WkJMvU.mjs} +4 -5
  69. package/dist/.setup/{plugin-app-cache-key-BW8rd98k.mjs → plugin-app-cache-key-Bg9DbDI6.mjs} +18 -23
  70. package/dist/.setup/{plugin-approval-roundtrip-C_SGp5YW.mjs → plugin-approval-roundtrip-BSV-51ig.mjs} +4 -6
  71. package/dist/.setup/{plugin-inventory-Bf0_piTw.mjs → plugin-inventory-CYgdo14P.mjs} +28 -43
  72. package/dist/.setup/{plugin-marketplace-discovery-SQPhSuic.mjs → plugin-marketplace-discovery-BblHM3DU.mjs} +7 -10
  73. package/dist/.setup/{plugin-metadata-cache-DWnB7VMj.mjs → plugin-metadata-cache-Bi8TAPwX.mjs} +5 -10
  74. package/dist/.setup/project-doc-thread-config-BVcvnps8.mjs +490 -0
  75. package/dist/.setup/{provider-BoIby-eX.mjs → provider-BJ4xhaGX.mjs} +4 -4
  76. package/dist/.setup/{provider-capabilities-B4yq6UgQ.mjs → provider-capabilities-CjRaV3bx.mjs} +1 -1
  77. package/dist/.setup/{rate-limits-CMPy24F5.mjs → rate-limits-CI8pTPqL.mjs} +15 -32
  78. package/dist/.setup/reasoning-effort-CS9kKWB9.mjs +37 -0
  79. package/dist/.setup/{request-DD3u22uv.mjs → request-Y8dmbqZ3.mjs} +28 -48
  80. package/dist/.setup/{rpc-error-hmWM21RB.mjs → rpc-error-C98SHchT.mjs} +3 -6
  81. package/dist/.setup/{run-attempt-DOVF5OON.mjs → run-attempt-Dx7a4Mfm.mjs} +927 -859
  82. package/dist/.setup/{run-attempt-lifecycle-BuZgVbDA.mjs → run-attempt-lifecycle-KN4oh-7O.mjs} +13 -4
  83. package/dist/.setup/{runtime-artifact-CUTOOnKw.mjs → runtime-artifact-C13pR7tD.mjs} +18 -22
  84. package/dist/.setup/{runtime-artifact-connection-CADz3_BY.mjs → runtime-artifact-connection-jS5DeCok.mjs} +3 -3
  85. package/dist/.setup/{sandbox-guard-WqE8yPge.mjs → sandbox-guard-DIImwCy1.mjs} +4 -6
  86. package/dist/.setup/service-tier-normalization-BPgw2Wdt.mjs +9 -0
  87. package/dist/.setup/{session-binding-Ce7BqiPN.mjs → session-binding-JEHNMPsr.mjs} +13 -40
  88. package/dist/.setup/{session-binding-record-BZB8RgcF.mjs → session-binding-record-DU_0biMD.mjs} +4 -4
  89. package/dist/.setup/{session-binding-record-codec-z4ZpDn6E.mjs → session-binding-record-codec-BpH8u_G9.mjs} +16 -39
  90. package/dist/.setup/{session-binding-sidecars-BrdV95Fg.mjs → session-binding-sidecars-DD-enC8w.mjs} +49 -54
  91. package/dist/.setup/{session-catalog-adoption-CPIP4S_y.mjs → session-catalog-adoption-Ca3OYGYM.mjs} +23 -27
  92. package/dist/.setup/{session-catalog-archive-DcgwvSbF.mjs → session-catalog-archive-Bv6gV7x9.mjs} +6 -6
  93. package/dist/.setup/{session-catalog-events-DRaivXvC.mjs → session-catalog-events-DzFlXNUe.mjs} +6 -5
  94. package/dist/.setup/{session-catalog-index-qwmgqC4t.mjs → session-catalog-index-DozvkUPd.mjs} +111 -105
  95. package/dist/.setup/{session-catalog-index-order-nhyO0wdW.mjs → session-catalog-index-order-CTfoefow.mjs} +28 -5
  96. package/dist/.setup/{session-catalog-limits-DEU36Qlo.mjs → session-catalog-limits-BynIoOYm.mjs} +1 -1
  97. package/dist/.setup/{session-catalog-list-request-tXephOB4.mjs → session-catalog-list-request-D4MYNgDB.mjs} +11 -8
  98. package/dist/.setup/{session-catalog-native-projection-z9Q608QW.mjs → session-catalog-native-projection-rCKnZud1.mjs} +5 -61
  99. package/dist/.setup/{session-catalog-node-adoption-7-WEQTB1.mjs → session-catalog-node-adoption-BdP9Zjqo.mjs} +2 -2
  100. package/dist/.setup/{session-catalog-node-continue-DLWBwAAO.mjs → session-catalog-node-continue-CNJibO4_.mjs} +27 -49
  101. package/dist/.setup/{session-catalog-node-lookup-Uufckwcm.mjs → session-catalog-node-lookup-BH_DBGa9.mjs} +3 -3
  102. package/dist/.setup/{session-catalog-parsing-B-qWJh2x.mjs → session-catalog-parsing-DkeoVn60.mjs} +9 -19
  103. package/dist/.setup/{session-catalog-projection-Cl0Nc7c6.mjs → session-catalog-projection-DDVmALHj.mjs} +8 -22
  104. package/dist/.setup/session-catalog-source-CygTGmrb.mjs +58 -0
  105. package/dist/.setup/{session-cli-kH4vuGod.mjs → session-cli-GwU0izn-.mjs} +20 -41
  106. package/dist/.setup/{session-history-BogBHKLk.mjs → session-history-BO6i_pfk.mjs} +1 -1
  107. package/dist/.setup/{session-history-import-NWKPa4ZO.mjs → session-history-import-CaO8s6ta.mjs} +4 -4
  108. package/dist/.setup/{session-history-read-CNN8zwbD.mjs → session-history-read-BI_2jRED.mjs} +4 -15
  109. package/dist/.setup/{session-history.worker-Cq_4DYgN.mjs → session-history.worker-DJQfek5p.mjs} +147 -159
  110. package/dist/.setup/{session-initialization-D6dtFQkE.mjs → session-initialization-Bi_2DKhc.mjs} +3 -5
  111. package/dist/.setup/{session-permission-policy-BxIUJ0Zd.mjs → session-permission-policy-CD2MAWU8.mjs} +12 -20
  112. package/dist/.setup/{session-retirement-Bt3b0fpe.mjs → session-retirement-IoS3zr17.mjs} +7 -7
  113. package/dist/.setup/{settled-turn-context-BZsMjkIO.mjs → settled-turn-context-BPL6D3RO.mjs} +1 -1
  114. package/dist/.setup/{settled-turn-finalizer-e_24O6HA.mjs → settled-turn-finalizer-X-Fylp-u.mjs} +12 -11
  115. package/dist/.setup/{shared-client-DeenOD8U.mjs → shared-client-ByIwuAC-.mjs} +172 -229
  116. package/dist/.setup/{side-question-BZHn_1Jm.mjs → side-question-BDUdozFy.mjs} +116 -137
  117. package/dist/.setup/{source-0ClinBHI.mjs → source-Bxbqf3S1.mjs} +37 -56
  118. package/dist/.setup/thread-archive-guard-LKdwQKyr.mjs +56 -0
  119. package/dist/.setup/{thread-lifecycle-CoqYpbpk.mjs → thread-lifecycle-run-CfP4PnEf.mjs} +348 -484
  120. package/dist/.setup/thread-model-selection-DcVebr8N.mjs +61 -0
  121. package/dist/.setup/{thread-ownership-CSDZ6mHd.mjs → thread-ownership-Be53aiaG.mjs} +5 -5
  122. package/dist/.setup/{thread-ownership-queue-Dp24d7-F.mjs → thread-ownership-queue-CeyYScUC.mjs} +5 -6
  123. package/dist/.setup/{thread-policy-DCC9lQjC.mjs → thread-policy-CHgY-KNl.mjs} +4 -4
  124. package/dist/.setup/thread-requests-BgzJwJtS.mjs +745 -0
  125. package/dist/.setup/{thread-resume--WOKWxZd.mjs → thread-resume-B2EmMcgE.mjs} +5 -5
  126. package/dist/.setup/{timeout-CXOfNoaX.mjs → timeout-D0mEWSGG.mjs} +6 -12
  127. package/dist/.setup/{transcript-history-projection-B9a7HwUV.mjs → transcript-history-projection-DfKcoZCB.mjs} +3 -4
  128. package/dist/.setup/{transcript-mirror-BfLRARNL.mjs → transcript-mirror-Bee2o6jj.mjs} +68 -68
  129. package/dist/.setup/{transcript-mirror-attestation-YSegaktH.mjs → transcript-mirror-attestation-BzUXnrvv.mjs} +5 -2
  130. package/dist/.setup/{transport-stdio-a0HDa2Mj.mjs → transport-stdio-CRWTkKOn.mjs} +67 -77
  131. package/dist/.setup/{transport-websocket-zqJ0Cmtn.mjs → transport-websocket-DIyPfkHo.mjs} +8 -16
  132. package/dist/.setup/{turn-router-BWhX_SBh.mjs → turn-router-DKDAziUW.mjs} +30 -31
  133. package/dist/.setup/upstream-prompt-provenance-Ccd9MFRJ.mjs +44 -0
  134. package/dist/.setup/{upstream-session-fork-BQvofnk7.mjs → upstream-session-fork-Djp_yssT.mjs} +50 -43
  135. package/dist/.setup/{usage-BEHcVwcZ.mjs → usage-DQA-peQC.mjs} +4 -4
  136. package/dist/.setup/{usage-limit-error-D1p3nE6n.mjs → usage-limit-error-2t3KBqiX.mjs} +12 -21
  137. package/dist/.setup/web-search-item-CvokaZOo.mjs +20 -0
  138. package/dist/.setup/{web-search-provider.runtime-CV9oiB-v.mjs → web-search-provider.runtime-BsuCMNix.mjs} +3 -3
  139. package/dist/.setup/{workspace-write-sandbox-probe-DmUHLrrl.mjs → workspace-write-sandbox-probe-BDWO2Qkh.mjs} +4 -4
  140. package/dist/api.js +15 -15
  141. package/dist/catalog-page.worker.js +1 -1
  142. package/dist/cli-metadata.js +1 -1
  143. package/dist/doctor-contract-api.js +5 -6
  144. package/dist/harness.js +32 -61
  145. package/dist/index.js +302 -416
  146. package/dist/media-understanding-provider.js +32 -43
  147. package/dist/migration-provider-api.js +1 -1
  148. package/dist/native-session-binding-api.js +1 -1
  149. package/dist/native-tool-policy.js +23 -1
  150. package/dist/provider-discovery.js +1 -1
  151. package/dist/session-history-worker-runtime.js +52 -31
  152. package/dist/session-history.worker.js +1 -1
  153. package/openclaw.plugin.json +20 -3
  154. package/package.json +7 -7
  155. package/dist/.setup/attempt-terminal-gZrxQ35N.mjs +0 -5
  156. package/dist/.setup/plugin-thread-config-deadline-CsScGgrk.mjs +0 -124
  157. package/dist/.setup/service-tier-normalization-Cei89SW6.mjs +0 -15
  158. package/dist/.setup/shell-dynamic-tools-BqGszXcq.mjs +0 -85
  159. package/dist/.setup/thread-archive-guard-C9frICzX.mjs +0 -60
  160. package/dist/.setup/thread-requests-Dwg2b4Xl.mjs +0 -2111
  161. package/dist/.setup/upstream-prompt-provenance-fXkKbPVC.mjs +0 -37
@@ -1,2111 +0,0 @@
1
- import { i as isJsonObject } from "./protocol-CANUwXJ3.mjs";
2
- import { u as fingerprintCodexPolicy } from "./config-security-KAPScztc.mjs";
3
- import { f as resolveCodexPluginsPolicy } from "./config-parsing-BQq-CHTF.mjs";
4
- import { n as resolveCodexAppServerLocalHomeDir } from "./auth-start-options-BPIPeEX8.mjs";
5
- import { d as readCodexEffectiveConfig, u as CODEX_SESSION_OVERRIDABLE_LAYER_TYPES } from "./config-options-HG_Rr3W_.mjs";
6
- import { a as defaultCodexAppInventoryCache, i as CodexAppInventoryCache, o as serializeCodexAppInventoryError, s as codexAppIdentityKey, t as buildCodexAppServerConnectionFingerprint } from "./plugin-app-cache-key-BW8rd98k.mjs";
7
- import { c as toCodexPluginOwnedAccountApp, o as readCodexPluginInventory } from "./plugin-inventory-Bf0_piTw.mjs";
8
- import "./config-0Gxk3_eq.mjs";
9
- import { t as isCodexAppServerNativeAuthProfile } from "./auth-profile-CgHQ8Vot.mjs";
10
- import { D as nativeHookRelayUnregisterQueue, W as readCodexClientSessionMeta } from "./shared-client-DeenOD8U.mjs";
11
- import { a as isCodexResponsesOAuthRun, i as isCodexResponsesOAuthCredential, t as CODEX_RESPONSES_OAUTH_PROVIDER } from "./responses-oauth-twnuTaAa.mjs";
12
- import { P as resolveCodexToolAbortTerminalReason } from "./client-BIRVBXXb.mjs";
13
- import { f as unsubscribeCodexThreadBestEffort, n as CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS } from "./attempt-client-cleanup-HXQxfMc1.mjs";
14
- import { t as ensureCodexPluginActivation } from "./plugin-activation-BcyBv8PG.mjs";
15
- import { a as hashCodexAppServerBindingFingerprint } from "./session-binding-Ce7BqiPN.mjs";
16
- import { t as codexNativeSubagentMonitorRuntime } from "./native-subagent-monitor-B2C8D_N0.mjs";
17
- import { normalizeOptionalString, normalizeUniqueStringEntries, normalizeUniqueTrimmedStringList } from "openclaw/plugin-sdk/string-coerce-runtime";
18
- import * as crypto$1 from "node:crypto";
19
- import crypto, { createHash } from "node:crypto";
20
- import { addTimerTimeoutGraceMs, finiteSecondsToTimerSafeMilliseconds } from "openclaw/plugin-sdk/number-runtime";
21
- import path from "node:path";
22
- import os from "node:os";
23
- import fs from "node:fs/promises";
24
- import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
25
- import { isPathInside } from "openclaw/plugin-sdk/file-access-runtime";
26
- import { resolveRequiredHomeDir, resolveStateDir } from "openclaw/plugin-sdk/state-paths";
27
- import { isIncognitoSessionKey } from "openclaw/plugin-sdk/session-key-runtime";
28
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
29
- import { escapeRegExp } from "openclaw/plugin-sdk/text-utility-runtime";
30
- import { emitTrustedDiagnosticEvent } from "openclaw/plugin-sdk/diagnostic-runtime";
31
- import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
32
- import { SKILL_WORKSHOP_TOOL_NAME, buildCredentialSafetyPrompt, buildDelegationGuidanceSection, buildSkillWorkshopPromptSection, buildUiPresentationPrompt, embeddedAgentLog, isHostScopedAgentToolActive, resolveMainSessionDelegationMode } from "openclaw/plugin-sdk/agent-harness-runtime";
33
- import { registerNativeHookRelayForBundledRuntime } from "openclaw/plugin-sdk/native-hook-relay-runtime";
34
- import { listRegisteredPluginAgentPromptGuidance } from "openclaw/plugin-sdk/plugin-runtime";
35
- import { buildHostnameAllowlistPolicyFromSuffixAllowlist } from "openclaw/plugin-sdk/ssrf-policy";
36
- //#region extensions/codex/src/app-server/plugin-app-approval-overrides.ts
37
- /** Projects ask approvals into the native session layer without changing saved settings. */
38
- function buildCodexAppApprovalOverrides(config, app) {
39
- const appsRoot = config.apps;
40
- const appConfig = isJsonObject(appsRoot) ? appsRoot[app.id] : void 0;
41
- if (!isJsonObject(appConfig)) return {};
42
- const overrides = {};
43
- const keys = app.approvalOverrideToolConfigKeys;
44
- for (const [section, fields] of [["tools", { approval_mode: "auto" }], ["links", {
45
- approvals_reviewer: "user",
46
- default_tools_approval_mode: "auto"
47
- }]]) {
48
- const entries = appConfig[section];
49
- if (!isJsonObject(entries)) continue;
50
- const projected = [];
51
- for (const [name, value] of Object.entries(entries).toSorted(([left], [right]) => left.localeCompare(right))) {
52
- if (!isJsonObject(value) || section === "tools" && keys && !keys.includes(name)) continue;
53
- if (Object.keys(fields).some((field) => value[field] !== void 0 && value[field] !== null)) projected.push([name, fields]);
54
- }
55
- if (projected.length > 0) overrides[section] = Object.fromEntries(projected);
56
- }
57
- return overrides;
58
- }
59
- //#endregion
60
- //#region extensions/codex/src/app-server/plugin-thread-app-admission.ts
61
- function resolveCodexPluginThreadAppCacheKey(params) {
62
- return params.threadId ? `${params.appCacheKey}:thread:${encodeURIComponent(params.threadId)}` : params.appCacheKey;
63
- }
64
- function createCodexPluginThreadAppInventoryRequest(params) {
65
- return async (method, requestParams) => await params.request(method, params.threadId ? {
66
- ...requestParams,
67
- threadId: params.threadId
68
- } : requestParams);
69
- }
70
- async function refreshCodexPluginAppInventory(params, appCache, options = {}) {
71
- if (!params.appCacheKey) return;
72
- const request = createCodexPluginThreadAppInventoryRequest(params);
73
- try {
74
- return await appCache.refreshNow({
75
- key: resolveCodexPluginThreadAppCacheKey(params),
76
- request,
77
- nowMs: params.nowMs,
78
- forceRefetch: options.forceRefetch,
79
- targetAppIds: options.targetAppIds
80
- });
81
- } catch (error) {
82
- embeddedAgentLog.warn("codex plugin thread config app inventory refresh failed", {
83
- reason: options.reason,
84
- forceRefetch: options.forceRefetch === true,
85
- error: serializeCodexAppInventoryError(error)
86
- });
87
- return;
88
- }
89
- }
90
- function collectCodexPluginOwnedAppIds(inventory) {
91
- return Array.from(new Set(inventory.records.flatMap((record) => record.ownedAppIds).filter(Boolean))).toSorted();
92
- }
93
- function collectCodexReservedPluginAppIds(params) {
94
- const reserved = new Set(params.inventory.records.flatMap((record) => record.appOwnership === "proven" ? record.ownedAppIds : []).map(codexAppIdentityKey));
95
- const recordsByConfigKey = new Map(params.inventory.records.map((record) => [record.policy.configKey, record]));
96
- const configuredOwnerNames = new Set(params.policy.pluginPolicies.flatMap((policy) => {
97
- const record = recordsByConfigKey.get(policy.configKey);
98
- return [
99
- policy.configKey,
100
- policy.pluginName,
101
- record?.summary.name,
102
- record?.summary.id
103
- ].filter((name) => Boolean(name)).map(normalizeCodexPluginOwnerName);
104
- }));
105
- for (const app of params.accountApps) if (app.pluginDisplayNames.some((name) => configuredOwnerNames.has(normalizeCodexPluginOwnerName(name)))) reserved.add(codexAppIdentityKey(app.id));
106
- return reserved;
107
- }
108
- function normalizeCodexPluginOwnerName(name) {
109
- return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "");
110
- }
111
- async function readCodexThreadAdmissibleAccountApps(params, appCache) {
112
- const request = createCodexPluginThreadAppInventoryRequest(params);
113
- const cachedInventory = appCache.read({
114
- key: resolveCodexPluginThreadAppCacheKey(params),
115
- request,
116
- nowMs: params.nowMs,
117
- suppressRefresh: true
118
- });
119
- const snapshot = cachedInventory.state === "fresh" && !cachedInventory.snapshot?.targetAppIds?.length ? cachedInventory.snapshot : await refreshCodexPluginAppInventory(params, appCache, {
120
- forceRefetch: false,
121
- reason: "account_apps_all",
122
- targetAppIds: []
123
- });
124
- if (!snapshot) return {
125
- apps: [],
126
- installedApps: [],
127
- diagnostic: {
128
- code: "account_app_inventory_unavailable",
129
- message: "Codex account app inventory was unavailable; account apps were not exposed."
130
- }
131
- };
132
- const installedAppsById = new Map(snapshot.installedApps.map((app) => [app.id, app]));
133
- return {
134
- apps: snapshot.apps.filter((app) => isCodexInstalledAppThreadAdmissible(installedAppsById.get(app.id))).toSorted((left, right) => left.id.localeCompare(right.id)),
135
- installedApps: snapshot.installedApps
136
- };
137
- }
138
- function isCodexPluginAppThreadAdmissible(app, inventory) {
139
- const snapshot = inventory.appInventory?.snapshot;
140
- if (!app.accessible || app.needsAuth || !snapshot) return false;
141
- return isCodexInstalledAppThreadAdmissible(snapshot.installedApps.find((candidate) => candidate.id === app.id));
142
- }
143
- function isCodexInstalledAppThreadAdmissible(installed) {
144
- return Boolean(installed && (installed.enabled && installed.callable || !installed.enabled && !installed.callable));
145
- }
146
- async function readCodexConfigForAppAdmission(params) {
147
- try {
148
- const response = await params.request("config/read", {
149
- includeLayers: true,
150
- ...params.configCwd ? { cwd: params.configCwd } : {}
151
- });
152
- if (!isJsonObject(response) || !isJsonObject(response.config) || !Array.isArray(response.layers)) throw new Error("Codex config/read omitted effective config or config layers");
153
- return {
154
- config: response.config,
155
- layers: response.layers.flatMap((layer) => {
156
- if (!isJsonObject(layer)) throw new Error("Codex config/read returned an invalid config layer");
157
- if (layer.disabledReason !== void 0 && layer.disabledReason !== null) {
158
- if (typeof layer.disabledReason !== "string") throw new Error("Codex config/read returned an invalid disabled layer");
159
- return [];
160
- }
161
- if (!isJsonObject(layer.config)) throw new Error("Codex config/read returned an invalid layer config");
162
- if (!isJsonObject(layer.name) || typeof layer.name.type !== "string") throw new Error("Codex config/read returned an invalid config layer source");
163
- if (layer.config.apps !== void 0 && !CODEX_SESSION_OVERRIDABLE_LAYER_TYPES.has(layer.name.type)) throw new Error(`Codex app policy cannot override ${layer.name.type}; move app settings to a supported user or project config layer before exposing native apps`);
164
- return [layer.config];
165
- })
166
- };
167
- } catch (error) {
168
- const details = serializeCodexAppInventoryError(error);
169
- embeddedAgentLog.warn("codex plugin app admission config read failed", { error: details });
170
- throw new Error(`Could not verify the Codex app allowlist: ${String(details.message)}. No native thread was started; resolve the native configuration error and retry.`, { cause: error });
171
- }
172
- }
173
- function resolveCodexExplicitAppEnablement(layersHighestPrecedenceFirst, appId) {
174
- for (const layer of layersHighestPrecedenceFirst) {
175
- const apps = layer.apps;
176
- const values = isJsonObject(apps) ? Object.entries(apps).filter(([id, app]) => codexAppIdentityKey(id) === codexAppIdentityKey(appId) && isJsonObject(app) && Object.hasOwn(app, "enabled")).map(([, app]) => isJsonObject(app) && app.enabled === true) : [];
177
- if (values.length > 0) return values.every(Boolean);
178
- }
179
- }
180
- function shouldForceRefreshCodexNotReadyPluginApps(params, policy, inventory) {
181
- if (!params.appCacheKey || !policy.pluginPolicies.some((plugin) => plugin.enabled) || inventory.appInventory?.state === "missing") return false;
182
- return inventory.records.some((record) => record.appOwnership === "proven" && record.ownedAppIds.length > 0 && (record.apps.length === 0 || record.apps.some((app) => !app.accessible)));
183
- }
184
- //#endregion
185
- //#region extensions/codex/src/app-server/plugin-thread-config.ts
186
- const CODEX_PLUGIN_THREAD_CONFIG_INPUT_FINGERPRINT_VERSION = 15;
187
- const CODEX_PLUGIN_THREAD_CONFIG_FINGERPRINT_VERSION = 2;
188
- function shouldBuildCodexPluginThreadConfig(pluginConfig) {
189
- return resolveCodexPluginsPolicy(pluginConfig).configured;
190
- }
191
- /** Fingerprints policy and app-cache identity before runtime inventory is read. */
192
- function buildCodexPluginThreadConfigInputFingerprint(params) {
193
- const policy = resolveCodexPluginsPolicy(params.pluginConfig);
194
- return fingerprintCodexPolicy({
195
- version: CODEX_PLUGIN_THREAD_CONFIG_INPUT_FINGERPRINT_VERSION,
196
- policy: policyFingerprint(policy),
197
- appCacheKey: params.appCacheKey ?? null
198
- });
199
- }
200
- /** Builds the deny-all app patch used when plugin discovery exceeds its turn budget. */
201
- function buildCodexPluginThreadConfigTimeoutFallback(params) {
202
- return {
203
- ...emptyPluginThreadConfig({
204
- enabled: true,
205
- inputFingerprint: buildCodexPluginThreadConfigInputFingerprint(params),
206
- configPatch: buildDisabledAppsConfigPatch()
207
- }),
208
- diagnostics: [{
209
- code: "plugin_config_timeout",
210
- message: params.message
211
- }]
212
- };
213
- }
214
- async function buildCodexPluginThreadConfig(params) {
215
- const appCache = params.appCache ?? defaultCodexAppInventoryCache;
216
- const threadAppCacheKey = resolveCodexPluginThreadAppCacheKey(params);
217
- const threadRequest = (method, requestParams) => params.request(method, (method === "app/installed" || method === "app/read") && params.threadId && isJsonObject(requestParams) ? {
218
- ...requestParams,
219
- threadId: params.threadId
220
- } : requestParams);
221
- let inputFingerprint = buildCodexPluginThreadConfigInputFingerprint({
222
- pluginConfig: params.pluginConfig,
223
- appCacheKey: params.appCacheKey
224
- });
225
- const policy = resolveCodexPluginsPolicy(params.pluginConfig);
226
- if (!policy.enabled) return emptyPluginThreadConfig({
227
- enabled: false,
228
- inputFingerprint,
229
- configPatch: buildDisabledAppsConfigPatch()
230
- });
231
- const readInventory = (suppressAppInventoryRefresh) => readCodexPluginInventory({
232
- pluginConfig: params.pluginConfig,
233
- policy,
234
- request: threadRequest,
235
- appCache,
236
- appCacheKey: params.appCacheKey,
237
- appInventoryCacheKey: threadAppCacheKey,
238
- configCwd: params.configCwd,
239
- metadataCache: params.metadataCache,
240
- nowMs: params.nowMs,
241
- suppressAppInventoryRefresh
242
- });
243
- let inventory = policy.pluginPolicies.length > 0 ? await readInventory(true) : {
244
- policy,
245
- records: [],
246
- diagnostics: []
247
- };
248
- const refreshInventory = async (options) => {
249
- await refreshCodexPluginAppInventory(params, appCache, {
250
- ...options,
251
- targetAppIds: collectCodexPluginOwnedAppIds(inventory)
252
- });
253
- inventory = await readInventory();
254
- inputFingerprint = buildCodexPluginThreadConfigInputFingerprint({
255
- pluginConfig: params.pluginConfig,
256
- appCacheKey: params.appCacheKey
257
- });
258
- };
259
- const activationRequired = inventory.records.some((record) => record.activationRequired);
260
- const appInventoryMissing = shouldRefreshMissingAppInventory(params, policy, inventory);
261
- const appInventoryRefreshDeferredForActivation = activationRequired && appInventoryMissing;
262
- if (!activationRequired && appInventoryMissing) await refreshInventory({
263
- forceRefetch: false,
264
- reason: "initial_missing"
265
- });
266
- const activationDiagnostics = [];
267
- const activationResults = [];
268
- for (const record of inventory.records) {
269
- if (!record.activationRequired) continue;
270
- const activation = await ensureCodexPluginActivation({
271
- identity: record.policy,
272
- request: threadRequest,
273
- appCache,
274
- appCacheKey: params.appCacheKey,
275
- appInventoryCacheKey: threadAppCacheKey,
276
- configCwd: params.configCwd,
277
- metadataCache: params.metadataCache,
278
- deferAppInventoryRefresh: true,
279
- targetAppIds: record.ownedAppIds
280
- });
281
- activationResults.push(activation);
282
- if (!activation.ok) activationDiagnostics.push({
283
- code: "plugin_activation_failed",
284
- plugin: record.policy,
285
- message: activation.diagnostics.map((item) => item.message).join(" ") || activation.reason
286
- });
287
- }
288
- const postInstallRefreshRequired = activationResults.some((activation) => activation.ok && activation.installAttempted);
289
- const deferredMissingRefreshRequired = appInventoryRefreshDeferredForActivation && !postInstallRefreshRequired && shouldRefreshMissingAppInventory(params, policy, inventory);
290
- if (postInstallRefreshRequired || deferredMissingRefreshRequired) await refreshInventory({
291
- forceRefetch: true,
292
- reason: postInstallRefreshRequired ? "post_install" : "deferred_missing"
293
- });
294
- if (shouldForceRefreshCodexNotReadyPluginApps(params, policy, inventory)) await refreshInventory({
295
- forceRefetch: true,
296
- reason: "not_ready_plugin_apps"
297
- });
298
- const accountAppsResult = policy.allowAllPlugins ? await readCodexThreadAdmissibleAccountApps(params, appCache) : {
299
- apps: [],
300
- installedApps: []
301
- };
302
- let appAdmissionConfig;
303
- const getAdmissionConfig = () => appAdmissionConfig ??= readCodexConfigForAppAdmission(params);
304
- const diagnostics = [
305
- ...inventory.diagnostics,
306
- ...activationDiagnostics,
307
- ...accountAppsResult.diagnostic ? [accountAppsResult.diagnostic] : []
308
- ];
309
- const provisionalAppIds = /* @__PURE__ */ new Set();
310
- const { apps } = buildDisabledAppsConfigPatch();
311
- const policyApps = {};
312
- const pluginAppIds = {};
313
- const pluginOwnedAppIds = collectCodexReservedPluginAppIds({
314
- policy: inventory.policy,
315
- inventory,
316
- accountApps: accountAppsResult.apps
317
- });
318
- const unresolvedDisabledPluginOwnership = policy.allowAllPlugins ? inventory.policy.pluginPolicies.find((pluginPolicy) => {
319
- const record = inventory.records.find((candidate) => candidate.policy.configKey === pluginPolicy.configKey);
320
- const disabledByMarketplacePolicy = record?.summary.availability === "DISABLED_BY_ADMIN" || record?.summary.installPolicy === "NOT_AVAILABLE";
321
- const unresolvedPluginIdentity = !record && inventory.diagnostics.some((diagnostic) => diagnostic.plugin?.configKey === pluginPolicy.configKey && (diagnostic.code === "plugin_disabled" || diagnostic.code === "plugin_missing" || diagnostic.code === "marketplace_missing"));
322
- return (!pluginPolicy.enabled || disabledByMarketplacePolicy || unresolvedPluginIdentity) && !record?.detail;
323
- }) : void 0;
324
- if (unresolvedDisabledPluginOwnership) diagnostics.push({
325
- code: "account_app_ownership_unavailable",
326
- plugin: unresolvedDisabledPluginOwnership,
327
- message: `Could not verify disabled Codex plugin app ownership for ${unresolvedDisabledPluginOwnership.pluginName}; account apps were not exposed.`
328
- });
329
- for (const record of inventory.records) {
330
- if (!record.policy.enabled) continue;
331
- const activation = activationResults.find((item) => item.identity.configKey === record.policy.configKey);
332
- if (activation?.ok === false || record.activationRequired && !activation?.ok) continue;
333
- if (record.appOwnership !== "proven") continue;
334
- pluginAppIds[record.policy.configKey] = [...record.ownedAppIds].toSorted();
335
- for (const app of inventory.appInventory?.state === "missing" ? [] : record.apps) {
336
- const admissionConfig = isCodexPluginAppThreadAdmissible(app, inventory) ? await getAdmissionConfig() : void 0;
337
- if (!admissionConfig || resolveCodexExplicitAppEnablement(admissionConfig.layers, app.id) === false) {
338
- diagnostics.push({
339
- code: "app_not_ready",
340
- plugin: record.policy,
341
- message: `${app.id} is not accessible for ${record.policy.pluginName}.`
342
- });
343
- continue;
344
- }
345
- provisionalAppIds.add(app.id);
346
- apps[app.id] = buildEnabledAppConfig(record.policy, record.policy.destructiveApprovalMode === "ask" ? buildCodexAppApprovalOverrides(admissionConfig.config, app) : void 0);
347
- policyApps[app.id] = {
348
- configKey: record.policy.configKey,
349
- marketplaceName: record.policy.marketplaceName,
350
- pluginName: record.policy.pluginName,
351
- allowDestructiveActions: record.policy.allowDestructiveActions,
352
- allowOpenWorld: true,
353
- destructiveApprovalMode: record.policy.destructiveApprovalMode,
354
- mcpServerNames: [...record.detail?.mcpServers ?? []].toSorted()
355
- };
356
- }
357
- }
358
- for (const app of unresolvedDisabledPluginOwnership ? [] : accountAppsResult.apps) {
359
- if (pluginOwnedAppIds.has(codexAppIdentityKey(app.id))) continue;
360
- const admissionConfig = await getAdmissionConfig();
361
- if (resolveCodexExplicitAppEnablement(admissionConfig.layers, app.id) === false) continue;
362
- const accountApp = toCodexPluginOwnedAccountApp(app, accountAppsResult.installedApps.find((installed) => installed.id === app.id));
363
- provisionalAppIds.add(app.id);
364
- apps[app.id] = buildEnabledAppConfig(policy, policy.destructiveApprovalMode === "ask" ? buildCodexAppApprovalOverrides(admissionConfig.config, accountApp) : void 0);
365
- policyApps[app.id] = {
366
- source: "account",
367
- appName: app.name,
368
- allowDestructiveActions: policy.allowDestructiveActions,
369
- allowOpenWorld: true,
370
- destructiveApprovalMode: policy.destructiveApprovalMode,
371
- mcpServerNames: []
372
- };
373
- }
374
- const configPatch = Object.keys(policyApps).length === 0 ? buildDisabledAppsConfigPatch() : disableUnlistedCodexApps({ apps }, (await getAdmissionConfig()).config);
375
- const policyContext = buildPluginAppPolicyContext(policyApps, pluginAppIds);
376
- return {
377
- enabled: true,
378
- configPatch,
379
- ...provisionalAppIds.size > 0 ? { provisionalAppIds: Array.from(provisionalAppIds).toSorted() } : {},
380
- fingerprint: fingerprintCodexPolicy({
381
- version: CODEX_PLUGIN_THREAD_CONFIG_FINGERPRINT_VERSION,
382
- inputFingerprint,
383
- configPatch,
384
- policyContext
385
- }),
386
- inputFingerprint,
387
- policyContext,
388
- inventory,
389
- diagnostics
390
- };
391
- }
392
- /** Deep-merges optional Codex thread config patches, returning undefined when empty. */
393
- function mergeCodexThreadConfigs(...configs) {
394
- let merged;
395
- for (const config of configs) {
396
- if (!config) continue;
397
- merged = mergeJsonObjects(merged ?? {}, normalizeShellEnvironmentOverrides(config));
398
- }
399
- return merged && Object.keys(merged).length > 0 ? merged : void 0;
400
- }
401
- function isCodexPluginThreadBindingStale(params) {
402
- if (!params.codexPluginsEnabled) return Boolean(params.bindingFingerprint || params.bindingInputFingerprint || params.hasBindingPolicyContext);
403
- if (!params.bindingFingerprint || !params.bindingInputFingerprint || !params.hasBindingPolicyContext) return true;
404
- return params.bindingInputFingerprint !== params.currentInputFingerprint;
405
- }
406
- function emptyPluginThreadConfig(params) {
407
- const policyContext = buildPluginAppPolicyContext({}, {});
408
- return {
409
- enabled: params.enabled,
410
- fingerprint: fingerprintCodexPolicy({
411
- version: CODEX_PLUGIN_THREAD_CONFIG_FINGERPRINT_VERSION,
412
- inputFingerprint: params.inputFingerprint,
413
- configPatch: params.configPatch ?? null,
414
- policyContext
415
- }),
416
- inputFingerprint: params.inputFingerprint,
417
- ...params.configPatch ? { configPatch: params.configPatch } : {},
418
- policyContext,
419
- diagnostics: []
420
- };
421
- }
422
- function buildDisabledAppsConfigPatch() {
423
- return {
424
- "features.apps": false,
425
- apps: { _default: {
426
- enabled: false,
427
- destructive_enabled: false,
428
- open_world_enabled: false
429
- } }
430
- };
431
- }
432
- function disableUnlistedCodexApps(configPatch, nativeConfig) {
433
- const apps = { ...configPatch.apps };
434
- for (const id of Object.keys(isJsonObject(nativeConfig.apps) ? nativeConfig.apps : {})) if (id !== "_default" && !Object.hasOwn(apps, id)) apps[id] = { enabled: false };
435
- return {
436
- ...configPatch,
437
- apps
438
- };
439
- }
440
- function buildEnabledAppConfig(policy, approvalOverrides = {}) {
441
- return {
442
- ...approvalOverrides,
443
- enabled: true,
444
- destructive_enabled: policy.allowDestructiveActions,
445
- open_world_enabled: policy.allowOpenWorld !== false,
446
- ...policy.destructiveApprovalMode === "ask" ? {
447
- default_tools_approval_mode: "auto",
448
- approvals_reviewer: "user"
449
- } : {}
450
- };
451
- }
452
- /** Rebuilds the safe per-thread apps patch persisted with a Codex thread binding. */
453
- function buildCodexPluginAppsConfigPatchFromPolicyContext(policyContext) {
454
- const disabledConfigPatch = buildDisabledAppsConfigPatch();
455
- const { apps } = disabledConfigPatch;
456
- for (const [appId, policy] of Object.entries(policyContext.apps).toSorted(([left], [right]) => left.localeCompare(right))) apps[appId] = buildEnabledAppConfig(policy);
457
- return Object.keys(policyContext.apps).length > 0 ? { apps } : disabledConfigPatch;
458
- }
459
- /** Projects current ask overrides before a side thread replays its bound app policy. */
460
- async function refreshCodexPluginAppApprovalPolicy(params) {
461
- if (Object.keys(params.policyContext.apps).length === 0) return {
462
- policyContext: params.policyContext,
463
- configPatch: buildDisabledAppsConfigPatch(),
464
- diagnostics: []
465
- };
466
- const targetApps = Object.entries(params.policyContext.apps).filter(([, app]) => app.destructiveApprovalMode === "ask").toSorted(([left], [right]) => left.localeCompare(right));
467
- const targetAppIds = targetApps.map(([id]) => id);
468
- const diagnostics = [];
469
- const readParams = {
470
- ...params,
471
- appCacheKey: "approval-policy-replay"
472
- };
473
- const [inventory, admissionConfig] = await Promise.all([targetAppIds.length > 0 ? refreshCodexPluginAppInventory(readParams, new CodexAppInventoryCache(), { targetAppIds }) : void 0, readCodexConfigForAppAdmission(readParams)]);
474
- const configPatch = disableUnlistedCodexApps(buildCodexPluginAppsConfigPatchFromPolicyContext(params.policyContext), admissionConfig.config);
475
- const currentApps = new Map(inventory?.apps.map((app) => [app.id, toCodexPluginOwnedAccountApp(app, inventory.installedApps.find((installed) => installed.id === app.id))]));
476
- const apps = { ...params.policyContext.apps };
477
- for (const [id, policy] of targetApps) {
478
- const app = currentApps.get(id);
479
- if (!app) diagnostics.push({
480
- code: "app_not_ready",
481
- message: `Could not verify current Codex app approval policy for ${id}; the app was not exposed.`
482
- });
483
- else {
484
- configPatch.apps[id] = buildEnabledAppConfig(policy, buildCodexAppApprovalOverrides(admissionConfig.config, app));
485
- continue;
486
- }
487
- delete apps[id];
488
- configPatch.apps[id] = { enabled: false };
489
- }
490
- return {
491
- policyContext: buildPluginAppPolicyContext(apps, Object.fromEntries(Object.entries(params.policyContext.pluginAppIds).map(([key, ids]) => [key, ids.filter((id) => Object.hasOwn(apps, id))]))),
492
- configPatch,
493
- diagnostics
494
- };
495
- }
496
- function buildPluginAppPolicyContext(apps, pluginAppIds) {
497
- return {
498
- fingerprint: fingerprintCodexPolicy({
499
- version: 2,
500
- apps,
501
- pluginAppIds
502
- }),
503
- apps,
504
- pluginAppIds
505
- };
506
- }
507
- function shouldRefreshMissingAppInventory(params, policy, inventory) {
508
- return Boolean(params.appCacheKey && policy.pluginPolicies.some((plugin) => plugin.enabled) && inventory.appInventory?.state === "missing");
509
- }
510
- function policyFingerprint(policy) {
511
- return {
512
- enabled: policy.enabled,
513
- allowAllPlugins: policy.allowAllPlugins,
514
- allowDestructiveActions: policy.allowDestructiveActions,
515
- destructiveApprovalMode: policy.destructiveApprovalMode,
516
- plugins: policy.pluginPolicies.map((plugin) => ({
517
- configKey: plugin.configKey,
518
- marketplaceName: plugin.marketplaceName,
519
- pluginName: plugin.pluginName,
520
- enabled: plugin.enabled,
521
- allowDestructiveActions: plugin.allowDestructiveActions,
522
- destructiveApprovalMode: plugin.destructiveApprovalMode
523
- }))
524
- };
525
- }
526
- function normalizeShellEnvironmentOverrides(config) {
527
- let normalized = { ...config };
528
- for (const [key, value] of Object.entries(config)) {
529
- if (!key.startsWith("shell_environment_policy.")) continue;
530
- delete normalized[key];
531
- let patch = value;
532
- for (const segment of key.split(".").toReversed()) patch = { [segment]: patch };
533
- normalized = mergeJsonObjects(normalized, patch);
534
- }
535
- return normalized;
536
- }
537
- function mergeJsonObjects(left, right) {
538
- const merged = {
539
- ...left,
540
- ...right
541
- };
542
- for (const [key, value] of Object.entries(right)) {
543
- const existing = left[key];
544
- if (Object.hasOwn(left, key) && isJsonObject(existing) && isJsonObject(value)) merged[key] = mergeJsonObjects(existing, value);
545
- }
546
- return merged;
547
- }
548
- //#endregion
549
- //#region extensions/codex/src/app-server/dynamic-tool-profile.ts
550
- /** Tool names owned by Codex app-server and normally excluded from OpenClaw dynamic tools. */
551
- const CODEX_APP_SERVER_OWNED_DYNAMIC_TOOL_EXCLUDES = [
552
- "read",
553
- "write",
554
- "edit",
555
- "apply_patch",
556
- "exec",
557
- "process",
558
- "update_plan",
559
- "tool_call",
560
- "tool_describe",
561
- "tool_search"
562
- ];
563
- const CODEX_NATIVE_GOAL_TOOL_EXCLUDES = [
564
- "get_goal",
565
- "create_goal",
566
- "update_goal"
567
- ];
568
- const CODEX_APP_SERVER_OWNED_REPLACEABLE_TOOL_EXCLUDES = /* @__PURE__ */ new Set([
569
- "read",
570
- "write",
571
- "edit",
572
- "apply_patch",
573
- ...CODEX_NATIVE_GOAL_TOOL_EXCLUDES
574
- ]);
575
- const CODEX_APP_SERVER_OWNED_SHELL_TOOL_EXCLUDES = /* @__PURE__ */ new Set(["exec", "process"]);
576
- const DYNAMIC_TOOL_NAME_ALIASES = {
577
- bash: "exec",
578
- "apply-patch": "apply_patch"
579
- };
580
- function normalizeCodexDynamicToolName(name) {
581
- const normalized = name.trim().toLowerCase();
582
- return DYNAMIC_TOOL_NAME_ALIASES[normalized] ?? normalized;
583
- }
584
- /** True only for the host-scoped OpenClaw run's exact tool contract. */
585
- function isSystemAgentOnlyCodexDynamicToolAllowlist(toolsAllow) {
586
- return toolsAllow?.length === 1 && normalizeCodexDynamicToolName(toolsAllow[0] ?? "") === "openclaw";
587
- }
588
- /** True when a private source reply may use the message delivery tool only. */
589
- function isMessageOnlyCodexSourceReply(params) {
590
- return params.sourceReplyDeliveryMode === "message_tool_only" && params.toolsAllow?.length === 1 && normalizeCodexDynamicToolName(params.toolsAllow[0] ?? "") === "message";
591
- }
592
- function isForcedPrivateQaCodexRuntime(env = process.env) {
593
- return env.OPENCLAW_BUILD_PRIVATE_QA === "1" && env.OPENCLAW_QA_FORCE_RUNTIME?.trim().toLowerCase() === "codex";
594
- }
595
- function resolveCodexDynamicToolsLoading(config, env = process.env) {
596
- return isForcedPrivateQaCodexRuntime(env) ? "direct" : config.codexDynamicToolsLoading ?? "searchable";
597
- }
598
- /** Returns true for models whose tool-search path is unsupported or inefficient. */
599
- function shouldDisableCodexToolSearchForModel(modelId) {
600
- return modelId?.trim().toLowerCase().split("/").at(-1) === "gpt-5.4-nano";
601
- }
602
- /** Resolves dynamic-tool loading for the app-server connection that will execute the turn. */
603
- function resolveCodexDynamicToolsLoadingForRuntime(config, modelId, options = {}, env = process.env) {
604
- const loading = resolveCodexDynamicToolsLoading(config, env);
605
- return loading === "searchable" && (shouldDisableCodexToolSearchForModel(modelId) || options.connectionClass === "remote") ? "direct" : loading;
606
- }
607
- /** Filters OpenClaw tools that Codex owns natively or config explicitly excludes. */
608
- function filterCodexDynamicTools(tools, config, env = process.env) {
609
- return filterCodexDynamicToolsWithOptions(tools, config, env, {
610
- preserveOpenClawReplacements: false,
611
- preserveOpenClawShell: false
612
- });
613
- }
614
- /** Keeps OpenClaw coding tools that replace a disabled Codex native surface. */
615
- function filterCodexDynamicToolsForDisabledNativeSurface(tools, config, options, env = process.env) {
616
- return filterCodexDynamicToolsWithOptions(tools, config, env, {
617
- preserveOpenClawReplacements: true,
618
- preserveOpenClawShell: options.preserveShell
619
- });
620
- }
621
- function filterCodexDynamicToolsWithOptions(tools, config, env, options) {
622
- const excludes = /* @__PURE__ */ new Set();
623
- if (!options.preserveOpenClawReplacements) for (const name of CODEX_NATIVE_GOAL_TOOL_EXCLUDES) excludes.add(name);
624
- if (isForcedPrivateQaCodexRuntime(env)) excludes.add("apply_patch");
625
- else for (const name of CODEX_APP_SERVER_OWNED_DYNAMIC_TOOL_EXCLUDES) {
626
- if (options.preserveOpenClawReplacements && CODEX_APP_SERVER_OWNED_REPLACEABLE_TOOL_EXCLUDES.has(name)) continue;
627
- if (options.preserveOpenClawShell && CODEX_APP_SERVER_OWNED_SHELL_TOOL_EXCLUDES.has(name)) continue;
628
- excludes.add(name);
629
- }
630
- for (const name of config.codexDynamicToolsExclude ?? []) {
631
- const trimmed = normalizeCodexDynamicToolName(name);
632
- if (trimmed) excludes.add(trimmed);
633
- }
634
- return excludes.size === 0 ? tools : tools.filter((tool) => !excludes.has(normalizeCodexDynamicToolName(tool.name)));
635
- }
636
- //#endregion
637
- //#region extensions/codex/src/app-server/thread-binding-policy.ts
638
- function shouldRotateCodexAppServerBindingForRuntime(params) {
639
- if (!params.current) return false;
640
- if (params.binding === params.current) return false;
641
- return params.connectionClass === "remote" || Boolean(params.binding);
642
- }
643
- function resolveCodexGpt56MultiAgentVersion(modelRef) {
644
- let modelId = modelRef?.trim().toLowerCase();
645
- if (!modelId) return;
646
- const slashIndex = modelId.indexOf("/");
647
- if (slashIndex > 0) {
648
- const provider = modelId.slice(0, slashIndex);
649
- if (provider !== "openai" && provider !== "codex") return;
650
- modelId = modelId.slice(slashIndex + 1);
651
- }
652
- if (modelId === "gpt-5.6-sol" || modelId === "gpt-5.6-terra") return "v2";
653
- return modelId === "gpt-5.6-luna" ? "v1" : void 0;
654
- }
655
- function shouldRotateCodexGpt56MultiAgentBinding(params) {
656
- const bindingVersion = resolveCodexGpt56MultiAgentVersion(params.bindingModel);
657
- const requestedVersion = resolveCodexGpt56MultiAgentVersion(params.requestedModel);
658
- return Boolean(bindingVersion && requestedVersion && bindingVersion !== requestedVersion);
659
- }
660
- function isTransientWebSearchRestriction(params) {
661
- if (params.nativeProviderWebSearchSupport === "unknown") return true;
662
- if (params.params.config?.tools?.web?.search?.enabled === false) return false;
663
- if (params.params.disableTools === true) return true;
664
- const persistentWebSearchRestriction = params.webSearchAllowed === false && params.persistentWebSearchAllowed === false;
665
- if (params.nativeCodeModeEnabled === false && !persistentWebSearchRestriction) return true;
666
- if (params.webSearchAllowed !== false) return false;
667
- if (params.persistentWebSearchAllowed !== void 0) return params.persistentWebSearchAllowed;
668
- if (params.params.toolsAllow === void 0) return false;
669
- return !params.params.toolsAllow.some((name) => {
670
- const normalized = normalizeCodexDynamicToolName(name);
671
- return normalized === "*" || normalized === "web_search";
672
- });
673
- }
674
- function shouldRecheckRecoverablePluginBinding(params) {
675
- if (!params.pluginThreadConfig?.enabled) return false;
676
- if (!params.binding.pluginAppsFingerprint || !params.binding.pluginAppsInputFingerprint || params.binding.pluginAppsInputFingerprint !== params.pluginThreadConfig.inputFingerprint) return false;
677
- const policyContext = params.binding.pluginAppPolicyContext;
678
- if (!policyContext) return false;
679
- const enabledPluginConfigKeys = params.pluginThreadConfig.enabledPluginConfigKeys ?? [];
680
- const recoverablePluginConfigKeys = params.pluginThreadConfig.recoverablePluginConfigKeys ?? enabledPluginConfigKeys;
681
- const recoverablePluginConfigKeySet = new Set(recoverablePluginConfigKeys);
682
- const bindingContainsSettledPlugin = enabledPluginConfigKeys.filter((configKey) => !recoverablePluginConfigKeySet.has(configKey)).some((configKey) => (policyContext.pluginAppIds[configKey]?.length ?? 0) > 0 || Object.values(policyContext.apps).some((app) => app.source !== "account" && app.configKey === configKey));
683
- const accountAppRecoveryEnabled = params.pluginThreadConfig.accountAppRecoveryEnabled ?? enabledPluginConfigKeys.length === 0;
684
- return bindingContainsSettledPlugin || accountAppRecoveryEnabled && Object.keys(policyContext.apps).length === 0 || recoverablePluginConfigKeys.length > 0;
685
- }
686
- //#endregion
687
- //#region extensions/codex/src/app-server/thread-fingerprints.ts
688
- function codexDynamicToolsFingerprint(dynamicTools) {
689
- return hashCodexAppServerBindingFingerprint(codexLegacyDynamicToolsFingerprint(dynamicTools));
690
- }
691
- function areCodexDynamicToolFingerprintsCompatible(params) {
692
- return !params.previous || params.previous === params.next || params.previous === params.nextLegacy;
693
- }
694
- function codexLegacyDynamicToolsFingerprint(dynamicTools) {
695
- return JSON.stringify(dynamicTools.map(stabilizeJsonValue).toSorted(compareJsonFingerprint));
696
- }
697
- function legacyFingerprintUserMcpServersConfigPatch(configPatch) {
698
- return configPatch ? JSON.stringify(stabilizeJsonValue(configPatch)) : void 0;
699
- }
700
- function fingerprintUserMcpServersConfigPatch(configPatch) {
701
- return configPatch ? hashCodexAppServerBindingFingerprint(JSON.stringify(stabilizeJsonValue(redactUserMcpServersFingerprintSecrets(configPatch)))) : void 0;
702
- }
703
- function redactUserMcpServersFingerprintSecrets(value) {
704
- if (Array.isArray(value)) return value.map(redactUserMcpServersFingerprintSecrets);
705
- if (!value || typeof value !== "object") return value;
706
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
707
- if (key === "http_headers" && entry && typeof entry === "object" && !Array.isArray(entry)) return [key, Object.fromEntries(Object.entries(entry).map(([header, headerValue]) => [header, header.toLowerCase() === "authorization" ? fingerprintUserMcpServersAuthorizationHeader(headerValue) : headerValue]))];
708
- return [key, redactUserMcpServersFingerprintSecrets(entry)];
709
- }));
710
- }
711
- function fingerprintUserMcpServersAuthorizationHeader(value) {
712
- return typeof value === "string" && value.length > 0 ? `<redacted:sha256:${crypto$1.createHash("sha256").update(value).digest("hex")}>` : "<redacted>";
713
- }
714
- function fingerprintJsonObject(value) {
715
- return JSON.stringify(stabilizeJsonValue(value));
716
- }
717
- /** Hash thread-creation identity; settings already applied by turn/start must not restart Codex. */
718
- function fingerprintCodexThreadConfig(request, authProfileId, dynamicToolsFingerprint) {
719
- return hashCodexAppServerBindingFingerprint(fingerprintJsonObject({
720
- authProfileId: authProfileId ?? null,
721
- dynamicToolsFingerprint: dynamicToolsFingerprint ?? null,
722
- nativeMultiAgentVersion: resolveCodexGpt56MultiAgentVersion(typeof request.requestedModel === "string" ? request.requestedModel : typeof request.model === "string" ? request.model : void 0) ?? null,
723
- modelProvider: request.modelProvider ?? null,
724
- requestedModelProvider: request.requestedModelProvider === void 0 ? request.modelProvider ?? null : request.requestedModelProvider,
725
- permissions: request.permissions ?? null,
726
- baseInstructions: request.baseInstructions ?? null,
727
- developerInstructions: request.developerInstructions ?? null,
728
- config: request.config ?? {}
729
- }));
730
- }
731
- function fingerprintEnvironmentSelection(environments) {
732
- return environments ? JSON.stringify(environments.map(stabilizeJsonValue)) : void 0;
733
- }
734
- function stabilizeJsonValue(value) {
735
- if (Array.isArray(value)) return value.map(stabilizeJsonValue);
736
- if (!isJsonObject(value)) return value;
737
- return Object.fromEntries(Object.entries(value).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stabilizeJsonValue(child)]));
738
- }
739
- function readActiveCodexTurnIdsFromResume(response) {
740
- return (response.initialTurnsPage?.data ?? response.thread.turns ?? []).filter((turn) => turn.status === "inProgress" && turn.id.trim().length > 0).map((turn) => turn.id);
741
- }
742
- const LEGACY_EMPTY_DYNAMIC_TOOLS_FINGERPRINT = codexLegacyDynamicToolsFingerprint([]);
743
- const EMPTY_DYNAMIC_TOOLS_FINGERPRINT = hashCodexAppServerBindingFingerprint(LEGACY_EMPTY_DYNAMIC_TOOLS_FINGERPRINT);
744
- function areUserMcpServersFingerprintsCompatible(params) {
745
- return params.previous === params.next || params.previous === params.nextLegacy || params.nextLegacy !== void 0 && params.previous === hashCodexAppServerBindingFingerprint(params.nextLegacy);
746
- }
747
- function shouldStartTransientNoToolThread(params) {
748
- return Boolean(params.previous && !isEmptyDynamicToolsFingerprint(params.previous) && !params.nextHasDynamicTools);
749
- }
750
- function isEmptyDynamicToolsFingerprint(fingerprint) {
751
- return fingerprint === EMPTY_DYNAMIC_TOOLS_FINGERPRINT || fingerprint === LEGACY_EMPTY_DYNAMIC_TOOLS_FINGERPRINT;
752
- }
753
- function compareJsonFingerprint(left, right) {
754
- return JSON.stringify(left).localeCompare(JSON.stringify(right));
755
- }
756
- //#endregion
757
- //#region extensions/codex/src/app-server/native-skill-isolation.ts
758
- const MAX_PERSONAL_SKILL_DIRECTORIES = 2e3;
759
- const MAX_PERSONAL_SKILL_DEPTH = 6;
760
- const MAX_PERSONAL_SKILL_ENTRIES = 1e4;
761
- const nativeSkillIsolationByClient = /* @__PURE__ */ new WeakMap();
762
- function isMissingPathError(error) {
763
- return error.code === "ENOENT";
764
- }
765
- async function canonicalizeExistingPath(candidate) {
766
- try {
767
- return await fs.realpath(candidate);
768
- } catch {
769
- return path.resolve(candidate);
770
- }
771
- }
772
- async function usesDefaultStateDir() {
773
- if (!process.env.OPENCLAW_STATE_DIR?.trim()) return true;
774
- const home = resolveRequiredHomeDir();
775
- const [stateDir, defaultStateDir] = await Promise.all([canonicalizeExistingPath(resolveStateDir()), canonicalizeExistingPath(path.join(home, ".openclaw"))]);
776
- return stateDir === defaultStateDir;
777
- }
778
- async function collectPersonalSkillRealPaths(homes, codexHome) {
779
- const realStateDir = await canonicalizeExistingPath(resolveStateDir());
780
- const roots = [];
781
- for (const home of homes) {
782
- for (const dir of [".agents", ".claude"]) roots.push({
783
- dir: path.join(home, dir, "skills"),
784
- onlyEscapedStateTargets: false
785
- });
786
- const defaultCodexHome = path.join(home, ".codex");
787
- const realDefaultCodexHome = await canonicalizeExistingPath(defaultCodexHome);
788
- roots.push({
789
- dir: path.join(defaultCodexHome, "skills"),
790
- onlyEscapedStateTargets: isPathInside(realStateDir, realDefaultCodexHome)
791
- });
792
- }
793
- const configuredCodexHome = codexHome?.trim() || process.env.CODEX_HOME?.trim();
794
- if (configuredCodexHome) {
795
- const realCodexHome = await canonicalizeExistingPath(configuredCodexHome);
796
- const stateOwned = isPathInside(realStateDir, realCodexHome);
797
- roots.push({
798
- dir: path.join(configuredCodexHome, "skills"),
799
- onlyEscapedStateTargets: stateOwned
800
- });
801
- }
802
- const skillPaths = /* @__PURE__ */ new Set();
803
- let complete = true;
804
- const seenDirectories = /* @__PURE__ */ new Set();
805
- const queue = roots.map((root) => ({
806
- dir: root.dir,
807
- onlyEscapedStateTargets: root.onlyEscapedStateTargets,
808
- depth: 0
809
- }));
810
- let entryCount = 0;
811
- const recordSkillFile = async (filePath, onlyEscapedStateTargets) => {
812
- try {
813
- const skillRealPath = await fs.realpath(filePath);
814
- if (!onlyEscapedStateTargets || !isPathInside(realStateDir, skillRealPath)) skillPaths.add(skillRealPath);
815
- } catch (error) {
816
- if (!isMissingPathError(error)) complete = false;
817
- }
818
- };
819
- for (const current of queue) {
820
- let realDir;
821
- try {
822
- realDir = await fs.realpath(current.dir);
823
- } catch (error) {
824
- if (isMissingPathError(error)) continue;
825
- complete = false;
826
- continue;
827
- }
828
- if (seenDirectories.has(realDir)) continue;
829
- seenDirectories.add(realDir);
830
- if (seenDirectories.size > MAX_PERSONAL_SKILL_DIRECTORIES) {
831
- complete = false;
832
- break;
833
- }
834
- let directory;
835
- try {
836
- directory = await fs.opendir(current.dir);
837
- } catch (error) {
838
- if (!isMissingPathError(error)) complete = false;
839
- continue;
840
- }
841
- try {
842
- for await (const entry of directory) {
843
- entryCount += 1;
844
- if (entryCount > MAX_PERSONAL_SKILL_ENTRIES) {
845
- complete = false;
846
- queue.length = 0;
847
- break;
848
- }
849
- if (entry.name.startsWith(".")) continue;
850
- const entryPath = path.join(current.dir, entry.name);
851
- let isFile = entry.isFile();
852
- let isDirectory = entry.isDirectory();
853
- if (entry.isSymbolicLink()) try {
854
- const stat = await fs.stat(entryPath);
855
- isFile = stat.isFile();
856
- isDirectory = stat.isDirectory();
857
- } catch (error) {
858
- if (!isMissingPathError(error)) complete = false;
859
- continue;
860
- }
861
- if (entry.name === "SKILL.md" && isFile) {
862
- await recordSkillFile(entryPath, current.onlyEscapedStateTargets);
863
- continue;
864
- }
865
- if (isDirectory) {
866
- if (current.depth >= MAX_PERSONAL_SKILL_DEPTH) complete = false;
867
- else queue.push({
868
- dir: entryPath,
869
- depth: current.depth + 1,
870
- onlyEscapedStateTargets: current.onlyEscapedStateTargets
871
- });
872
- }
873
- }
874
- } catch (error) {
875
- if (!isMissingPathError(error)) complete = false;
876
- }
877
- }
878
- return {
879
- complete,
880
- skillPaths
881
- };
882
- }
883
- /** Resolves the native user-scope skills that an isolated OpenClaw thread must disable. */
884
- async function resolveCodexNativeSkillIsolation(params) {
885
- params.signal?.throwIfAborted();
886
- if (!process.env.OPENCLAW_STATE_DIR?.trim()) return;
887
- const key = JSON.stringify([
888
- path.resolve(resolveStateDir()),
889
- path.resolve(params.cwd),
890
- params.codexHome?.trim() || process.env.CODEX_HOME?.trim() || "",
891
- params.home?.trim() || process.env.HOME?.trim() || "",
892
- params.userProfile?.trim() || process.env.USERPROFILE?.trim() || ""
893
- ]);
894
- let cache = nativeSkillIsolationByClient.get(params.client);
895
- if (!cache) {
896
- cache = { revision: 0 };
897
- nativeSkillIsolationByClient.set(params.client, cache);
898
- const clientCache = cache;
899
- params.client.addNotificationHandler((notification) => {
900
- if (notification.method === "skills/changed") {
901
- clientCache.revision += 1;
902
- clientCache.snapshot = void 0;
903
- }
904
- });
905
- }
906
- for (;;) {
907
- params.signal?.throwIfAborted();
908
- let snapshot = cache.snapshot;
909
- if (snapshot?.key !== key || !snapshot.settled && snapshot.signal !== params.signal) {
910
- snapshot = {
911
- key,
912
- revision: cache.revision,
913
- result: resolveUncachedCodexNativeSkillIsolation(params),
914
- settled: false,
915
- signal: params.signal
916
- };
917
- cache.snapshot = snapshot;
918
- }
919
- try {
920
- const isolation = await snapshot.result;
921
- snapshot.settled = true;
922
- params.signal?.throwIfAborted();
923
- if (snapshot.revision === cache.revision) return isolation;
924
- } catch (error) {
925
- if (cache.snapshot === snapshot) cache.snapshot = void 0;
926
- throw error;
927
- }
928
- }
929
- }
930
- async function resolveUncachedCodexNativeSkillIsolation(params) {
931
- if (await usesDefaultStateDir()) return;
932
- const response = await params.client.request("skills/list", {
933
- cwds: [params.cwd],
934
- forceReload: true
935
- }, { signal: params.signal });
936
- const homes = [params.home?.trim() || process.env.HOME?.trim() || process.env.USERPROFILE?.trim() || os.homedir()];
937
- if (process.platform === "win32") homes.push(params.userProfile?.trim() || os.homedir());
938
- const { complete, skillPaths } = await collectPersonalSkillRealPaths([...new Set(homes.map((home) => path.resolve(home)))], params.codexHome);
939
- if (!complete) {
940
- for (const entry of response.data) for (const skill of entry.skills) if (skill.scope === "user") skillPaths.add(skill.path);
941
- }
942
- return { disabledUserSkillPaths: [...skillPaths].toSorted((left, right) => left.localeCompare(right)) };
943
- }
944
- /** Applies path-exact session rules after caller config so isolated user skills stay disabled. */
945
- function applyCodexNativeSkillIsolation(config, isolation) {
946
- if (!isolation) return config;
947
- const existingRules = config?.["skills.config"];
948
- if (existingRules !== void 0 && !Array.isArray(existingRules)) throw new Error("Codex thread skills.config must be an array");
949
- const disabledRules = isolation.disabledUserSkillPaths.map((skillPath) => ({
950
- path: skillPath,
951
- enabled: false
952
- }));
953
- return {
954
- ...config,
955
- "skills.include_instructions": false,
956
- "skills.config": [...existingRules ?? [], ...disabledRules]
957
- };
958
- }
959
- //#endregion
960
- //#region extensions/codex/src/app-server/native-tool-catalog.ts
961
- function hasCodexNativeToolCatalog(binding) {
962
- return binding?.connectionScope === "supervision" && !binding.pendingSupervisionBranch;
963
- }
964
- /** Pinned serde omits empty catalogs and false deferLoading; declarations remain native-owned. */
965
- function parseCodexNativeToolCatalog(metadata, threadId, fingerprint) {
966
- const fail = () => /* @__PURE__ */ new Error("The canonical Codex native tool catalog is missing, corrupt, or changed; the thread is preserved. Reconnect and inspect its native metadata before retrying.");
967
- if (!isJsonObject(metadata) || metadata.id !== threadId) throw fail();
968
- const catalog = metadata.dynamic_tools ?? [];
969
- if (!Array.isArray(catalog) || Buffer.byteLength(JSON.stringify(catalog)) > 1048576) throw fail();
970
- const names = /* @__PURE__ */ new Set();
971
- const namespaces = /* @__PURE__ */ new Set();
972
- const validName = (name) => typeof name === "string" && /^[a-zA-Z0-9_-]{1,128}$/u.test(name);
973
- const readFunction = (value) => {
974
- if (!isJsonObject(value) || value.type !== "function" || !validName(value.name) || typeof value.description !== "string" || !isJsonObject(value.inputSchema) || value.deferLoading !== void 0 && typeof value.deferLoading !== "boolean" || Object.keys(value).some((key) => ![
975
- "type",
976
- "name",
977
- "description",
978
- "inputSchema",
979
- "deferLoading"
980
- ].includes(key)) || names.has(value.name) || names.size >= 2e3) throw fail();
981
- names.add(value.name);
982
- return {
983
- type: "function",
984
- name: value.name,
985
- description: value.description,
986
- inputSchema: structuredClone(value.inputSchema),
987
- ...value.deferLoading === true ? { deferLoading: true } : {}
988
- };
989
- };
990
- const tools = catalog.map((value) => {
991
- if (!isJsonObject(value) || value.type !== "namespace") return readFunction(value);
992
- if (!validName(value.name) || namespaces.has(value.name) || typeof value.description !== "string" || !Array.isArray(value.tools) || !value.tools.length || Object.keys(value).some((key) => ![
993
- "type",
994
- "name",
995
- "description",
996
- "tools"
997
- ].includes(key))) throw fail();
998
- namespaces.add(value.name);
999
- return {
1000
- type: "namespace",
1001
- name: value.name,
1002
- description: value.description,
1003
- tools: value.tools.map(readFunction)
1004
- };
1005
- });
1006
- if (fingerprint !== void 0 && codexDynamicToolsFingerprint(tools) !== fingerprint) throw fail();
1007
- return tools;
1008
- }
1009
- /** Existing supervised bindings identify data, never authorize an executor or a new adoption. */
1010
- async function loadCodexNativeToolCatalog(params) {
1011
- const { binding, client, appServer, agentDir, assertCurrent } = params;
1012
- assertCurrent();
1013
- const home = resolveCodexAppServerLocalHomeDir(appServer.start, agentDir);
1014
- const actualHome = client.getRuntimeIdentity()?.codexHome;
1015
- if (!hasCodexNativeToolCatalog(binding) || !binding.dynamicToolsFingerprint || appServer.start.transport !== "stdio" && appServer.start.transport !== "unix" || appServer.remoteWorkspaceRoot || !actualHome || path.resolve(actualHome) !== path.resolve(home) || binding.appServerRuntimeFingerprint !== buildCodexAppServerConnectionFingerprint(appServer, agentDir)) throw new Error("Canonical Codex declarations require the original verified local binding and selected native connection; the thread is preserved.");
1016
- const metadata = await readCodexClientSessionMeta(client, path.join(home, "sessions"), binding.rolloutPath, binding.threadId);
1017
- const consume = () => {
1018
- assertCurrent();
1019
- return parseCodexNativeToolCatalog(metadata, binding.threadId, binding.dynamicToolsFingerprint);
1020
- };
1021
- return params.authority ? await params.authority.withCurrent(consume) : consume();
1022
- }
1023
- //#endregion
1024
- //#region extensions/codex/src/app-server/thread-mcp-attestation.ts
1025
- async function attestCodexRestrictedToolSurfaceMcpServersDisabled(client, threadId, threadConfig, signal, expectedActiveServerNames = []) {
1026
- const configuredServers = threadConfig?.mcp_servers;
1027
- if (configuredServers !== void 0 && !isJsonObject(configuredServers)) throw new Error("Codex restricted-tool-surface thread config has invalid mcp_servers");
1028
- const expectedServers = /* @__PURE__ */ new Map();
1029
- for (const [name, serverConfig] of Object.entries(configuredServers ?? {})) {
1030
- if (!isJsonObject(serverConfig) || serverConfig.enabled !== false) throw new Error(`Codex restricted-tool-surface MCP server ${name} is not disabled`);
1031
- expectedServers.set(name, "disabled");
1032
- }
1033
- for (const name of expectedActiveServerNames) {
1034
- if (expectedServers.get(name) === "disabled") throw new Error(`Codex restricted-tool-surface MCP server ${name} has conflicting policy`);
1035
- expectedServers.set(name, "active");
1036
- }
1037
- const response = await client.request("mcpServerStatus/list", {
1038
- threadId,
1039
- detail: "toolsAndAuthOnly"
1040
- }, { signal });
1041
- if (!isJsonObject(response) || !Array.isArray(response.data)) throw new Error("Codex mcpServerStatus/list returned an invalid restricted-tool-surface attestation");
1042
- const observedServerNames = /* @__PURE__ */ new Set();
1043
- for (const status of response.data) {
1044
- if (!isJsonObject(status) || typeof status.name !== "string" || !isJsonObject(status.tools)) throw new Error("Codex mcpServerStatus/list returned an invalid restricted-tool-surface server");
1045
- if (!expectedServers.has(status.name)) throw new Error(`Codex restricted-tool-surface MCP attestation found unexpected server ${status.name}`);
1046
- if (observedServerNames.has(status.name)) throw new Error(`Codex restricted-tool-surface MCP attestation returned duplicate server ${status.name}`);
1047
- observedServerNames.add(status.name);
1048
- if (!Object.hasOwn(status, "serverInfo")) throw new Error(`Codex restricted-tool-surface MCP attestation returned malformed server ${status.name}`);
1049
- if (expectedServers.get(status.name) === "active") {
1050
- if (status.serverInfo === null || Object.keys(status.tools).length === 0) throw new Error(`Codex restricted-tool-surface MCP attestation found inactive admitted server ${status.name}`);
1051
- continue;
1052
- }
1053
- if (status.serverInfo !== null) throw new Error(`Codex restricted-tool-surface MCP attestation found active server ${status.name}`);
1054
- if (Object.keys(status.tools).length > 0) throw new Error(`Codex restricted-tool-surface MCP attestation found tools for server ${status.name}`);
1055
- }
1056
- for (const [expectedName, state] of expectedServers) if (!observedServerNames.has(expectedName)) throw new Error(`Codex restricted-tool-surface MCP attestation is missing ${state === "active" ? "admitted " : ""}server ${expectedName}`);
1057
- if (response.nextCursor !== void 0 && response.nextCursor !== null) throw new Error("Codex mcpServerStatus/list returned an invalid empty-page cursor");
1058
- }
1059
- //#endregion
1060
- //#region extensions/codex/src/app-server/plugin-thread-attestation.ts
1061
- /**
1062
- * Checks app availability and enforces restricted MCP surfaces before a turn.
1063
- */
1064
- /** Every admission path checks the same surface; its lifecycle owner keeps the claim fenced. */
1065
- async function attestCodexThreadToolSurface(params) {
1066
- if (params.appIds.length === 0 && !params.restrictedToolSurface) {
1067
- params.signal?.throwIfAborted();
1068
- params.assertCurrent();
1069
- return;
1070
- }
1071
- if (params.withCurrent) await params.withCurrent(params.assertCurrent);
1072
- else params.assertCurrent();
1073
- if (params.appIds.length > 0) {
1074
- await params.lifecycleTiming.measure("plugin-app-attestation", () => checkCodexThreadAppAvailability(params));
1075
- if (params.withCurrent) await params.withCurrent(params.assertCurrent);
1076
- else params.assertCurrent();
1077
- }
1078
- if (params.restrictedToolSurface) {
1079
- await params.lifecycleTiming.measure("restricted-tool-surface-mcp-attestation", () => attestCodexRestrictedToolSurfaceMcpServersDisabled(params.client, params.threadId, params.threadConfig, params.signal, params.appIds.length > 0 ? ["codex_apps"] : []));
1080
- if (params.withCurrent) await params.withCurrent(params.assertCurrent);
1081
- else params.assertCurrent();
1082
- }
1083
- }
1084
- var CodexPluginThreadAppAttestationError = class extends Error {
1085
- constructor(message, options) {
1086
- super(message, options);
1087
- this.name = "CodexPluginThreadAppAttestationError";
1088
- }
1089
- };
1090
- /** Reads the existing runtime snapshot with the started thread's effective app policy. */
1091
- async function checkCodexThreadAppAvailability(params) {
1092
- const appIds = Array.from(new Set(params.appIds.filter(Boolean))).toSorted();
1093
- if (appIds.length === 0) return;
1094
- let response;
1095
- try {
1096
- response = await params.client.request("app/installed", {
1097
- threadId: params.threadId,
1098
- forceRefresh: false
1099
- }, {
1100
- signal: params.signal,
1101
- withCurrent: params.withCurrent
1102
- });
1103
- } catch (error) {
1104
- params.signal?.throwIfAborted();
1105
- throw new CodexPluginThreadAppAttestationError(`Codex could not confirm admitted apps for thread ${params.threadId}`, { cause: error });
1106
- }
1107
- params.signal?.throwIfAborted();
1108
- const installedById = new Map(response.apps.map((app) => [app.id, app]));
1109
- const failures = appIds.flatMap((appId) => {
1110
- const app = installedById.get(appId);
1111
- if (!app) return [`${appId}:missing`];
1112
- if (!app.enabled) return [`${appId}:disabled`];
1113
- return app.callable ? [] : [`${appId}:not-callable`];
1114
- });
1115
- if (failures.length > 0) embeddedAgentLog.warn("codex apps unavailable; continuing with remaining tools", {
1116
- threadId: params.threadId,
1117
- failures
1118
- });
1119
- }
1120
- /** Deletes a persistent pre-turn thread; ephemeral threads can only be unsubscribed. */
1121
- async function discardUnattestedCodexPluginThread(params) {
1122
- if (params.ephemeral) return await unsubscribeCodexThreadBestEffort(params.client, {
1123
- threadId: params.threadId,
1124
- timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS
1125
- });
1126
- try {
1127
- await params.client.request("thread/delete", { threadId: params.threadId }, { timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS });
1128
- return true;
1129
- } catch (error) {
1130
- embeddedAgentLog.debug("codex plugin app attestation thread deletion failed", {
1131
- threadId: params.threadId,
1132
- error
1133
- });
1134
- await unsubscribeCodexThreadBestEffort(params.client, {
1135
- threadId: params.threadId,
1136
- timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS
1137
- });
1138
- return false;
1139
- }
1140
- }
1141
- //#endregion
1142
- //#region extensions/codex/src/app-server/native-hook-relay.ts
1143
- const CODEX_NATIVE_HOOK_RELAY_EVENTS = [
1144
- "pre_tool_use",
1145
- "post_tool_use",
1146
- "permission_request",
1147
- "before_agent_finalize"
1148
- ];
1149
- const CODEX_NATIVE_HOOK_RELAY_EVENTS_WITH_APP_SERVER_APPROVALS = CODEX_NATIVE_HOOK_RELAY_EVENTS.filter((event) => event !== "permission_request");
1150
- const CODEX_NATIVE_HOOK_RELAY_MIN_TTL_MS = 18e5;
1151
- /** Extra relay lifetime after the expected turn budget, preventing late hook drops. */
1152
- const CODEX_NATIVE_HOOK_RELAY_TTL_GRACE_MS = 3e5;
1153
- const CODEX_NATIVE_HOOK_RELAY_COMMAND_MIN_PARENT_MARGIN_MS = 250;
1154
- const CODEX_NATIVE_HOOK_RELAY_COMMAND_MAX_PARENT_MARGIN_MS = 1e3;
1155
- const CODEX_NATIVE_HOOK_RELAY_DEFAULT_TIMEOUT_SEC = 10;
1156
- const CODEX_NATIVE_HOOK_RELAY_UNREGISTER_GRACE_MS = 1e4;
1157
- const CODEX_NATIVE_HOOK_RELAY_UNREGISTER_EXTRA_GRACE_MS = 5e3;
1158
- const MAX_PENDING_DIRECT_CHILD_ADMISSIONS = 32;
1159
- const CODEX_NATIVE_SPAWN_HOOK_NAMES = ["spawn_agent", "Agent"];
1160
- const CODEX_HOOK_MATCHER_NAMES_BY_TOOL_ID = {
1161
- exec: [
1162
- "Bash",
1163
- "exec",
1164
- "exec_command"
1165
- ],
1166
- apply_patch: [
1167
- "apply_patch",
1168
- "Write",
1169
- "Edit"
1170
- ],
1171
- spawn_agent: CODEX_NATIVE_SPAWN_HOOK_NAMES
1172
- };
1173
- var CodexManagedHooksOnlyError = class extends Error {
1174
- constructor() {
1175
- super("Codex managed-only hooks disable the OpenClaw native hook relay; refusing unenforced execution");
1176
- this.name = "CodexManagedHooksOnlyError";
1177
- }
1178
- };
1179
- /** Enterprise managed-only policy silently drops the session-layer hooks that enforce OpenClaw. */
1180
- async function assertCodexNativeHookRelayAllowed(client, signal, timeoutMs) {
1181
- const response = await client.request("configRequirements/read", void 0, {
1182
- signal,
1183
- ...timeoutMs === void 0 ? {} : { timeoutMs }
1184
- });
1185
- if (!isJsonObject(response) || !Object.hasOwn(response, "requirements")) throw new Error("Codex configRequirements/read returned an invalid hook policy response");
1186
- const requirements = response.requirements;
1187
- if (requirements === null) return;
1188
- if (!isJsonObject(requirements)) throw new Error("Codex configRequirements/read returned invalid hook policy requirements");
1189
- const managedOnly = requirements.allowManagedHooksOnly;
1190
- if (managedOnly !== void 0 && managedOnly !== null && typeof managedOnly !== "boolean") throw new Error("Codex configRequirements/read returned invalid managed-only hook policy");
1191
- if (managedOnly === true) throw new CodexManagedHooksOnlyError();
1192
- }
1193
- /** Defers relay unregister so late native hook subprocesses can still resolve. */
1194
- function scheduleCodexNativeHookRelayUnregister(params) {
1195
- nativeHookRelayUnregisterQueue.schedule(params.relay, resolveCodexNativeHookRelayUnregisterGraceMs(params.hookTimeoutSec));
1196
- }
1197
- function resolveCodexNativeHookRelayUnregisterGraceMs(hookTimeoutSec) {
1198
- const hookTimeoutMs = finiteSecondsToTimerSafeMilliseconds(normalizeHookTimeoutSec(hookTimeoutSec)) ?? 0;
1199
- return Math.max(CODEX_NATIVE_HOOK_RELAY_UNREGISTER_GRACE_MS, addTimerTimeoutGraceMs(hookTimeoutMs, CODEX_NATIVE_HOOK_RELAY_UNREGISTER_EXTRA_GRACE_MS) ?? 0);
1200
- }
1201
- /** Records a native pre-tool failure that Codex does not project as a tool item. */
1202
- function emitCodexNativePreToolUseFailureDiagnostic(params) {
1203
- emitTrustedDiagnosticEvent({
1204
- type: "tool.execution.error",
1205
- ...params.agentId ? { agentId: params.agentId } : {},
1206
- sessionId: params.sessionId,
1207
- ...params.sessionKey ? { sessionKey: params.sessionKey } : {},
1208
- runId: params.runId,
1209
- toolName: params.failure.toolName,
1210
- toolCallId: params.failure.toolCallId,
1211
- durationMs: params.failure.durationMs,
1212
- errorCategory: "before_tool_call",
1213
- terminalReason: params.terminalReason ?? (params.signal?.aborted ? resolveCodexToolAbortTerminalReason(params.signal) : params.failure.disposition),
1214
- ...params.sourceTimestampMs !== void 0 ? { sourceTimestampMs: params.sourceTimestampMs } : {}
1215
- });
1216
- }
1217
- function createCodexNativeHookRelay(params) {
1218
- if (params.options?.enabled === false) return;
1219
- const modelInputTools = params.nativeModelAdmission?.tools ?? ["multi_agent_v1send_input"];
1220
- const directChildClaims = /* @__PURE__ */ new Map();
1221
- const pendingDirectChildAdmissions = /* @__PURE__ */ new Map();
1222
- let foregroundClosed = false;
1223
- let successfulYieldRetentionAuthorized = false;
1224
- const assertClaim = (threadId, claim) => () => directChildClaims.get(threadId) === claim;
1225
- const rejectPendingAdmissions = (reason) => {
1226
- for (const pending of pendingDirectChildAdmissions.values()) pending.reject(new Error(reason));
1227
- pendingDirectChildAdmissions.clear();
1228
- };
1229
- let releaseProcessAdmission;
1230
- let processAdmissionDisposed = false;
1231
- const relay = registerNativeHookRelayForBundledRuntime({
1232
- provider: "codex",
1233
- relayId: buildCodexNativeHookRelayId({
1234
- agentId: params.agentId,
1235
- sessionId: params.sessionId,
1236
- sessionKey: params.sessionKey
1237
- }),
1238
- ...params.generation ? { generation: params.generation } : {},
1239
- ...params.generationMismatchGraceMs ? { generationMismatchGraceMs: params.generationMismatchGraceMs } : {},
1240
- ...params.agentId ? { agentId: params.agentId } : {},
1241
- sessionId: params.sessionId,
1242
- ...params.sessionKey ? { sessionKey: params.sessionKey } : {},
1243
- ...params.config ? { config: params.config } : {},
1244
- autoApproveMcpTools: params.autoApproveMcpTools,
1245
- projectedMcpServers: params.projectedMcpServers,
1246
- runId: params.runId,
1247
- ...params.channelId ? { channelId: params.channelId } : {},
1248
- ...params.requester ? { requester: params.requester } : {},
1249
- ...params.approvalContext ? { approvalContext: params.approvalContext } : {},
1250
- allowedEvents: params.events,
1251
- preToolUseLoopDetection: params.loopDetectionPreToolUseRelay,
1252
- ttlMs: resolveCodexNativeHookRelayTtlMs({
1253
- explicitTtlMs: params.options?.ttlMs,
1254
- attemptTimeoutMs: params.attemptTimeoutMs,
1255
- startupTimeoutMs: params.startupTimeoutMs,
1256
- turnStartTimeoutMs: params.turnStartTimeoutMs
1257
- }),
1258
- signal: params.signal,
1259
- runBeforeToolCall: params.hostCapabilities.runBeforeToolCall,
1260
- executionAdmission: params.nativeProcessAuthority || params.nativeModelAdmission ? {
1261
- toolNames: [...params.nativeProcessAuthority ? ["exec"] : [], ...params.nativeModelAdmission ? modelInputTools : []],
1262
- admit: async (invocation, assertAdmissionCurrent, preparation) => {
1263
- const payload = invocation.rawPayload;
1264
- const toolName = CODEX_NATIVE_SPAWN_HOOK_NAMES.includes(invocation.toolName ?? "") ? "spawn_agent" : invocation.toolName;
1265
- if (params.nativeModelAdmission && toolName && modelInputTools.includes(toolName)) {
1266
- const admission = params.nativeModelAdmission;
1267
- if (toolName.endsWith("spawn_agent")) {
1268
- const assertSpawnAllowed = () => {
1269
- assertAdmissionCurrent();
1270
- if (!readCodexNativeChildThreadId(payload)) try {
1271
- params.hostCapabilities.assertNativeSubagentSpawnAllowed?.();
1272
- } catch (error) {
1273
- return `${toErrorObject(error, "Native spawn participant selection failed").message} Use sessions_spawn with the requester's requester_profile.id as user.`;
1274
- }
1275
- };
1276
- return assertSpawnAllowed;
1277
- }
1278
- const input = isJsonObject(payload) ? payload.tool_input : void 0;
1279
- const targetThreadId = isJsonObject(input) && typeof input.target === "string" ? input.target.trim() : void 0;
1280
- const threadId = readCodexNativeChildThreadId(payload) ?? admission.threadId();
1281
- if (!threadId || !targetThreadId || !invocation.turnId || !invocation.toolUseId) throw new Error("Codex native input requires exact sender, receiver, turn, and tool identities");
1282
- assertAdmissionCurrent();
1283
- const request = {
1284
- client: admission.client(),
1285
- threadId,
1286
- turnId: invocation.turnId,
1287
- itemId: invocation.toolUseId
1288
- };
1289
- await codexNativeSubagentMonitorRuntime.prepareModelInput({
1290
- ...request,
1291
- target: targetThreadId,
1292
- readQualification: admission.readQualification,
1293
- signal: preparation.signal,
1294
- assertCurrent: preparation.assertCurrent
1295
- });
1296
- assertAdmissionCurrent();
1297
- return;
1298
- }
1299
- const rootThreadId = isJsonObject(payload) && typeof payload.session_id === "string" ? payload.session_id.trim() : void 0;
1300
- const childThreadId = readCodexNativeChildThreadId(payload);
1301
- const threadId = childThreadId ?? rootThreadId;
1302
- if (!threadId || !invocation.turnId || !invocation.toolUseId) throw new Error("Codex native process admission requires exact thread, turn, and tool identities");
1303
- params.nativeProcessAuthority.owner.admit(params.nativeProcessAuthority.client(), {
1304
- threadId,
1305
- turnId: invocation.turnId,
1306
- itemId: invocation.toolUseId
1307
- }, assertAdmissionCurrent, childThreadId ? rootThreadId : void 0);
1308
- }
1309
- } : void 0,
1310
- approvalHost: params.hostCapabilities,
1311
- assertActive: () => {
1312
- params.hostCapabilities.assertActive();
1313
- params.assertCurrent?.();
1314
- },
1315
- retention: {
1316
- readClaim: readCodexNativeChildThreadId,
1317
- shouldRetainAfterForegroundClose: () => successfulYieldRetentionAuthorized && directChildClaims.size > 0,
1318
- allowPreToolUse: (childThreadId) => directChildClaims.has(childThreadId),
1319
- awaitForegroundAdmission: (childThreadId, signal) => {
1320
- const existingClaim = directChildClaims.get(childThreadId);
1321
- if (existingClaim) return Promise.resolve(assertClaim(childThreadId, existingClaim));
1322
- if (foregroundClosed) return Promise.reject(/* @__PURE__ */ new Error("native hook relay foreground admission unavailable"));
1323
- let pending = pendingDirectChildAdmissions.get(childThreadId);
1324
- if (!pending) {
1325
- if (pendingDirectChildAdmissions.size >= MAX_PENDING_DIRECT_CHILD_ADMISSIONS) return Promise.reject(/* @__PURE__ */ new Error("native hook relay foreground admission capacity reached"));
1326
- pending = {
1327
- ...createDeferred(),
1328
- waiters: 0
1329
- };
1330
- pendingDirectChildAdmissions.set(childThreadId, pending);
1331
- }
1332
- const admission = pending;
1333
- admission.waiters++;
1334
- let onAbort;
1335
- return new Promise((resolve, reject) => {
1336
- admission.promise.then(resolve, reject);
1337
- onAbort = () => reject(toErrorObject(signal?.reason, "native hook relay admission aborted"));
1338
- signal?.addEventListener("abort", onAbort, { once: true });
1339
- if (signal?.aborted) onAbort();
1340
- }).then((claim) => assertClaim(childThreadId, claim)).finally(() => {
1341
- if (onAbort) signal?.removeEventListener("abort", onAbort);
1342
- admission.waiters--;
1343
- if (admission.waiters === 0 && pendingDirectChildAdmissions.get(childThreadId) === admission) pendingDirectChildAdmissions.delete(childThreadId);
1344
- });
1345
- },
1346
- onDispose: () => {
1347
- foregroundClosed = true;
1348
- rejectPendingAdmissions("native hook relay registration closed");
1349
- processAdmissionDisposed = true;
1350
- releaseProcessAdmission?.();
1351
- }
1352
- },
1353
- onPreToolUseFailure: params.onPreToolUseFailure,
1354
- command: {
1355
- nice: 10,
1356
- timeoutMs: params.options?.gatewayTimeoutMs
1357
- }
1358
- });
1359
- if (!processAdmissionDisposed) try {
1360
- releaseProcessAdmission = params.nativeProcessAuthority?.owner.retainAdmission();
1361
- } catch (error) {
1362
- relay.unregister();
1363
- throw error;
1364
- }
1365
- const unregister = () => {
1366
- foregroundClosed = true;
1367
- rejectPendingAdmissions("native hook relay foreground closed");
1368
- relay.unregister();
1369
- };
1370
- return {
1371
- ...relay,
1372
- unregister,
1373
- authorizeRetentionAfterSuccessfulYield: () => {
1374
- successfulYieldRetentionAuthorized = true;
1375
- },
1376
- hasClaimedDirectChild: () => directChildClaims.size > 0,
1377
- rejectPendingDirectChild: (threadIdInput, reason) => {
1378
- const threadId = threadIdInput.trim();
1379
- const pending = threadId ? pendingDirectChildAdmissions.get(threadId) : void 0;
1380
- if (!pending) return;
1381
- pendingDirectChildAdmissions.delete(threadId);
1382
- pending.reject(new Error(reason));
1383
- },
1384
- claimDirectChild: (threadIdInput) => {
1385
- const threadId = threadIdInput.trim();
1386
- if (!threadId) return () => void 0;
1387
- if (directChildClaims.get(threadId)) return () => void 0;
1388
- const claim = Symbol(threadId);
1389
- directChildClaims.set(threadId, claim);
1390
- const pending = pendingDirectChildAdmissions.get(threadId);
1391
- pendingDirectChildAdmissions.delete(threadId);
1392
- pending?.resolve(claim);
1393
- let released = false;
1394
- return () => {
1395
- if (released) return;
1396
- released = true;
1397
- if (directChildClaims.get(threadId) !== claim) return;
1398
- directChildClaims.delete(threadId);
1399
- if (foregroundClosed && directChildClaims.size === 0) {
1400
- relay.unregister();
1401
- nativeHookRelayUnregisterQueue.track(relay.drain());
1402
- }
1403
- };
1404
- }
1405
- };
1406
- }
1407
- function readCodexNativeChildThreadId(rawPayload) {
1408
- if (!isJsonObject(rawPayload) || typeof rawPayload.agent_id !== "string") return;
1409
- return rawPayload.agent_id.trim() || void 0;
1410
- }
1411
- function resolveCodexNativeHookRelayEvents(params) {
1412
- if (params.configuredEvents?.length) return params.configuredEvents;
1413
- return params.appServer.approvalPolicy === "never" ? CODEX_NATIVE_HOOK_RELAY_EVENTS : CODEX_NATIVE_HOOK_RELAY_EVENTS_WITH_APP_SERVER_APPROVALS;
1414
- }
1415
- function resolveCodexNativeHookRelayTtlMs(params) {
1416
- if (params.explicitTtlMs !== void 0) return params.explicitTtlMs;
1417
- const relayBudgetMs = params.attemptTimeoutMs + params.startupTimeoutMs + params.turnStartTimeoutMs + CODEX_NATIVE_HOOK_RELAY_TTL_GRACE_MS;
1418
- return Math.max(CODEX_NATIVE_HOOK_RELAY_MIN_TTL_MS, Math.floor(relayBudgetMs));
1419
- }
1420
- function buildCodexNativeHookRelayId(params) {
1421
- const hash = createHash("sha256");
1422
- hash.update("openclaw:codex:native-hook-relay:v1");
1423
- hash.update("\0");
1424
- hash.update(params.agentId?.trim() || "");
1425
- hash.update("\0");
1426
- hash.update(params.sessionKey?.trim() || params.sessionId);
1427
- return `codex-${hash.digest("hex").slice(0, 40)}`;
1428
- }
1429
- const CODEX_HOOK_EVENTS = {
1430
- pre_tool_use: {
1431
- name: "PreToolUse",
1432
- keyLabel: "pre_tool_use"
1433
- },
1434
- post_tool_use: {
1435
- name: "PostToolUse",
1436
- keyLabel: "post_tool_use"
1437
- },
1438
- permission_request: {
1439
- name: "PermissionRequest",
1440
- keyLabel: "permission_request"
1441
- },
1442
- before_agent_finalize: {
1443
- name: "Stop",
1444
- keyLabel: "stop"
1445
- }
1446
- };
1447
- const CODEX_SESSION_FLAGS_HOOK_SOURCE_PATHS = ["/<session-flags>/config.toml", "<session-flags>/config.toml"];
1448
- function buildCodexNativeHookRelayConfig(params) {
1449
- const events = params.events?.length ? params.events : CODEX_NATIVE_HOOK_RELAY_EVENTS;
1450
- const selectedEvents = new Set(events);
1451
- const config = { "features.hooks": true };
1452
- const hookState = {};
1453
- for (const event of CODEX_NATIVE_HOOK_RELAY_EVENTS) {
1454
- const { name, keyLabel } = CODEX_HOOK_EVENTS[event];
1455
- const selected = selectedEvents.has(event);
1456
- const shouldRelay = params.relay.shouldRelayEvent(event);
1457
- if (!selected || !shouldRelay) {
1458
- if (selected || params.clearOmittedEvents) config[`hooks.${name}`] = [];
1459
- if (params.clearOmittedEvents) for (const sourcePath of CODEX_SESSION_FLAGS_HOOK_SOURCE_PATHS) hookState[`${sourcePath}:${keyLabel}:0:0`] = { enabled: false };
1460
- continue;
1461
- }
1462
- const timeout = normalizeHookTimeoutSec(params.hookTimeoutSec);
1463
- const command = params.relay.commandForEvent(event, { timeoutMs: resolveCodexNativeHookRelayCommandTimeoutMs(timeout) });
1464
- const matcher = buildCodexNativeToolMatcher(params.relay.toolMatcherForEvent(event));
1465
- const group = {
1466
- ...matcher ? { matcher } : {},
1467
- hooks: [{
1468
- type: "command",
1469
- command,
1470
- timeout,
1471
- async: false,
1472
- statusMessage: "OpenClaw native hook relay"
1473
- }]
1474
- };
1475
- config[`hooks.${name}`] = [group];
1476
- const state = {
1477
- enabled: true,
1478
- trusted_hash: `sha256:${fingerprintCodexPolicy({
1479
- event_name: keyLabel,
1480
- ...group
1481
- })}`
1482
- };
1483
- for (const sourcePath of CODEX_SESSION_FLAGS_HOOK_SOURCE_PATHS) hookState[`${sourcePath}:${keyLabel}:0:0`] = state;
1484
- }
1485
- config["hooks.state"] = hookState;
1486
- return config;
1487
- }
1488
- function buildCodexNativeHookRelayDisabledConfig() {
1489
- return {
1490
- "features.hooks": false,
1491
- "hooks.PreToolUse": [],
1492
- "hooks.PostToolUse": [],
1493
- "hooks.PermissionRequest": [],
1494
- "hooks.Stop": []
1495
- };
1496
- }
1497
- function normalizeHookTimeoutSec(value) {
1498
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.ceil(value) : CODEX_NATIVE_HOOK_RELAY_DEFAULT_TIMEOUT_SEC;
1499
- }
1500
- function resolveCodexNativeHookRelayCommandTimeoutMs(hookTimeoutSec) {
1501
- const parentTimeoutMs = finiteSecondsToTimerSafeMilliseconds(normalizeHookTimeoutSec(hookTimeoutSec)) ?? 5e3;
1502
- const parentMarginMs = Math.min(CODEX_NATIVE_HOOK_RELAY_COMMAND_MAX_PARENT_MARGIN_MS, Math.max(CODEX_NATIVE_HOOK_RELAY_COMMAND_MIN_PARENT_MARGIN_MS, Math.floor(parentTimeoutMs / 5)));
1503
- return Math.max(1, parentTimeoutMs - parentMarginMs);
1504
- }
1505
- function buildCodexNativeToolMatcher(toolNames) {
1506
- if (toolNames === void 0) return;
1507
- if (toolNames.length === 0) throw new TypeError("Codex native hook matcher requires at least one tool name");
1508
- const nativeNames = /* @__PURE__ */ new Set();
1509
- let hasCustomToolName = false;
1510
- for (const toolName of toolNames) {
1511
- const canonicalToolName = toolName.trim();
1512
- if (!canonicalToolName || canonicalToolName === "*") throw new TypeError("Codex native hook matcher requires canonical OpenClaw tool ids");
1513
- const nativeAliases = CODEX_HOOK_MATCHER_NAMES_BY_TOOL_ID[canonicalToolName];
1514
- if (!nativeAliases) hasCustomToolName = true;
1515
- for (const nativeName of nativeAliases ?? [canonicalToolName]) nativeNames.add(nativeName);
1516
- }
1517
- const sortedNames = Array.from(nativeNames).toSorted();
1518
- if (!hasCustomToolName && sortedNames.every((toolName) => /^[A-Za-z0-9_]+$/.test(toolName))) return sortedNames.join("|");
1519
- return `(?i)^(?:${sortedNames.map(escapeRegExp).join("|")})$`;
1520
- }
1521
- //#endregion
1522
- //#region extensions/codex/src/app-server/project-doc-thread-config.ts
1523
- const CODEX_NATIVE_PROJECT_DOC_MAX_BYTES = 131072;
1524
- function buildCodexProjectDocThreadConfig(config, effectiveNativeConfig) {
1525
- const defaults = { project_doc_max_bytes: resolveCodexNativeProjectDocMaxBytes(effectiveNativeConfig) ?? CODEX_NATIVE_PROJECT_DOC_MAX_BYTES };
1526
- return mergeCodexThreadConfigs(defaults, config) ?? defaults;
1527
- }
1528
- function resolveCodexNativeProjectDocMaxBytes(effectiveNativeConfig) {
1529
- if (effectiveNativeConfig?.origins?.project_doc_max_bytes === void 0) return;
1530
- const authoredMaxBytes = effectiveNativeConfig.config.project_doc_max_bytes;
1531
- if (typeof authoredMaxBytes !== "number" || !Number.isSafeInteger(authoredMaxBytes) || authoredMaxBytes < 0) throw new Error("Codex config/read returned an invalid project_doc_max_bytes value");
1532
- return authoredMaxBytes;
1533
- }
1534
- function mergeCodexNativeProjectDocThreadConfig(config, effectiveNativeConfig) {
1535
- const authoredMaxBytes = resolveCodexNativeProjectDocMaxBytes(effectiveNativeConfig);
1536
- return authoredMaxBytes === void 0 ? config : mergeCodexThreadConfigs({ project_doc_max_bytes: authoredMaxBytes }, config);
1537
- }
1538
- //#endregion
1539
- //#region extensions/codex/src/app-server/developer-instruction-sections.ts
1540
- function joinPresentSections(...sections) {
1541
- return sections.filter((section) => Boolean(section?.trim())).join("\n\n");
1542
- }
1543
- //#endregion
1544
- //#region extensions/codex/src/app-server/thread-model-selection.ts
1545
- const CODEX_NATIVE_PERSONALITY_NONE = "none";
1546
- function resolveCodexBindingModelProviderFallback(params) {
1547
- const provider = params.provider?.trim().toLowerCase();
1548
- if (provider && provider !== "codex") return;
1549
- const currentModel = params.currentModel?.trim();
1550
- const bindingModel = params.bindingModel?.trim();
1551
- if (currentModel && bindingModel && currentModel === bindingModel && params.bindingModelProvider) return params.bindingModelProvider;
1552
- return hasProviderQualifiedModelRef(currentModel) ? void 0 : params.bindingModelProvider;
1553
- }
1554
- function resolveCodexAppServerThreadModelSelection(params) {
1555
- const authProfileId = params.inheritBindingAuthProfile === false ? params.authProfileId : params.authProfileId ?? params.binding?.authProfileId;
1556
- const explicitModelProvider = resolveCodexAppServerModelProvider({
1557
- ...params,
1558
- authProfileId
1559
- });
1560
- const bindingModelProvider = params.binding?.threadId ? resolveCodexBindingModelProviderFallback({
1561
- provider: params.provider,
1562
- currentModel: params.model,
1563
- bindingModel: params.binding.model,
1564
- bindingModelProvider: params.binding.modelProvider
1565
- }) : void 0;
1566
- return resolveCodexAppServerRequestModelSelection({
1567
- ...params,
1568
- model: params.requestModel ?? params.model,
1569
- modelProvider: explicitModelProvider ?? bindingModelProvider,
1570
- authProfileId
1571
- });
1572
- }
1573
- function resolveCodexAppServerRequestModelSelection(params) {
1574
- const model = params.model.trim();
1575
- const modelProvider = params.modelProvider?.trim();
1576
- if (modelProvider) return {
1577
- model,
1578
- modelProvider
1579
- };
1580
- const slashIndex = model.indexOf("/");
1581
- if (slashIndex <= 0 || slashIndex >= model.length - 1) return { model };
1582
- const inferredProvider = model.slice(0, slashIndex);
1583
- const inferredModelProvider = resolveCodexAppServerModelProvider({
1584
- ...params,
1585
- provider: inferredProvider
1586
- });
1587
- return {
1588
- model: model.slice(slashIndex + 1).trim(),
1589
- ...inferredModelProvider ? { modelProvider: inferredModelProvider } : {}
1590
- };
1591
- }
1592
- function hasProviderQualifiedModelRef(model) {
1593
- const trimmed = model?.trim();
1594
- const slashIndex = trimmed?.indexOf("/") ?? -1;
1595
- return slashIndex > 0 && slashIndex < (trimmed?.length ?? 0) - 1;
1596
- }
1597
- function resolveCodexAppServerModelProvider(params) {
1598
- const normalized = params.provider.trim();
1599
- const normalizedLower = normalized.toLowerCase();
1600
- if (normalizedLower === "openai" && params.authProfileId && isCodexResponsesOAuthCredential(params.authProfileStore?.profiles[params.authProfileId])) return CODEX_RESPONSES_OAUTH_PROVIDER;
1601
- if (!normalized || normalizedLower === "codex") return;
1602
- if (normalizedLower === "openai" && (params.homeScope === "user" || isCodexAppServerNativeAuthProfile(params))) return;
1603
- return normalizedLower === "openai" ? "openai" : normalized;
1604
- }
1605
- //#endregion
1606
- //#region extensions/codex/src/app-server/thread-prompt.ts
1607
- function buildDeveloperInstructions(params, options = {}) {
1608
- const deferredToolNames = /* @__PURE__ */ new Set();
1609
- let screenToolName;
1610
- let showWidgetToolName;
1611
- let dashboardToolName;
1612
- let portalToolName;
1613
- let messageTool;
1614
- let hasSkillWorkshop = false;
1615
- let hasSessionsSpawn = false;
1616
- let hasSessionsYield = false;
1617
- let hasSubagentsList = false;
1618
- let hasSessionsSend = false;
1619
- let hasControlTools = false;
1620
- let hasSeenDirectNamespace = false;
1621
- for (const spec of options.dynamicTools ?? []) {
1622
- const isDirectNamespace = spec.type === "namespace" && !hasSeenDirectNamespace && spec.name.trim() === "openclaw_direct";
1623
- if (isDirectNamespace) hasSeenDirectNamespace = true;
1624
- for (const tool of spec.type === "namespace" ? spec.tools : [spec]) {
1625
- const name = tool.name.trim();
1626
- const qualifiedName = spec.type === "namespace" ? `${spec.name}.${name}` : name;
1627
- if (tool.deferLoading === true && name) deferredToolNames.add(name);
1628
- if (name === "screen") screenToolName ??= qualifiedName;
1629
- if (name === "show_widget") showWidgetToolName ??= qualifiedName;
1630
- if (name === "dashboard") dashboardToolName ??= qualifiedName;
1631
- if (name === "portal") portalToolName ??= qualifiedName;
1632
- if (name === "message") messageTool ??= {
1633
- name: qualifiedName,
1634
- parameters: tool.inputSchema
1635
- };
1636
- hasSkillWorkshop ||= name === SKILL_WORKSHOP_TOOL_NAME;
1637
- hasSessionsSpawn ||= name === "sessions_spawn";
1638
- hasSessionsYield ||= isDirectNamespace && name === "sessions_yield";
1639
- hasSubagentsList ||= name === "subagents";
1640
- hasSessionsSend ||= name === "sessions_send";
1641
- hasControlTools ||= name === "openclaw" || name === "gateway";
1642
- }
1643
- }
1644
- const nativeCommandGuidance = listRegisteredPluginAgentPromptGuidance({
1645
- surface: "codex_app_server",
1646
- includeLegacyGlobalGuidance: false
1647
- }).join("\n");
1648
- const delegationGuidanceAvailable = params.disableTools !== true && params.toolsAllow?.length !== 0 && params.delegationCapability !== "report_only" && !isMessageOnlyCodexSourceReply(params);
1649
- const nativeDelegationAvailable = delegationGuidanceAvailable && !isCodexResponsesOAuthRun(params) && !isSystemAgentOnlyCodexDynamicToolAllowlist(params.toolsAllow) && !shouldDisableCodexToolSearchForModel(params.modelId);
1650
- const deferredToolDiscoveryGuidance = deferredToolNames.size > 0 || nativeDelegationAvailable ? "Deferred tools may be absent from the direct tool list. Use `tool_search` when directly callable. On code-mode-only models, use `exec` instead: filter `ALL_TOOLS` by name and description, then call the matching entry through `tools`." : void 0;
1651
- return [
1652
- "You are a personal agent running inside OpenClaw. OpenClaw has dynamic tools for OpenClaw-owned messaging, cron, sessions, media, gateway, and nodes.",
1653
- deferredToolNames.size > 0 ? `Deferred searchable OpenClaw dynamic tools available: ${[...deferredToolNames].toSorted((left, right) => left.localeCompare(right)).join(", ")}.` : void 0,
1654
- deferredToolDiscoveryGuidance,
1655
- hasSkillWorkshop ? buildSkillWorkshopPromptSection().join("\n") : void 0,
1656
- nativeDelegationAvailable ? `Use Codex native \`spawn_agent\` for Codex subagents. \`spawn_agent\` and the other native collaboration tools may be deferred. For follow-up work on an existing native child, use the native collaboration tool that starts or queues a new turn.${hasSessionsSpawn ? " Use OpenClaw `sessions_spawn` only for OpenClaw or ACP delegation, never as a substitute for `spawn_agent` on internal legwork." : ""}` : void 0,
1657
- hasSessionsYield && nativeDelegationAvailable ? "When a native child's result belongs in a later turn, end the current turn with `openclaw_direct.sessions_yield`; the completion arrives as the next model-visible input. Use native `wait_agent` only for an intentional same-turn wait when the immediate next step is blocked on the child. Never loop-poll for native child completion." : void 0,
1658
- delegationGuidanceAvailable ? buildDelegationGuidanceSection({
1659
- mode: resolveMainSessionDelegationMode({
1660
- config: params.config,
1661
- agentId: params.agentId,
1662
- sessionKey: params.sessionKey
1663
- }),
1664
- isMinimal: params.promptMode === "minimal" || params.promptMode === "none",
1665
- hiddenDelegationTool: nativeDelegationAvailable ? "native `spawn_agent`" : hasSessionsSpawn ? "`sessions_spawn`" : "",
1666
- hasVisibleSessionSpawn: hasSessionsSpawn,
1667
- hasSessionsYield,
1668
- hasSubagentsList,
1669
- hasSessionsSend
1670
- }).join("\n") : void 0,
1671
- params.disableTools !== true && params.promptMode !== "minimal" && params.promptMode !== "none" ? buildUiPresentationPrompt({
1672
- screenToolName,
1673
- showWidgetToolName,
1674
- dashboardToolName,
1675
- portalToolName,
1676
- messageTool
1677
- }) : void 0,
1678
- buildCredentialSafetyPrompt({ controlToolsAvailable: params.disableTools !== true && hasControlTools }),
1679
- nativeCommandGuidance,
1680
- params.gitCoauthorPrompt,
1681
- params.extraSystemPrompt
1682
- ].filter((section) => typeof section === "string" && section.trim()).join("\n\n");
1683
- }
1684
- //#endregion
1685
- //#region extensions/codex/src/app-server/thread-shell-environment.ts
1686
- /** Retain native policy beneath request overrides before applying host-owned values. */
1687
- function mergeCodexNativeShellEnvironment(config, nativePolicy) {
1688
- return isJsonObject(nativePolicy) ? mergeCodexThreadConfigs({ shell_environment_policy: Object.fromEntries(Object.entries(nativePolicy).filter(([, value]) => value !== null)) }, config) : config;
1689
- }
1690
- /** Applies host-selected values and any required login-shell restriction last. */
1691
- function applyCodexManagedShellEnvironment(config, environment, disableLoginShell = false, pathPrepend) {
1692
- if (!environment || Object.keys(environment).length === 0) return disableLoginShell ? {
1693
- ...config,
1694
- allow_login_shell: false
1695
- } : config;
1696
- const current = isJsonObject(config.shell_environment_policy) ? config.shell_environment_policy : {};
1697
- const currentSet = isJsonObject(current.set) ? current.set : {};
1698
- const managedEnvironment = { ...environment };
1699
- if (pathPrepend?.length) for (const key of Object.keys(environment)) {
1700
- if (key.toUpperCase() !== "PATH") continue;
1701
- const aliases = Object.keys(currentSet).filter((name) => name === key || process.platform === "win32" && name.toUpperCase() === "PATH");
1702
- const authoredKey = aliases.includes(key) ? key : aliases[0];
1703
- if (authoredKey !== void 0 && typeof currentSet[authoredKey] === "string") {
1704
- const merged = normalizeUniqueStringEntries([...pathPrepend, ...currentSet[authoredKey].split(path.delimiter)]).join(path.delimiter);
1705
- for (const name of [key, ...aliases]) managedEnvironment[name] = merged;
1706
- }
1707
- }
1708
- const names = Object.keys(managedEnvironment).toSorted();
1709
- const includeOnly = Array.isArray(current.include_only) ? current.include_only.filter((entry) => typeof entry === "string") : [];
1710
- const filters = isJsonObject(current.filters) ? current.filters : void 0;
1711
- const hasIncludeFilter = filters && Object.values(filters).includes("include");
1712
- const managedFilterNames = new Set(names.map((name) => name.toLowerCase()));
1713
- const managedConfig = {
1714
- ...config,
1715
- shell_environment_policy: {
1716
- ...current,
1717
- experimental_use_profile: false,
1718
- set: {
1719
- ...currentSet,
1720
- ...managedEnvironment
1721
- },
1722
- ...filters ? hasIncludeFilter ? { filters: {
1723
- ...Object.fromEntries(Object.entries(filters).filter(([name]) => !managedFilterNames.has(name.toLowerCase()))),
1724
- ...Object.fromEntries([...managedFilterNames].map((name) => [name, "include"]))
1725
- } } : {} : includeOnly.length > 0 ? { include_only: [.../* @__PURE__ */ new Set([...includeOnly, ...names])] } : {}
1726
- }
1727
- };
1728
- return disableLoginShell ? {
1729
- ...managedConfig,
1730
- allow_login_shell: false
1731
- } : managedConfig;
1732
- }
1733
- //#endregion
1734
- //#region extensions/codex/src/app-server/web-search.ts
1735
- const CODEX_NATIVE_WEB_SEARCH_DISABLED_CONFIG = {
1736
- "features.standalone_web_search": false,
1737
- web_search: "disabled"
1738
- };
1739
- function buildCodexNativeWebSearchThreadConfig(config) {
1740
- const nativeConfig = config?.tools?.web?.search?.openaiCodex;
1741
- const threadConfig = {
1742
- "features.standalone_web_search": false,
1743
- web_search: nativeConfig?.mode === "live" ? "live" : "cached"
1744
- };
1745
- const allowedDomains = normalizeUniqueTrimmedStringList(nativeConfig?.allowedDomains);
1746
- if (allowedDomains.length > 0) threadConfig["tools.web_search.allowed_domains"] = allowedDomains;
1747
- if (nativeConfig?.contextSize) threadConfig["tools.web_search.context_size"] = nativeConfig.contextSize;
1748
- for (const key of [
1749
- "country",
1750
- "region",
1751
- "city",
1752
- "timezone"
1753
- ]) {
1754
- const value = normalizeOptionalString(nativeConfig?.userLocation?.[key]);
1755
- if (value) threadConfig[`tools.web_search.location.${key}`] = value;
1756
- }
1757
- return threadConfig;
1758
- }
1759
- function resolveCodexWebSearchPlan(params) {
1760
- if (params.disableTools === true || params.webSearchAllowed === false || params.config?.tools?.web?.search?.enabled === false) return {
1761
- kind: "disabled",
1762
- suppressManagedWebSearch: true,
1763
- threadConfig: CODEX_NATIVE_WEB_SEARCH_DISABLED_CONFIG
1764
- };
1765
- const nativeConfig = params.config?.tools?.web?.search?.openaiCodex;
1766
- const managedSearchExplicit = normalizeOptionalString(params.config?.tools?.web?.search?.provider) !== void 0 || nativeConfig?.enabled === false;
1767
- const nativeProviderSupportsSearch = params.nativeProviderWebSearchSupport === void 0 || params.nativeProviderWebSearchSupport === "supported";
1768
- if (!(params.nativeToolSurfaceEnabled !== false && nativeProviderSupportsSearch && !managedSearchExplicit)) {
1769
- if (!managedSearchExplicit && normalizeUniqueTrimmedStringList(nativeConfig?.allowedDomains).length > 0) return {
1770
- kind: "disabled",
1771
- suppressManagedWebSearch: true,
1772
- threadConfig: CODEX_NATIVE_WEB_SEARCH_DISABLED_CONFIG
1773
- };
1774
- return {
1775
- kind: "managed",
1776
- suppressManagedWebSearch: false,
1777
- threadConfig: CODEX_NATIVE_WEB_SEARCH_DISABLED_CONFIG
1778
- };
1779
- }
1780
- return {
1781
- kind: "native-hosted",
1782
- suppressManagedWebSearch: true,
1783
- threadConfig: buildCodexNativeWebSearchThreadConfig(params.config),
1784
- webFetchHostnameAllowlist: buildHostnameAllowlistPolicyFromSuffixAllowlist(nativeConfig?.allowedDomains)?.hostnameAllowlist
1785
- };
1786
- }
1787
- const CODEX_CODE_MODE_THREAD_CONFIG = {
1788
- "features.code_mode": true,
1789
- "features.code_mode_only": false,
1790
- "features.shell_tool": true,
1791
- "features.apply_patch_streaming_events": true,
1792
- suppress_unstable_features_warning: true
1793
- };
1794
- const CODEX_GOAL_CONTINUATION_DISABLED_THREAD_CONFIG = { "features.goals": false };
1795
- const CODEX_NATIVE_UPDATE_PLAN_DISABLED_THREAD_CONFIG = { "tools.update_plan.enabled": false };
1796
- const CODEX_CODE_MODE_DISABLED_THREAD_CONFIG = {
1797
- "features.code_mode": false,
1798
- "features.code_mode_only": false
1799
- };
1800
- const CODEX_NO_PROJECT_DOCS_CONFIG = { project_doc_max_bytes: 0 };
1801
- const CODEX_TOOL_SEARCH_UNSUPPORTED_THREAD_CONFIG = { "features.multi_agent": false };
1802
- const CODEX_DELEGATION_DISABLED_THREAD_CONFIG = {
1803
- "agents.enabled": false,
1804
- "features.multi_agent": false,
1805
- "features.multi_agent_v2": false
1806
- };
1807
- const CODEX_RING_ZERO_RESTRICTED_FEATURES = /* @__PURE__ */ new Set([
1808
- "apps",
1809
- "artifact",
1810
- "browser_use",
1811
- "browser_use_external",
1812
- "browser_use_full_cdp_access",
1813
- "chronicle",
1814
- "code_mode",
1815
- "code_mode_only",
1816
- "computer_use",
1817
- "context_management",
1818
- "current_time_reminder",
1819
- "default_mode_request_user_input",
1820
- "deferred_executor",
1821
- "goals",
1822
- "hooks",
1823
- "image_generation",
1824
- "memories",
1825
- "multi_agent",
1826
- "multi_agent_v2",
1827
- "plugins",
1828
- "request_permissions_tool",
1829
- "skill_search",
1830
- "shell_tool",
1831
- "standalone_web_search",
1832
- "token_budget",
1833
- "unified_exec",
1834
- "view_image",
1835
- "web_search_cached",
1836
- "web_search_request",
1837
- "workspace_dependencies"
1838
- ]);
1839
- const CODEX_RING_ZERO_THREAD_CONFIG = {
1840
- ...CODEX_DELEGATION_DISABLED_THREAD_CONFIG,
1841
- ...Object.fromEntries([...CODEX_RING_ZERO_RESTRICTED_FEATURES].map((feature) => [`features.${feature}`, false])),
1842
- "orchestrator.mcp.enabled": false,
1843
- "orchestrator.skills.enabled": false,
1844
- "skills.bundled.enabled": false,
1845
- "skills.include_instructions": false,
1846
- "tools.experimental_request_user_input.enabled": false,
1847
- hooks: {
1848
- PreToolUse: [],
1849
- PermissionRequest: [],
1850
- PostToolUse: [],
1851
- PreCompact: [],
1852
- PostCompact: [],
1853
- SessionStart: [],
1854
- UserPromptSubmit: [],
1855
- SubagentStart: [],
1856
- SubagentStop: [],
1857
- Stop: []
1858
- },
1859
- notify: [],
1860
- web_search: "disabled"
1861
- };
1862
- const CODEX_RING_ZERO_RESTRICTED_FEATURE_ALIASES = /* @__PURE__ */ new Map([
1863
- ["connectors", "apps"],
1864
- ["imagegenext", "image_generation"],
1865
- ["collab", "multi_agent"],
1866
- ["memory_tool", "memories"],
1867
- ["telepathy", "chronicle"],
1868
- ["codex_hooks", "hooks"]
1869
- ]);
1870
- /** Common deterministic start/resume/fork fields; no run resources or unsupported setters. */
1871
- function buildCodexThreadConfiguration(params, options) {
1872
- return {
1873
- ...options.cwd !== void 0 ? { cwd: options.cwd } : {},
1874
- ...options.appServer.sessionRoot ? { runtimeWorkspaceRoots: [options.appServer.sessionRoot] } : {},
1875
- approvalPolicy: options.appServer.approvalPolicy,
1876
- approvalsReviewer: resolveCodexThreadApprovalsReviewer(options.appServer, options.config),
1877
- ...codexThreadSandboxOrPermissions(options.appServer),
1878
- ...options.appServer.serviceTier !== void 0 ? { serviceTier: options.appServer.serviceTier } : {},
1879
- config: buildCodexRuntimeThreadConfigForRun(params, options.config, {
1880
- ...options,
1881
- directOnlyToolNamespaces: resolveDirectOnlyToolNamespaces(options.dynamicTools)
1882
- }),
1883
- developerInstructions: joinPresentSections(options.developerInstructions ?? buildDeveloperInstructions(params, { dynamicTools: options.dynamicTools }), options.refreshableInstructions)
1884
- };
1885
- }
1886
- function buildThreadStartParams(params, options) {
1887
- const resolvedModelProvider = resolveCodexAppServerModelProvider({
1888
- ...params,
1889
- homeScope: options.appServer.start.homeScope
1890
- });
1891
- const modelSelection = resolveCodexAppServerRequestModelSelection({
1892
- ...params,
1893
- homeScope: options.appServer.start.homeScope,
1894
- model: options.model ?? params.modelId,
1895
- modelProvider: options.modelProvider ?? resolvedModelProvider
1896
- });
1897
- return {
1898
- model: modelSelection.model,
1899
- ...modelSelection.modelProvider ? { modelProvider: modelSelection.modelProvider } : {},
1900
- ...buildCodexThreadConfiguration(params, options),
1901
- ...(options.hostSystemAgentActive ?? isHostScopedAgentToolActive("openclaw")) && isSystemAgentOnlyCodexDynamicToolAllowlist(params.toolsAllow) ? { baseInstructions: "" } : {},
1902
- personality: CODEX_NATIVE_PERSONALITY_NONE,
1903
- serviceName: "OpenClaw",
1904
- threadSource: "openclaw",
1905
- ...resolveCodexThreadEnvironmentSelection(params.requireWorkspaceOnly === true ? { nativeCodeModeEnabled: false } : options),
1906
- dynamicTools: [...options.dynamicTools],
1907
- experimentalRawEvents: true,
1908
- ...isIncognitoSessionKey(params.sessionKey) ? { ephemeral: true } : {}
1909
- };
1910
- }
1911
- function buildThreadResumeParams(params, options) {
1912
- const modelSelection = options.preserveNativeModel ? void 0 : resolveCodexAppServerRequestModelSelection({
1913
- ...params,
1914
- homeScope: options.appServer.start.homeScope,
1915
- model: options.model ?? params.modelId,
1916
- modelProvider: options.modelProvider ?? resolveCodexAppServerModelProvider({
1917
- ...params,
1918
- homeScope: options.appServer.start.homeScope,
1919
- authProfileId: options.authProfileId ?? params.authProfileId
1920
- }),
1921
- authProfileId: options.authProfileId ?? params.authProfileId
1922
- });
1923
- return {
1924
- threadId: options.threadId,
1925
- excludeTurns: true,
1926
- initialTurnsPage: {
1927
- limit: 1,
1928
- sortDirection: "desc",
1929
- itemsView: "notLoaded"
1930
- },
1931
- ...modelSelection ? {
1932
- model: modelSelection.model,
1933
- ...modelSelection.modelProvider ? { modelProvider: modelSelection.modelProvider } : {}
1934
- } : {},
1935
- ...buildCodexThreadConfiguration(params, options),
1936
- personality: CODEX_NATIVE_PERSONALITY_NONE
1937
- };
1938
- }
1939
- function buildCodexRuntimeThreadConfig(config, options = {}) {
1940
- const configured = buildCodexProjectDocThreadConfig(config);
1941
- const codeModeConfig = {
1942
- ...CODEX_CODE_MODE_THREAD_CONFIG,
1943
- "features.code_mode_only": options.nativeCodeModeOnlyEnabled === true
1944
- };
1945
- if (options.nativeCodeModeEnabled === false) {
1946
- const disabledConfig = expectDefined(mergeCodexThreadConfigs(configured, CODEX_CODE_MODE_DISABLED_THREAD_CONFIG, CODEX_GOAL_CONTINUATION_DISABLED_THREAD_CONFIG, CODEX_NATIVE_UPDATE_PLAN_DISABLED_THREAD_CONFIG), "Codex disabled code mode config");
1947
- delete disabledConfig["features.apply_patch_streaming_events"];
1948
- return disabledConfig;
1949
- }
1950
- return ensureDirectOnlyToolNamespaces(expectDefined(mergeCodexThreadConfigs(codeModeConfig, configured, CODEX_GOAL_CONTINUATION_DISABLED_THREAD_CONFIG, CODEX_NATIVE_UPDATE_PLAN_DISABLED_THREAD_CONFIG, options.nativeCodeModeOnlyEnabled === true ? { "features.code_mode_only": true } : void 0), options.nativeCodeModeOnlyEnabled === true ? "Codex code mode only config" : "Codex code mode config"), options.directOnlyToolNamespaces);
1951
- }
1952
- function ensureDirectOnlyToolNamespaces(config, requiredNamespaces) {
1953
- if (!requiredNamespaces?.length) return config;
1954
- const feature = expectDefined(config["features.code_mode"], "Codex code mode config");
1955
- const configured = isJsonObject(feature) ? feature : { enabled: feature };
1956
- const namespaces = Array.isArray(configured.direct_only_tool_namespaces) ? configured.direct_only_tool_namespaces.filter((entry) => typeof entry === "string" && entry.length > 0) : [];
1957
- return {
1958
- ...config,
1959
- "features.code_mode": {
1960
- ...configured,
1961
- direct_only_tool_namespaces: [.../* @__PURE__ */ new Set([...namespaces, ...requiredNamespaces])]
1962
- }
1963
- };
1964
- }
1965
- function resolveDirectOnlyToolNamespaces(dynamicTools) {
1966
- return (dynamicTools ?? []).filter((tool) => tool.type === "namespace" && tool.name === "openclaw_direct").map((tool) => tool.name);
1967
- }
1968
- function isCodexNativeDelegationDisabledForRun(params, hostSystemAgentActive = isHostScopedAgentToolActive("openclaw")) {
1969
- return isCodexResponsesOAuthRun(params) || params.delegationCapability === "report_only" || params.requireWorkspaceOnly === true || params.pluginHarnessToolPolicyRestricted === true || isMessageOnlyCodexSourceReply(params) || hostSystemAgentActive && isSystemAgentOnlyCodexDynamicToolAllowlist(params.toolsAllow);
1970
- }
1971
- function buildCodexRuntimeThreadConfigForRun(params, config, options = {}) {
1972
- const ringZeroActive = (options.hostSystemAgentActive ?? isHostScopedAgentToolActive("openclaw")) && isSystemAgentOnlyCodexDynamicToolAllowlist(params.toolsAllow);
1973
- const messageOnlySourceReply = isMessageOnlyCodexSourceReply(params);
1974
- const restrictedToolSurface = ringZeroActive || messageOnlySourceReply || params.pluginHarnessToolPolicyRestricted === true || params.requireWorkspaceOnly === true;
1975
- const restrictedTurnDisablesProjectDocs = ringZeroActive || messageOnlySourceReply || params.pluginHarnessToolPolicyRestricted && params.disableTools;
1976
- const configMcpServers = config?.mcp_servers;
1977
- if (restrictedToolSurface && configMcpServers !== void 0 && !isJsonObject(configMcpServers)) throw new Error("Codex restricted tool surface received invalid thread mcp_servers config");
1978
- const restrictedToolSurfaceMcpServerNames = [...options.restrictedToolSurfaceInheritedMcpServerNames ?? [], ...isJsonObject(configMcpServers) ? Object.keys(configMcpServers) : []];
1979
- const webSearchConfig = resolveCodexWebSearchPlan({
1980
- config: params.config,
1981
- disableTools: params.disableTools,
1982
- nativeToolSurfaceEnabled: isCodexResponsesOAuthRun(params) || options.nativeCodeModeEnabled,
1983
- nativeProviderWebSearchSupport: options.nativeProviderWebSearchSupport,
1984
- webSearchAllowed: options.webSearchAllowed
1985
- }).threadConfig;
1986
- const baseConfig = buildCodexRuntimeThreadConfig(mergeCodexThreadConfigs(config, webSearchConfig), options);
1987
- return applyCodexManagedShellEnvironment({
1988
- ...mergeCodexThreadConfigs(baseConfig, options.appServer?.networkProxy?.configPatch, isCodexNativeDelegationDisabledForRun(params, options.hostSystemAgentActive) ? CODEX_DELEGATION_DISABLED_THREAD_CONFIG : void 0, isCodexResponsesOAuthRun(params) ? {
1989
- "features.apps": false,
1990
- "features.plugins": false,
1991
- "features.image_generation": false,
1992
- "features.memories": false,
1993
- "features.skill_search": false,
1994
- "orchestrator.skills.enabled": false,
1995
- "orchestrator.mcp.enabled": false,
1996
- "skills.bundled.enabled": false
1997
- } : void 0, params.pluginHarnessToolPolicySafeDeniedTools?.includes("image_generate") ? { "features.image_generation": false } : void 0, shouldDisableCodexToolSearchForModel(params.modelId) ? CODEX_TOOL_SEARCH_UNSUPPORTED_THREAD_CONFIG : void 0, messageOnlySourceReply || params.pluginHarnessToolPolicyRestricted === true || params.requireWorkspaceOnly === true ? buildRestrictedToolConfigPatch(restrictedToolSurfaceMcpServerNames, Boolean(params.scheduledRuntimeAuthority) && !isCodexResponsesOAuthRun(params) && params.requireWorkspaceOnly !== true) : buildCodexRingZeroThreadConfigPatch(params, options.hostSystemAgentActive, restrictedToolSurfaceMcpServerNames), restrictedTurnDisablesProjectDocs ? CODEX_NO_PROJECT_DOCS_CONFIG : void 0, params.authoredContextTokenCap === void 0 ? void 0 : { model_context_window: params.authoredContextTokenCap }) ?? baseConfig,
1998
- ...params.bootstrapContextMode === "lightweight" ? CODEX_NO_PROJECT_DOCS_CONFIG : {}
1999
- }, options.shellEnvironment, options.disableLoginShell, options.shellPathPrepend);
2000
- }
2001
- function buildCodexRingZeroThreadConfigPatch(params, hostSystemAgentActive = isHostScopedAgentToolActive("openclaw"), inheritedMcpServerNames = []) {
2002
- if (!hostSystemAgentActive || !isSystemAgentOnlyCodexDynamicToolAllowlist(params.toolsAllow)) return;
2003
- return {
2004
- ...buildRestrictedToolConfigPatch(inheritedMcpServerNames),
2005
- ...CODEX_NO_PROJECT_DOCS_CONFIG
2006
- };
2007
- }
2008
- function buildRestrictedToolConfigPatch(inheritedMcpServerNames, scheduledAppAuthorityActive = false) {
2009
- const mcpServers = Object.fromEntries([...new Set(inheritedMcpServerNames)].toSorted().map((name) => [name, { enabled: false }]));
2010
- return {
2011
- ...CODEX_RING_ZERO_THREAD_CONFIG,
2012
- ...scheduledAppAuthorityActive ? {
2013
- "features.apps": true,
2014
- "orchestrator.mcp.enabled": true
2015
- } : {},
2016
- ...Object.keys(mcpServers).length > 0 ? { mcp_servers: mcpServers } : {}
2017
- };
2018
- }
2019
- async function readCodexInheritedMcpServerNames(client, cwd, signal, effectiveConfig) {
2020
- const response = effectiveConfig ?? await readCodexEffectiveConfig(client, cwd, { signal });
2021
- if (!Array.isArray(response.layers)) throw new Error("Codex config/read omitted effective config layers");
2022
- for (const layer of response.layers) {
2023
- if (!isJsonObject(layer) || !isJsonObject(layer.name) || typeof layer.name.type !== "string") throw new Error("Codex config/read returned invalid effective config layers");
2024
- if (layer.name.type === "legacyManagedConfigTomlFromFile" || layer.name.type === "legacyManagedConfigTomlFromMdm") {
2025
- const migrationGuidance = layer.name.type === "legacyManagedConfigTomlFromFile" ? "migrate /etc/codex/managed_config.toml to /etc/codex/requirements.toml before running restricted or isolated turns. For ChatGPT-only authentication, use allowed_login_methods = [\"chatgpt\"] in /etc/codex/requirements.toml" : "replace the legacy MDM payload with base64-encoded TOML requirements in the com.openai.codex managed preference requirements_toml_base64 before running restricted or isolated turns. For ChatGPT-only authentication, include allowed_login_methods = [\"chatgpt\"] in that TOML payload";
2026
- throw new Error(`Codex restricted tool surface cannot override config layer ${layer.name.type}; ${migrationGuidance}.`);
2027
- }
2028
- if (!CODEX_SESSION_OVERRIDABLE_LAYER_TYPES.has(layer.name.type)) throw new Error(`Codex restricted tool surface does not recognize config layer ${layer.name.type}`);
2029
- }
2030
- const configuredServers = response.config.mcp_servers;
2031
- if (configuredServers === void 0) return [];
2032
- if (!isJsonObject(configuredServers)) throw new Error("Codex config/read returned invalid mcp_servers");
2033
- return Object.keys(configuredServers).toSorted();
2034
- }
2035
- async function assertCodexManagedRequirementsDoNotOverrideToolPolicy(client, options, signal) {
2036
- const requirements = await readCodexManagedRequirements(client, signal);
2037
- const managedRequirementsFingerprint = buildCodexManagedRequirementsFingerprint(requirements);
2038
- const managedRequirementsMatch = options.allowedManagedRequirementsFingerprint !== void 0 && managedRequirementsFingerprint === options.allowedManagedRequirementsFingerprint;
2039
- const managedHooksAllowed = managedRequirementsMatch || options.allowConfiguredManagedHooks === true;
2040
- if (options.allowedManagedRequirementsFingerprint !== void 0 && !managedRequirementsMatch) throw new Error("Codex managed requirements changed since this automation was authorized; reauthorize the automation from a fresh owner turn");
2041
- if (requirements === null) return { enableManagedHooks: managedHooksAllowed && options.privateManagedHooksPresent === true };
2042
- let hasManagedHooks = false;
2043
- let requiredHooksEnabled;
2044
- if (options.restrictedToolSurface) for (const key of [
2045
- "hooks",
2046
- "managedHooks",
2047
- "managed_hooks"
2048
- ]) {
2049
- const hooks = requirements[key];
2050
- if (hooks === void 0 || hooks === null) continue;
2051
- if (!isJsonObject(hooks)) throw new Error("Codex configRequirements/read returned invalid managed hooks");
2052
- hasManagedHooks ||= hasNonEmptyJsonValue(hooks);
2053
- if (hasManagedHooks && !managedHooksAllowed) throw new Error("Codex restricted tool surface cannot override managed hooks");
2054
- }
2055
- const additionalDeniedFeatures = new Set(options.additionalDeniedFeatures);
2056
- for (const key of ["featureRequirements", "feature_requirements"]) {
2057
- const featureRequirements = requirements[key];
2058
- if (featureRequirements === void 0 || featureRequirements === null) continue;
2059
- if (!isJsonObject(featureRequirements)) throw new Error("Codex configRequirements/read returned invalid feature requirements");
2060
- for (const [feature, enabled] of Object.entries(featureRequirements)) {
2061
- if (typeof enabled !== "boolean") throw new Error("Codex configRequirements/read returned invalid feature requirements");
2062
- const canonicalFeature = CODEX_RING_ZERO_RESTRICTED_FEATURE_ALIASES.get(feature) ?? feature;
2063
- if (options.requiredNativeShell && canonicalFeature === "shell_tool" && !enabled) throw new Error("Codex native code mode requires shell_tool, but managed requirements disable it. Ask your administrator to allow the shell, or select a tool policy that disables native code mode; no automation authority was captured.");
2064
- const deniedByToolPolicy = options.restrictedToolSurface && CODEX_RING_ZERO_RESTRICTED_FEATURES.has(canonicalFeature) || additionalDeniedFeatures.has(canonicalFeature);
2065
- if (canonicalFeature === "hooks" && managedHooksAllowed) {
2066
- requiredHooksEnabled = enabled;
2067
- continue;
2068
- }
2069
- if (enabled && deniedByToolPolicy) throw new Error(`Codex tool policy cannot override required feature ${feature}`);
2070
- }
2071
- }
2072
- return { enableManagedHooks: managedHooksAllowed && requiredHooksEnabled !== false && (hasManagedHooks || options.privateManagedHooksPresent === true || requiredHooksEnabled === true) };
2073
- }
2074
- /** Hashes the exact managed requirements without retaining their hook commands or policy details. */
2075
- function buildCodexManagedRequirementsFingerprint(requirements) {
2076
- const fingerprint = fingerprintJsonObject({
2077
- version: 1,
2078
- requirements
2079
- });
2080
- return crypto.createHash("sha256").update(fingerprint).digest("hex");
2081
- }
2082
- /** Reads and fingerprints the exact managed requirements active on this app-server. */
2083
- async function readCodexManagedRequirementsFingerprint(client, signal) {
2084
- return buildCodexManagedRequirementsFingerprint(await readCodexManagedRequirements(client, signal));
2085
- }
2086
- async function readCodexManagedRequirements(client, signal) {
2087
- const response = await client.request("configRequirements/read", void 0, { signal });
2088
- if (!isJsonObject(response) || !Object.hasOwn(response, "requirements")) throw new Error("Codex configRequirements/read returned an invalid response");
2089
- if (response.requirements !== null && !isJsonObject(response.requirements)) throw new Error("Codex configRequirements/read returned invalid requirements");
2090
- return response.requirements;
2091
- }
2092
- function hasNonEmptyJsonValue(value) {
2093
- if (value === null || value === false || value === "") return false;
2094
- if (Array.isArray(value)) return value.length > 0;
2095
- if (typeof value === "object") return Object.values(value).some(hasNonEmptyJsonValue);
2096
- return true;
2097
- }
2098
- function resolveCodexThreadApprovalsReviewer(appServer, config) {
2099
- return config?.approvals_reviewer === "user" ? "user" : appServer.approvalsReviewer;
2100
- }
2101
- function codexThreadSandboxOrPermissions(appServer) {
2102
- if (appServer.networkProxy) return {};
2103
- return { sandbox: appServer.sandbox };
2104
- }
2105
- function resolveCodexThreadEnvironmentSelection(options) {
2106
- if (options.nativeCodeModeEnabled === false) return { environments: [] };
2107
- if (options.environmentSelection) return { environments: options.environmentSelection };
2108
- return {};
2109
- }
2110
- //#endregion
2111
- export { legacyFingerprintUserMcpServersConfigPatch as $, buildCodexNativeHookRelayId as A, hasCodexNativeToolCatalog as B, buildCodexProjectDocThreadConfig as C, mergeCodexThreadConfigs as Ct, assertCodexNativeHookRelayAllowed as D, CodexManagedHooksOnlyError as E, buildCodexAppApprovalOverrides as Et, scheduleCodexNativeHookRelayUnregister as F, areCodexDynamicToolFingerprintsCompatible as G, parseCodexNativeToolCatalog as H, attestCodexThreadToolSurface as I, codexLegacyDynamicToolsFingerprint as J, areUserMcpServersFingerprintsCompatible as K, checkCodexThreadAppAvailability as L, emitCodexNativePreToolUseFailureDiagnostic as M, resolveCodexNativeHookRelayEvents as N, buildCodexNativeHookRelayConfig as O, resolveCodexNativeHookRelayTtlMs as P, fingerprintUserMcpServersConfigPatch as Q, discardUnattestedCodexPluginThread as R, joinPresentSections as S, isCodexPluginThreadBindingStale as St, CODEX_NATIVE_HOOK_RELAY_TTL_GRACE_MS as T, shouldBuildCodexPluginThreadConfig as Tt, applyCodexNativeSkillIsolation as U, loadCodexNativeToolCatalog as V, resolveCodexNativeSkillIsolation as W, fingerprintEnvironmentSelection as X, fingerprintCodexThreadConfig as Y, fingerprintJsonObject as Z, CODEX_NATIVE_PERSONALITY_NONE as _, buildCodexPluginThreadConfigInputFingerprint as _t, buildCodexThreadConfiguration as a, shouldRotateCodexAppServerBindingForRuntime as at, resolveCodexAppServerThreadModelSelection as b, buildPluginAppPolicyContext as bt, codexThreadSandboxOrPermissions as c, filterCodexDynamicToolsForDisabledNativeSurface as ct, readCodexManagedRequirementsFingerprint as d, isSystemAgentOnlyCodexDynamicToolAllowlist as dt, readActiveCodexTurnIdsFromResume as et, resolveCodexThreadApprovalsReviewer as f, normalizeCodexDynamicToolName as ft, buildDeveloperInstructions as g, buildCodexPluginThreadConfig as gt, mergeCodexNativeShellEnvironment as h, buildCodexPluginAppsConfigPatchFromPolicyContext as ht, buildCodexRuntimeThreadConfigForRun as i, shouldRecheckRecoverablePluginBinding as it, createCodexNativeHookRelay as j, buildCodexNativeHookRelayDisabledConfig as k, isCodexNativeDelegationDisabledForRun as l, isForcedPrivateQaCodexRuntime as lt, resolveCodexWebSearchPlan as m, resolveCodexDynamicToolsLoadingForRuntime as mt, buildCodexRingZeroThreadConfigPatch as n, stabilizeJsonValue as nt, buildThreadResumeParams as o, shouldRotateCodexGpt56MultiAgentBinding as ot, buildCodexNativeWebSearchThreadConfig as p, resolveCodexDynamicToolsLoading as pt, codexDynamicToolsFingerprint as q, buildCodexRuntimeThreadConfig as r, isTransientWebSearchRestriction as rt, buildThreadStartParams as s, filterCodexDynamicTools as st, assertCodexManagedRequirementsDoNotOverrideToolPolicy as t, shouldStartTransientNoToolThread as tt, readCodexInheritedMcpServerNames as u, isMessageOnlyCodexSourceReply as ut, resolveCodexAppServerModelProvider as v, buildCodexPluginThreadConfigTimeoutFallback as vt, mergeCodexNativeProjectDocThreadConfig as w, refreshCodexPluginAppApprovalPolicy as wt, resolveCodexBindingModelProviderFallback as x, disableUnlistedCodexApps as xt, resolveCodexAppServerRequestModelSelection as y, buildDisabledAppsConfigPatch as yt, attestCodexRestrictedToolSurfaceMcpServersDisabled as z };