@openclaw/codex 2026.10.1 → 2026.10.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/.setup/{account-usage-runtime-B7Vg4rmy.mjs → account-usage-runtime-QBZsvZS8.mjs} +8 -7
  2. package/dist/.setup/{app-server-policy-Bg4FZw1f.mjs → app-server-policy-D_zv8J7V.mjs} +3 -4
  3. package/dist/.setup/{apply-BzlIkqSz.mjs → apply-CBMV8LN0.mjs} +40 -51
  4. package/dist/.setup/{attempt-client-cleanup-HXQxfMc1.mjs → attempt-client-cleanup-t-kd_1ys.mjs} +6 -6
  5. package/dist/.setup/attempt-terminal-jO5IMj9K.mjs +2 -0
  6. package/dist/.setup/{attempt-workspace-context-BmCutoyg.mjs → attempt-workspace-context-CcwP3DA3.mjs} +21 -18
  7. package/dist/.setup/{auth-binding-BoMwpuPN.mjs → auth-binding-BaxlhaNx.mjs} +2 -2
  8. package/dist/.setup/{auth-cache-key-BCCQHWdc.mjs → auth-cache-key-DyfUvsSa.mjs} +30 -41
  9. package/dist/.setup/{binding-connection-C-08ez1w.mjs → binding-connection-B7HAAZSI.mjs} +2 -2
  10. package/dist/.setup/{binding-connection.runtime-Dn2p-fdy.mjs → binding-connection.runtime-DAXn7iFl.mjs} +6 -5
  11. package/dist/.setup/{bounded-turn-Cv4uIEzz.mjs → bounded-turn-CyQVQwGe.mjs} +21 -17
  12. package/dist/.setup/{bounded-turn-isolation-DklXNk3k.mjs → bounded-turn-isolation-BfDAo-qZ.mjs} +4 -4
  13. package/dist/.setup/{build-state-BwxNfFEB.mjs → build-state-CzLMy1S9.mjs} +1 -1
  14. package/dist/.setup/{capabilities-kQntafj_.mjs → capabilities-DbOzOglY.mjs} +1 -1
  15. package/dist/.setup/{client-catalog-response-BNFDYAKh.mjs → client-catalog-response-DsbEAtpd.mjs} +25 -32
  16. package/dist/.setup/{client-BIRVBXXb.mjs → client-y7nO6X9c.mjs} +198 -247
  17. package/dist/.setup/{command-dispatch-D3_ypl-R.mjs → command-dispatch-uA9lz2Kf.mjs} +3 -4
  18. package/dist/.setup/{command-formatters-DV3DHhdr.mjs → command-formatters-xW9KpoSZ.mjs} +16 -26
  19. package/dist/.setup/{command-handlers-KPit4G0p.mjs → command-handlers-VBaJnpZo.mjs} +270 -360
  20. package/dist/.setup/{command-rpc-CmQDOxY9.mjs → command-rpc-C9VxOLuG.mjs} +19 -18
  21. package/dist/.setup/{compact-CLLteFIY.mjs → compact-CD8xJxXS.mjs} +41 -61
  22. package/dist/.setup/{computer-use-BVxocZZc.mjs → computer-use-CiToXF5C.mjs} +109 -147
  23. package/dist/.setup/{config-0Gxk3_eq.mjs → config-C1YVVLEA.mjs} +32 -59
  24. package/dist/.setup/config-contracts.shared-D85SGEuq.mjs +4 -0
  25. package/dist/.setup/{config-options-HG_Rr3W_.mjs → config-options-DDzeNQ8m.mjs} +52 -90
  26. package/dist/.setup/{config-parsing-BQq-CHTF.mjs → config-parsing-DsWSCPHO.mjs} +19 -55
  27. package/dist/.setup/{config-runtime-cUYrqu_a.mjs → config-runtime-DWzK-k0n.mjs} +2 -2
  28. package/dist/.setup/{config-security-KAPScztc.mjs → config-security-clxAZYWX.mjs} +35 -39
  29. package/dist/.setup/config-utils-DN_YT7dE.mjs +47 -0
  30. package/dist/.setup/{context-engine-projection-CsgYSQhW.mjs → context-engine-projection-ps-yn_ci.mjs} +10 -22
  31. package/dist/.setup/{conversation-binding-DJ_288rC.mjs → conversation-binding-CTSLDM9S.mjs} +85 -119
  32. package/dist/.setup/{conversation-binding-data-DJ4ix-W5.mjs → conversation-binding-data-UgLuTSQT.mjs} +9 -8
  33. package/dist/.setup/{conversation-control-CuiZ_pDL.mjs → conversation-control-GXM3unE4.mjs} +7 -10
  34. package/dist/.setup/{cyber-failover-Bb1J6hS1.mjs → cyber-failover-D4dgNfFf.mjs} +2 -5
  35. package/dist/.setup/{cyber-failover-notice-XR03ef31.mjs → cyber-failover-notice-ljgGGL0s.mjs} +1 -1
  36. package/dist/.setup/{doctor-start-options-DPW9JxIE.mjs → doctor-start-options-JjTAl-q_.mjs} +5 -5
  37. package/dist/.setup/{dynamic-tool-build-DgWZMfAQ.mjs → dynamic-tool-build-D731PCdv.mjs} +57 -69
  38. package/dist/.setup/{dynamic-tools-Ct6GKAFr.mjs → dynamic-tools-D0pYbxHH.mjs} +689 -710
  39. package/dist/.setup/{effective-mcp-catalog-DmCSc8TS.mjs → effective-mcp-catalog-1hWFKghy.mjs} +11 -20
  40. package/dist/.setup/{elicitation-input-r9axtppm.mjs → elicitation-input-DXG_qaXr.mjs} +14 -20
  41. package/dist/.setup/{ephemeral-turn-_cBMKCFb.mjs → ephemeral-turn-Cphy5Qr_.mjs} +3 -3
  42. package/dist/.setup/{event-projector-assistant-message-C3Tpt370.mjs → event-projector-assistant-message-CLMKN4x-.mjs} +2 -2
  43. package/dist/.setup/{event-projector-usage-03R0I2dM.mjs → event-projector-usage-BpKfdoTm.mjs} +20 -33
  44. package/dist/.setup/{event-projector-values-DTqZHizf.mjs → event-projector-values-CLvG1Hil.mjs} +4 -5
  45. package/dist/.setup/history-rejection-B4nOXNXF.mjs +13 -0
  46. package/dist/.setup/{inference-context-D-9gWlTR.mjs → inference-context-DNlGwzwy.mjs} +10 -11
  47. package/dist/.setup/{inference-dispatch-B5UKEUyC.mjs → inference-dispatch-CO6tTs4q.mjs} +5 -4
  48. package/dist/.setup/{inference-metadata-CgIf7sOx.mjs → inference-metadata-DCvcG_N_.mjs} +36 -41
  49. package/dist/.setup/{inference-proxy-DUO5E2QQ.mjs → inference-proxy-BDWV0djM.mjs} +10 -14
  50. package/dist/.setup/{isolated-completion-CjrQEeke.mjs → isolated-completion-Bhqd2yBq.mjs} +8 -8
  51. package/dist/.setup/local-runtime-attribution-CZz2DJ4q.mjs +15 -0
  52. package/dist/.setup/{managed-binary-C1VFoVPf.mjs → managed-binary-BtIjV7yN.mjs} +16 -36
  53. package/dist/.setup/{mcp-app-session-preparation-D0yRoreX.mjs → mcp-app-session-preparation-DqSvxFqc.mjs} +24 -25
  54. package/dist/.setup/{mcp-tool-metadata-j10HhfTC.mjs → mcp-tool-metadata-DW41snf3.mjs} +1 -1
  55. package/dist/.setup/{model-catalog--G4arndd.mjs → model-catalog-B227ST3D.mjs} +6 -6
  56. package/dist/.setup/{models-BYbLQPnj.mjs → models-DdRyi93L.mjs} +6 -10
  57. package/dist/.setup/{native-auth-Cjb9y7IZ.mjs → native-auth-esN5MdIv.mjs} +5 -5
  58. package/dist/.setup/{native-execution-policy-ClzpdG3D.mjs → native-execution-policy-MXEe7PB3.mjs} +11 -28
  59. package/dist/.setup/native-hook-relay-BUWIOrSr.mjs +561 -0
  60. package/dist/.setup/{native-mcp-app-5i5eRCwO.mjs → native-mcp-app-CjxJQ4F7.mjs} +6 -6
  61. package/dist/.setup/native-skill-isolation-UMVoNjZz.mjs +391 -0
  62. package/dist/.setup/{native-subagent-monitor-B2C8D_N0.mjs → native-subagent-monitor-iHc8oLg5.mjs} +505 -639
  63. package/dist/.setup/{native-subagent-pending-assignments-BDqhOdJp.mjs → native-subagent-pending-assignments-DmVhedNs.mjs} +11 -23
  64. package/dist/.setup/{native-task-assignments-C6KVqiN1.mjs → native-task-assignments-DimsQ9Qa.mjs} +73 -27
  65. package/dist/.setup/{node-cli-sessions-B5oNDkUS.mjs → node-cli-sessions-CzKg2nGq.mjs} +18 -26
  66. package/dist/.setup/{node-exec-server.runtime-0xSEjKYt.mjs → node-exec-server.runtime-BWkULhBM.mjs} +5 -8
  67. package/dist/.setup/{plan-B5bDIEuQ.mjs → plan-C_F3aio0.mjs} +40 -50
  68. package/dist/.setup/{plugin-activation-BcyBv8PG.mjs → plugin-activation-D7WkJMvU.mjs} +4 -5
  69. package/dist/.setup/{plugin-app-cache-key-BW8rd98k.mjs → plugin-app-cache-key-Bg9DbDI6.mjs} +18 -23
  70. package/dist/.setup/{plugin-approval-roundtrip-C_SGp5YW.mjs → plugin-approval-roundtrip-BSV-51ig.mjs} +4 -6
  71. package/dist/.setup/{plugin-inventory-Bf0_piTw.mjs → plugin-inventory-CYgdo14P.mjs} +28 -43
  72. package/dist/.setup/{plugin-marketplace-discovery-SQPhSuic.mjs → plugin-marketplace-discovery-BblHM3DU.mjs} +7 -10
  73. package/dist/.setup/{plugin-metadata-cache-DWnB7VMj.mjs → plugin-metadata-cache-Bi8TAPwX.mjs} +5 -10
  74. package/dist/.setup/project-doc-thread-config-BVcvnps8.mjs +490 -0
  75. package/dist/.setup/{provider-BoIby-eX.mjs → provider-BJ4xhaGX.mjs} +4 -4
  76. package/dist/.setup/{provider-capabilities-B4yq6UgQ.mjs → provider-capabilities-CjRaV3bx.mjs} +1 -1
  77. package/dist/.setup/{rate-limits-CMPy24F5.mjs → rate-limits-CI8pTPqL.mjs} +15 -32
  78. package/dist/.setup/reasoning-effort-CS9kKWB9.mjs +37 -0
  79. package/dist/.setup/{request-DD3u22uv.mjs → request-Y8dmbqZ3.mjs} +28 -48
  80. package/dist/.setup/{rpc-error-hmWM21RB.mjs → rpc-error-C98SHchT.mjs} +3 -6
  81. package/dist/.setup/{run-attempt-DOVF5OON.mjs → run-attempt-Dx7a4Mfm.mjs} +927 -859
  82. package/dist/.setup/{run-attempt-lifecycle-BuZgVbDA.mjs → run-attempt-lifecycle-KN4oh-7O.mjs} +13 -4
  83. package/dist/.setup/{runtime-artifact-CUTOOnKw.mjs → runtime-artifact-C13pR7tD.mjs} +18 -22
  84. package/dist/.setup/{runtime-artifact-connection-CADz3_BY.mjs → runtime-artifact-connection-jS5DeCok.mjs} +3 -3
  85. package/dist/.setup/{sandbox-guard-WqE8yPge.mjs → sandbox-guard-DIImwCy1.mjs} +4 -6
  86. package/dist/.setup/service-tier-normalization-BPgw2Wdt.mjs +9 -0
  87. package/dist/.setup/{session-binding-Ce7BqiPN.mjs → session-binding-JEHNMPsr.mjs} +13 -40
  88. package/dist/.setup/{session-binding-record-BZB8RgcF.mjs → session-binding-record-DU_0biMD.mjs} +4 -4
  89. package/dist/.setup/{session-binding-record-codec-z4ZpDn6E.mjs → session-binding-record-codec-BpH8u_G9.mjs} +16 -39
  90. package/dist/.setup/{session-binding-sidecars-BrdV95Fg.mjs → session-binding-sidecars-DD-enC8w.mjs} +49 -54
  91. package/dist/.setup/{session-catalog-adoption-CPIP4S_y.mjs → session-catalog-adoption-Ca3OYGYM.mjs} +23 -27
  92. package/dist/.setup/{session-catalog-archive-DcgwvSbF.mjs → session-catalog-archive-Bv6gV7x9.mjs} +6 -6
  93. package/dist/.setup/{session-catalog-events-DRaivXvC.mjs → session-catalog-events-DzFlXNUe.mjs} +6 -5
  94. package/dist/.setup/{session-catalog-index-qwmgqC4t.mjs → session-catalog-index-DozvkUPd.mjs} +111 -105
  95. package/dist/.setup/{session-catalog-index-order-nhyO0wdW.mjs → session-catalog-index-order-CTfoefow.mjs} +28 -5
  96. package/dist/.setup/{session-catalog-limits-DEU36Qlo.mjs → session-catalog-limits-BynIoOYm.mjs} +1 -1
  97. package/dist/.setup/{session-catalog-list-request-tXephOB4.mjs → session-catalog-list-request-D4MYNgDB.mjs} +11 -8
  98. package/dist/.setup/{session-catalog-native-projection-z9Q608QW.mjs → session-catalog-native-projection-rCKnZud1.mjs} +5 -61
  99. package/dist/.setup/{session-catalog-node-adoption-7-WEQTB1.mjs → session-catalog-node-adoption-BdP9Zjqo.mjs} +2 -2
  100. package/dist/.setup/{session-catalog-node-continue-DLWBwAAO.mjs → session-catalog-node-continue-CNJibO4_.mjs} +27 -49
  101. package/dist/.setup/{session-catalog-node-lookup-Uufckwcm.mjs → session-catalog-node-lookup-BH_DBGa9.mjs} +3 -3
  102. package/dist/.setup/{session-catalog-parsing-B-qWJh2x.mjs → session-catalog-parsing-DkeoVn60.mjs} +9 -19
  103. package/dist/.setup/{session-catalog-projection-Cl0Nc7c6.mjs → session-catalog-projection-DDVmALHj.mjs} +8 -22
  104. package/dist/.setup/session-catalog-source-CygTGmrb.mjs +58 -0
  105. package/dist/.setup/{session-cli-kH4vuGod.mjs → session-cli-GwU0izn-.mjs} +20 -41
  106. package/dist/.setup/{session-history-BogBHKLk.mjs → session-history-BO6i_pfk.mjs} +1 -1
  107. package/dist/.setup/{session-history-import-NWKPa4ZO.mjs → session-history-import-CaO8s6ta.mjs} +4 -4
  108. package/dist/.setup/{session-history-read-CNN8zwbD.mjs → session-history-read-BI_2jRED.mjs} +4 -15
  109. package/dist/.setup/{session-history.worker-Cq_4DYgN.mjs → session-history.worker-DJQfek5p.mjs} +147 -159
  110. package/dist/.setup/{session-initialization-D6dtFQkE.mjs → session-initialization-Bi_2DKhc.mjs} +3 -5
  111. package/dist/.setup/{session-permission-policy-BxIUJ0Zd.mjs → session-permission-policy-CD2MAWU8.mjs} +12 -20
  112. package/dist/.setup/{session-retirement-Bt3b0fpe.mjs → session-retirement-IoS3zr17.mjs} +7 -7
  113. package/dist/.setup/{settled-turn-context-BZsMjkIO.mjs → settled-turn-context-BPL6D3RO.mjs} +1 -1
  114. package/dist/.setup/{settled-turn-finalizer-e_24O6HA.mjs → settled-turn-finalizer-X-Fylp-u.mjs} +12 -11
  115. package/dist/.setup/{shared-client-DeenOD8U.mjs → shared-client-ByIwuAC-.mjs} +172 -229
  116. package/dist/.setup/{side-question-BZHn_1Jm.mjs → side-question-BDUdozFy.mjs} +116 -137
  117. package/dist/.setup/{source-0ClinBHI.mjs → source-Bxbqf3S1.mjs} +37 -56
  118. package/dist/.setup/thread-archive-guard-LKdwQKyr.mjs +56 -0
  119. package/dist/.setup/{thread-lifecycle-CoqYpbpk.mjs → thread-lifecycle-run-CfP4PnEf.mjs} +348 -484
  120. package/dist/.setup/thread-model-selection-DcVebr8N.mjs +61 -0
  121. package/dist/.setup/{thread-ownership-CSDZ6mHd.mjs → thread-ownership-Be53aiaG.mjs} +5 -5
  122. package/dist/.setup/{thread-ownership-queue-Dp24d7-F.mjs → thread-ownership-queue-CeyYScUC.mjs} +5 -6
  123. package/dist/.setup/{thread-policy-DCC9lQjC.mjs → thread-policy-CHgY-KNl.mjs} +4 -4
  124. package/dist/.setup/thread-requests-BgzJwJtS.mjs +745 -0
  125. package/dist/.setup/{thread-resume--WOKWxZd.mjs → thread-resume-B2EmMcgE.mjs} +5 -5
  126. package/dist/.setup/{timeout-CXOfNoaX.mjs → timeout-D0mEWSGG.mjs} +6 -12
  127. package/dist/.setup/{transcript-history-projection-B9a7HwUV.mjs → transcript-history-projection-DfKcoZCB.mjs} +3 -4
  128. package/dist/.setup/{transcript-mirror-BfLRARNL.mjs → transcript-mirror-Bee2o6jj.mjs} +68 -68
  129. package/dist/.setup/{transcript-mirror-attestation-YSegaktH.mjs → transcript-mirror-attestation-BzUXnrvv.mjs} +5 -2
  130. package/dist/.setup/{transport-stdio-a0HDa2Mj.mjs → transport-stdio-CRWTkKOn.mjs} +67 -77
  131. package/dist/.setup/{transport-websocket-zqJ0Cmtn.mjs → transport-websocket-DIyPfkHo.mjs} +8 -16
  132. package/dist/.setup/{turn-router-BWhX_SBh.mjs → turn-router-DKDAziUW.mjs} +30 -31
  133. package/dist/.setup/upstream-prompt-provenance-Ccd9MFRJ.mjs +44 -0
  134. package/dist/.setup/{upstream-session-fork-BQvofnk7.mjs → upstream-session-fork-Djp_yssT.mjs} +50 -43
  135. package/dist/.setup/{usage-BEHcVwcZ.mjs → usage-DQA-peQC.mjs} +4 -4
  136. package/dist/.setup/{usage-limit-error-D1p3nE6n.mjs → usage-limit-error-2t3KBqiX.mjs} +12 -21
  137. package/dist/.setup/web-search-item-CvokaZOo.mjs +20 -0
  138. package/dist/.setup/{web-search-provider.runtime-CV9oiB-v.mjs → web-search-provider.runtime-BsuCMNix.mjs} +3 -3
  139. package/dist/.setup/{workspace-write-sandbox-probe-DmUHLrrl.mjs → workspace-write-sandbox-probe-BDWO2Qkh.mjs} +4 -4
  140. package/dist/api.js +15 -15
  141. package/dist/catalog-page.worker.js +1 -1
  142. package/dist/cli-metadata.js +1 -1
  143. package/dist/doctor-contract-api.js +5 -6
  144. package/dist/harness.js +32 -61
  145. package/dist/index.js +302 -416
  146. package/dist/media-understanding-provider.js +32 -43
  147. package/dist/migration-provider-api.js +1 -1
  148. package/dist/native-session-binding-api.js +1 -1
  149. package/dist/native-tool-policy.js +23 -1
  150. package/dist/provider-discovery.js +1 -1
  151. package/dist/session-history-worker-runtime.js +52 -31
  152. package/dist/session-history.worker.js +1 -1
  153. package/openclaw.plugin.json +20 -3
  154. package/package.json +7 -7
  155. package/dist/.setup/attempt-terminal-gZrxQ35N.mjs +0 -5
  156. package/dist/.setup/plugin-thread-config-deadline-CsScGgrk.mjs +0 -124
  157. package/dist/.setup/service-tier-normalization-Cei89SW6.mjs +0 -15
  158. package/dist/.setup/shell-dynamic-tools-BqGszXcq.mjs +0 -85
  159. package/dist/.setup/thread-archive-guard-C9frICzX.mjs +0 -60
  160. package/dist/.setup/thread-requests-Dwg2b4Xl.mjs +0 -2111
  161. package/dist/.setup/upstream-prompt-provenance-fXkKbPVC.mjs +0 -37
