@openclaw/codex 2026.9.5 → 2026.9.6

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