@@ -1,22 +1,24 @@
1
- import { c as codexNativeSubagentRunId, d as readNativeSubagentThreadIds, f as readThreadParentThreadId, l as normalizeIdentifier, m as assertHistoryOwnerMatchesRegistration, p as readThreadSpawnSource, t as matchesNativeAssignmentLifecycle, u as readCodexNativeSubagentRunId } from "./native-subagent-pending-assignments-BDqhOdJp.mjs";
1
+ import { c as codexNativeSubagentRunId, d as readNativeSubagentThreadIds, f as readThreadParentThreadId, l as normalizeIdentifier, m as assertHistoryOwnerMatchesRegistration, p as readThreadSpawnSource, t as matchesNativeAssignmentLifecycle, u as readCodexNativeSubagentRunId } from "./native-subagent-pending-assignments-DmVhedNs.mjs";
2
2
  import { i as isJsonObject } from "./protocol-CANUwXJ3.mjs";
3
- import { n as defineCodexBuildState } from "./build-state-BwxNfFEB.mjs";
4
- import { a as readHookOutputEntries, o as readItem, s as readNullableString } from "./event-projector-values-DTqZHizf.mjs";
5
- import { t as attachCodexMirrorIdentity } from "./upstream-prompt-provenance-fXkKbPVC.mjs";
6
- import { t as readCodexMirroredSessionHistoryMessages } from "./session-history-BogBHKLk.mjs";
7
- import { K as retainCodexAppServerLiveThread, P as claimCodexAppServerLiveThread, R as hasCodexAppServerLiveThread } from "./shared-client-DeenOD8U.mjs";
8
- import { L as readCodexAppServerWarningMessage } from "./client-BIRVBXXb.mjs";
9
- import { _ as itemStatus, c as auditNativeToolName, d as isMutatingNativeToolItem, f as isNonSuccessItemStatus, g as itemName, h as itemKind, l as auditNativeToolTerminalStatus, m as isSideEffectingNativeToolItem, p as isProjectedNativeToolItem, v as itemTitle, x as unknownItemStatus, y as matchesCodexSnapshotTurn } from "./turn-router-BWhX_SBh.mjs";
10
- import { s as interruptCodexTurnAndWaitBestEffort } from "./attempt-client-cleanup-HXQxfMc1.mjs";
11
- import { n as codexApprovalTimeoutText } from "./plugin-approval-roundtrip-C_SGp5YW.mjs";
12
- import { t as __exportAll } from "./session-binding-sidecars-BrdV95Fg.mjs";
13
- import { asFiniteNumber, asNonArrayRecord, normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeTrimmedStringList, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
3
+ import { n as defineCodexBuildState } from "./build-state-CzLMy1S9.mjs";
4
+ import { a as readHookOutputEntries, o as readItem, s as readNullableString } from "./event-projector-values-CLvG1Hil.mjs";
5
+ import { n as attachCodexMirrorIdentity } from "./upstream-prompt-provenance-Ccd9MFRJ.mjs";
6
+ import { t as readCodexMirroredSessionHistoryMessages } from "./session-history-BO6i_pfk.mjs";
7
+ import { K as retainCodexAppServerLiveThread, P as claimCodexAppServerLiveThread, R as hasCodexAppServerLiveThread } from "./shared-client-ByIwuAC-.mjs";
8
+ import { M as readCodexAppServerWarningMessage } from "./client-y7nO6X9c.mjs";
9
+ import { C as unknownItemStatus, _ as itemName, b as matchesCodexSnapshotTurn, f as isMutatingNativeToolItem, g as itemKind, h as isSideEffectingNativeToolItem, l as auditNativeToolName, m as isProjectedNativeToolItem, p as isNonSuccessItemStatus, u as auditNativeToolTerminalStatus, v as itemStatus, y as itemTitle } from "./turn-router-DKDAziUW.mjs";
10
+ import { s as interruptCodexTurnAndWaitBestEffort } from "./attempt-client-cleanup-t-kd_1ys.mjs";
11
+ import { t as projectCodexWebSearchItem } from "./web-search-item-CvokaZOo.mjs";
12
+ import { n as codexApprovalTimeoutText } from "./plugin-approval-roundtrip-BSV-51ig.mjs";
13
+ import { t as resolveCodexLocalRuntimeAttribution } from "./local-runtime-attribution-CZz2DJ4q.mjs";
14
+ import { t as __exportAll } from "./session-binding-sidecars-DD-enC8w.mjs";
15
+ import { asFiniteNumber, asNonArrayRecord, normalizeOptionalString, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
14
16
  import { randomUUID } from "node:crypto";
15
17
  import { asDateTimestampMs } from "openclaw/plugin-sdk/number-runtime";
18
+ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
16
19
  import path from "node:path";
17
20
  import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
18
21
  import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
19
- import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
20
22
  import { TOOL_PROGRESS_OUTPUT_MAX_CHARS, embeddedAgentLog, emitAgentEvent, formatErrorMessage as formatErrorMessage$1, inferToolMetaFromArgs, projectAgentActivityItem, projectAgentToolActivity, runAgentHarnessAfterToolCallHook, sanitizeToolArgs } from "openclaw/plugin-sdk/agent-harness-runtime";
21
23
  import { MAX_TOOL_OUTPUT_DELTA_MESSAGES_PER_ITEM, NativeToolOutputAccumulator, TOOL_TRANSCRIPT_OUTPUT_MAX_CHARS, createAgentHarnessToolCallMessage, createAgentHarnessToolResultMessage, formatNativeToolOutput, formatNativeToolSummary, truncateNativeToolTranscriptText } from "openclaw/plugin-sdk/agent-harness-attempt-runtime";
22
24
  import { captureAgentHarnessCompletionCustody, createAgentHarnessCompletionEventSink, deliverAgentHarnessCompletion, isDurableAgentHarnessCompletionDelivery } from "openclaw/plugin-sdk/agent-harness-completion";
@@ -48,11 +50,10 @@ function matchingNativeModelAdmissions(request, admissions, parentThreadId) {
48
50
  return [...admissions.values()].flat().filter((entry) => entry.kind === "interaction" && (parentThreadId === void 0 || entry.parentThreadId === parentThreadId) && entry.childThreadId === request.threadId && (entry.modelSourceRequiresInference || !(entry.modelSourceTurnId ?? entry.nativeTurnId) || (entry.modelSourceTurnId ?? entry.nativeTurnId) === request.turnId) && entry.modelSource !== void 0 && matchingNativeModelCause(entry.modelSource.owner, request));
49
51
  }
50
52
  function findUnqualifiedNativeModelParent(request, parents, admissions) {
51
- const candidates = new Set(matchingNativeModelAdmissions(request, admissions).flatMap((entry) => {
53
+ const candidates = /* @__PURE__ */ new Set([...matchingNativeModelAdmissions(request, admissions).flatMap((entry) => {
52
54
  const state = parents.get(entry.parentThreadId);
53
55
  return state && entry.modelSource?.owner.unqualifiedModelExecution ? [state] : [];
54
- }));
55
- for (const state of parents.values()) if ([...state.owners.values()].some((owner) => owner.unqualifiedModelExecution && !owner.modelExecutionCancelled && !owner.modelExecutionSettled && matchingNativeModelCause(owner, request))) candidates.add(state);
56
+ }), ...[...parents.values()].filter((state) => [...state.owners.values()].some((owner) => owner.unqualifiedModelExecution && !owner.modelExecutionCancelled && !owner.modelExecutionSettled && matchingNativeModelCause(owner, request)))]);
56
57
  return candidates.size === 1 ? candidates.values().next().value : void 0;
57
58
  }
58
59
  function currentNativeModelExecution(threadId, parents, knownChildren, children) {
@@ -285,16 +286,17 @@ function bindNativeChildModelAdmission(evidence, known, child) {
285
286
  source.assertCurrent();
286
287
  const turnId = evidence.modelSourceTurnId ?? evidence.nativeTurnId;
287
288
  if (!turnId) return true;
289
+ const retainExecution = () => retainNativeModelExecution(source.owner, turnId, evidence.childThreadId, evidence.completionCustody);
288
290
  const pending = known.pendingTurns.find((entry) => entry.turnId === turnId);
289
291
  if (pending) {
290
292
  if (!pending.state || pending.state === "active") {
291
293
  pending.completionCustody ??= evidence.completionCustody?.retain();
292
- pending.modelSource ??= retainNativeModelExecution(source.owner, turnId, evidence.childThreadId, evidence.completionCustody);
294
+ pending.modelSource ??= retainExecution();
293
295
  }
294
296
  } else if (child?.nativeTurnId === turnId) {
295
297
  if (!child.terminal && !child.settledWithoutCompletion) {
296
298
  child.completionCustody ??= evidence.completionCustody?.retain();
297
- child.modelExecution ??= retainNativeModelExecution(source.owner, turnId, evidence.childThreadId, evidence.completionCustody);
299
+ child.modelExecution ??= retainExecution();
298
300
  }
299
301
  } else return true;
300
302
  consumeNativeChildModelAdmission(evidence);
@@ -318,7 +320,8 @@ function releaseNativeParentModelSources(state, children) {
318
320
  pending.modelSource = void 0;
319
321
  }
320
322
  }
321
- function associateNativeChildInteraction(known, threadId, nativeTurnId, admissions, drain) {
323
+ function associateNativeChildInteraction(known, nativeTurnId, admissions, drain) {
324
+ const threadId = known.assignment.childThreadId;
322
325
  for (const [parentTurnId, pending] of admissions) {
323
326
  const interaction = pending.find((evidence) => evidence.kind === "interaction" && evidence.parentThreadId === known.parent.parentThreadId && evidence.childThreadId === threadId && !evidence.nativeTurnId);
324
327
  if (interaction?.kind !== "interaction") continue;
@@ -407,8 +410,8 @@ function executionOwner(request, state, dependencies) {
407
410
  modelSource,
408
411
  completionCustody: completionCustody?.retain()
409
412
  });
410
- for (const entry of admitted) if (entry.kind === "interaction" && entry.modelSource?.owner === owner) consumeNativeChildModelAdmission(entry);
411
- if (pending?.state === "active" || child?.nativeTurnId === request.turnId) dependencies.onExecutionAdmitted(known, request.threadId);
413
+ for (const entry of admitted) if (entry.modelSource?.owner === owner) consumeNativeChildModelAdmission(entry);
414
+ if (pending?.state === "active" || child?.nativeTurnId === request.turnId) dependencies.onExecutionAdmitted(known);
412
415
  return modelSource.executionOwner;
413
416
  }
414
417
  async function captureNativeModelSource(request, dependencies) {
@@ -432,22 +435,19 @@ async function captureNativeModelSource(request, dependencies) {
432
435
  const immediate = unqualified.filter((candidate) => candidate.turnId === request.parentTurnId);
433
436
  const waitingOwners = immediate.length > 0 ? immediate : unqualified;
434
437
  const waitingOwner = waitingOwners.length === 1 ? waitingOwners[0] : void 0;
435
- if (waitingOwner) {
436
- const capture = waitingOwner.modelSource?.capture();
437
- let binding;
438
- try {
438
+ const capture = waitingOwner?.modelSource?.capture();
439
+ let binding;
440
+ try {
441
+ if (waitingOwner) {
439
442
  binding = capture?.source?.bindModelExecution?.(void 0);
440
443
  if (!binding) return;
441
444
  binding.assertCurrent();
442
- await waitForNativeModelSourceChange(state, request.signal ? AbortSignal.any([request.signal, binding.signal]) : binding.signal);
443
- } finally {
444
- binding?.release();
445
- capture?.release();
446
- }
447
- continue;
445
+ } else if (!pending && !dependencies.hasPendingInput(request) && !(observedChildTurn && parentExecution && matchingNativeModelCause(parentExecution, request))) return;
446
+ await waitForNativeModelSourceChange(state, binding && request.signal ? AbortSignal.any([request.signal, binding.signal]) : binding?.signal ?? request.signal);
447
+ } finally {
448
+ binding?.release();
449
+ capture?.release();
448
450
  }
449
- if (!pending && !dependencies.hasPendingInput(request) && !(observedChildTurn && parentExecution && matchingNativeModelCause(parentExecution, request))) return;
450
- await waitForNativeModelSourceChange(state, request.signal);
451
451
  }
452
452
  }
453
453
  //#endregion
@@ -476,13 +476,15 @@ var CodexNativeSubagentAdmissionCustody = class {
476
476
  }
477
477
  if (pending.some((candidate) => candidate.parentThreadId === evidence.parentThreadId && candidate.kind === evidence.kind && candidate.childThreadId === evidence.childThreadId && candidate.agentPath === evidence.agentPath && (candidate.kind === "spawn" || evidence.kind === "spawn" || candidate.modelSourceTurnId === evidence.modelSourceTurnId && (candidate.nativeTurnId !== void 0 && candidate.nativeTurnId === evidence.nativeTurnId || evidence.itemId !== void 0 && candidate.itemId === evidence.itemId))) || requiresUnboundOwner && [...this.pending.values()].reduce((count, entries) => count + entries.length, 0) >= 32) return;
478
478
  try {
479
- if (evidence.kind === "interaction") evidence.completionCustody ??= (evidence.owner ?? evidence.modelOwner)?.completionCustody?.retain();
480
- if (evidence.kind === "interaction" && !evidence.modelSourceConsumed) {
481
- const owner = evidence.modelOwner ?? evidence.owner;
482
- if (owner?.unqualifiedModelExecution && !owner.nativeInputConfiguration) {
483
- evidence.modelSourceRequiresInference = evidence.modelSourceTurnId ? void 0 : true;
484
- evidence.modelSource = retainNativeModelExecution(owner, void 0, evidence.childThreadId, evidence.completionCustody);
485
- } else evidence.modelSource = retainNativeModelSource(owner);
479
+ if (evidence.kind === "interaction") {
480
+ evidence.completionCustody ??= (evidence.owner ?? evidence.modelOwner)?.completionCustody?.retain();
481
+ if (!evidence.modelSourceConsumed) {
482
+ const owner = evidence.modelOwner ?? evidence.owner;
483
+ if (owner?.unqualifiedModelExecution && !owner.nativeInputConfiguration) {
484
+ evidence.modelSourceRequiresInference = evidence.modelSourceTurnId ? void 0 : true;
485
+ evidence.modelSource = retainNativeModelExecution(owner, void 0, evidence.childThreadId, evidence.completionCustody);
486
+ } else evidence.modelSource = retainNativeModelSource(owner);
487
+ }
486
488
  }
487
489
  } catch (error) {
488
490
  if (evidence.kind === "interaction") {
@@ -512,11 +514,7 @@ var CodexNativeSubagentAdmissionCustody = class {
512
514
  const known = this.dependencies.knownChild(evidence.childThreadId);
513
515
  if (known && known.parent.parentThreadId !== evidence.parentThreadId) return false;
514
516
  const state = this.dependencies.parentState(evidence.parentThreadId);
515
- if (evidence.kind === "interaction" && (evidence.owner || evidence.modelSource)) {
516
- if (evidence.modelSource && state && !isRetired(state)) return true;
517
- if (state && evidence.owner && [...state.owners.values()].includes(evidence.owner)) return true;
518
- return false;
519
- }
517
+ if (evidence.kind === "interaction" && (evidence.owner || evidence.modelSource)) return Boolean(evidence.modelSource && state && !isRetired(state) || state && evidence.owner && [...state.owners.values()].includes(evidence.owner));
520
518
  return this.hasUnboundParentOwner(evidence.parentThreadId);
521
519
  });
522
520
  }
@@ -785,10 +783,8 @@ var CodexNativeSubagentRecoveryCoordinator = class {
785
783
  };
786
784
  }
787
785
  clearRecoveryTimers(childState) {
788
- if (childState.recoveryTimer) {
789
- clearTimeout(childState.recoveryTimer);
790
- childState.recoveryTimer = void 0;
791
- }
786
+ clearTimeout(childState.recoveryTimer);
787
+ childState.recoveryTimer = void 0;
792
788
  }
793
789
  };
794
790
  function logRecoveryFailure(childThreadId, error) {
@@ -867,7 +863,7 @@ var CodexNativeSubagentCloseOwner = class {
867
863
  if (!calls) return;
868
864
  for (const [key, call] of calls) {
869
865
  if (call.completing && !call.settled) continue;
870
- if (![...state.owners.values()].some((owner) => call.owners.has(owner) && (!owner.turnId || owner.turnId === call.turnId))) calls.delete(key);
866
+ if (!this.hasCallOwner(state, call, true)) calls.delete(key);
871
867
  }
872
868
  }
873
869
  async retireChild(state, childState, releaseSubscription) {
@@ -889,7 +885,7 @@ var CodexNativeSubagentCloseOwner = class {
889
885
  }
890
886
  this.callbacks.markTerminalRevision(childState.childThreadId);
891
887
  }
892
- if (childState.pendingCompletion) childState.pendingCompletion = void 0;
888
+ childState.pendingCompletion = void 0;
893
889
  childState.subscriptionClosed = true;
894
890
  this.callbacks.unregisterChild(childState);
895
891
  releaseSubscription?.();
@@ -898,6 +894,9 @@ var CodexNativeSubagentCloseOwner = class {
898
894
  const threadId = receiver.assignment.childThreadId;
899
895
  if (this.callbacks.isParentRetired(receiver.parent) && this.callbacks.knownChild(threadId) === receiver && !this.callbacks.currentChild(threadId)) releaseSubscription();
900
896
  }
897
+ hasCallOwner(state, call, allowUnbound) {
898
+ return [...state.owners.values()].some((owner) => call.owners.has(owner) && (owner.turnId === call.turnId || allowUnbound && !owner.turnId));
899
+ }
901
900
  completeChildClose(state, key, call) {
902
901
  if (call.settlement) return call.settlement;
903
902
  const settlement = this.confirmChildClose(state, key, call);
@@ -911,7 +910,7 @@ var CodexNativeSubagentCloseOwner = class {
911
910
  const childState = this.callbacks.currentChild(target.childThreadId);
912
911
  return known?.parent === state && known.assignment.runId === target.runId && known.turnId === target.nativeTurnId && known.pendingTurns.length === 0 && (childState === void 0 || childState === target.childState);
913
912
  };
914
- if (call.completing || !isCurrent() || ![...state.owners.values()].some((owner) => call.owners.has(owner) && owner.turnId === call.turnId)) return;
913
+ if (call.completing || !isCurrent() || !this.hasCallOwner(state, call, false)) return;
915
914
  call.completing = true;
916
915
  let settled = false;
917
916
  let retiring = false;
@@ -1030,12 +1029,9 @@ var CodexNativeSubagentCompletionDelivery = class {
1030
1029
  this.dependencies.unregisterChild(childState);
1031
1030
  return;
1032
1031
  }
1033
- if (delivery.recoveryPending) {
1034
- this.scheduleRetry(childState, delivery.error ?? "requester recovery owns completion", false);
1035
- return;
1036
- }
1037
- const error = delivery.error ?? "completion delivery did not produce a parent response";
1038
- this.scheduleRetry(childState, error);
1032
+ const recoveryPending = delivery.recoveryPending;
1033
+ const error = delivery.error ?? (recoveryPending ? "requester recovery owns completion" : "completion delivery did not produce a parent response");
1034
+ this.scheduleRetry(childState, error, !recoveryPending);
1039
1035
  } catch (error) {
1040
1036
  if (!this.isCurrent(state, childState)) return;
1041
1037
  if (!this.claim(state, childState)) {
@@ -1055,17 +1051,15 @@ var CodexNativeSubagentCompletionDelivery = class {
1055
1051
  }
1056
1052
  }
1057
1053
  finish(state, child) {
1058
- if (child.completionDeliveryTimer) {
1059
- clearTimeout(child.completionDeliveryTimer);
1060
- child.completionDeliveryTimer = void 0;
1061
- }
1054
+ clearTimeout(child.completionDeliveryTimer);
1055
+ child.completionDeliveryTimer = void 0;
1062
1056
  this.deliverPending(state, child);
1063
1057
  }
1064
- applyReceipts(state, runIds, children) {
1058
+ applyReceipts(state, runIds) {
1065
1059
  for (const runId of runIds) {
1066
- const child = children.get(runId);
1067
- const deliveryParent = child && this.dependencies.getParent(child.parentThreadId);
1068
- if (!child || !deliveryParent || !this.isCurrent(state, child) || !this.dependencies.isCurrentParent(deliveryParent) || this.dependencies.isRetiredParent(deliveryParent)) continue;
1060
+ const child = this.dependencies.children.get(runId);
1061
+ const deliveryParent = child && this.dependencies.parents.get(child.parentThreadId);
1062
+ if (!child || !deliveryParent || !this.isCurrent(state, child) || this.dependencies.parents.get(deliveryParent.parentThreadId) !== deliveryParent || this.dependencies.retiredParents.has(deliveryParent)) continue;
1069
1063
  if (deliveryParent !== state) {
1070
1064
  if (!state.requesterSessionKey?.trim() || state.requesterSessionKey !== deliveryParent.requesterSessionKey) continue;
1071
1065
  try {
@@ -1079,18 +1073,18 @@ var CodexNativeSubagentCompletionDelivery = class {
1079
1073
  if (child.pendingCompletion && !child.deliveringCompletion) this.finish(deliveryParent, child);
1080
1074
  }
1081
1075
  }
1082
- deliverDetached(state, children) {
1083
- for (const child of children) if (child.parentThreadId === state.parentThreadId && child.pendingCompletion) this.deliverPending(state, child);
1076
+ deliverDetached(state) {
1077
+ for (const child of this.dependencies.children.values()) if (child.parentThreadId === state.parentThreadId && child.pendingCompletion) this.deliverPending(state, child);
1084
1078
  }
1085
1079
  release(childState) {
1086
1080
  childState.completionCustody?.release();
1087
- if (childState.completionDeliveryTimer) clearTimeout(childState.completionDeliveryTimer);
1081
+ clearTimeout(childState.completionDeliveryTimer);
1088
1082
  const deliveryOwnerKey = childState.deliveryOwnerKey;
1089
1083
  if (deliveryOwnerKey && completionDeliveryOwners.get(deliveryOwnerKey) === childState) completionDeliveryOwners.delete(deliveryOwnerKey);
1090
1084
  childState.deliveryOwnerKey = void 0;
1091
1085
  }
1092
1086
  isCurrent(state, child) {
1093
- return this.dependencies.isCurrentChild(child) && this.dependencies.isCurrentParent(state) && !this.dependencies.isRetiredParent(state);
1087
+ return this.dependencies.children.get(child.runId) === child && this.dependencies.parents.get(state.parentThreadId) === state && !this.dependencies.retiredParents.has(state);
1094
1088
  }
1095
1089
  prepareDelivery(state, child) {
1096
1090
  if (!child.pendingCompletion) return false;
@@ -1107,7 +1101,7 @@ var CodexNativeSubagentCompletionDelivery = class {
1107
1101
  return true;
1108
1102
  }
1109
1103
  scheduleRetry(childState, error, chargeAttempt = true) {
1110
- if (!childState.pendingCompletion || childState.completionDeliveryTimer || !this.dependencies.isCurrentChild(childState)) return;
1104
+ if (!childState.pendingCompletion || childState.completionDeliveryTimer || this.dependencies.children.get(childState.runId) !== childState) return;
1111
1105
  if (chargeAttempt && childState.completionDeliveryAttempt >= this.maxRetries) {
1112
1106
  embeddedAgentLog.warn("Native subagent completion retries exhausted", {
1113
1107
  childThreadId: childState.childThreadId,
@@ -1119,8 +1113,8 @@ var CodexNativeSubagentCompletionDelivery = class {
1119
1113
  const delayMs = delayForAttempt(this.retryDelaysMs, chargeAttempt ? childState.completionDeliveryAttempt++ : childState.completionDeliveryAttempt);
1120
1114
  childState.completionDeliveryTimer = setTimeout(() => {
1121
1115
  childState.completionDeliveryTimer = void 0;
1122
- if (!this.dependencies.isCurrentChild(childState)) return;
1123
- const state = this.dependencies.getParent(childState.parentThreadId);
1116
+ if (this.dependencies.children.get(childState.runId) !== childState) return;
1117
+ const state = this.dependencies.parents.get(childState.parentThreadId);
1124
1118
  if (state) this.deliverPending(state, childState);
1125
1119
  }, delayMs);
1126
1120
  childState.completionDeliveryTimer.unref();
@@ -1181,8 +1175,19 @@ function extractCodexNativeSubagentCompletions(notification) {
1181
1175
  if (kinds[index] !== "multi_agent.subagent_notification" || !isJsonObject(entry) || entry.type !== "input_text") return [];
1182
1176
  const text = readStringField(entry, "text")?.trim();
1183
1177
  if (!text?.startsWith(CODEX_SUBAGENT_NOTIFICATION_START) || !text.endsWith(CODEX_SUBAGENT_NOTIFICATION_END)) return [];
1184
- const completion = parseCodexNativeSubagentNotificationBody(text.slice(23, -24));
1185
- return completion ? [completion] : [];
1178
+ let payload;
1179
+ try {
1180
+ payload = JSON.parse(text.slice(23, -24).trim());
1181
+ } catch {
1182
+ return [];
1183
+ }
1184
+ if (!isJsonObject(payload)) return [];
1185
+ const agentPath = readStringField(payload, "agent_path")?.trim();
1186
+ const completion = readCompletionStatus(payload.status);
1187
+ return agentPath && completion ? [{
1188
+ agentPath,
1189
+ ...completion
1190
+ }] : [];
1186
1191
  });
1187
1192
  }
1188
1193
  const codexNativeSubagentNotifications = {
@@ -1212,21 +1217,6 @@ function readDeliveredNativeCompletionPaths(notification) {
1212
1217
  if (!isJsonObject(part) || readStringField(part, "type") !== "input_text") return [];
1213
1218
  return readStringField(part, "text")?.startsWith(`Message Type: FINAL_ANSWER\nTask name: ${recipient}\nSender: ${author}\nPayload:\n`) ? [author] : [];
1214
1219
  }
1215
- function parseCodexNativeSubagentNotificationBody(body) {
1216
- let payload;
1217
- try {
1218
- payload = JSON.parse(body.trim());
1219
- } catch {
1220
- return;
1221
- }
1222
- if (!isJsonObject(payload)) return;
1223
- const agentPath = readStringField(payload, "agent_path")?.trim();
1224
- const completion = readCompletionStatus(payload.status);
1225
- return agentPath && completion ? {
1226
- agentPath,
1227
- ...completion
1228
- } : void 0;
1229
- }
1230
1220
  function readCompletionStatus(status) {
1231
1221
  if (status === "shutdown" || status === "not_found") return {
1232
1222
  status: status === "shutdown" ? "cancelled" : "failed",
@@ -1340,19 +1330,9 @@ var CodexNativeSubagentDeliveryReceipts = class {
1340
1330
  for (let index = 0; index < this.pending.length;) {
1341
1331
  const receipt = this.pending[index];
1342
1332
  const matches = [...this.outcomes].filter(([, outcome]) => outcome.paths.has(receipt.agentPath));
1343
- let match;
1344
- for (const candidate of matches) {
1345
- const outcome = candidate[1];
1346
- if (outcome.result !== void 0 && outcome.result === receipt.result || outcome.receiptResults.has(receipt.result)) {
1347
- match = candidate;
1348
- break;
1349
- }
1350
- if (outcome.result === void 0) {
1351
- match = matches.length === 1 ? candidate : void 0;
1352
- break;
1353
- }
1354
- }
1355
- if (!match) {
1333
+ const match = matches.find(([, outcome]) => outcome.result === void 0 || outcome.result === receipt.result || outcome.receiptResults.has(receipt.result));
1334
+ const ambiguous = match && match[1].result === void 0 && !match[1].receiptResults.has(receipt.result) && matches.length > 1;
1335
+ if (!match || ambiguous) {
1356
1336
  index += 1;
1357
1337
  continue;
1358
1338
  }
@@ -1379,9 +1359,10 @@ function receiptResultKey(result) {
1379
1359
  //#region extensions/codex/src/app-server/native-subagent-history-recovery.ts
1380
1360
  const THREAD_READ_TIMEOUT_MS = 3e4;
1381
1361
  var CodexNativeSubagentHistoryRecovery = class {
1382
- constructor(client, queries) {
1362
+ constructor(client, knownChildren, children) {
1383
1363
  this.client = client;
1384
- this.queries = queries;
1364
+ this.knownChildren = knownChildren;
1365
+ this.children = children;
1385
1366
  }
1386
1367
  requestThreadRead(childThreadId, includeTurns) {
1387
1368
  return this.client.request("thread/read", {
@@ -1389,14 +1370,6 @@ var CodexNativeSubagentHistoryRecovery = class {
1389
1370
  includeTurns
1390
1371
  }, { timeoutMs: THREAD_READ_TIMEOUT_MS });
1391
1372
  }
1392
- requestLatestThreadTurn(childThreadId) {
1393
- return this.client.request("thread/turns/list", {
1394
- threadId: childThreadId,
1395
- limit: 1,
1396
- sortDirection: "desc",
1397
- itemsView: "full"
1398
- }, { timeoutMs: THREAD_READ_TIMEOUT_MS });
1399
- }
1400
1373
  async read(assignment, options) {
1401
1374
  const { childThreadId } = assignment;
1402
1375
  const { recordedCompletion } = options;
@@ -1429,7 +1402,7 @@ var CodexNativeSubagentHistoryRecovery = class {
1429
1402
  };
1430
1403
  }
1431
1404
  const turnId = assignment.nativeTurnId ?? initialTurnId;
1432
- const pendingTurnIds = new Set(this.queries.getPendingTurnIds(childThreadId));
1405
+ const pendingTurnIds = new Set(this.knownChildren.get(childThreadId)?.pendingTurns.map((turn) => turn.turnId) ?? []);
1433
1406
  const unresolvedAssignment = options.resumeInterrupted && !turnId && pendingTurnIds.size > 0;
1434
1407
  const observedPendingTurns = [];
1435
1408
  for (const turn of rawTurns) {
@@ -1440,11 +1413,8 @@ var CodexNativeSubagentHistoryRecovery = class {
1440
1413
  });
1441
1414
  }
1442
1415
  const threadStatus = isJsonObject(thread.status) ? normalizeIdentifier(readStringField(thread.status, "type")) : void 0;
1443
- let completion;
1416
+ let recovery = readTurnRecovery(void 0, childThreadId);
1444
1417
  let fallbackCompletion;
1445
- let nativeTurnId;
1446
- let nativeTurnState;
1447
- let resumable = false;
1448
1418
  let threadState = threadStatus === "active" ? "active" : threadStatus === "systemerror" ? "system_error" : threadStatus ? "other" : "unavailable";
1449
1419
  if (unresolvedAssignment) threadState = "unavailable";
1450
1420
  else if (turnId) {
@@ -1453,26 +1423,22 @@ var CodexNativeSubagentHistoryRecovery = class {
1453
1423
  while (options.resumeInterrupted && index >= 0 && index + 1 < turns.length && normalizeIdentifier(readStringField(turns[index], "status")) === "interrupted") index += 1;
1454
1424
  const turn = turns[index];
1455
1425
  const turnStatus = normalizeIdentifier(readStringField(turn, "status"));
1456
- nativeTurnId = readStringField(turn, "id");
1457
- nativeTurnState = readNativeTurnState(turn);
1458
- completion = isJsonObject(turn) ? readTurnCompletion(turn, childThreadId) : void 0;
1459
- resumable = turnStatus === "interrupted";
1426
+ recovery = readTurnRecovery(turn, childThreadId);
1460
1427
  threadState = turnStatus === "inprogress" ? "active" : turnStatus ? "other" : "unavailable";
1461
1428
  } else if (threadStatus === "active") {
1462
1429
  const turn = rawTurns.at(-1);
1463
1430
  if (normalizeIdentifier(readStringField(turn, "status")) === "inprogress") {
1464
- nativeTurnId = readStringField(turn, "id");
1465
- nativeTurnState = "active";
1431
+ recovery.nativeTurnId = readStringField(turn, "id");
1432
+ recovery.nativeTurnState = "active";
1466
1433
  }
1467
- } else if (threadStatus !== "systemerror") {
1468
- const turnRecovery = readThreadTurnRecovery(thread, childThreadId);
1469
- nativeTurnId = turnRecovery.nativeTurnId;
1470
- nativeTurnState = turnRecovery.nativeTurnState;
1471
- completion = turnRecovery.completion;
1472
- resumable = turnRecovery.resumable;
1473
- }
1474
- if (!unresolvedAssignment && threadStatus === "systemerror" && (!turnId || threadState === "unavailable" && !completion)) {
1475
- const turnsResponse = await this.requestLatestThreadTurn(childThreadId).catch(() => void 0);
1434
+ } else if (threadStatus !== "systemerror") recovery = readTurnRecovery(rawTurns.findLast(isJsonObject), childThreadId);
1435
+ if (!unresolvedAssignment && threadStatus === "systemerror" && (!turnId || threadState === "unavailable" && !recovery.completion)) {
1436
+ const turnsResponse = await this.client.request("thread/turns/list", {
1437
+ threadId: childThreadId,
1438
+ limit: 1,
1439
+ sortDirection: "desc",
1440
+ itemsView: "full"
1441
+ }, { timeoutMs: THREAD_READ_TIMEOUT_MS }).catch(() => void 0);
1476
1442
  const data = isJsonObject(turnsResponse) && Array.isArray(turnsResponse.data) ? turnsResponse.data : [];
1477
1443
  const latestTurn = isJsonObject(data[0]) ? data[0] : void 0;
1478
1444
  const latestTurnId = readStringField(latestTurn, "id");
@@ -1483,51 +1449,45 @@ var CodexNativeSubagentHistoryRecovery = class {
1483
1449
  const latestTurnStatus = normalizeIdentifier(readStringField(latestTurn, "status"));
1484
1450
  const matchesAssignment = !turnId || readStringField(latestTurn, "id") === turnId;
1485
1451
  if (latestTurn && matchesAssignment) {
1486
- if (turnId) {
1487
- const turnRecovery = readThreadTurnRecovery({ turns: [latestTurn] }, childThreadId);
1488
- nativeTurnId = turnRecovery.nativeTurnId;
1489
- nativeTurnState = turnRecovery.nativeTurnState;
1490
- completion = turnRecovery.completion;
1491
- resumable = turnRecovery.resumable;
1492
- } else if (latestTurnStatus === "failed") completion = readTurnCompletion(latestTurn, childThreadId);
1452
+ if (turnId) recovery = readTurnRecovery(latestTurn, childThreadId);
1453
+ else if (latestTurnStatus === "failed") recovery.completion = readTurnCompletion(latestTurn, childThreadId);
1493
1454
  }
1494
- const current = !latestTurn ? this.queries.getCurrentAssignmentState(childThreadId) : void 0;
1495
- const unresolvedCurrentAssignment = current?.runId === assignment.runId && current?.nativeTurnState !== "completed";
1455
+ const current = !latestTurn ? this.knownChildren.get(childThreadId)?.assignment : void 0;
1456
+ const unresolvedCurrentAssignment = current?.runId === assignment.runId && this.children.get(current.runId)?.nativeTurnState !== "completed";
1496
1457
  if (latestTurnStatus === "inprogress" && matchesAssignment) {
1497
- nativeTurnId = readStringField(latestTurn, "id");
1498
- nativeTurnState = "active";
1458
+ recovery.nativeTurnId = readStringField(latestTurn, "id");
1459
+ recovery.nativeTurnState = "active";
1499
1460
  threadState = "active";
1500
- } else if (!completion && !resumable && latestTurnStatus !== "inprogress" && (!turnId || !latestTurn && unresolvedCurrentAssignment)) fallbackCompletion = systemErrorFallbackCompletion(childThreadId);
1461
+ } else if (!recovery.completion && !recovery.resumable && latestTurnStatus !== "inprogress" && (!turnId || !latestTurn && unresolvedCurrentAssignment)) fallbackCompletion = systemErrorFallbackCompletion(childThreadId);
1501
1462
  }
1502
- if (recordedCompletion && (!turnId || !completion || completion.status !== recordedCompletion.status)) {
1503
- completion = recordedCompletion;
1463
+ if (recordedCompletion && (!turnId || !recovery.completion || recovery.completion.status !== recordedCompletion.status)) {
1464
+ recovery.completion = recordedCompletion;
1504
1465
  if (!turnId) {
1505
- nativeTurnId = void 0;
1506
- nativeTurnState = void 0;
1466
+ recovery.nativeTurnId = void 0;
1467
+ recovery.nativeTurnState = void 0;
1507
1468
  }
1508
1469
  fallbackCompletion = void 0;
1509
- resumable = false;
1470
+ recovery.resumable = false;
1510
1471
  threadState = "other";
1511
1472
  }
1512
1473
  return {
1513
1474
  parentThreadId: readThreadParentThreadId(thread),
1514
1475
  agentPath: normalizeOptionalString(readStringField(readThreadSpawnSource(thread), "agent_path")),
1515
- nativeTurnId,
1516
- nativeTurnState,
1476
+ nativeTurnId: recovery.nativeTurnId,
1477
+ nativeTurnState: recovery.nativeTurnState,
1517
1478
  observedPendingTurns,
1518
- completion,
1479
+ completion: recovery.completion,
1519
1480
  fallbackCompletion,
1520
- resumable,
1481
+ resumable: recovery.resumable,
1521
1482
  threadState
1522
1483
  };
1523
1484
  }
1524
1485
  };
1525
- function readThreadTurnRecovery(thread, childThreadId) {
1526
- const turn = (Array.isArray(thread.turns) ? thread.turns : []).findLast(isJsonObject);
1486
+ function readTurnRecovery(turn, childThreadId) {
1527
1487
  return turn ? {
1528
1488
  nativeTurnId: readStringField(turn, "id"),
1529
1489
  nativeTurnState: readNativeTurnState(turn),
1530
- completion: readTurnCompletion(turn, childThreadId),
1490
+ completion: isJsonObject(turn) ? readTurnCompletion(turn, childThreadId) : void 0,
1531
1491
  resumable: normalizeIdentifier(readStringField(turn, "status")) === "interrupted"
1532
1492
  } : { resumable: false };
1533
1493
  }
@@ -1538,10 +1498,6 @@ function readNativeTurnEnd(turn) {
1538
1498
  function readNativeTurnState(turn) {
1539
1499
  return normalizeIdentifier(readStringField(turn, "status")) === "inprogress" ? "active" : readNativeTurnEnd(turn);
1540
1500
  }
1541
- function readTurnErrorMessage(turn) {
1542
- const error = isJsonObject(turn.error) ? turn.error : void 0;
1543
- return normalizeOptionalString(readStringField(error, "message")) ?? normalizeOptionalString(isJsonObject(error?.codexErrorInfo) ? readStringField(error.codexErrorInfo, "message") : void 0);
1544
- }
1545
1501
  function systemErrorFallbackCompletion(childThreadId) {
1546
1502
  return {
1547
1503
  childThreadId,
@@ -1563,14 +1519,16 @@ function readTurnCompletion(turn, childThreadId, source = "history") {
1563
1519
  result: result ?? "Subagent completed without a final assistant message.",
1564
1520
  ...timestamp
1565
1521
  };
1566
- if (status === "interrupted") return;
1567
- if (status === "failed") return {
1568
- childThreadId,
1569
- status: "failed",
1570
- statusLabel: source === "history" ? "task_failed" : "turn_failed",
1571
- result: readTurnErrorMessage(turn) ?? (source === "history" ? result : void 0) ?? "Subagent failed.",
1572
- ...timestamp
1573
- };
1522
+ if (status === "failed") {
1523
+ const error = isJsonObject(turn.error) ? turn.error : void 0;
1524
+ return {
1525
+ childThreadId,
1526
+ status: "failed",
1527
+ statusLabel: source === "history" ? "task_failed" : "turn_failed",
1528
+ result: normalizeOptionalString(readStringField(error, "message")) ?? normalizeOptionalString(isJsonObject(error?.codexErrorInfo) ? readStringField(error.codexErrorInfo, "message") : void 0) ?? (source === "history" ? result : void 0) ?? "Subagent failed.",
1529
+ ...timestamp
1530
+ };
1531
+ }
1574
1532
  }
1575
1533
  function readLastAgentMessage(turn) {
1576
1534
  const items = Array.isArray(turn.items) ? turn.items : [];
@@ -1612,7 +1570,7 @@ function nativeAgentPath(known) {
1612
1570
  const paths = [...known?.agentPaths ?? []].filter((path) => /^\/root(?:\/[a-z0-9_]+)*$/.test(path));
1613
1571
  return paths.length === 1 ? paths[0] : void 0;
1614
1572
  }
1615
- function nativeRootThreadId(threadId, knownChildren) {
1573
+ function nativeRootThreadId(threadId, knownChildren, parent) {
1616
1574
  const visited = /* @__PURE__ */ new Set();
1617
1575
  let current = threadId;
1618
1576
  let expectedPath;
@@ -1620,7 +1578,7 @@ function nativeRootThreadId(threadId, knownChildren) {
1620
1578
  visited.add(current);
1621
1579
  const known = knownChildren.get(current);
1622
1580
  const path = nativeAgentPath(known);
1623
- if (!known || !path || expectedPath && path !== expectedPath) return;
1581
+ if (!known || parent && known.parent !== parent || !path || expectedPath && path !== expectedPath) return;
1624
1582
  if (path === "/root") return current;
1625
1583
  expectedPath = path.slice(0, path.lastIndexOf("/"));
1626
1584
  if (expectedPath === "/root") return known.nativeParentThreadId;
@@ -1645,15 +1603,20 @@ function resolveInputTarget(request, dependencies) {
1645
1603
  }
1646
1604
  /** Qualification is read before the native handler; source custody remains with its existing call. */
1647
1605
  async function prepareNativeModelToolInput(request, dependencies) {
1648
- const state = dependencies.parents.get(request.threadId) ?? dependencies.knownChildren.get(request.threadId)?.parent;
1649
- const owner = state && resolveNativeModelParentOwner(state, request.turnId, request.threadId, dependencies.children, dependencies.knownChildren);
1606
+ const resolveSender = () => {
1607
+ const state = dependencies.parents.get(request.threadId) ?? dependencies.knownChildren.get(request.threadId)?.parent;
1608
+ return {
1609
+ state,
1610
+ owner: state && resolveNativeModelParentOwner(state, request.turnId, request.threadId, dependencies.children, dependencies.knownChildren)
1611
+ };
1612
+ };
1613
+ const { state, owner } = resolveSender();
1650
1614
  const capture = owner?.modelSource?.capture();
1651
1615
  if (!state || !owner || !capture || owner.modelExecutionSettled || owner.modelExecutionCancelled) {
1652
1616
  capture?.release();
1653
1617
  throw new Error("Codex native input requires its exact admitted sender turn");
1654
1618
  }
1655
1619
  let preparedSource;
1656
- let captureTransferred = false;
1657
1620
  let pendingBinding;
1658
1621
  let targetRevision;
1659
1622
  let assertTargetCurrent;
@@ -1673,7 +1636,10 @@ async function prepareNativeModelToolInput(request, dependencies) {
1673
1636
  const targetChild = dependencies.knownChildren.get(targetThreadId);
1674
1637
  const targetConfiguration = targetChild?.configurationQualification;
1675
1638
  const targetRouting = request.readQualification(targetThreadId);
1639
+ let metadataRead = false;
1676
1640
  assertTargetCurrent = () => {
1641
+ const nativeRoot = nativeRootThreadId(request.threadId, dependencies.knownChildren, state);
1642
+ if (!(targetParent ? (targetParent === state || nativeRoot === targetThreadId) && dependencies.canPrepareReceiver(state, targetThreadId) : targetChild ? dependencies.canPrepareReceiver(state, targetThreadId) : !metadataRead || nativeRoot === targetThreadId || nativeParentThreadId === state.parentThreadId || nativeParentThreadId !== void 0 && dependencies.knownChildren.get(nativeParentThreadId)?.parent === state)) throw new Error("Codex native input target is outside the sender's admitted tree");
1677
1643
  if (!targetRevision?.isCurrent() || dependencies.parents.get(targetThreadId) !== targetParent || dependencies.knownChildren.get(targetThreadId) !== targetChild || targetChild?.configurationQualification !== targetConfiguration || request.readQualification(targetThreadId) !== targetRouting) throw new Error("Codex native receiver changed during input preparation; retry with its current thread");
1678
1644
  targetConfiguration?.assertCurrent();
1679
1645
  targetRouting?.assertCurrent();
@@ -1687,6 +1653,8 @@ async function prepareNativeModelToolInput(request, dependencies) {
1687
1653
  timeoutMs: 3e4,
1688
1654
  assertCurrent
1689
1655
  });
1656
+ const nativeParentThreadId = readThreadParentThreadId(thread);
1657
+ metadataRead = true;
1690
1658
  assertCurrent();
1691
1659
  if (thread.id !== targetThreadId || !thread.modelProvider || resolveInputTarget(request, dependencies) !== targetThreadId) throw new Error("Codex native target returned a different thread or no provider");
1692
1660
  if (thread.status?.type !== "idle" && thread.status?.type !== "notLoaded" && !dependencies.currentModelExecution(targetThreadId)) throw new Error("Codex active input requires the receiver's exact admitted execution");
@@ -1736,18 +1704,16 @@ async function prepareNativeModelToolInput(request, dependencies) {
1736
1704
  }, state, () => {
1737
1705
  if (!dependencies.isCurrent(state)) throw new Error("Codex native input source owner is no longer current");
1738
1706
  }, () => {});
1739
- captureTransferred = true;
1740
1707
  preparedOwner.modelSource = preparedSource;
1741
1708
  }
1742
1709
  assertCurrent();
1743
- const nativeParentThreadId = readThreadParentThreadId(thread);
1710
+ if (targetChild && nativeParentThreadId !== targetChild.nativeParentThreadId) throw new Error("Codex native input receiver lineage changed during preparation");
1744
1711
  if (!dependencies.prepareReceiver(state, thread.id, nativeParentThreadId)) throw new Error("Codex native input receiver cannot retain this sender's admitted source");
1745
1712
  if (!dependencies.knownChildren.has(thread.id) && !dependencies.parents.has(thread.id)) dependencies.registerChildThread(state, thread.id, {
1746
1713
  nativeParentThreadId,
1747
1714
  agentPath: readStringField(readThreadSpawnSource(thread), "agent_path")
1748
1715
  });
1749
- const currentState = dependencies.parents.get(request.threadId) ?? dependencies.knownChildren.get(request.threadId)?.parent;
1750
- const currentOwner = currentState && resolveNativeModelParentOwner(currentState, request.turnId, request.threadId, dependencies.children, dependencies.knownChildren);
1716
+ const { state: currentState, owner: currentOwner } = resolveSender();
1751
1717
  if (!currentOwner || currentOwner.modelExecutionSettled || currentOwner.modelExecutionCancelled) throw new Error("Codex native input requires its exact admitted sender turn");
1752
1718
  if (currentState !== state || currentOwner !== owner) throw new Error("Codex native input sender changed during preparation");
1753
1719
  const pendingModelSources = [...dependencies.admissions.values()].flat().filter((entry) => entry.kind === "interaction" && entry.modelSource?.owner.modelSource?.hasOperatorSource).length;
@@ -1758,13 +1724,14 @@ async function prepareNativeModelToolInput(request, dependencies) {
1758
1724
  } finally {
1759
1725
  targetRevision?.release();
1760
1726
  preparedSource?.release();
1761
- if (!captureTransferred) capture.release();
1727
+ if (!preparedSource) capture.release();
1762
1728
  }
1763
1729
  }
1764
1730
  function drainNativeChildModelAdmissions(state, owner, turnId, observeActivity, dependencies) {
1765
1731
  const pending = dependencies.admissions.get(turnId);
1766
1732
  const ownerIsCurrent = [...state.owners.values()].includes(owner);
1767
- if (!pending || !dependencies.isCurrent(state) || !ownerIsCurrent && !pending.some((entry) => entry.kind === "interaction" && (entry.admittedOwner === owner || entry.modelSource?.owner === owner || entry.owner === owner && entry.modelSource))) return;
1733
+ const admittedByOwner = (entry) => entry.kind === "interaction" && (entry.admittedOwner === owner || entry.modelSource?.owner === owner || entry.owner === owner && entry.modelSource);
1734
+ if (!pending || !dependencies.isCurrent(state) || !ownerIsCurrent && !pending.some(admittedByOwner)) return;
1768
1735
  const remaining = [];
1769
1736
  const affectedChildren = /* @__PURE__ */ new Set();
1770
1737
  for (const evidence of pending) {
@@ -1773,7 +1740,7 @@ function drainNativeChildModelAdmissions(state, owner, turnId, observeActivity,
1773
1740
  continue;
1774
1741
  }
1775
1742
  if (evidence.kind === "interaction") {
1776
- if (!ownerIsCurrent && evidence.admittedOwner !== owner && evidence.modelSource?.owner !== owner && !(evidence.owner === owner && evidence.modelSource)) {
1743
+ if (!ownerIsCurrent && !admittedByOwner(evidence)) {
1777
1744
  remaining.push(evidence);
1778
1745
  continue;
1779
1746
  }
@@ -1821,7 +1788,7 @@ function drainNativeChildModelAdmissions(state, owner, turnId, observeActivity,
1821
1788
  const known = dependencies.knownChildren.get(threadId);
1822
1789
  if (known?.parent !== state) continue;
1823
1790
  const previous = dependencies.currentChild(threadId);
1824
- const child = dependencies.admitFollowupChild(known, threadId, ownerIsCurrent ? owner : void 0);
1791
+ const child = dependencies.admitFollowupChild(known, ownerIsCurrent ? owner : void 0);
1825
1792
  if (observeActivity && child && child !== previous && child.nativeTurnState === "active") dependencies.observeActivity(child);
1826
1793
  }
1827
1794
  }
@@ -1938,6 +1905,12 @@ function createCodexNativeSubagentNotificationRouter(deps) {
1938
1905
  if (state && parentThreadId) {
1939
1906
  const turnId = readStringField(params, "turnId");
1940
1907
  const owner = deps.resolveParentOwner(state, turnId, parentThreadId);
1908
+ const registerSpawn = (childThreadId, agentPath) => deps.registerDirectSpawnChild(state, turnId, {
1909
+ parentThreadId: state.parentThreadId,
1910
+ nativeParentThreadId: parentThreadId,
1911
+ childThreadId,
1912
+ ...agentPath === void 0 ? {} : { agentPath }
1913
+ }, owner);
1941
1914
  if (notification.method === "item/completed") {
1942
1915
  if (readStringField(item, "type") === "subAgentActivity" && readStringField(item, "kind") === "interacted") {
1943
1916
  const childThreadId = readStringField(item, "agentThreadId");
@@ -1959,12 +1932,7 @@ function createCodexNativeSubagentNotificationRouter(deps) {
1959
1932
  if (notification.method === "item/completed" && readStringField(item, "type") === "subAgentActivity" && normalizeIdentifier(readStringField(item, "kind")) === "started") {
1960
1933
  const childThreadId = readStringField(item, "agentThreadId")?.trim();
1961
1934
  const agentPath = readStringField(item, "agentPath");
1962
- if (childThreadId) deps.registerDirectSpawnChild(state, turnId, {
1963
- parentThreadId: state.parentThreadId,
1964
- nativeParentThreadId: parentThreadId,
1965
- childThreadId,
1966
- ...agentPath === void 0 ? {} : { agentPath }
1967
- }, owner);
1935
+ if (childThreadId) registerSpawn(childThreadId, agentPath);
1968
1936
  return state;
1969
1937
  }
1970
1938
  const isCompletedSpawnAgentTool = notification.method === "item/completed" && readStringField(item, "type") === "collabAgentToolCall" && normalizeIdentifier(readStringField(item, "tool")) === "spawnagent" && normalizeIdentifier(readStringField(item, "status")) === "completed";
@@ -1972,11 +1940,7 @@ function createCodexNativeSubagentNotificationRouter(deps) {
1972
1940
  if (parentThreadId !== state.parentThreadId && !isCompletedSpawnAgentTool) return state;
1973
1941
  const childThreadIds = new Set(readNativeSubagentThreadIds(item?.receiverThreadIds));
1974
1942
  let accepted = true;
1975
- for (const childThreadId of childThreadIds) accepted = Boolean(isCompletedSpawnAgentTool ? deps.registerDirectSpawnChild(state, turnId, {
1976
- parentThreadId: state.parentThreadId,
1977
- nativeParentThreadId: parentThreadId,
1978
- childThreadId
1979
- }, owner) : deps.registerChildThread(state, childThreadId)) && accepted;
1943
+ for (const childThreadId of childThreadIds) accepted = Boolean(isCompletedSpawnAgentTool ? registerSpawn(childThreadId) : deps.registerChildThread(state, childThreadId)) && accepted;
1980
1944
  if (!accepted) return;
1981
1945
  }
1982
1946
  return state;
@@ -2028,6 +1992,7 @@ async function registerNativeSubagentParent(input, dependencies) {
2028
1992
  const requesterSessionKey = state.requesterSessionKey;
2029
1993
  state.pendingRegistrations = (state.pendingRegistrations ?? 0) + 1;
2030
1994
  const registeredState = state;
1995
+ const isCurrent = () => !dependencies.isClosed() && !dependencies.isRetired(registeredState) && dependencies.states.get(parentThreadId) === registeredState;
2031
1996
  const ownerKey = Symbol("codex-native-subagent-owner");
2032
1997
  let owner = {
2033
1998
  configurationQualification: params.configurationQualification,
@@ -2060,11 +2025,11 @@ async function registerNativeSubagentParent(input, dependencies) {
2060
2025
  };
2061
2026
  try {
2062
2027
  owner.completionCustody = params.completionScope ? await dependencies.runtime.captureAgentHarnessCompletionCustody(params.completionScope) : void 0;
2063
- if (dependencies.isClosed() || dependencies.isRetired(state) || dependencies.states.get(parentThreadId) !== state || state.requesterSessionKey !== requesterSessionKey || owner.completionCustody && !owner.completionCustody.isCurrent()) throw new Error("Codex native subagent parent registration is no longer current");
2028
+ if (!isCurrent() || state.requesterSessionKey !== requesterSessionKey || owner.completionCustody && !owner.completionCustody.isCurrent()) throw new Error("Codex native subagent parent registration is no longer current");
2064
2029
  params.assertCurrent?.();
2065
2030
  params.modelSource?.assertCurrent();
2066
2031
  if (Object.hasOwn(params, "modelSource")) owner.modelSource = createNativeModelSourceOwner(params.modelSource, state, () => {
2067
- if (dependencies.isClosed() || dependencies.isRetired(registeredState) || dependencies.states.get(parentThreadId) !== registeredState) throw new Error("Codex native model source owner is no longer current");
2032
+ if (!isCurrent()) throw new Error("Codex native model source owner is no longer current");
2068
2033
  }, () => dependencies.prune(registeredState));
2069
2034
  if (owner.unqualifiedModelExecution && params.modelSource) {
2070
2035
  rootModelBinding = params.modelSource.bindModelExecution?.(void 0);
@@ -2163,233 +2128,264 @@ async function registerNativeSubagentParent(input, dependencies) {
2163
2128
  };
2164
2129
  }
2165
2130
  //#endregion
2166
- //#region extensions/codex/src/app-server/native-subagent-submission-call.ts
2167
- function admitSubmissionModelInput(params) {
2168
- const { state, owner, request, calls, dependencies, isCurrent } = params;
2169
- if (!owner.modelSource || !isCurrent()) throw new Error("Codex native input has no admitted model source");
2170
- assertNativeModelInputCompatible(owner, dependencies.currentModelExecution(request.targetThreadId) ?? owner);
2171
- for (const entries of calls.values()) for (const pending of entries.values()) if (pending.modelInput?.threadId === request.targetThreadId) assertNativeModelInputCompatible(owner, pending.modelInput.source.owner);
2172
- const key = `${request.turnId}\0${request.itemId}`;
2173
- if (owner.modelSource.hasOperatorSource && !calls.get(state)?.has(key)) {
2174
- if ([...calls.values()].reduce((count, entries) => count + [...entries.values()].filter((call) => call.modelInput?.source.owner.modelSource?.hasOperatorSource).length, 0) + params.pendingModelSources >= 32) throw new Error("Codex pending native input admission capacity reached");
2175
- }
2176
- observeSubmissionCall(state, request.turnId, {
2177
- id: request.itemId,
2178
- receiverThreadIds: [request.targetThreadId]
2179
- }, calls, dependencies, isCurrent);
2180
- const call = calls.get(state)?.get(key);
2181
- if (!call || call.closed || call.owner !== owner || call.modelInput?.threadId !== request.targetThreadId) throw new Error("Codex native input reused an unsettled call identity");
2182
- if (params.preparedOwner && call.modelInput.source.owner === owner) {
2183
- const prepared = retainNativeModelSource(params.preparedOwner);
2184
- if (!prepared) throw new Error("Codex native input lost its prepared model source");
2185
- call.modelInput.source.release();
2186
- call.modelInput.source = prepared;
2187
- }
2188
- }
2189
- function hasPendingSubmissionModelInput(calls, request) {
2190
- for (const entries of calls.values()) for (const call of entries.values()) if (!call.closed && call.modelInput?.threadId === request.threadId && (call.parentTurnId === request.parentTurnId || call.parentTurnId === request.rootTurnId)) {
2191
- const capture = call.modelInput.source.owner.modelSource?.capture();
2192
- capture?.release();
2193
- return Boolean(capture);
2194
- }
2195
- return false;
2196
- }
2197
- function retireReceiverModelInputs(calls, threadId, dependencies) {
2198
- for (const entries of calls.values()) for (const call of entries.values()) if (call.modelInput?.threadId === threadId) {
2199
- settleSubmissionModelInput(call, false, dependencies);
2200
- call.closed = true;
2131
+ //#region extensions/codex/src/app-server/native-subagent-receiver.ts
2132
+ /** Read-only eligibility; transferring observation still needs fresh native lineage. */
2133
+ function canPrepareNativeReceiver(state, previous, child, threadId, dependencies) {
2134
+ if (previous === state) return true;
2135
+ if (!dependencies.isCurrent(state) || child && (!child.assignment.terminal || child.pendingTurns.length > 0 || dependencies.hasChildCustody(child.parent, threadId))) return false;
2136
+ if (!previous) return true;
2137
+ if (dependencies.isRetired(previous) || !state.requesterSessionKey || previous.requesterSessionKey !== state.requesterSessionKey || !previous.historyOwner || !state.historyOwner || !matchesNativeAssignmentLifecycle(previous.historyOwner, state.historyOwner) || ![...state.owners.values()].some((owner) => owner.completionCustody?.isCurrent())) return false;
2138
+ try {
2139
+ state.assignmentStore?.assertCurrent();
2140
+ return true;
2141
+ } catch {
2142
+ return false;
2201
2143
  }
2202
2144
  }
2203
- function readObservedSubmissionTurn(state, threadId, turnId, dependencies) {
2204
- const known = dependencies.knownChildren.get(threadId);
2205
- if (known?.parent !== state) return;
2206
- const pending = known.pendingTurns.find((turn) => turn.turnId === turnId);
2207
- const child = dependencies.currentChild(threadId);
2208
- const status = pending?.state ?? (child?.nativeTurnId === turnId ? child.nativeTurnState : void 0);
2209
- return status ? {
2210
- id: turnId,
2211
- status: status === "active" ? "inProgress" : status
2212
- } : void 0;
2213
- }
2214
- function observeSubmissionCall(state, turnId, item, allCalls, dependencies, isCurrent) {
2215
- const callId = readStringField(item, "id");
2216
- if (!turnId || !callId || !isCurrent()) return;
2217
- const owner = dependencies.parentOwner(state, turnId);
2218
- if (!owner && ![...state.owners.values()].some((candidate) => !candidate.turnId)) return;
2219
- const calls = allCalls.get(state) ?? /* @__PURE__ */ new Map();
2220
- const key = `${turnId}\0${callId}`;
2221
- if (calls.has(key) || !owner && calls.size >= 32) return;
2222
- const receivers = Array.isArray(item.receiverThreadIds) ? item.receiverThreadIds : [];
2223
- const targets = receivers.flatMap((id) => {
2224
- if (typeof id !== "string") return [];
2225
- dependencies.prepareReceiver(state, id);
2226
- const predecessor = captureSubmissionPredecessor({
2227
- state,
2228
- known: dependencies.knownChildren.get(id),
2229
- child: dependencies.currentChild(id)
2145
+ //#endregion
2146
+ //#region extensions/codex/src/app-server/native-subagent-submission-call.ts
2147
+ function createNativeSubagentSubmissionCalls(calls, dependencies, operations) {
2148
+ const { isCurrent } = operations;
2149
+ function admitModelInput(state, owner, request, pendingModelSources, preparedOwner) {
2150
+ if (!owner.modelSource || !isCurrent(state)) throw new Error("Codex native input has no admitted model source");
2151
+ assertNativeModelInputCompatible(owner, dependencies.currentModelExecution(request.targetThreadId) ?? owner);
2152
+ for (const entries of calls.values()) for (const pending of entries.values()) if (pending.modelInput?.threadId === request.targetThreadId) assertNativeModelInputCompatible(owner, pending.modelInput.source.owner);
2153
+ const key = `${request.turnId}\0${request.itemId}`;
2154
+ if (owner.modelSource.hasOperatorSource && !calls.get(state)?.has(key)) {
2155
+ if ([...calls.values()].reduce((count, entries) => count + [...entries.values()].filter((call) => call.modelInput?.source.owner.modelSource?.hasOperatorSource).length, 0) + pendingModelSources >= 32) throw new Error("Codex pending native input admission capacity reached");
2156
+ }
2157
+ observeCall(state, request.turnId, {
2158
+ id: request.itemId,
2159
+ receiverThreadIds: [request.targetThreadId]
2230
2160
  });
2231
- return predecessor ? [{
2232
- childThreadId: id,
2233
- predecessor
2234
- }] : [];
2235
- });
2236
- const receiver = receivers.length === 1 ? receivers[0] : void 0;
2237
- const source = typeof receiver === "string" ? retainNativeModelSource(owner) : void 0;
2238
- if (!targets.length && !source) return;
2239
- calls.set(key, {
2240
- parentTurnId: turnId,
2241
- callId,
2242
- targets,
2243
- owner,
2244
- ...source && typeof receiver === "string" ? { modelInput: {
2245
- threadId: receiver,
2246
- source
2247
- } } : {}
2248
- });
2249
- allCalls.set(state, calls);
2250
- }
2251
- function assertSubmissionModelInputsCurrent(calls, threadId, owner) {
2252
- for (const pending of calls) for (const call of pending.values()) if (call.modelInput?.threadId === threadId) try {
2253
- assertNativeModelInputCompatible(call.modelInput.source.owner, owner);
2254
- } catch (error) {
2255
- if (call.accepted) owner.modelExecutionCancelled = true;
2256
- throw error;
2257
- }
2258
- }
2259
- function settleSubmissionModelInput(call, accepted, dependencies) {
2260
- const input = call.modelInput;
2261
- if (!input) return;
2262
- const receiver = accepted ? dependencies.currentModelExecution(input.threadId) : void 0;
2263
- call.modelInput = void 0;
2264
- try {
2265
- const known = dependencies.knownChildren.get(input.threadId);
2266
- const isOtherTurn = call.submissionId && known?.observedTurns.has(call.submissionId) && receiver?.turnId !== call.submissionId;
2267
- if (accepted && receiver && !isOtherTurn) try {
2268
- assertNativeModelInputCompatible(input.source.owner, receiver);
2269
- } catch {
2270
- receiver.modelExecutionCancelled = true;
2161
+ const call = calls.get(state)?.get(key);
2162
+ if (!call || call.closed || call.owner !== owner || call.modelInput?.threadId !== request.targetThreadId) throw new Error("Codex native input reused an unsettled call identity");
2163
+ if (preparedOwner && call.modelInput.source.owner === owner) {
2164
+ const prepared = retainNativeModelSource(preparedOwner);
2165
+ if (!prepared) throw new Error("Codex native input lost its prepared model source");
2166
+ call.modelInput.source.release();
2167
+ call.modelInput.source = prepared;
2271
2168
  }
2272
- } finally {
2273
- input.source.release();
2274
2169
  }
2275
- }
2276
- function hasSubmissionCallCustody(state, call, hasObservationBacking) {
2277
- return Boolean(call.accepted && call.targets.some(({ childThreadId }) => state.owners.size > 0 || hasObservationBacking?.(state.parentThreadId, childThreadId)));
2278
- }
2279
- function captureSubmissionPredecessor(params) {
2280
- const { state, known, child } = params;
2281
- if (known?.parent !== state) return;
2282
- if (!known.assignment.nativeTurnId) return child && child.runId === known.assignment.runId && !child.terminal && !known.assignment.terminal && !known.assignment.unanchored ? { child } : void 0;
2283
- return {
2284
- runId: known.assignment.runId,
2285
- nativeTurnId: known.assignment.nativeTurnId,
2286
- terminal: known.assignment.terminal || child?.nativeTurnState === "completed" || child?.nativeTurnState === "failed"
2287
- };
2288
- }
2289
- function observeSubmissionPredecessor(params) {
2290
- const { state, call, threadId, turn, known } = params;
2291
- const submissionId = call.submissionId;
2292
- if (!call.accepted || !submissionId) return;
2293
- call.targets = call.targets.filter(({ childThreadId, predecessor }) => {
2294
- if (childThreadId !== threadId || !("child" in predecessor)) return true;
2295
- const child = predecessor.child;
2296
- if (known?.parent !== state || known.assignment.runId !== child.runId || state.owners.size === 0 && !params.hasObservationBacking?.(state.parentThreadId, threadId)) return false;
2297
- const nativeTurnId = child.nativeTurnId;
2298
- if (!nativeTurnId || nativeTurnId === submissionId || known.assignment.nativeTurnId !== nativeTurnId) return true;
2299
- const nativeState = (readStringField(turn, "id") === nativeTurnId ? readNativeTurnEnd(turn) : void 0) ?? child.nativeTurnState;
2300
- const owner = call.owner && [...state.owners.values()].includes(call.owner) ? call.owner : void 0;
2301
- if (nativeState === "interrupted") {
2302
- if (owner) params.acceptContinuation(owner);
2303
- return false;
2170
+ function hasPendingModelInput(request) {
2171
+ for (const entries of calls.values()) for (const call of entries.values()) if (!call.closed && call.modelInput?.threadId === request.threadId && (call.parentTurnId === request.parentTurnId || call.parentTurnId === request.rootTurnId)) {
2172
+ const capture = call.modelInput.source.owner.modelSource?.capture();
2173
+ capture?.release();
2174
+ return Boolean(capture);
2304
2175
  }
2305
- if (!known.assignment.terminal && nativeState !== "completed" && nativeState !== "failed") return true;
2306
- params.capture({
2307
- parentTurnId: call.parentTurnId,
2308
- callId: call.callId,
2309
- childThreadId,
2310
- submissionId,
2311
- predecessorRunId: child.runId,
2312
- predecessorNativeTurnId: nativeTurnId
2313
- }, owner);
2314
2176
  return false;
2315
- });
2316
- if (call.targets.length === 0) {
2317
- call.owner = void 0;
2318
- call.completionCustody?.release();
2319
- call.completionCustody = void 0;
2320
2177
  }
2321
- }
2322
- function pruneSubmissionCalls(state, calls, dependencies) {
2323
- const hasUnboundOwner = [...state.owners.values()].some((owner) => !owner.turnId);
2324
- for (const [key, call] of calls ?? []) {
2325
- if (hasSubmissionCallCustody(state, call, dependencies.hasObservationBacking)) {
2326
- if (!call.owner || ![...state.owners.values()].includes(call.owner)) call.owner = void 0;
2327
- continue;
2178
+ function retireReceiverModelInputs(threadId) {
2179
+ for (const entries of calls.values()) for (const call of entries.values()) if (call.modelInput?.threadId === threadId) {
2180
+ settleSubmissionModelInput(call, false);
2181
+ call.closed = true;
2328
2182
  }
2329
- if (call.owner && ![...state.owners.values()].includes(call.owner) || !dependencies.parentOwner(state, call.parentTurnId) && !hasUnboundOwner) {
2330
- settleSubmissionModelInput(call, false, dependencies);
2331
- calls.delete(key);
2332
- call.completionCustody?.release();
2183
+ }
2184
+ function observeCall(state, turnId, item) {
2185
+ const callId = readStringField(item, "id");
2186
+ if (!turnId || !callId || !isCurrent(state)) return;
2187
+ const owner = dependencies.parentOwner(state, turnId);
2188
+ if (!owner && ![...state.owners.values()].some((candidate) => !candidate.turnId)) return;
2189
+ const entries = calls.get(state) ?? /* @__PURE__ */ new Map();
2190
+ const key = `${turnId}\0${callId}`;
2191
+ if (entries.has(key) || !owner && entries.size >= 32) return;
2192
+ const receivers = Array.isArray(item.receiverThreadIds) ? item.receiverThreadIds : [];
2193
+ const targets = receivers.flatMap((id) => {
2194
+ if (typeof id !== "string") return [];
2195
+ dependencies.prepareReceiver(state, id);
2196
+ const predecessor = captureSubmissionPredecessor({
2197
+ state,
2198
+ known: dependencies.knownChildren.get(id),
2199
+ child: dependencies.currentChild(id)
2200
+ });
2201
+ return predecessor ? [{
2202
+ childThreadId: id,
2203
+ predecessor
2204
+ }] : [];
2205
+ });
2206
+ const receiver = receivers.length === 1 ? receivers[0] : void 0;
2207
+ const source = typeof receiver === "string" ? retainNativeModelSource(owner) : void 0;
2208
+ if (!targets.length && !source) return;
2209
+ entries.set(key, {
2210
+ parentTurnId: turnId,
2211
+ callId,
2212
+ targets,
2213
+ owner,
2214
+ ...source && typeof receiver === "string" ? { modelInput: {
2215
+ threadId: receiver,
2216
+ source
2217
+ } } : {}
2218
+ });
2219
+ calls.set(state, entries);
2220
+ }
2221
+ function assertModelInputCurrent(threadId, owner) {
2222
+ for (const pending of calls.values()) for (const call of pending.values()) if (call.modelInput?.threadId === threadId) try {
2223
+ assertNativeModelInputCompatible(call.modelInput.source.owner, owner);
2224
+ } catch (error) {
2225
+ if (call.accepted) owner.modelExecutionCancelled = true;
2226
+ throw error;
2333
2227
  }
2334
2228
  }
2335
- }
2336
- function acceptSubmissionModelInteraction(calls, turnId, itemId, threadId, accept, dependencies) {
2337
- const call = calls?.get(`${turnId ?? ""}\0${itemId ?? ""}`);
2338
- if (!call) return false;
2339
- if (call.closed || !call.modelInput) return true;
2340
- if (call.modelInput.threadId !== threadId) throw new Error("Codex native interaction changed its admitted target");
2341
- call.accepted = true;
2342
- accept(call.modelInput.source.owner);
2343
- call.closed = true;
2344
- settleSubmissionModelInput(call, true, dependencies);
2345
- return true;
2346
- }
2347
- function acceptNativeSubmission(state, call, dependencies) {
2348
- const owner = dependencies.parentOwner(state, call.parentTurnId);
2349
- if (call.closed || !owner || call.owner && owner !== call.owner || !call.submissionId || !dependencies.isCurrent(state)) return;
2350
- call.closed = true;
2351
- call.accepted = true;
2352
- call.owner = owner;
2353
- call.completionCustody ??= owner.completionCustody?.retain();
2354
- const modelSource = retainNativeModelSource(call.modelInput?.source.owner);
2355
- try {
2356
- settleSubmissionModelInput(call, true, dependencies);
2357
- const targets = call.targets;
2358
- call.targets = [];
2359
- for (const target of targets) {
2360
- const { childThreadId, predecessor } = target;
2361
- const modelOwner = modelSource?.owner ?? owner;
2362
- if (modelOwner.modelSource && ("child" in predecessor || predecessor.terminal)) dependencies.acceptContinuation(state, {
2363
- ...owner,
2364
- claimDirectChild: void 0,
2365
- rejectPendingDirectChild: void 0,
2366
- onDirectChildAccepted: void 0
2367
- }, childThreadId, call, modelOwner);
2368
- if ("child" in predecessor) {
2369
- call.targets.push(target);
2370
- continue;
2229
+ function acceptInteraction(state, turnId, itemId, threadId, accept) {
2230
+ const call = calls.get(state)?.get(`${turnId ?? ""}\0${itemId ?? ""}`);
2231
+ if (!call) return false;
2232
+ if (call.closed || !call.modelInput) return true;
2233
+ if (call.modelInput.threadId !== threadId) throw new Error("Codex native interaction changed its admitted target");
2234
+ call.accepted = true;
2235
+ accept(call.modelInput.source.owner);
2236
+ call.closed = true;
2237
+ settleSubmissionModelInput(call, true);
2238
+ return true;
2239
+ }
2240
+ function readObservedSubmissionTurn(state, threadId, turnId) {
2241
+ const known = dependencies.knownChildren.get(threadId);
2242
+ if (known?.parent !== state) return;
2243
+ const pending = known.pendingTurns.find((turn) => turn.turnId === turnId);
2244
+ const child = dependencies.currentChild(threadId);
2245
+ const status = pending?.state ?? (child?.nativeTurnId === turnId ? child.nativeTurnState : void 0);
2246
+ return status ? {
2247
+ id: turnId,
2248
+ status: status === "active" ? "inProgress" : status
2249
+ } : void 0;
2250
+ }
2251
+ function settleSubmissionModelInput(call, accepted) {
2252
+ const input = call.modelInput;
2253
+ if (!input) return;
2254
+ const receiver = accepted ? dependencies.currentModelExecution(input.threadId) : void 0;
2255
+ call.modelInput = void 0;
2256
+ try {
2257
+ const known = dependencies.knownChildren.get(input.threadId);
2258
+ const isOtherTurn = call.submissionId && known?.observedTurns.has(call.submissionId) && receiver?.turnId !== call.submissionId;
2259
+ if (accepted && receiver && !isOtherTurn) try {
2260
+ assertNativeModelInputCompatible(input.source.owner, receiver);
2261
+ } catch {
2262
+ receiver.modelExecutionCancelled = true;
2371
2263
  }
2372
- if (!predecessor.terminal) {
2373
- dependencies.acceptContinuation(state, owner, childThreadId, call, modelOwner);
2374
- continue;
2264
+ } finally {
2265
+ input.source.release();
2266
+ }
2267
+ }
2268
+ function hasSubmissionCallCustody(state, call) {
2269
+ return Boolean(call.accepted && call.targets.some(({ childThreadId }) => state.owners.size > 0 || dependencies.hasObservationBacking?.(state.parentThreadId, childThreadId)));
2270
+ }
2271
+ function observeSubmissionPredecessor(state, call, threadId, turn) {
2272
+ const known = dependencies.knownChildren.get(threadId);
2273
+ const submissionId = call.submissionId;
2274
+ if (!call.accepted || !submissionId) return;
2275
+ call.targets = call.targets.filter(({ childThreadId, predecessor }) => {
2276
+ if (childThreadId !== threadId || !("child" in predecessor)) return true;
2277
+ const child = predecessor.child;
2278
+ if (known?.parent !== state || known.assignment.runId !== child.runId || state.owners.size === 0 && !dependencies.hasObservationBacking?.(state.parentThreadId, threadId)) return false;
2279
+ const nativeTurnId = child.nativeTurnId;
2280
+ if (!nativeTurnId || nativeTurnId === submissionId || known.assignment.nativeTurnId !== nativeTurnId) return true;
2281
+ const nativeState = (readStringField(turn, "id") === nativeTurnId ? readNativeTurnEnd(turn) : void 0) ?? child.nativeTurnState;
2282
+ const owner = call.owner && [...state.owners.values()].includes(call.owner) ? call.owner : void 0;
2283
+ if (nativeState === "interrupted") {
2284
+ if (owner) dependencies.acceptContinuation(state, owner, threadId, call);
2285
+ return false;
2375
2286
  }
2376
- dependencies.capture(state, {
2287
+ if (!known.assignment.terminal && nativeState !== "completed" && nativeState !== "failed") return true;
2288
+ operations.capture(state, {
2377
2289
  parentTurnId: call.parentTurnId,
2378
2290
  callId: call.callId,
2379
2291
  childThreadId,
2380
- submissionId: call.submissionId,
2381
- predecessorRunId: predecessor.runId,
2382
- predecessorNativeTurnId: predecessor.nativeTurnId
2383
- }, owner, true);
2384
- }
2385
- for (const { childThreadId } of call.targets) dependencies.observeKnownChild(childThreadId);
2386
- if (!call.targets.length) {
2292
+ submissionId,
2293
+ predecessorRunId: child.runId,
2294
+ predecessorNativeTurnId: nativeTurnId
2295
+ }, owner, true, call.completionCustody);
2296
+ return false;
2297
+ });
2298
+ if (call.targets.length === 0) {
2299
+ call.owner = void 0;
2387
2300
  call.completionCustody?.release();
2388
2301
  call.completionCustody = void 0;
2389
2302
  }
2390
- } finally {
2391
- modelSource?.release();
2392
2303
  }
2304
+ function pruneSubmissionCalls(state, parentCalls) {
2305
+ const hasUnboundOwner = [...state.owners.values()].some((owner) => !owner.turnId);
2306
+ for (const [key, call] of parentCalls ?? []) {
2307
+ if (hasSubmissionCallCustody(state, call)) {
2308
+ if (!call.owner || ![...state.owners.values()].includes(call.owner)) call.owner = void 0;
2309
+ continue;
2310
+ }
2311
+ if (call.owner && ![...state.owners.values()].includes(call.owner) || !dependencies.parentOwner(state, call.parentTurnId) && !hasUnboundOwner) {
2312
+ settleSubmissionModelInput(call, false);
2313
+ parentCalls.delete(key);
2314
+ call.completionCustody?.release();
2315
+ }
2316
+ }
2317
+ }
2318
+ function acceptNativeSubmission(state, call) {
2319
+ const owner = dependencies.parentOwner(state, call.parentTurnId);
2320
+ if (call.closed || !owner || call.owner && owner !== call.owner || !call.submissionId || !isCurrent(state)) return;
2321
+ call.closed = true;
2322
+ call.accepted = true;
2323
+ call.owner = owner;
2324
+ call.completionCustody ??= owner.completionCustody?.retain();
2325
+ const modelSource = retainNativeModelSource(call.modelInput?.source.owner);
2326
+ try {
2327
+ settleSubmissionModelInput(call, true);
2328
+ const targets = call.targets;
2329
+ call.targets = [];
2330
+ for (const target of targets) {
2331
+ const { childThreadId, predecessor } = target;
2332
+ const modelOwner = modelSource?.owner ?? owner;
2333
+ if (modelOwner.modelSource && ("child" in predecessor || predecessor.terminal)) dependencies.acceptContinuation(state, {
2334
+ ...owner,
2335
+ claimDirectChild: void 0,
2336
+ rejectPendingDirectChild: void 0,
2337
+ onDirectChildAccepted: void 0
2338
+ }, childThreadId, call, modelOwner);
2339
+ if ("child" in predecessor) {
2340
+ call.targets.push(target);
2341
+ continue;
2342
+ }
2343
+ if (!predecessor.terminal) {
2344
+ dependencies.acceptContinuation(state, owner, childThreadId, call, modelOwner);
2345
+ continue;
2346
+ }
2347
+ operations.capture(state, {
2348
+ parentTurnId: call.parentTurnId,
2349
+ callId: call.callId,
2350
+ childThreadId,
2351
+ submissionId: call.submissionId,
2352
+ predecessorRunId: predecessor.runId,
2353
+ predecessorNativeTurnId: predecessor.nativeTurnId
2354
+ }, owner, true);
2355
+ }
2356
+ for (const { childThreadId } of call.targets) operations.observeKnownChild(childThreadId);
2357
+ if (!call.targets.length) {
2358
+ call.completionCustody?.release();
2359
+ call.completionCustody = void 0;
2360
+ }
2361
+ } finally {
2362
+ modelSource?.release();
2363
+ }
2364
+ }
2365
+ return {
2366
+ admitModelInput,
2367
+ hasPendingModelInput,
2368
+ retireReceiverModelInputs,
2369
+ observeCall,
2370
+ assertModelInputCurrent,
2371
+ acceptInteraction,
2372
+ readObservedSubmissionTurn,
2373
+ settleSubmissionModelInput,
2374
+ hasSubmissionCallCustody,
2375
+ observeSubmissionPredecessor,
2376
+ pruneSubmissionCalls,
2377
+ acceptNativeSubmission
2378
+ };
2379
+ }
2380
+ function captureSubmissionPredecessor(params) {
2381
+ const { state, known, child } = params;
2382
+ if (known?.parent !== state) return;
2383
+ if (!known.assignment.nativeTurnId) return child && child.runId === known.assignment.runId && !child.terminal && !known.assignment.terminal && !known.assignment.unanchored ? { child } : void 0;
2384
+ return {
2385
+ runId: known.assignment.runId,
2386
+ nativeTurnId: known.assignment.nativeTurnId,
2387
+ terminal: known.assignment.terminal || child?.nativeTurnState === "completed" || child?.nativeTurnState === "failed"
2388
+ };
2393
2389
  }
2394
2390
  //#endregion
2395
2391
  //#region extensions/codex/src/app-server/native-subagent-submission-history.ts
@@ -2404,8 +2400,7 @@ async function readCodexNativeSubmissionTurn(receipt, dependencies) {
2404
2400
  if (!revision.isCurrent() || !dependencies.isCurrent()) return;
2405
2401
  const thread = isJsonObject(response.thread) ? response.thread : void 0;
2406
2402
  if (readStringField(thread, "id") !== receipt.childThreadId || readThreadParentThreadId(thread) !== dependencies.parentThreadId()) return;
2407
- const turns = [];
2408
- for (const turn of Array.isArray(thread?.turns) ? thread.turns : []) if (isJsonObject(turn)) turns.push(turn);
2403
+ const turns = (Array.isArray(thread?.turns) ? thread.turns : []).flatMap((turn) => isJsonObject(turn) ? [turn] : []);
2409
2404
  const predecessorIndex = turns.findIndex((turn) => readStringField(turn, "id") === receipt.predecessorNativeTurnId);
2410
2405
  const turnIndex = turns.findIndex((turn) => readStringField(turn, "id") === receipt.submissionId);
2411
2406
  if (predecessorIndex < 0 || turnIndex <= predecessorIndex || !["completed", "failed"].includes(readStringField(turns[predecessorIndex], "status") ?? "")) return;
@@ -2427,6 +2422,11 @@ var CodexNativeSubagentSubmissionOwner = class {
2427
2422
  this.writes = /* @__PURE__ */ new Map();
2428
2423
  this.disposed = false;
2429
2424
  this.pollDelays = dependencies.recoveryPollDelaysMs ?? DEFAULT_RECOVERY_POLL_DELAYS_MS;
2425
+ this.modelInputs = createNativeSubagentSubmissionCalls(this.calls, dependencies, {
2426
+ isCurrent: (state) => this.isCurrent(state),
2427
+ capture: (state, receipt, owner, persist, completionCustody) => this.capture(state, receipt, owner, persist, completionCustody),
2428
+ observeKnownChild: (threadId) => this.observeKnownChild(threadId)
2429
+ });
2430
2430
  }
2431
2431
  isCurrent(state) {
2432
2432
  if (this.dependencies.isCurrent(state)) return true;
@@ -2446,33 +2446,6 @@ var CodexNativeSubagentSubmissionOwner = class {
2446
2446
  }
2447
2447
  return true;
2448
2448
  }
2449
- observeCall(state, turnId, item) {
2450
- observeSubmissionCall(state, turnId, item, this.calls, this.dependencies, () => this.isCurrent(state));
2451
- }
2452
- admitModelInput(state, owner, request, pendingModelSources, preparedOwner) {
2453
- admitSubmissionModelInput({
2454
- state,
2455
- owner,
2456
- request,
2457
- pendingModelSources,
2458
- preparedOwner,
2459
- calls: this.calls,
2460
- dependencies: this.dependencies,
2461
- isCurrent: () => this.isCurrent(state)
2462
- });
2463
- }
2464
- acceptInteraction(state, turnId, itemId, threadId, accept) {
2465
- return acceptSubmissionModelInteraction(this.calls.get(state), turnId, itemId, threadId, accept, this.dependencies);
2466
- }
2467
- hasPendingModelInput(request) {
2468
- return hasPendingSubmissionModelInput(this.calls, request);
2469
- }
2470
- retireReceiverModelInputs(threadId) {
2471
- retireReceiverModelInputs(this.calls, threadId, this.dependencies);
2472
- }
2473
- assertModelInputCurrent(threadId, owner) {
2474
- assertSubmissionModelInputsCurrent(this.calls.values(), threadId, owner);
2475
- }
2476
2449
  observeOutput(state, turnId, item) {
2477
2450
  if (item.type !== "function_call_output" || !turnId) return;
2478
2451
  const key = `${turnId}\0${readStringField(item, "call_id") ?? ""}`;
@@ -2485,14 +2458,14 @@ var CodexNativeSubagentSubmissionOwner = class {
2485
2458
  const submissionId = isJsonObject(output) ? readStringField(output, "submission_id")?.trim() : void 0;
2486
2459
  if (!submissionId) {
2487
2460
  call.closed = true;
2488
- settleSubmissionModelInput(call, false, this.dependencies);
2461
+ this.modelInputs.settleSubmissionModelInput(call, false);
2489
2462
  return;
2490
2463
  }
2491
2464
  call.submissionId = submissionId;
2492
- this.accept(state, call);
2465
+ this.modelInputs.acceptNativeSubmission(state, call);
2493
2466
  }
2494
2467
  bind(state, turnId) {
2495
- for (const call of this.calls.get(state)?.values() ?? []) if (call.parentTurnId === turnId && call.submissionId) this.accept(state, call);
2468
+ for (const call of this.calls.get(state)?.values() ?? []) if (call.parentTurnId === turnId && call.submissionId) this.modelInputs.acceptNativeSubmission(state, call);
2496
2469
  }
2497
2470
  restore(state, owner) {
2498
2471
  try {
@@ -2508,17 +2481,17 @@ var CodexNativeSubagentSubmissionOwner = class {
2508
2481
  for (const [state, entries] of this.pending) for (const custody of entries.values()) if (custody.receipt.childThreadId === threadId && custody.receipt.submissionId === turnId) this.promote(state, custody, turn);
2509
2482
  }
2510
2483
  hasCustody(state) {
2511
- return Boolean(this.pending.get(state)?.size || this.writes.get(state)?.size) || [...this.calls.get(state)?.values() ?? []].some((call) => hasSubmissionCallCustody(state, call, this.dependencies.hasObservationBacking));
2484
+ return Boolean(this.pending.get(state)?.size || this.writes.get(state)?.size) || [...this.calls.get(state)?.values() ?? []].some((call) => this.modelInputs.hasSubmissionCallCustody(state, call));
2512
2485
  }
2513
2486
  hasChildCustody(state, childThreadId) {
2514
- return [...this.pending.get(state)?.values() ?? []].some((entry) => entry.receipt.childThreadId === childThreadId) || [...this.calls.get(state)?.values() ?? []].some((call) => call.targets.some((target) => target.childThreadId === childThreadId) && hasSubmissionCallCustody(state, call, this.dependencies.hasObservationBacking));
2487
+ return [...this.pending.get(state)?.values() ?? []].some((entry) => entry.receipt.childThreadId === childThreadId) || [...this.calls.get(state)?.values() ?? []].some((call) => call.targets.some((target) => target.childThreadId === childThreadId) && this.modelInputs.hasSubmissionCallCustody(state, call));
2515
2488
  }
2516
2489
  async settleWrites(state) {
2517
2490
  while (this.writes.get(state)?.size) await Promise.allSettled(this.writes.get(state));
2518
2491
  }
2519
2492
  async drain(state) {
2520
2493
  const calls = this.calls.get(state);
2521
- pruneSubmissionCalls(state, calls, this.dependencies);
2494
+ this.modelInputs.pruneSubmissionCalls(state, calls);
2522
2495
  if (!calls?.size) this.calls.delete(state);
2523
2496
  await this.settleWrites(state);
2524
2497
  if (state.owners.size === 0) for (const custody of this.pending.get(state)?.values() ?? []) {
@@ -2532,13 +2505,13 @@ var CodexNativeSubagentSubmissionOwner = class {
2532
2505
  }
2533
2506
  retire(state) {
2534
2507
  for (const call of this.calls.get(state)?.values() ?? []) {
2535
- settleSubmissionModelInput(call, false, this.dependencies);
2508
+ this.modelInputs.settleSubmissionModelInput(call, false);
2536
2509
  call.completionCustody?.release();
2537
2510
  }
2538
2511
  this.calls.delete(state);
2539
2512
  for (const custody of this.pending.get(state)?.values() ?? []) {
2540
2513
  custody.phase = "settled";
2541
- if (custody.timer) clearTimeout(custody.timer);
2514
+ clearTimeout(custody.timer);
2542
2515
  custody.release();
2543
2516
  custody.completionCustody?.release();
2544
2517
  }
@@ -2548,27 +2521,10 @@ var CodexNativeSubagentSubmissionOwner = class {
2548
2521
  this.disposed = true;
2549
2522
  for (const state of /* @__PURE__ */ new Set([...this.pending.keys(), ...this.calls.keys()])) this.retire(state);
2550
2523
  }
2551
- accept(state, call) {
2552
- acceptNativeSubmission(state, call, {
2553
- ...this.dependencies,
2554
- isCurrent: (parent) => this.isCurrent(parent),
2555
- capture: (parent, receipt, owner, persist) => this.capture(parent, receipt, owner, persist),
2556
- observeKnownChild: (threadId) => this.observeKnownChild(threadId)
2557
- });
2558
- }
2559
2524
  observeKnownChild(threadId, turn) {
2560
2525
  for (const [state, calls] of this.calls) {
2561
2526
  if (!this.isCurrent(state)) continue;
2562
- for (const call of calls.values()) observeSubmissionPredecessor({
2563
- state,
2564
- call,
2565
- threadId,
2566
- turn,
2567
- known: this.dependencies.knownChildren.get(threadId),
2568
- hasObservationBacking: this.dependencies.hasObservationBacking,
2569
- acceptContinuation: (owner) => this.dependencies.acceptContinuation(state, owner, threadId, call),
2570
- capture: (receipt, owner) => this.capture(state, receipt, owner, true, call.completionCustody)
2571
- });
2527
+ for (const call of calls.values()) this.modelInputs.observeSubmissionPredecessor(state, call, threadId, turn);
2572
2528
  this.dependencies.onSettled(state);
2573
2529
  }
2574
2530
  }
@@ -2597,14 +2553,14 @@ var CodexNativeSubagentSubmissionOwner = class {
2597
2553
  embeddedAgentLog.warn("Accepted native follow-up lost restart protection; retaining local observation", { error: formatErrorMessage$1(error) });
2598
2554
  }
2599
2555
  })());
2600
- const observed = readObservedSubmissionTurn(state, receipt.childThreadId, receipt.submissionId, this.dependencies);
2556
+ const observed = this.modelInputs.readObservedSubmissionTurn(state, receipt.childThreadId, receipt.submissionId);
2601
2557
  if (observed) this.promote(state, custody, observed);
2602
2558
  if (custody.phase !== "promoting") this.reconcile(state, custody);
2603
2559
  }
2604
2560
  promote(state, custody, turn, historyValidated = false) {
2605
- if (!this.isObserving(state, custody) || !this.admitTurn(state, custody.receipt, turn, custody.owner, historyValidated, custody.completionCustody)) return;
2561
+ if (!this.isObserving(state, custody) || !this.admitTurn(state, custody, turn, historyValidated)) return;
2606
2562
  custody.phase = "promoting";
2607
- if (custody.timer) clearTimeout(custody.timer);
2563
+ clearTimeout(custody.timer);
2608
2564
  }
2609
2565
  settleChild(state, child) {
2610
2566
  for (const custody of this.pending.get(state)?.values() ?? []) {
@@ -2626,7 +2582,15 @@ var CodexNativeSubagentSubmissionOwner = class {
2626
2582
  async reconcile(state, custody) {
2627
2583
  if (!this.isObserving(state, custody)) return;
2628
2584
  try {
2629
- const turn = await this.readTurn(state, custody);
2585
+ const childThreadId = custody.receipt.childThreadId;
2586
+ const turn = await readCodexNativeSubmissionTurn(custody.receipt, {
2587
+ client: this.dependencies.client,
2588
+ recovery: this.dependencies.recovery,
2589
+ prepareReceiver: () => this.dependencies.prepareReceiver(state, childThreadId),
2590
+ isCurrent: () => this.isObserving(state, custody),
2591
+ parentThreadId: () => this.nativeParentThreadId(state, childThreadId),
2592
+ currentChild: () => this.dependencies.currentChild(childThreadId)
2593
+ });
2630
2594
  if (turn) this.promote(state, custody, turn, true);
2631
2595
  } catch (error) {
2632
2596
  embeddedAgentLog.warn("Failed to reconcile an accepted native follow-up receipt", { error: formatErrorMessage$1(error) });
@@ -2638,20 +2602,9 @@ var CodexNativeSubagentSubmissionOwner = class {
2638
2602
  }, delayForAttempt(this.pollDelays, custody.attempt++));
2639
2603
  custody.timer.unref();
2640
2604
  }
2641
- readTurn(state, custody) {
2642
- const childThreadId = custody.receipt.childThreadId;
2643
- return readCodexNativeSubmissionTurn(custody.receipt, {
2644
- client: this.dependencies.client,
2645
- recovery: this.dependencies.recovery,
2646
- prepareReceiver: () => this.dependencies.prepareReceiver(state, childThreadId),
2647
- isCurrent: () => this.isObserving(state, custody),
2648
- parentThreadId: () => this.nativeParentThreadId(state, childThreadId),
2649
- currentChild: () => this.dependencies.currentChild(childThreadId)
2650
- });
2651
- }
2652
2605
  finishCustody(state, custody) {
2653
2606
  custody.phase = "settled";
2654
- if (custody.timer) clearTimeout(custody.timer);
2607
+ clearTimeout(custody.timer);
2655
2608
  const entries = this.pending.get(state);
2656
2609
  for (const [key, entry] of entries ?? []) if (entry === custody) entries.delete(key);
2657
2610
  if (!entries?.size) this.pending.delete(state);
@@ -2659,7 +2612,7 @@ var CodexNativeSubagentSubmissionOwner = class {
2659
2612
  custody.completionCustody?.release();
2660
2613
  this.dependencies.onSettled(state);
2661
2614
  }
2662
- admitTurn(state, receipt, turn, owner, historyValidated, completionCustody) {
2615
+ admitTurn(state, { receipt, owner, completionCustody }, turn, historyValidated) {
2663
2616
  if (readStringField(turn, "id") !== receipt.submissionId || this.disposed || !this.isCurrent(state)) return false;
2664
2617
  const runId = codexNativeSubagentRunId(receipt.childThreadId, receipt.submissionId);
2665
2618
  let known = this.dependencies.knownChildren.get(receipt.childThreadId);
@@ -2707,7 +2660,7 @@ var CodexNativeSubagentSubmissionOwner = class {
2707
2660
  pending.admittedOwner = owner;
2708
2661
  owner.onDirectChildAccepted?.();
2709
2662
  }
2710
- this.dependencies.admitFollowup(known, receipt.childThreadId);
2663
+ this.dependencies.admitFollowup(known);
2711
2664
  }
2712
2665
  const child = this.dependencies.currentChild(receipt.childThreadId);
2713
2666
  if (child?.runId !== runId) return false;
@@ -2777,25 +2730,7 @@ function sanitizeCodexAgentEventRecord(value) {
2777
2730
  return sanitizeToolArgs(value);
2778
2731
  }
2779
2732
  function sanitizeCodexToolArguments(value) {
2780
- if (!isJsonObject(value)) return;
2781
- return sanitizeCodexAgentEventRecord(value);
2782
- }
2783
- //#endregion
2784
- //#region extensions/codex/src/app-server/web-search-item.ts
2785
- function projectCodexWebSearchItem(item) {
2786
- const action = isJsonObject(item.action) ? item.action : void 0;
2787
- const actionType = normalizeOptionalString(action?.type);
2788
- const queries = actionType === "search" ? normalizeTrimmedStringList(action?.queries) : [];
2789
- const query = normalizeOptionalString(item.query) ?? (actionType === "search" ? normalizeOptionalString(action?.query) : void 0) ?? queries[0];
2790
- const url = normalizeOptionalString(action?.url);
2791
- const pattern = normalizeOptionalString(action?.pattern);
2792
- return {
2793
- ...query ? { query } : {},
2794
- ...queries.length > 0 ? { queries } : {},
2795
- ...actionType && actionType !== "search" ? { action: actionType } : {},
2796
- ...url ? { url } : {},
2797
- ...pattern ? { pattern } : {}
2798
- };
2733
+ return isJsonObject(value) ? sanitizeCodexAgentEventRecord(value) : void 0;
2799
2734
  }
2800
2735
  //#endregion
2801
2736
  //#region extensions/codex/src/app-server/event-projector-tool-items.ts
@@ -2828,23 +2763,21 @@ function projectCodexToolActivity(item, phase, meta) {
2828
2763
  }) : void 0;
2829
2764
  }
2830
2765
  function isNativePostToolUseRelayItem(item) {
2831
- switch (item.type) {
2832
- case "commandExecution":
2833
- case "fileChange":
2834
- case "mcpToolCall": return true;
2835
- default: return false;
2836
- }
2766
+ return [
2767
+ "commandExecution",
2768
+ "fileChange",
2769
+ "mcpToolCall"
2770
+ ].includes(item.type);
2837
2771
  }
2838
2772
  function shouldSuppressChannelProgressForItem(item) {
2839
- if (isProjectedNativeToolItem(item)) return true;
2840
- return item.type === "dynamicToolCall";
2773
+ return isProjectedNativeToolItem(item) || item.type === "dynamicToolCall";
2841
2774
  }
2842
2775
  function itemToolArgs(item) {
2843
2776
  if (item.type === "commandExecution") return sanitizeCodexAgentEventRecord({
2844
2777
  command: item.command,
2845
2778
  ...typeof item.cwd === "string" ? { cwd: item.cwd } : {}
2846
2779
  });
2847
- if (item.type === "fileChange") return sanitizeCodexAgentEventRecord({ changes: itemFileChangesForTranscript(item) });
2780
+ if (item.type === "fileChange") return sanitizeCodexAgentEventRecord({ changes: itemFileChanges(item, true) });
2848
2781
  if (item.type === "webSearch") return webSearchToolArgs(item);
2849
2782
  if (item.type === "dynamicToolCall" || item.type === "mcpToolCall") return sanitizeCodexToolArguments(item.arguments);
2850
2783
  }
@@ -2873,10 +2806,7 @@ function itemToolResult(item) {
2873
2806
  ...item.error ? { error: item.error } : {},
2874
2807
  ...item.result ? { result: item.result } : {}
2875
2808
  });
2876
- if (item.type === "webSearch") return webSearchToolResult(item);
2877
- }
2878
- function webSearchToolResult(item) {
2879
- return sanitizeCodexAgentEventRecord({
2809
+ if (item.type === "webSearch") return sanitizeCodexAgentEventRecord({
2880
2810
  status: itemStatus(item),
2881
2811
  ...typeof item.durationMs === "number" ? { durationMs: item.durationMs } : {},
2882
2812
  ...webSearchToolArgs(item)
@@ -2886,20 +2816,6 @@ function itemFileChangeRecords(item) {
2886
2816
  const changes = item.changes;
2887
2817
  return Array.isArray(changes) ? changes.filter(isJsonObject) : [];
2888
2818
  }
2889
- function itemFileChanges(item) {
2890
- return itemFileChangeRecords(item).flatMap((change) => {
2891
- const path = normalizeOptionalString(change.path);
2892
- if (!path || change.kind === void 0) return [];
2893
- return [{
2894
- path,
2895
- kind: change.kind
2896
- }];
2897
- });
2898
- }
2899
- function fileChangeKindType(kind) {
2900
- if (typeof kind === "string") return kind;
2901
- return isJsonObject(kind) ? normalizeOptionalString(kind.type) : void 0;
2902
- }
2903
2819
  function countFileContentLines(content) {
2904
2820
  if (!content) return 0;
2905
2821
  const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
@@ -2907,7 +2823,7 @@ function countFileContentLines(content) {
2907
2823
  return lines.length;
2908
2824
  }
2909
2825
  function fileChangeDiffStat(diff, kind) {
2910
- const kindType = fileChangeKindType(kind);
2826
+ const kindType = typeof kind === "string" ? kind : isJsonObject(kind) ? normalizeOptionalString(kind.type) : void 0;
2911
2827
  if (kindType === "add") return {
2912
2828
  added: countFileContentLines(diff),
2913
2829
  removed: 0
@@ -2942,7 +2858,7 @@ function truncateFileChangeDiffAtLineBoundary(diff, maxChars) {
2942
2858
  diffTruncated: true
2943
2859
  } : { diffTruncated: true };
2944
2860
  }
2945
- function itemFileChangesForTranscript(item) {
2861
+ function itemFileChanges(item, includeDiff = false) {
2946
2862
  let remainingDiffChars = 1e4;
2947
2863
  return itemFileChangeRecords(item).flatMap((change) => {
2948
2864
  const path = normalizeOptionalString(change.path);
@@ -2951,7 +2867,7 @@ function itemFileChangesForTranscript(item) {
2951
2867
  path,
2952
2868
  kind: change.kind
2953
2869
  };
2954
- if (typeof change.diff !== "string") return [result];
2870
+ if (!includeDiff || typeof change.diff !== "string") return [result];
2955
2871
  result.stat = fileChangeDiffStat(change.diff, change.kind);
2956
2872
  const bounded = truncateFileChangeDiffAtLineBoundary(change.diff, remainingDiffChars);
2957
2873
  if (bounded.diff !== void 0) {
@@ -3024,7 +2940,7 @@ var CodexToolProgressProjection = class {
3024
2940
  this.output = new NativeToolOutputAccumulator("Codex");
3025
2941
  this.metas = /* @__PURE__ */ new Map();
3026
2942
  this.sideEffectingNativeIds = /* @__PURE__ */ new Set();
3027
- this.sideEffectingDynamicIds = /* @__PURE__ */ new Set();
2943
+ this.hasDynamicSideEffects = false;
3028
2944
  this.transcriptProgressCallIds = /* @__PURE__ */ new Set();
3029
2945
  this.approvalTimeoutKinds = /* @__PURE__ */ new Map();
3030
2946
  }
@@ -3044,7 +2960,7 @@ var CodexToolProgressProjection = class {
3044
2960
  return this.lastNativeToolError;
3045
2961
  }
3046
2962
  get hasPotentialSideEffects() {
3047
- return this.sideEffectingNativeIds.size > 0 || this.sideEffectingDynamicIds.size > 0;
2963
+ return this.sideEffectingNativeIds.size > 0 || this.hasDynamicSideEffects;
3048
2964
  }
3049
2965
  approvalTimeoutExplanation(itemId, status) {
3050
2966
  const kind = isNonSuccessItemStatus(status) && this.approvalTimeoutKinds.get(itemId);
@@ -3088,7 +3004,7 @@ var CodexToolProgressProjection = class {
3088
3004
  error: resultText || (params.terminalType === "blocked" ? "codex dynamic tool blocked" : "codex dynamic tool failed")
3089
3005
  };
3090
3006
  else if (this.lastNativeToolError?.mutatingAction !== true) this.lastNativeToolError = void 0;
3091
- if (params.sideEffectEvidence === true) this.sideEffectingDynamicIds.add(params.callId);
3007
+ this.hasDynamicSideEffects ||= params.sideEffectEvidence === true;
3092
3008
  }
3093
3009
  handleOutputDelta(params, toolName) {
3094
3010
  const itemId = readStringField(params, "itemId");
@@ -3381,22 +3297,6 @@ function codeModeCommandFailed(output) {
3381
3297
  }
3382
3298
  }
3383
3299
  //#endregion
3384
- //#region extensions/codex/src/app-server/local-runtime-attribution.ts
3385
- const OPENAI_PROVIDER_ID = "openai";
3386
- const OPENAI_RESPONSES_API = "openai-responses";
3387
- const OPENAI_CODEX_RESPONSES_API = "openai-chatgpt-responses";
3388
- function resolveCodexLocalRuntimeAttribution(params) {
3389
- const authProfileProvider = normalizeLowercaseStringOrEmpty(params.runtimePlan?.auth?.authProfileProviderForAuth);
3390
- if (normalizeLowercaseStringOrEmpty(params.runtimePlan?.observability.harnessId) === "codex" && authProfileProvider !== OPENAI_PROVIDER_ID && normalizeLowercaseStringOrEmpty(params.model.provider) === OPENAI_PROVIDER_ID && normalizeLowercaseStringOrEmpty(params.model.api) === OPENAI_RESPONSES_API) return {
3391
- provider: OPENAI_PROVIDER_ID,
3392
- api: OPENAI_CODEX_RESPONSES_API
3393
- };
3394
- return {
3395
- provider: params.provider,
3396
- api: params.model.api
3397
- };
3398
- }
3399
- //#endregion
3400
3300
  //#region extensions/codex/src/app-server/event-projector-tool-transcript.ts
3401
3301
  const MISSING_TOOL_RESULT_ERROR = "OpenClaw recorded a native Codex tool.call without a matching tool.result before the turn completed.";
3402
3302
  const NATIVE_PATCH_REJECTION_RE = /^\s*patch rejected:\s*writing outside of the project;\s*rejected by user approval settings\s*$/iu;
@@ -3698,7 +3598,7 @@ var CodexToolTranscriptProjection = class {
3698
3598
  });
3699
3599
  }
3700
3600
  emitAfterToolCallObservation(item) {
3701
- if (!this.shouldEmitAfterToolCallObservation(item)) return;
3601
+ if (!isProjectedNativeToolItem(item) || this.afterToolCallObservedItemIds.has(item.id) || this.options.nativePostToolUseRelayEnabled && isNativePostToolUseRelayItem(item)) return;
3702
3602
  const name = itemName(item);
3703
3603
  const status = itemStatus(item);
3704
3604
  if (!name || status === "running") return;
@@ -3822,10 +3722,6 @@ var CodexToolTranscriptProjection = class {
3822
3722
  ...item && isMutatingNativeToolItem(item) ? { mutatingAction: true } : {}
3823
3723
  });
3824
3724
  }
3825
- shouldEmitAfterToolCallObservation(item) {
3826
- if (!isProjectedNativeToolItem(item) || this.afterToolCallObservedItemIds.has(item.id)) return false;
3827
- return !(this.options.nativePostToolUseRelayEnabled && isNativePostToolUseRelayItem(item));
3828
- }
3829
3725
  createToolCallMessage(params) {
3830
3726
  const attribution = resolveCodexLocalRuntimeAttribution(this.params);
3831
3727
  return createAgentHarnessToolCallMessage({
@@ -4075,13 +3971,10 @@ var CodexEventProjection = class {
4075
3971
  ...reason ? { reason } : {}
4076
3972
  }
4077
3973
  });
4078
- if (reason === "highRiskCyberActivity") {
4079
- this.cyberNoticeState = "fallback";
4080
- this.emitCyberNotice("fallback", {
4081
- model: fromModel,
4082
- fallbackModel: toModel
4083
- });
4084
- }
3974
+ if (reason === "highRiskCyberActivity") this.emitCyberNotice("fallback", {
3975
+ model: fromModel,
3976
+ fallbackModel: toModel
3977
+ });
4085
3978
  }
4086
3979
  }
4087
3980
  handleSafetyBuffering(params) {
@@ -4090,7 +3983,6 @@ var CodexEventProjection = class {
4090
3983
  return;
4091
3984
  }
4092
3985
  if (this.safetyBufferingEnded || this.cyberNoticeState === "blocked" || this.cyberNoticeState === "fallback" || params.showBufferingUi !== true || !Array.isArray(params.useCases) || !params.useCases.includes("cyber")) return;
4093
- this.cyberNoticeState = "buffering";
4094
3986
  const model = readStringField(params, "model");
4095
3987
  const fallbackModel = readStringField(params, "fasterModel");
4096
3988
  this.emitCyberNotice("buffering", {
@@ -4100,7 +3992,6 @@ var CodexEventProjection = class {
4100
3992
  }
4101
3993
  handleCyberPolicyError(codexErrorInfo, model) {
4102
3994
  if (codexErrorInfo !== "cyberPolicy" || this.cyberNoticeState === "blocked") return;
4103
- this.cyberNoticeState = "blocked";
4104
3995
  this.emitCyberNotice("blocked", { model: this.responseModel ?? model });
4105
3996
  }
4106
3997
  endSafetyBuffering() {
@@ -4112,10 +4003,10 @@ var CodexEventProjection = class {
4112
4003
  }
4113
4004
  clearSafetyBuffering() {
4114
4005
  if (this.cyberNoticeState !== "buffering") return;
4115
- this.cyberNoticeState = void 0;
4116
4006
  this.emitCyberNotice("cleared");
4117
4007
  }
4118
4008
  emitCyberNotice(state, models = {}) {
4009
+ this.cyberNoticeState = state === "cleared" ? void 0 : state;
4119
4010
  if (this.provider !== "openai") return;
4120
4011
  this.emitAgentEvent({
4121
4012
  stream: "notice",
@@ -4316,16 +4207,7 @@ var CodexNativeSubagentTurnObservation = class {
4316
4207
  });
4317
4208
  }
4318
4209
  markActivityUnknown(childState) {
4319
- this.projectedActivityWaits.delete(childState);
4320
- childState.activityObserved = true;
4321
- this.callbacks.emitTaskEvent(childState, {
4322
- stream: "execution",
4323
- data: {
4324
- state: "unknown",
4325
- sourceId: this.observationSourceId,
4326
- executionId: childState.nativeTurnId
4327
- }
4328
- });
4210
+ this.observeActivity(childState, "unknown", void 0, { executionId: childState.nativeTurnId });
4329
4211
  }
4330
4212
  refreshWaitDependency(childState, receiverThreadId) {
4331
4213
  const activityWait = childState.activityWait;
@@ -4349,7 +4231,7 @@ var CodexNativeSubagentTurnObservation = class {
4349
4231
  };
4350
4232
  if (this.projectedActivityWaits.has(childState)) this.observeActivity(childState, "waiting", wait);
4351
4233
  }
4352
- observeActivity(childState, state, wait) {
4234
+ observeActivity(childState, state, wait, execution = childState.nativeTurnId ? { executionId: childState.nativeTurnId } : {}) {
4353
4235
  if (wait && wait === childState.activityWait?.wait) this.projectedActivityWaits.add(childState);
4354
4236
  else this.projectedActivityWaits.delete(childState);
4355
4237
  childState.activityObserved = true;
@@ -4358,7 +4240,7 @@ var CodexNativeSubagentTurnObservation = class {
4358
4240
  data: {
4359
4241
  state,
4360
4242
  sourceId: this.observationSourceId,
4361
- ...childState.nativeTurnId ? { executionId: childState.nativeTurnId } : {},
4243
+ ...execution,
4362
4244
  ...wait ? { wait } : {}
4363
4245
  }
4364
4246
  });
@@ -4490,23 +4372,14 @@ var Monitor = class {
4490
4372
  releaseClientRetentionIfIdle: () => this.releaseClientRetentionIfIdle(),
4491
4373
  pruneParent: (state) => this.pruneParentIfUnused(state)
4492
4374
  });
4493
- this.historyRecovery = new CodexNativeSubagentHistoryRecovery(client, {
4494
- getPendingTurnIds: (id) => this.knownChildren.get(id)?.pendingTurns.map((turn) => turn.turnId) ?? [],
4495
- getCurrentAssignmentState: (id) => {
4496
- return {
4497
- runId: this.knownChildren.get(id)?.assignment.runId,
4498
- nativeTurnState: this.currentChild(id)?.nativeTurnState
4499
- };
4500
- }
4501
- });
4375
+ this.historyRecovery = new CodexNativeSubagentHistoryRecovery(client, this.knownChildren, this.childStates);
4502
4376
  this.completionDelivery = new CodexNativeSubagentCompletionDelivery({
4503
4377
  deliver: (params) => runtime.deliverAgentHarnessCompletion(params),
4504
4378
  retryDelaysMs: options.completionDeliveryRetryDelaysMs,
4505
4379
  maxRetries: options.completionDeliveryMaxRetries,
4506
- isCurrentChild: (child) => this.childStates.get(child.runId) === child,
4507
- isCurrentParent: (state) => this.parentStates.get(state.parentThreadId) === state,
4508
- isRetiredParent: (state) => this.retiredParentStates.has(state),
4509
- getParent: (id) => this.parentStates.get(id),
4380
+ children: this.childStates,
4381
+ parents: this.parentStates,
4382
+ retiredParents: this.retiredParentStates,
4510
4383
  unregisterChild: (child) => this.unregisterChild(child),
4511
4384
  releaseClientRetentionIfIdle: () => this.releaseClientRetentionIfIdle()
4512
4385
  });
@@ -4568,7 +4441,7 @@ var Monitor = class {
4568
4441
  restoreKnownChild: (state, assignment) => this.restoreKnownChild(state, assignment),
4569
4442
  prepareReceiver: (state, threadId) => this.prepareReceiverChild(state, threadId),
4570
4443
  registerChild: (state, assignment, childOptions) => this.registerChildThread(state, assignment, childOptions),
4571
- admitFollowup: (known, id) => this.admitFollowupChild(known, id),
4444
+ admitFollowup: (known) => this.admitFollowupChild(known),
4572
4445
  resumeChild: (child) => this.resumeChild(child),
4573
4446
  completeChild: (notification, child) => this.handleChildTurnCompletion(notification, child),
4574
4447
  retain: (state, threadId) => {
@@ -4577,11 +4450,8 @@ var Monitor = class {
4577
4450
  this.retainParentThread?.(state.parentThreadId),
4578
4451
  this.retainParentThread?.(threadId)
4579
4452
  ];
4580
- let retained = true;
4581
4453
  return () => {
4582
- if (!retained) return;
4583
- retained = false;
4584
- for (const release of releases) release?.();
4454
+ for (const release of releases.splice(0)) release?.();
4585
4455
  };
4586
4456
  },
4587
4457
  hasObservationBacking: options.hasObservationBacking,
@@ -4654,10 +4524,10 @@ var Monitor = class {
4654
4524
  currentChild: this.currentChild.bind(this),
4655
4525
  resolveParentOwner: this.resolveParentOwner.bind(this),
4656
4526
  registerChildThread: this.registerChildThread.bind(this),
4657
- registerDirectSpawnChild: this.registerDirectSpawnChild.bind(this),
4527
+ registerDirectSpawnChild: (state, turnId, evidence, owner) => this.admissionCustody.registerDirectSpawnChild(turnId, evidence, owner, (registration) => this.registerChildThread(state, evidence.childThreadId, registration)),
4658
4528
  observeParentInteraction: this.observeParentInteraction.bind(this),
4659
- acceptInteraction: this.submissions.acceptInteraction.bind(this.submissions),
4660
- observeCall: this.submissions.observeCall.bind(this.submissions)
4529
+ acceptInteraction: this.submissions.modelInputs.acceptInteraction,
4530
+ observeCall: this.submissions.modelInputs.observeCall
4661
4531
  });
4662
4532
  this.removeCloseHandler = client.addCloseHandler(() => {
4663
4533
  this.dispose().catch((error) => {
@@ -4713,10 +4583,10 @@ var Monitor = class {
4713
4583
  state.turnIds.clear();
4714
4584
  notifyNativeModelSourceWaiters(state);
4715
4585
  this.childCloses.clear(state);
4716
- this.completionDelivery.deliverDetached(state, this.childStates.values());
4586
+ this.completionDelivery.deliverDetached(state);
4717
4587
  }
4718
4588
  this.admissionCustody.retainOnly(() => false);
4719
- for (const [parentThreadId] of this.parentStates) if (![...this.childStates.values()].some((childState) => childState.parentThreadId === parentThreadId)) this.parentStates.delete(parentThreadId);
4589
+ for (const [parentThreadId] of this.parentStates) if (!this.hasChildrenForParent(parentThreadId)) this.parentStates.delete(parentThreadId);
4720
4590
  for (const known of this.knownChildren.values()) known.pendingTurns.forEach(releaseCompletionCustody);
4721
4591
  this.knownChildren.clear();
4722
4592
  this.childThreadIdsByAgentPath.clear();
@@ -4730,7 +4600,7 @@ var Monitor = class {
4730
4600
  submissions: this.submissions,
4731
4601
  assignments: this.assignments,
4732
4602
  closes: this.childCloses,
4733
- deliverDetached: (state) => this.completionDelivery.deliverDetached(state, this.childStates.values()),
4603
+ deliverDetached: (state) => this.completionDelivery.deliverDetached(state),
4734
4604
  drainAdmissions: (state, owner, turnId) => this.drainPendingChildAdmissionEvidence(state, owner, turnId, true),
4735
4605
  clearAdmissions: () => this.clearUnconsumablePendingChildAdmissionEvidence(),
4736
4606
  prune: (state) => this.pruneParentIfUnused(state),
@@ -4743,10 +4613,10 @@ var Monitor = class {
4743
4613
  children: this.childStates,
4744
4614
  knownChildren: this.knownChildren,
4745
4615
  admissions: this.admissionCustody.entries,
4746
- assertInputCurrent: (threadId, owner) => this.submissions.assertModelInputCurrent(threadId, owner),
4747
- hasPendingInput: (input) => this.submissions.hasPendingModelInput(input),
4748
- onExecutionAdmitted: (known, threadId) => {
4749
- this.admitFollowupChild(known, threadId);
4616
+ assertInputCurrent: (threadId, owner) => this.submissions.modelInputs.assertModelInputCurrent(threadId, owner),
4617
+ hasPendingInput: (input) => this.submissions.modelInputs.hasPendingModelInput(input),
4618
+ onExecutionAdmitted: (known) => {
4619
+ this.admitFollowupChild(known);
4750
4620
  },
4751
4621
  registerChildExecution: (state, modelRequest, agentPath, completionCustody) => {
4752
4622
  this.registerChildThread(state, {
@@ -4788,7 +4658,7 @@ var Monitor = class {
4788
4658
  const assertCurrent = () => {
4789
4659
  request.signal?.throwIfAborted();
4790
4660
  capture.assertCurrent();
4791
- if (this.disposed || this.retiredParentStates.has(state) || this.parentStates.get(state.parentThreadId) !== state || this.knownChildren.get(request.threadId) !== known || (current ? this.currentChild(request.threadId) !== current || current.terminal || current.settledWithoutCompletion || current.nativeTurnId !== request.turnId : !pending || !known.pendingTurns.includes(pending) || !pending.modelSource)) throw new Error("Native model execution assignment changed before admission.");
4661
+ if (!this.isCurrentParent(state) || this.knownChildren.get(request.threadId) !== known || (current ? this.currentChild(request.threadId) !== current || current.terminal || current.settledWithoutCompletion || current.nativeTurnId !== request.turnId : !pending || !known.pendingTurns.includes(pending) || !pending.modelSource)) throw new Error("Native model execution assignment changed before admission.");
4792
4662
  };
4793
4663
  assertCurrent();
4794
4664
  await this.assignments.recordExecution(state, {
@@ -4814,13 +4684,14 @@ var Monitor = class {
4814
4684
  retainTargetRevision: (threadId) => this.recovery.retainThreadStatusRevision(threadId),
4815
4685
  currentModelExecution: (threadId) => currentNativeModelExecution(threadId, this.parentStates, this.knownChildren, this.childStates),
4816
4686
  admissions: this.admissionCustody.entries,
4687
+ canPrepareReceiver: (state, threadId) => this.canPrepareReceiverChild(state, threadId),
4817
4688
  prepareReceiver: (state, threadId, nativeParentThreadId) => this.prepareReceiverChild(state, threadId, nativeParentThreadId),
4818
4689
  registerChildThread: (state, threadId, options) => this.registerChildThread(state, threadId, options),
4819
- admit: (state, owner, input, count, preparedOwner) => this.submissions.admitModelInput(state, owner, input, count, preparedOwner)
4690
+ admit: (state, owner, input, count, preparedOwner) => this.submissions.modelInputs.admitModelInput(state, owner, input, count, preparedOwner)
4820
4691
  });
4821
4692
  }
4822
4693
  releasePendingModelInputs(threadId) {
4823
- this.submissions.retireReceiverModelInputs(threadId);
4694
+ this.submissions.modelInputs.retireReceiverModelInputs(threadId);
4824
4695
  releasePendingNativeModelInputs(threadId, this.admissionCustody.entries);
4825
4696
  this.clearUnconsumablePendingChildAdmissionEvidence();
4826
4697
  notifyNativeModelSourceChange("thread/closed", this.parentStates.values());
@@ -4907,7 +4778,7 @@ var Monitor = class {
4907
4778
  state: parent,
4908
4779
  notification,
4909
4780
  knownChildren: this.knownChildren.values(),
4910
- applyReceipts: (runIds) => this.applyNativeReceipts(parent, runIds)
4781
+ applyReceipts: (runIds) => this.completionDelivery.applyReceipts(parent, runIds)
4911
4782
  });
4912
4783
  if (childState && !childState.terminal && (!pendingTurns?.length || notification.method === "turn/completed")) this.turnObservation.emitChildTaskActivity(notification, childState);
4913
4784
  if (!pendingNativeTurn) await this.handleChildTurnCompletion(notification, childState);
@@ -5082,7 +4953,6 @@ var Monitor = class {
5082
4953
  const observedTurn = Boolean(child.nativeTurnId && child.nativeTurnId !== turnId);
5083
4954
  if (child.nativeTurnId !== turnId) {
5084
4955
  child.nativeTurnId = turnId;
5085
- child.nativeTurnState = void 0;
5086
4956
  child.activityWait = void 0;
5087
4957
  }
5088
4958
  child.nativeTurnState = recovery.nativeTurnState;
@@ -5096,9 +4966,9 @@ var Monitor = class {
5096
4966
  known.assignment.nativeTurnId = child.nativeTurnId;
5097
4967
  known.assignment.unanchored = void 0;
5098
4968
  if (!known.observedTurns.has(child.nativeTurnId)) known.observedTurns.set(child.nativeTurnId, observedTurn ? { awaitingInteraction: true } : {});
5099
- if (observedTurn && known.pendingTurns.length === 0) this.associatePendingChildInteraction(known, child.childThreadId, child.nativeTurnId);
4969
+ if (observedTurn && known.pendingTurns.length === 0) this.associatePendingChildInteraction(known, child.nativeTurnId);
5100
4970
  this.submissions.observeKnownChild(child.childThreadId);
5101
- return this.admitFollowupChild(known, child.childThreadId);
4971
+ return this.admitFollowupChild(known);
5102
4972
  }
5103
4973
  async processCompletion(state, childState, completion, eventAt = Date.now()) {
5104
4974
  if (childState.terminal) return;
@@ -5123,28 +4993,26 @@ var Monitor = class {
5123
4993
  this.recovery.markTerminalRevision(childState.childThreadId);
5124
4994
  releaseNativeDirectChild(childState);
5125
4995
  this.recovery.clearRecoveryTimers(childState);
5126
- this.applyNativeReceipts(state, childState.deliveryReceipts.record(childState.runId, this.knownChildren.get(childState.childThreadId)?.agentPaths ?? [childState.childThreadId], acceptedCompletion.result));
4996
+ this.completionDelivery.applyReceipts(state, childState.deliveryReceipts.record(childState.runId, this.knownChildren.get(childState.childThreadId)?.agentPaths ?? [childState.childThreadId], acceptedCompletion.result));
5127
4997
  await this.completionDelivery.deliverPending(state, childState);
5128
4998
  }
5129
- applyNativeReceipts(state, runIds) {
5130
- this.completionDelivery.applyReceipts(state, runIds, this.childStates);
5131
- }
5132
4999
  resolveChildReceiptOwner(state, childThreadId) {
5133
5000
  const known = this.knownChildren.get(childThreadId);
5134
5001
  return known?.parent === state ? known.deliveryReceipts : state.deliveryReceipts;
5135
5002
  }
5003
+ canPrepareReceiverChild(state, threadId) {
5004
+ const child = this.knownChildren.get(threadId);
5005
+ return canPrepareNativeReceiver(state, child?.parent ?? this.parentStates.get(threadId), child, threadId, {
5006
+ isCurrent: (parent) => this.isCurrentParent(parent),
5007
+ isRetired: (parent) => this.retiredParentStates.has(parent),
5008
+ hasChildCustody: (parent, id) => this.submissions.hasChildCustody(parent, id)
5009
+ });
5010
+ }
5136
5011
  prepareReceiverChild(state, threadId, nativeParentThreadId) {
5012
+ if (!this.canPrepareReceiverChild(state, threadId)) return false;
5137
5013
  const known = this.knownChildren.get(threadId);
5138
- if (known?.parent === state) return true;
5139
- if (!this.isCurrentParent(state) || known && (!known.assignment.terminal || known.pendingTurns.length > 0 || this.submissions.hasChildCustody(known.parent, threadId))) return false;
5140
- if (!known) return true;
5141
- const previous = known.parent;
5142
- if (nativeParentThreadId !== known.nativeParentThreadId || this.retiredParentStates.has(previous) || !state.requesterSessionKey || previous.requesterSessionKey !== state.requesterSessionKey || !previous.historyOwner || !state.historyOwner || !matchesNativeAssignmentLifecycle(previous.historyOwner, state.historyOwner) || ![...state.owners.values()].some((owner) => owner.completionCustody?.isCurrent())) return false;
5143
- try {
5144
- state.assignmentStore?.assertCurrent();
5145
- } catch {
5146
- return false;
5147
- }
5014
+ if (!known || known.parent === state) return true;
5015
+ if (nativeParentThreadId !== known.nativeParentThreadId) return false;
5148
5016
  known.parent = state;
5149
5017
  for (const agentPath of known.agentPaths) this.registerAgentPath(state, threadId, agentPath);
5150
5018
  return true;
@@ -5222,7 +5090,7 @@ var Monitor = class {
5222
5090
  const agentPath = normalizeOptionalString(options.agentPath);
5223
5091
  if (agentPath) this.registerAgentPath(state, childThreadId, agentPath);
5224
5092
  for (const path of this.knownChildren.get(childThreadId)?.agentPaths ?? []) this.registerAgentPath(state, childThreadId, path);
5225
- this.applyNativeReceipts(state, childState.deliveryReceipts.track(runId, this.knownChildren.get(childThreadId)?.agentPaths ?? [childThreadId]));
5093
+ this.completionDelivery.applyReceipts(state, childState.deliveryReceipts.track(runId, this.knownChildren.get(childThreadId)?.agentPaths ?? [childThreadId]));
5226
5094
  const restored = this.knownChildren.get(childThreadId);
5227
5095
  if (restored && !known && options.nativeParentThreadId) restored.nativeParentThreadId = options.nativeParentThreadId;
5228
5096
  if (observedTurns.length > 0 && restored?.parent === state) {
@@ -5280,7 +5148,7 @@ var Monitor = class {
5280
5148
  releaseNativeDirectChild(previous);
5281
5149
  this.turnObservation.markActivityUnknown(previous);
5282
5150
  }
5283
- this.applyNativeReceipts(known.parent, known.deliveryReceipts.track(codexNativeSubagentRunId(threadId, turnId), known.agentPaths));
5151
+ this.completionDelivery.applyReceipts(known.parent, known.deliveryReceipts.track(codexNativeSubagentRunId(threadId, turnId), known.agentPaths));
5284
5152
  }
5285
5153
  known.turnId = turnId;
5286
5154
  if (previous && !previous.terminal && known.pendingTurns.length === 0) {
@@ -5291,8 +5159,8 @@ var Monitor = class {
5291
5159
  this.assignments.record(known.parent, previous);
5292
5160
  if (previous.modelExecution && !previous.modelExecution.executionOwner.turnId) previous.modelExecution.bindTurn(turnId);
5293
5161
  }
5294
- if (observedTurn) this.associatePendingChildInteraction(known, threadId, turnId);
5295
- this.admitFollowupChild(known, threadId);
5162
+ if (observedTurn) this.associatePendingChildInteraction(known, turnId);
5163
+ this.admitFollowupChild(known);
5296
5164
  const startedChild = this.currentChild(threadId);
5297
5165
  if (startedChild && !known.pendingTurns.some((candidate) => candidate.turnId === turnId)) {
5298
5166
  startedChild.nativeCompletionDelivered = false;
@@ -5300,8 +5168,8 @@ var Monitor = class {
5300
5168
  }
5301
5169
  return true;
5302
5170
  }
5303
- associatePendingChildInteraction(known, threadId, nativeTurnId) {
5304
- associateNativeChildInteraction(known, threadId, nativeTurnId, this.admissionCustody.entries, (owner, turnId) => this.drainPendingChildAdmissionEvidence(known.parent, owner, turnId));
5171
+ associatePendingChildInteraction(known, nativeTurnId) {
5172
+ associateNativeChildInteraction(known, nativeTurnId, this.admissionCustody.entries, (owner, turnId) => this.drainPendingChildAdmissionEvidence(known.parent, owner, turnId));
5305
5173
  }
5306
5174
  observeParentInteraction(state, owner, threadId, agentPath, interaction = {}) {
5307
5175
  this.prepareReceiverChild(state, threadId);
@@ -5325,7 +5193,8 @@ var Monitor = class {
5325
5193
  if (!known && unqualified) admissionOwner.onDirectChildAccepted?.();
5326
5194
  if (admissionOwner && parentTurnId) this.drainPendingChildAdmissionEvidence(state, admissionOwner, parentTurnId, true);
5327
5195
  }
5328
- admitFollowupChild(known, threadId, owner) {
5196
+ admitFollowupChild(known, owner) {
5197
+ const threadId = known.assignment.childThreadId;
5329
5198
  if (this.parentStates.get(known.parent.parentThreadId) !== known.parent || this.retiredParentStates.has(known.parent)) return;
5330
5199
  let child = this.currentChild(threadId);
5331
5200
  if (!child && !known.assignment.terminal) return;
@@ -5355,7 +5224,7 @@ var Monitor = class {
5355
5224
  }
5356
5225
  for (const continuation of continuations) continuation.modelSource?.release();
5357
5226
  transitioned = true;
5358
- this.applyNativeReceipts(known.parent, known.deliveryReceipts.resumeAssignment(child.runId, continuations.map((turn) => codexNativeSubagentRunId(threadId, turn.turnId))));
5227
+ this.completionDelivery.applyReceipts(known.parent, known.deliveryReceipts.resumeAssignment(child.runId, continuations.map((turn) => codexNativeSubagentRunId(threadId, turn.turnId))));
5359
5228
  continue;
5360
5229
  }
5361
5230
  if (child && !child.terminal && !known.assignment.terminal && child.nativeTurnState !== "completed" && child.nativeTurnState !== "failed") {
@@ -5410,9 +5279,6 @@ var Monitor = class {
5410
5279
  resolveNativeParentState(threadId) {
5411
5280
  return this.parentStates.get(threadId) ?? this.knownChildren.get(threadId)?.parent;
5412
5281
  }
5413
- registerDirectSpawnChild(state, turnIdInput, evidence, owner) {
5414
- return this.admissionCustody.registerDirectSpawnChild(turnIdInput, evidence, owner, (options) => this.registerChildThread(state, evidence.childThreadId, options));
5415
- }
5416
5282
  drainPendingChildAdmissionEvidence(state, owner, turnId, observeActivity = false) {
5417
5283
  drainNativeChildModelAdmissions(state, owner, turnId, observeActivity, {
5418
5284
  admissions: this.admissionCustody.entries,
@@ -5422,7 +5288,7 @@ var Monitor = class {
5422
5288
  currentChild: (threadId) => this.currentChild(threadId),
5423
5289
  registerAgentPath: (parent, threadId, path) => this.registerAgentPath(parent, threadId, path),
5424
5290
  registerChildThread: (parent, threadId, options) => this.registerChildThread(parent, threadId, options),
5425
- admitFollowupChild: (known, threadId, admittedOwner) => this.admitFollowupChild(known, threadId, admittedOwner),
5291
+ admitFollowupChild: (known, admittedOwner) => this.admitFollowupChild(known, admittedOwner),
5426
5292
  observeActivity: (child) => this.turnObservation.emitChildTaskActivity({
5427
5293
  method: "turn/started",
5428
5294
  params: {
@@ -5439,7 +5305,7 @@ var Monitor = class {
5439
5305
  this.admissionCustody.retainOnly((evidence) => evidence.childThreadId !== childThreadId || evidence.kind === "interaction");
5440
5306
  }
5441
5307
  registerAgentPath(state, childThreadId, agentPath) {
5442
- this.applyNativeReceipts(state, registerCodexNativeSubagentReceiptAlias({
5308
+ this.completionDelivery.applyReceipts(state, registerCodexNativeSubagentReceiptAlias({
5443
5309
  state,
5444
5310
  childThreadId,
5445
5311
  agentPath,
@@ -5455,7 +5321,7 @@ var Monitor = class {
5455
5321
  this.recovery.clearRecoveryTimers(childState);
5456
5322
  this.completionDelivery.release(childState);
5457
5323
  if (this.childStates.get(childState.runId) === childState) this.childStates.delete(childState.runId);
5458
- if (![...this.childStates.values()].some((remainingChild) => remainingChild.parentThreadId === childState.parentThreadId)) {
5324
+ if (!this.hasChildrenForParent(childState.parentThreadId)) {
5459
5325
  const releaseParentThread = this.parentThreadRetentions.get(childState.parentThreadId);
5460
5326
  this.parentThreadRetentions.delete(childState.parentThreadId);
5461
5327
  releaseParentThread?.();
@@ -5497,14 +5363,14 @@ var Monitor = class {
5497
5363
  return [...this.parentStates.values()].filter((state) => state === source || Boolean(source.requesterSessionKey && state.requesterSessionKey === source.requesterSessionKey && state.agentId === source.agentId && source.historyOwner && state.historyOwner && matchesNativeAssignmentLifecycle(source.historyOwner, state.historyOwner)));
5498
5364
  }
5499
5365
  hasParentWork(state) {
5500
- if (state.modelSourceReferences || state.pendingRegistrations && !this.disposed && !this.retiredParentStates.has(state)) return true;
5501
- if (this.assignments.hasWrites(state) || this.submissions.hasCustody(state)) return true;
5502
- if (state.owners.size > 0) return true;
5503
- if (this.childCloses.hasPending(state)) return true;
5504
- for (const childState of this.childStates.values()) if (childState.parentThreadId === state.parentThreadId) return true;
5366
+ if (state.modelSourceReferences || state.pendingRegistrations && !this.disposed && !this.retiredParentStates.has(state) || this.assignments.hasWrites(state) || this.submissions.hasCustody(state) || state.owners.size > 0 || this.childCloses.hasPending(state) || this.hasChildrenForParent(state.parentThreadId)) return true;
5505
5367
  for (const known of this.knownChildren.values()) if (known.parent === state && this.currentChild(known.assignment.childThreadId)) return true;
5506
5368
  return false;
5507
5369
  }
5370
+ hasChildrenForParent(parentThreadId) {
5371
+ for (const childState of this.childStates.values()) if (childState.parentThreadId === parentThreadId) return true;
5372
+ return false;
5373
+ }
5508
5374
  pruneParentIfUnused(source) {
5509
5375
  if (this.parentStates.get(source.parentThreadId) !== source) return;
5510
5376
  const states = this.requesterParents(source);
@@ -5559,4 +5425,4 @@ var Monitor = class {
5559
5425
  };
5560
5426
  const codexNativeSubagentMonitorRuntime = createCodexNativeSubagentMonitorRuntime(Monitor);
5561
5427
  //#endregion
5562
- export { CodexToolTranscriptProjection as a, shouldEmitTranscriptToolProgress as c, resolveCodexToolProgressDetailMode as d, sanitizeCodexAgentEventRecord as f, emitCodexAgentEvent as i, projectCodexWebSearchItem as l, native_subagent_monitor_exports as n, resolveCodexLocalRuntimeAttribution as o, sanitizeCodexToolArguments as p, CodexEventProjection as r, CodexToolProgressProjection as s, codexNativeSubagentMonitorRuntime as t, isCodexCommandBearingToolCall as u };
5428
+ export { CodexToolTranscriptProjection as a, isCodexCommandBearingToolCall as c, sanitizeCodexToolArguments as d, emitCodexAgentEvent as i, resolveCodexToolProgressDetailMode as l, native_subagent_monitor_exports as n, CodexToolProgressProjection as o, CodexEventProjection as r, shouldEmitTranscriptToolProgress as s, codexNativeSubagentMonitorRuntime as t, sanitizeCodexAgentEventRecord as u };