chainlesschain 0.162.188 → 0.162.193

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 (337) hide show
  1. package/README.md +61 -11
  2. package/bin/chainlesschain.js +7 -52
  3. package/completions/_cc +209 -0
  4. package/completions/cc.bash +18 -0
  5. package/completions/cc.fish +13 -0
  6. package/completions/cc.ps1 +226 -0
  7. package/package.json +10 -2
  8. package/src/assets/web-panel/assets/{AIOps-Brr1LVcE.js → AIOps-DBLkaTje.js} +1 -1
  9. package/src/assets/web-panel/assets/{ActionButton-DQU74DKG.js → ActionButton-BAy-Qebo.js} +1 -1
  10. package/src/assets/web-panel/assets/{Analytics-CYp9178y.js → Analytics-Dfb1Mlau.js} +3 -3
  11. package/src/assets/web-panel/assets/{AppLayout-DW4SCYsW.js → AppLayout-BbFkN8m0.js} +5 -5
  12. package/src/assets/web-panel/assets/{Artifacts-CYlD_ed1.js → Artifacts-kM4-cEEH.js} +1 -1
  13. package/src/assets/web-panel/assets/{Audit-CWl1rZOi.js → Audit-BSQfYWf3.js} +1 -1
  14. package/src/assets/web-panel/assets/{BackgroundAgents-BOR-LPsa.js → BackgroundAgents-CWDbI_fG.js} +1 -1
  15. package/src/assets/web-panel/assets/{Backup-DLpG7j1X.js → Backup-BxLPbq_Q.js} +1 -1
  16. package/src/assets/web-panel/assets/{BaseInput-B35K9wdr.js → BaseInput-DuIbdrp6.js} +1 -1
  17. package/src/assets/web-panel/assets/{Chat-CwUJb9gB.js → Chat-NEmjGahU.js} +5 -5
  18. package/src/assets/web-panel/assets/{ChatBubbleRenderer-1v6aMS1m.js → ChatBubbleRenderer-DfJEo-5_.js} +1 -1
  19. package/src/assets/web-panel/assets/{Checkbox-pi3-tPNW.js → Checkbox-CaoeG3Ns.js} +1 -1
  20. package/src/assets/web-panel/assets/{Codegen-FyNF35eL.js → Codegen-BFf_g3xY.js} +1 -1
  21. package/src/assets/web-panel/assets/{Col-tGt_JDEr.js → Col-CNOd8mdQ.js} +1 -1
  22. package/src/assets/web-panel/assets/{Community-CC7LonQX.js → Community-BhpDqz-i.js} +1 -1
  23. package/src/assets/web-panel/assets/{Compact-BGXrHHjE.js → Compact-CQ42T7Z6.js} +1 -1
  24. package/src/assets/web-panel/assets/{Compliance-DSW0TBZ8.js → Compliance-DI5PcLMN.js} +1 -1
  25. package/src/assets/web-panel/assets/{Cowork-Bhk7rbvE.js → Cowork-wYYZe0wR.js} +3 -3
  26. package/src/assets/web-panel/assets/{Cron-DxyiQ2NZ.js → Cron-Dlq03DD_.js} +2 -2
  27. package/src/assets/web-panel/assets/{Crosschain-B2ZkxHok.js → Crosschain-BzqS8PP3.js} +1 -1
  28. package/src/assets/web-panel/assets/{DID-yOJV99eJ.js → DID-It55Yem7.js} +2 -2
  29. package/src/assets/web-panel/assets/{Dashboard-CKsttz7D.js → Dashboard-9HkH6oxn.js} +2 -2
  30. package/src/assets/web-panel/assets/{Dropdown-CVFldXSL.js → Dropdown-00e2YWRB.js} +1 -1
  31. package/src/assets/web-panel/assets/{EmailListRenderer-Bufv638J.js → EmailListRenderer-By-ugRDL.js} +1 -1
  32. package/src/assets/web-panel/assets/{FamilyGuardDashboard-4ncjoIjL.js → FamilyGuardDashboard-C396yu5m.js} +1 -1
  33. package/src/assets/web-panel/assets/{Federation-DsknEDoX.js → Federation-BME5sbZY.js} +1 -1
  34. package/src/assets/web-panel/assets/{FormItemContext-Cqe5jWXA.js → FormItemContext-B4TEZCr-.js} +1 -1
  35. package/src/assets/web-panel/assets/{GenericCardRenderer-NAJaFKxc.js → GenericCardRenderer-_9CX9ieY.js} +1 -1
  36. package/src/assets/web-panel/assets/{Git-CszKQpnl.js → Git-BrS6WVSr.js} +2 -2
  37. package/src/assets/web-panel/assets/{Governance-BXGodXi6.js → Governance-BMdCWnKF.js} +1 -1
  38. package/src/assets/web-panel/assets/{Inference-CkoYuG2c.js → Inference-Bcp3vzcA.js} +1 -1
  39. package/src/assets/web-panel/assets/{KnowledgeGraph-DFlEr_T0.js → KnowledgeGraph-DlLuqGY5.js} +1 -1
  40. package/src/assets/web-panel/assets/{Logs-CVaENddA.js → Logs-D-W_6x09.js} +2 -2
  41. package/src/assets/web-panel/assets/MarkdownRenderer-DElGPxCZ.js +1 -0
  42. package/src/assets/web-panel/assets/{Marketplace-CDlLT0fw.js → Marketplace-Dzn2guvI.js} +1 -1
  43. package/src/assets/web-panel/assets/{McpTools-DdwOyszN.js → McpTools-uPict-KL.js} +6 -6
  44. package/src/assets/web-panel/assets/{Memory-DKQnkKuG.js → Memory-BCw43kOb.js} +2 -2
  45. package/src/assets/web-panel/assets/{MobileBridge-DGseqlzJ.js → MobileBridge-DmV8Wv7F.js} +1 -1
  46. package/src/assets/web-panel/assets/{MobileProjects-COBbEOlj.js → MobileProjects-C-HaCmSM.js} +1 -1
  47. package/src/assets/web-panel/assets/{Mtc-O61Vwyli.js → Mtc-C6jxJ34Y.js} +5 -5
  48. package/src/assets/web-panel/assets/{MtcAudit-Dw2SyasS.js → MtcAudit-Za8ExwhQ.js} +5 -5
  49. package/src/assets/web-panel/assets/{Multisig-hSu_l8kf.js → Multisig-KKDbuEgb.js} +3 -3
  50. package/src/assets/web-panel/assets/{NLProgramming-CX1Epurr.js → NLProgramming-Dj97zbCk.js} +1 -1
  51. package/src/assets/web-panel/assets/{Notes-R9xX8o8_.js → Notes-DBXvMraU.js} +4 -4
  52. package/src/assets/web-panel/assets/{NotificationSettings-jtSNLCuK.js → NotificationSettings-DOxITLYl.js} +1 -1
  53. package/src/assets/web-panel/assets/OrderTableRenderer-7DVjZwMM.js +1 -0
  54. package/src/assets/web-panel/assets/{Organization-Pu2WO-U3.js → Organization-D1i73mjb.js} +4 -4
  55. package/src/assets/web-panel/assets/{Overflow-BjnqUyFp.js → Overflow-kW6Q3rvg.js} +1 -1
  56. package/src/assets/web-panel/assets/{P2P-jjkvz44c.js → P2P-C-v_8p2v.js} +2 -2
  57. package/src/assets/web-panel/assets/PdhVaultBrowser-tUbbY64W.js +7 -0
  58. package/src/assets/web-panel/assets/{Permissions-D4yDpivd.js → Permissions-DkHxEZ58.js} +4 -4
  59. package/src/assets/web-panel/assets/{PersonalDataHub-0qsL6iH1.js → PersonalDataHub-DWuMPGrK.js} +5 -5
  60. package/src/assets/web-panel/assets/{Pipeline-Cx7Ybrk2.js → Pipeline-30IYXWWm.js} +1 -1
  61. package/src/assets/web-panel/assets/{Privacy-PbfR_M_V.js → Privacy-DZNQ4RrH.js} +1 -1
  62. package/src/assets/web-panel/assets/{ProjectInit-CyV6Gsub.js → ProjectInit-De2MCElf.js} +2 -2
  63. package/src/assets/web-panel/assets/{ProjectSettings-C7KZ2Wdk.js → ProjectSettings-5uHk9wsC.js} +2 -2
  64. package/src/assets/web-panel/assets/{Projects-DQDjO-yK.js → Projects-XjDfrFLb.js} +1 -1
  65. package/src/assets/web-panel/assets/{Providers-DyFVBBMX.js → Providers-Bgwj6gcE.js} +1 -1
  66. package/src/assets/web-panel/assets/{QrScannerModal-CzB1BC9_.js → QrScannerModal-gKql9umv.js} +1 -1
  67. package/src/assets/web-panel/assets/{QuickAsk-Bk636mC1.js → QuickAsk-BWvmwkh7.js} +1 -1
  68. package/src/assets/web-panel/assets/{Recommend-DoWxHIT3.js → Recommend-Uok4hZPd.js} +1 -1
  69. package/src/assets/web-panel/assets/{RemoteSession-oOVIv9wq.js → RemoteSession-DLJzTk9a.js} +3 -3
  70. package/src/assets/web-panel/assets/{Reputation-BucoReGG.js → Reputation-ZVwIPMSO.js} +1 -1
  71. package/src/assets/web-panel/assets/{Row-DzmOdJU7.js → Row-CN04HxWR.js} +1 -1
  72. package/src/assets/web-panel/assets/{RssFeed-C1tK7KGU.js → RssFeed-BdSrEG4g.js} +3 -3
  73. package/src/assets/web-panel/assets/{Search-CSnInOqk.js → Search-5PwVd0IR.js} +1 -1
  74. package/src/assets/web-panel/assets/{Security-dlejr15l.js → Security-DdBo4zjN.js} +3 -3
  75. package/src/assets/web-panel/assets/{Services-BioPZuNh.js → Services-D3letU7M.js} +2 -2
  76. package/src/assets/web-panel/assets/{Skeleton-DWMibwpC.js → Skeleton--Jb83f1v.js} +1 -1
  77. package/src/assets/web-panel/assets/{Skills-BAAnx1B2.js → Skills-Bg-CulHX.js} +1 -1
  78. package/src/assets/web-panel/assets/{Sla-jWNp4hNO.js → Sla-7QOa7S-X.js} +1 -1
  79. package/src/assets/web-panel/assets/{SpeechSettings-y5kqKha-.js → SpeechSettings-DQwppjRw.js} +1 -1
  80. package/src/assets/web-panel/assets/{SyncSettings-B9GNsc3e.js → SyncSettings-dNPQGL-s.js} +2 -2
  81. package/src/assets/web-panel/assets/{Tasks-BDBYKRen.js → Tasks-Ggs-Z48q.js} +1 -1
  82. package/src/assets/web-panel/assets/{Templates-DRiE5eaN.js → Templates-78TYHgRO.js} +1 -1
  83. package/src/assets/web-panel/assets/{Tenant-BGlAvExF.js → Tenant-xHwwv9vO.js} +1 -1
  84. package/src/assets/web-panel/assets/{Terminal-B8uzrbNY.js → Terminal-BJXSJfm4.js} +2 -2
  85. package/src/assets/web-panel/assets/{TimelineRenderer-Df48iveY.js → TimelineRenderer-fLbjRhJw.js} +1 -1
  86. package/src/assets/web-panel/assets/{Tokens-CcmHndN6.js → Tokens-oMSBSBmB.js} +1 -1
  87. package/src/assets/web-panel/assets/{Trigger-DPkWxmQ2.js → Trigger-CfnY_wX_.js} +1 -1
  88. package/src/assets/web-panel/assets/{Trust-DTb5a5AV.js → Trust-AdyTgYKO.js} +1 -1
  89. package/src/assets/web-panel/assets/{UkeySign-CBmg5vch.js → UkeySign-C5K_81dS.js} +1 -1
  90. package/src/assets/web-panel/assets/{VideoEditing-B0mZrz4O.js → VideoEditing-vcGVDqki.js} +1 -1
  91. package/src/assets/web-panel/assets/{Wallet-Bxs7_mpd.js → Wallet-hhOc3hlY.js} +4 -4
  92. package/src/assets/web-panel/assets/{WebAuthn-C8x3cMxU.js → WebAuthn-CVloC11s.js} +3 -3
  93. package/src/assets/web-panel/assets/{WorkflowEditor-DPrNznrP.js → WorkflowEditor-CYeE32R5.js} +1 -1
  94. package/src/assets/web-panel/assets/{chat-D3bYWu7S.js → chat-CNROR5bN.js} +1 -1
  95. package/src/assets/web-panel/assets/{colors-DY-PwMu4.js → colors-Cjx-cnwU.js} +1 -1
  96. package/src/assets/web-panel/assets/{compact-item-LDk10Kw6.js → compact-item-DOIfelvD.js} +1 -1
  97. package/src/assets/web-panel/assets/{createContext-C-2MZnFq.js → createContext-DfA7UZ8u.js} +1 -1
  98. package/src/assets/web-panel/assets/devWarning-ChcCBGs7.js +1 -0
  99. package/src/assets/web-panel/assets/{hasIn-BQIBjcnB.js → hasIn-BMSCzcfM.js} +1 -1
  100. package/src/assets/web-panel/assets/{index-CQVb2dWp.js → index-5-HXgOX5.js} +1 -1
  101. package/src/assets/web-panel/assets/{index-BdXnYMCZ.js → index-AWg-0M1S.js} +1 -1
  102. package/src/assets/web-panel/assets/{index-Cx6D_dx2.js → index-B4iYzpkL.js} +1 -1
  103. package/src/assets/web-panel/assets/{index-_HRO_cIu.js → index-B5Udeb_6.js} +1 -1
  104. package/src/assets/web-panel/assets/{index-DlRYqt3S.js → index-B7gf77CJ.js} +1 -1
  105. package/src/assets/web-panel/assets/{index-BrnRO9yE.js → index-BEMwBBHk.js} +1 -1
  106. package/src/assets/web-panel/assets/{index-VCh5zNJo.js → index-BM1y_9hM.js} +1 -1
  107. package/src/assets/web-panel/assets/{index-BRI3ngNg.js → index-BUonmKSE.js} +1 -1
  108. package/src/assets/web-panel/assets/{index-C3GNvExG.js → index-BbQ2eQ8H.js} +1 -1
  109. package/src/assets/web-panel/assets/{index-DSvo_bp0.js → index-BemJ2u_E.js} +1 -1
  110. package/src/assets/web-panel/assets/{index-L6qixyLc.js → index-BolaOQxx.js} +1 -1
  111. package/src/assets/web-panel/assets/{index-BI4KgcYC.js → index-BxOk9vkG.js} +1 -1
  112. package/src/assets/web-panel/assets/{index-CY4KnaO9.js → index-By61ojUx.js} +1 -1
  113. package/src/assets/web-panel/assets/{index-L3smcoQX.js → index-C2K9SNVX.js} +1 -1
  114. package/src/assets/web-panel/assets/{index-BX2b9Orc.js → index-C3L5gdiD.js} +1 -1
  115. package/src/assets/web-panel/assets/{index-Cz4b6Z_7.js → index-C7xn0Nub.js} +1 -1
  116. package/src/assets/web-panel/assets/{index-COG61sRv.js → index-CAnvhwg6.js} +1 -1
  117. package/src/assets/web-panel/assets/{index-C7FC8cP2.js → index-CEKMcOyU.js} +1 -1
  118. package/src/assets/web-panel/assets/{index-BN-xdSWZ.js → index-CNC5onm4.js} +1 -1
  119. package/src/assets/web-panel/assets/{index-DY2FIrmz.js → index-CVL27kXC.js} +1 -1
  120. package/src/assets/web-panel/assets/{index-CiTvBAr-.js → index-CVm1_i3t.js} +1 -1
  121. package/src/assets/web-panel/assets/{index-DhRt9cYJ.js → index-CdYBye8B.js} +1 -1
  122. package/src/assets/web-panel/assets/{index-B5pgtZnY.js → index-ClNMrqEY.js} +1 -1
  123. package/src/assets/web-panel/assets/{index-7xKu7Fns.js → index-Cs6l7uRu.js} +1 -1
  124. package/src/assets/web-panel/assets/{index-D4K1weKc.js → index-CshQbilz.js} +1 -1
  125. package/src/assets/web-panel/assets/{index-k7C_oDCO.js → index-Cyweh0Hy.js} +1 -1
  126. package/src/assets/web-panel/assets/{index-D3Oq-DLL.js → index-DBpWXFed.js} +3 -3
  127. package/src/assets/web-panel/assets/{index-DYyLJPlF.js → index-DHtpHZAQ.js} +1 -1
  128. package/src/assets/web-panel/assets/{index-Dh-tkpKQ.js → index-DLmn0BoK.js} +1 -1
  129. package/src/assets/web-panel/assets/{index-8JC9BJa1.js → index-DPAWBrMf.js} +1 -1
  130. package/src/assets/web-panel/assets/{index-Dd2Km97U.js → index-DjEsxO5h.js} +1 -1
  131. package/src/assets/web-panel/assets/{index-KFZO_lcx.js → index-FBc_CJBd.js} +1 -1
  132. package/src/assets/web-panel/assets/{index-DTIZpPtG.js → index-Icdoqmzt.js} +1 -1
  133. package/src/assets/web-panel/assets/index-Q2IajL54.js +1 -0
  134. package/src/assets/web-panel/assets/index-bRkHgOMc.js +1 -0
  135. package/src/assets/web-panel/assets/{index-lmm9p-jm.js → index-dCd8cSUq.js} +1 -1
  136. package/src/assets/web-panel/assets/{index-HasPt4-h.js → index-m2vG9gG_.js} +1 -1
  137. package/src/assets/web-panel/assets/{index-CaslYch6.js → index-mTpHoEzr.js} +1 -1
  138. package/src/assets/web-panel/assets/{index-CbR6ROOa.js → index-ti_lnTWl.js} +1 -1
  139. package/src/assets/web-panel/assets/{initDefaultProps-zQPSHf2C.js → initDefaultProps-Bu8k7H1Y.js} +1 -1
  140. package/src/assets/web-panel/assets/{motion-CKCStGVk.js → motion-s3iVK41k.js} +1 -1
  141. package/src/assets/web-panel/assets/{move-BufVDGYF.js → move-B6B-E5Jz.js} +1 -1
  142. package/src/assets/web-panel/assets/{mtc-parser-DcaFxy5D.js → mtc-parser-BiYgTidA.js} +1 -1
  143. package/src/assets/web-panel/assets/{omit-EScpkGdo.js → omit-pU1RdUDA.js} +1 -1
  144. package/src/assets/web-panel/assets/{pickAttrs-72hG_qfT.js → pickAttrs-Cdoq_SeM.js} +1 -1
  145. package/src/assets/web-panel/assets/{placementArrow-CMFWiH20.js → placementArrow-DIuvAn2K.js} +1 -1
  146. package/src/assets/web-panel/assets/{responsiveObserve-DKQHS41p.js → responsiveObserve-8w16YR2D.js} +1 -1
  147. package/src/assets/web-panel/assets/{slide-QVAFHTIQ.js → slide-VZ01cZe3.js} +1 -1
  148. package/src/assets/web-panel/assets/{statusUtils-DIz38e2G.js → statusUtils-lh8YMN8Z.js} +1 -1
  149. package/src/assets/web-panel/assets/{styleChecker-zK5cyLby.js → styleChecker-CmDyreec.js} +1 -1
  150. package/src/assets/web-panel/assets/{useFlexGapSupport-DhZngk62.js → useFlexGapSupport-hiJWMU5y.js} +1 -1
  151. package/src/assets/web-panel/assets/{useFs-BvV2cvkg.js → useFs-Thnu-Iaj.js} +1 -1
  152. package/src/assets/web-panel/assets/{usePersonalDataHub-CRmxb9l3.js → usePersonalDataHub-LBdOxjwY.js} +1 -1
  153. package/src/assets/web-panel/assets/{vnode-CgQIbobP.js → vnode-Cg6lFY_X.js} +1 -1
  154. package/src/assets/web-panel/assets/{zoom-D4XrrO0R.js → zoom-DVfsR1YO.js} +1 -1
  155. package/src/assets/web-panel/index.html +1 -1
  156. package/src/cli-help.js +181 -0
  157. package/src/command-help-index.json +181 -0
  158. package/src/command-manifest.json +1107 -175
  159. package/src/command-surface-policy.js +197 -0
  160. package/src/commands/agent.js +98 -33
  161. package/src/commands/artifacts.js +400 -2
  162. package/src/commands/background-session.js +41 -3
  163. package/src/commands/checkpoint-managed.js +1059 -0
  164. package/src/commands/checkpoint-restore-recovery.js +1476 -0
  165. package/src/commands/checkpoint.js +950 -22
  166. package/src/commands/compact.js +101 -25
  167. package/src/commands/config.js +506 -20
  168. package/src/commands/doctor.js +4 -1
  169. package/src/commands/hub.js +1 -1
  170. package/src/commands/mcp.js +688 -24
  171. package/src/commands/pack.js +16 -2
  172. package/src/commands/plugin.js +20 -12
  173. package/src/commands/session-mcp-recovery.js +218 -0
  174. package/src/commands/session.js +470 -110
  175. package/src/commands/setup.js +36 -10
  176. package/src/commands/skill.js +181 -110
  177. package/src/commands/status.js +21 -5
  178. package/src/commands/team-distributed.js +3324 -0
  179. package/src/commands/team.js +1130 -74
  180. package/src/commands/update.js +68 -6
  181. package/src/constants.js +11 -0
  182. package/src/data/changelog.json +26 -0
  183. package/src/gateways/ws/action-protocol.js +10 -0
  184. package/src/gateways/ws/session-protocol.js +555 -27
  185. package/src/gateways/ws/ws-agent-handler.js +541 -14
  186. package/src/gateways/ws/ws-session-gateway.js +129 -22
  187. package/src/gateways/ws/ws-session-state.js +431 -0
  188. package/src/harness/background-task-manager.js +233 -36
  189. package/src/harness/jsonl-session-store.js +2551 -167
  190. package/src/harness/mcp-client.js +802 -61
  191. package/src/harness/prompt-compressor.js +227 -27
  192. package/src/harness/session-index.js +89 -38
  193. package/src/harness/session-list-index.js +254 -0
  194. package/src/harness/structured-handoff.js +410 -0
  195. package/src/lazy-dispatch.js +747 -84
  196. package/src/lib/__tests__/logger.test.js +50 -2
  197. package/src/lib/advisor-runtime.js +1047 -0
  198. package/src/lib/agent-core.js +2 -0
  199. package/src/lib/agent-sandbox.js +120 -26
  200. package/src/lib/agent-session-export.js +20 -0
  201. package/src/lib/agent-team/task-lease.js +271 -3
  202. package/src/lib/agent-team/team-adjudication.js +1501 -0
  203. package/src/lib/agent-team/team-budget.js +4 -1
  204. package/src/lib/agent-team/team-control-store.js +582 -0
  205. package/src/lib/agent-team/team-distributed-queue.js +5246 -0
  206. package/src/lib/agent-team/team-process-checkpoint.js +211 -0
  207. package/src/lib/agent-team/team-runner.js +543 -24
  208. package/src/lib/agent-team/team-worktree.js +1403 -95
  209. package/src/lib/artifact-store.js +131 -8
  210. package/src/lib/background-agent-supervisor.js +185 -13
  211. package/src/lib/background-interaction-journal.js +37 -9
  212. package/src/lib/background-launch-profile.js +1058 -0
  213. package/src/lib/checkpoint-restore-already-completed-controller.js +902 -0
  214. package/src/lib/checkpoint-restore-orchestrator.js +987 -0
  215. package/src/lib/checkpoint-restore-partial-rollback-controller.js +1953 -0
  216. package/src/lib/checkpoint-restore-recovery-controller.js +689 -0
  217. package/src/lib/checkpoint-restore-recovery.js +884 -0
  218. package/src/lib/checkpoint-restore-retention.js +126 -0
  219. package/src/lib/checkpoint-restore-saga.js +5079 -0
  220. package/src/lib/checkpoint-restore-session-recovery.js +1178 -0
  221. package/src/lib/checkpoint-restore-workspace-target-verifier.js +270 -0
  222. package/src/lib/checkpoint-store.js +1688 -97
  223. package/src/lib/checkpoint-timeline-authority.js +522 -0
  224. package/src/lib/checkpoint-timeline.js +642 -0
  225. package/src/lib/config-keys.js +18 -119
  226. package/src/lib/config-manager.js +446 -27
  227. package/src/lib/config-redaction.js +57 -0
  228. package/src/lib/config-schema.js +853 -0
  229. package/src/lib/cowork-mcp-tools.js +5 -0
  230. package/src/lib/cowork-task-runner.js +458 -63
  231. package/src/lib/delivery-coordinator.js +1234 -0
  232. package/src/lib/delivery-evidence.js +450 -0
  233. package/src/lib/doctor-checkup.js +199 -14
  234. package/src/lib/executable-path.js +34 -0
  235. package/src/lib/fatal-handler.js +16 -0
  236. package/src/lib/file-checkpoint.js +4909 -186
  237. package/src/lib/file-lines.js +125 -0
  238. package/src/lib/headless-config-command.js +16 -5
  239. package/src/lib/hook-runner.cjs +139 -38
  240. package/src/lib/hooks-v2-workspace-context.js +10 -0
  241. package/src/lib/impacted-gate-selector.js +424 -0
  242. package/src/lib/interaction-adapter.js +62 -0
  243. package/src/lib/jsonl-session-store.js +1 -35
  244. package/src/lib/logger.js +66 -14
  245. package/src/lib/managed-checkpoint-render.js +60 -0
  246. package/src/lib/managed-tool-checkpoint.js +194 -0
  247. package/src/lib/mcp-call-ledger-store.js +1069 -0
  248. package/src/lib/mcp-call-ledger.js +747 -0
  249. package/src/lib/mcp-client.js +5 -0
  250. package/src/lib/mcp-conflict-scheduler.js +468 -0
  251. package/src/lib/mcp-effect-contract.js +102 -0
  252. package/src/lib/mcp-headers-helper-trust.js +145 -0
  253. package/src/lib/mcp-headers-helper.js +616 -0
  254. package/src/lib/mcp-host-recovery-runtime.js +131 -0
  255. package/src/lib/mcp-ledger-recovery-admission.js +1065 -0
  256. package/src/lib/mcp-recovery-adjudication.js +443 -0
  257. package/src/lib/output-context.js +86 -0
  258. package/src/lib/packer/file-identity.js +170 -0
  259. package/src/lib/packer/index.js +3 -0
  260. package/src/lib/packer/native-update-state.js +277 -0
  261. package/src/lib/packer/pack-update-applier.js +1983 -136
  262. package/src/lib/packer/pack-update-checker.js +34 -0
  263. package/src/lib/packer/pack-update-downloader.js +875 -86
  264. package/src/lib/packer/pack-update-signature.js +86 -0
  265. package/src/lib/packer/pkg-config-generator.js +6 -0
  266. package/src/lib/paths.js +65 -10
  267. package/src/lib/plan-mode.js +831 -14
  268. package/src/lib/plan-persistence.js +540 -0
  269. package/src/lib/plugin-runtime/hooks.js +227 -69
  270. package/src/lib/plugin-runtime/plugin-options.js +189 -44
  271. package/src/lib/pr-automation-policy.js +146 -8
  272. package/src/lib/process-execution-broker/credential-agent.js +7 -0
  273. package/src/lib/process-execution-broker/index.js +491 -13
  274. package/src/lib/process-execution-broker/linux-generic-bwrap-runtime.js +28 -1
  275. package/src/lib/process-execution-broker/linux-generic-bwrap.js +28 -4
  276. package/src/lib/process-execution-broker/platform-sandbox.js +92 -70
  277. package/src/lib/process-execution-broker/windows-sandbox-helper.dll +0 -0
  278. package/src/lib/process-execution-broker/windows-sandbox-helper.exe +0 -0
  279. package/src/lib/process-execution-broker/windows-sandbox.cs +284 -19
  280. package/src/lib/process-execution-broker/workspace-transaction.js +4459 -0
  281. package/src/lib/project-instructions.js +165 -29
  282. package/src/lib/project-mcp-trust.js +67 -0
  283. package/src/lib/public-ide-capability-manifest.js +272 -0
  284. package/src/lib/public-ide-capability-validation.js +351 -0
  285. package/src/lib/secret-store.js +267 -43
  286. package/src/lib/secure-file-identity.js +433 -0
  287. package/src/lib/secure-fs.js +1089 -0
  288. package/src/lib/security-audit.js +58 -0
  289. package/src/lib/service-manager.js +34 -13
  290. package/src/lib/session-budget-runtime.js +1452 -0
  291. package/src/lib/session-host-snapshot.js +388 -0
  292. package/src/lib/session-message-provenance.js +429 -0
  293. package/src/lib/session-projection.js +804 -0
  294. package/src/lib/session-resource-budget.js +1495 -0
  295. package/src/lib/settings-hooks.cjs +138 -22
  296. package/src/lib/settings-loader.cjs +25 -2
  297. package/src/lib/side-effect-ledger-store.js +45 -23
  298. package/src/lib/skill-execution-identity.js +217 -0
  299. package/src/lib/skill-loader.js +299 -18
  300. package/src/lib/sub-agent-context.js +236 -28
  301. package/src/lib/sub-agent-registry.js +5 -0
  302. package/src/lib/subagent-contract.js +94 -0
  303. package/src/lib/todo-manager.js +185 -18
  304. package/src/lib/todo-persistence.js +417 -0
  305. package/src/lib/turn-binding-store.js +41 -23
  306. package/src/lib/turn-binding.js +160 -2
  307. package/src/lib/with-file-lock.js +165 -24
  308. package/src/lib/ws-chat-handler.js +21 -0
  309. package/src/program-base.js +18 -0
  310. package/src/repl/advisor-command.js +103 -0
  311. package/src/repl/agent-repl.js +2175 -146
  312. package/src/repl/btw-command.js +93 -10
  313. package/src/repl/clipboard-image.js +119 -0
  314. package/src/repl/config-summary.js +64 -108
  315. package/src/repl/prompt-editor.js +233 -0
  316. package/src/repl/prompt-interactions.js +344 -0
  317. package/src/repl/prompt-stash.js +354 -0
  318. package/src/repl/prompt-suggestions.js +312 -0
  319. package/src/repl/repl-keybindings.js +227 -0
  320. package/src/repl/session-recap.js +217 -0
  321. package/src/repl/slash-command-registry.js +22 -0
  322. package/src/repl/terminal-layout.js +88 -0
  323. package/src/runtime/agent-core.js +1630 -447
  324. package/src/runtime/coding-agent-contract-shared.cjs +13 -1
  325. package/src/runtime/coding-agent-managed-tool-policy.cjs +7 -2
  326. package/src/runtime/diagnostics.js +32 -13
  327. package/src/runtime/headless-runner.js +310 -118
  328. package/src/runtime/headless-stream.js +356 -95
  329. package/src/runtime/mcp-config.js +148 -14
  330. package/src/runtime/policies/agent-policy.js +14 -0
  331. package/src/runtime/status-diagnostics-lite.js +137 -0
  332. package/src/assets/web-panel/assets/MarkdownRenderer-7iWGwZ-r.js +0 -1
  333. package/src/assets/web-panel/assets/OrderTableRenderer-BU2Yqq5H.js +0 -1
  334. package/src/assets/web-panel/assets/PdhVaultBrowser-69ca_WeR.js +0 -7
  335. package/src/assets/web-panel/assets/devWarning-B4dXIJqD.js +0 -1
  336. package/src/assets/web-panel/assets/index-C-C7DaG6.js +0 -1
  337. package/src/assets/web-panel/assets/index-DkfWzWtd.js +0 -1
@@ -18,6 +18,7 @@ import fs from "fs";
18
18
  import path from "path";
19
19
  import broker from "../lib/process-execution-broker/index.js";
20
20
  import os from "os";
21
+ import { isProxy } from "node:util/types";
21
22
  import sharedCodingAgentPolicy from "./coding-agent-policy.cjs";
22
23
  import sharedShellPolicy from "./coding-agent-shell-policy.cjs";
23
24
  import sharedPermissionRules from "../lib/permission-rules.cjs";
@@ -59,7 +60,6 @@ import {
59
60
  } from "../lib/idempotency.js";
60
61
  import { buildSearchCommand } from "../lib/search-command.js";
61
62
  import { discoverCommands } from "../lib/slash-commands.js";
62
- import { createSkillProcessBroker } from "../lib/skill-process-broker.js";
63
63
  import {
64
64
  isRetryableStreamError,
65
65
  STREAM_RETRY_BASE_MS,
@@ -70,10 +70,6 @@ import {
70
70
  replaceByHash,
71
71
  snippetAround,
72
72
  } from "../lib/hashline.js";
73
- import {
74
- mountSkillMcpServers,
75
- unmountSkillMcpServers,
76
- } from "../lib/skill-mcp.js";
77
73
  import {
78
74
  hasImageContent,
79
75
  toOllamaMessages,
@@ -95,6 +91,28 @@ import {
95
91
  } from "../lib/provider-http-error.js";
96
92
  import { buildPermissionDecision } from "../lib/permission-decision.js";
97
93
  import { resolveSandboxPolicyPath } from "../lib/agent-sandbox.js";
94
+ import {
95
+ beginManagedToolCheckpoint,
96
+ settleManagedToolCheckpoint,
97
+ } from "../lib/managed-tool-checkpoint.js";
98
+ import {
99
+ createMcpCallLedger,
100
+ McpEffect,
101
+ snapshotMcpJsonRpcInput,
102
+ } from "../lib/mcp-call-ledger.js";
103
+ import {
104
+ MCP_OUTCOME_UNKNOWN_CODE,
105
+ markMcpLedgerOutcomeUnknown,
106
+ } from "../lib/mcp-ledger-recovery-admission.js";
107
+ import {
108
+ createHostOwnedMcpEffectContract,
109
+ createMcpConflictScheduler,
110
+ } from "../lib/mcp-conflict-scheduler.js";
111
+ import {
112
+ buildExtractiveHandoff,
113
+ formatStructuredHandoff,
114
+ } from "../harness/structured-handoff.js";
115
+ import { projectCanonicalResumeMessages } from "../lib/session-message-provenance.js";
98
116
 
99
117
  export { formatProviderHttpError };
100
118
 
@@ -110,13 +128,31 @@ export function getActiveMcpServers() {
110
128
  return new Set(_activeMcpServers);
111
129
  }
112
130
 
131
+ // Direct executeTool callers do not pass agentLoop's run-scoped scheduler.
132
+ // Share a bounded scheduler per MCP client so two concurrent calls cannot each
133
+ // create a private lock and accidentally bypass unknown/write serialization.
134
+ const _directMcpSchedulers = new WeakMap();
135
+ function directMcpConflictScheduler(mcpClient) {
136
+ if (
137
+ (typeof mcpClient !== "object" || mcpClient === null) &&
138
+ typeof mcpClient !== "function"
139
+ ) {
140
+ return createMcpConflictScheduler({ maxActive: 1 });
141
+ }
142
+ let scheduler = _directMcpSchedulers.get(mcpClient);
143
+ if (!scheduler) {
144
+ scheduler = createMcpConflictScheduler();
145
+ _directMcpSchedulers.set(mcpClient, scheduler);
146
+ }
147
+ return scheduler;
148
+ }
149
+
113
150
  const { isDangerousGitCommand, isReadOnlyGitCommand, normalizeGitCommand } =
114
151
  sharedCodingAgentPolicy;
115
152
  const { evaluateShellCommandPolicy } = sharedShellPolicy;
116
153
  const { evaluatePermissionRules } = sharedPermissionRules;
117
154
  const { collectHooks, umbrellaFor } = sharedSettingsHooks;
118
- const { runHooks: runCommandHooks, runHooksParallel: runCommandHooksParallel } =
119
- sharedHookRunner;
155
+ const { runHooks: runCommandHooks } = sharedHookRunner;
120
156
  const {
121
157
  runObserveHooks,
122
158
  aggregateContext,
@@ -631,19 +667,6 @@ function _resolveShellTimeout(raw) {
631
667
  return Math.min(Math.floor(n), MAX_SHELL_TIMEOUT_MS);
632
668
  }
633
669
 
634
- /**
635
- * Opt-in: run ALL matching decision hooks and take the STRICTEST outcome
636
- * (block > ask > allow > continue) instead of the default in-order first-wins
637
- * short-circuit — so an earlier hook's `ask` can no longer mask a later hook's
638
- * `block`. Default off = byte-identical short-circuit behavior. Flipping the
639
- * default is a product decision (all matching hooks then run every time, which
640
- * changes hook-execution volume + side effects).
641
- */
642
- function _hookStrictMergeEnabled() {
643
- const v = process.env.CC_HOOK_STRICT_MERGE;
644
- return v === "1" || v === "true";
645
- }
646
-
647
670
  /**
648
671
  * Run settings.json `PreToolUse` hooks (decision-capable). DB hooks are handled
649
672
  * separately + stay observe-only. A `block` decision stops the tool; an `ask`
@@ -673,18 +696,18 @@ async function runSettingsPreToolUseHooks(name, args, context, cwd) {
673
696
  parentId: context.hookParentId || null,
674
697
  },
675
698
  );
676
- // Strict merge (opt-in) runs ALL matching hooks and takes the strictest
677
- // decision. This path is async so the hooks run in TRUE PARALLEL
678
- // (runHooksParallel) — wall-clock is the slowest hook, not their sum — while
679
- // still yielding the same strictest outcome. Default path is the sync in-order
680
- // short-circuit runner (byte-identical).
681
- const outcome = _hookStrictMergeEnabled()
682
- ? await runCommandHooksParallel(matched, payload, {
683
- cwd,
684
- event: "PreToolUse",
685
- broker,
686
- })
687
- : runCommandHooks(matched, payload, { cwd, event: "PreToolUse", broker });
699
+ // Run every matching authority-bearing hook in configured order, then merge
700
+ // the outcomes with block > ask > allow > continue. Sequential execution
701
+ // preserves the documented hook side-effect order while preventing an early
702
+ // ask/allow from masking a later block. Environment variables cannot weaken
703
+ // this permission boundary.
704
+ const outcome = runCommandHooks(matched, payload, {
705
+ cwd,
706
+ event: "PreToolUse",
707
+ mergeStrict: true,
708
+ failClosed: true,
709
+ broker,
710
+ });
688
711
  if (outcome.decision === "block") {
689
712
  return { blocked: true, reason: outcome.reason, hook: outcome.hook };
690
713
  }
@@ -738,6 +761,10 @@ async function runSettingsPreToolUseHooks(name, args, context, cwd) {
738
761
  * @returns {{decision:("allow"|"deny"|null), reason?:string, hook?:string}}
739
762
  */
740
763
  function runSettingsPermissionRequestHooks(name, args, context, cwd, reason) {
764
+ // Command hooks are arbitrary processes. Until a host-enforced read-only
765
+ // hook sandbox exists, no command hook may execute inside the planning-only
766
+ // capability fence (even when the underlying tool is read-only).
767
+ if (context.planReadOnlyFenceActive === true) return { decision: null };
741
768
  const matched = collectHooks(
742
769
  context.settingsHooks,
743
770
  "PermissionRequest",
@@ -764,7 +791,8 @@ function runSettingsPermissionRequestHooks(name, args, context, cwd, reason) {
764
791
  const outcome = runCommandHooks(matched, payload, {
765
792
  cwd,
766
793
  event: "PermissionRequest",
767
- mergeStrict: _hookStrictMergeEnabled(),
794
+ mergeStrict: true,
795
+ failClosed: true,
768
796
  broker,
769
797
  });
770
798
  // Precedence: deny > ask > allow > defer. The runner normalizes deny/block →
@@ -891,17 +919,21 @@ export function getAgentToolDefinitions({
891
919
  names = null,
892
920
  disabledTools = [],
893
921
  extraTools = [],
922
+ exactToolNames = false,
894
923
  } = {}) {
895
- const allowedNames =
896
- Array.isArray(names) && names.length > 0 ? new Set(names) : null;
897
- const disabledNames = new Set(
898
- Array.isArray(disabledTools) ? disabledTools : [],
899
- );
924
+ // `names` historically selects a built-in tool preset while independently
925
+ // contributed host/MCP tools remain visible. Preserve that top-level behavior
926
+ // for a non-empty preset, but let authority-bearing child contexts opt into an
927
+ // exact all-tool ceiling. An explicit empty array is always deny-all.
928
+ const allowedNames = Array.isArray(names) ? new Set(names) : null;
900
929
  const extraToolNames = new Set(
901
930
  (Array.isArray(extraTools) ? extraTools : [])
902
931
  .map((tool) => tool?.function?.name)
903
932
  .filter(Boolean),
904
933
  );
934
+ const disabledNames = new Set(
935
+ Array.isArray(disabledTools) ? disabledTools : [],
936
+ );
905
937
  const allTools = mergeToolDefinitions(
906
938
  AGENT_TOOLS,
907
939
  Array.isArray(extraTools) ? extraTools : [],
@@ -910,7 +942,11 @@ export function getAgentToolDefinitions({
910
942
  return allTools.filter((tool) => {
911
943
  const name = tool?.function?.name;
912
944
  if (!name) return false;
913
- if (allowedNames && !allowedNames.has(name) && !extraToolNames.has(name)) {
945
+ const unlistedExtraAllowed =
946
+ allowedNames?.size > 0 &&
947
+ exactToolNames !== true &&
948
+ extraToolNames.has(name);
949
+ if (allowedNames && !allowedNames.has(name) && !unlistedExtraAllowed) {
914
950
  return false;
915
951
  }
916
952
  if (disabledNames.has(name)) return false;
@@ -1594,7 +1630,8 @@ async function tryIdeDiffApprovalForEdit(
1594
1630
  ) {
1595
1631
  if (!IDE_DIFF_EDIT_TOOLS.has(name)) return null;
1596
1632
  if (typeof context.permissionConfirm !== "function") return null; // interactive only
1597
- if (!context.mcpClient || !context.externalToolExecutors) return null;
1633
+ const hostMcpClient = context.mcpHostClient || context.mcpClient;
1634
+ if (!hostMcpClient || !context.externalToolExecutors) return null;
1598
1635
  try {
1599
1636
  const {
1600
1637
  ideDiffApprovalEnabled,
@@ -1604,7 +1641,7 @@ async function tryIdeDiffApprovalForEdit(
1604
1641
  summarizeUserAmendments,
1605
1642
  } = await import("../lib/ide-context.js");
1606
1643
  const mcpLike = {
1607
- mcpClient: context.mcpClient,
1644
+ mcpClient: hostMcpClient,
1608
1645
  externalToolExecutors: context.externalToolExecutors,
1609
1646
  };
1610
1647
  if (!ideDiffApprovalEnabled() || !hasIdeOpenDiff(mcpLike)) return null;
@@ -1718,6 +1755,19 @@ export async function executeTool(name, args, context = {}) {
1718
1755
  const skillLoader = context.skillLoader || _defaultSkillLoader;
1719
1756
  const cwd = context.cwd || process.cwd();
1720
1757
  const planManager = context.planManager || getPlanModeManager();
1758
+ // The provider receives a filtered tool schema, but an untrusted/buggy model
1759
+ // can still emit an arbitrary tool_call. Enforce the exact same immutable
1760
+ // capability set again at execution time; null/absent preserves direct-call
1761
+ // compatibility, while [] is an explicit deny-all ceiling.
1762
+ if (
1763
+ Array.isArray(context.effectiveAllowedToolNames) &&
1764
+ !context.effectiveAllowedToolNames.includes(name)
1765
+ ) {
1766
+ return {
1767
+ error: `[Tool Capability] Tool "${name}" is outside this run's effective tool set.`,
1768
+ policy: { decision: "blocked", via: "effective-tool-set" },
1769
+ };
1770
+ }
1721
1771
  const localToolDescriptor =
1722
1772
  context.externalToolDescriptors &&
1723
1773
  typeof context.externalToolDescriptors === "object"
@@ -1785,11 +1835,60 @@ export async function executeTool(name, args, context = {}) {
1785
1835
  const workspacePathDenial = guardAgentFileToolPaths(name, args, context, cwd);
1786
1836
  if (workspacePathDenial) return workspacePathDenial;
1787
1837
 
1838
+ // A malformed settings source may have hidden a deny/ask hook. Runtime
1839
+ // loaders attach these parse failures as host-owned metadata; executing with
1840
+ // a partial authority set would be strictly wider than the configured path.
1841
+ const hookAuthorityErrors = context.settingsHooks?._authorityErrors;
1842
+ if (Array.isArray(hookAuthorityErrors) && hookAuthorityErrors.length > 0) {
1843
+ return {
1844
+ error:
1845
+ "[Hook Authority] Tool execution blocked because one or more hook policy sources could not be parsed.",
1846
+ policy: { decision: "blocked", via: "hook-authority-load" },
1847
+ incidents: hookAuthorityErrors.map((entry) => ({
1848
+ sourceFile: entry?.sourceFile || entry?.file || null,
1849
+ code: entry?.code || "CC_HOOK_AUTHORITY_INVALID",
1850
+ })),
1851
+ };
1852
+ }
1853
+
1788
1854
  const toolContext = createToolContext({
1789
1855
  toolName: runtimeDescriptor?.name || name,
1790
1856
  cwd,
1791
1857
  metadata: { descriptor: runtimeDescriptor },
1792
1858
  });
1859
+ const observeHookIncidents = [];
1860
+ const recordObserveHookIncident = (event, source, error) => {
1861
+ const incident = Object.freeze({
1862
+ code: "CC_HOOK_OBSERVER_DEGRADED",
1863
+ event,
1864
+ source,
1865
+ degraded: true,
1866
+ reason: String(error?.message || error || "hook observer failed")
1867
+ .replace(/\s+/g, " ")
1868
+ .slice(0, 240),
1869
+ });
1870
+ observeHookIncidents.push(incident);
1871
+ try {
1872
+ emitHooksV2Event("HookFailure", {
1873
+ schema_version: 1,
1874
+ session_id: context.sessionId || null,
1875
+ turn_id: context.turnId || null,
1876
+ tool_use_id: context.toolCallId || null,
1877
+ tool_name: name,
1878
+ hook_event_name: event,
1879
+ hook_source: source,
1880
+ incident_code: incident.code,
1881
+ });
1882
+ } catch {
1883
+ // Incident delivery must never turn an observe-only failure into a new
1884
+ // authority decision or hide the original tool outcome.
1885
+ }
1886
+ try {
1887
+ context.onHookIncident?.(incident);
1888
+ } catch {
1889
+ // Optional observer only.
1890
+ }
1891
+ };
1793
1892
 
1794
1893
  // Persona toolsDisabled guard
1795
1894
  const persona = _loadProjectPersona(cwd);
@@ -1811,10 +1910,10 @@ export async function executeTool(name, args, context = {}) {
1811
1910
  // 3. settings `ask` → confirm (headless w/o confirmer falls closed).
1812
1911
  // Reached only after BOTH denies clear, so a denied
1813
1912
  // tool never wastes a confirmation round-trip.
1814
- // 4. settings `allow` → pre-authorize (ruleAllowed): short-circuit the
1815
- // plan-mode block + run_shell ApprovalGate. The hard
1816
- // shell-policy denylist still applies — allow never
1817
- // re-enables an unsafe `rm -rf /`.
1913
+ // 4. settings `allow` → pre-authorize interactive gates OUTSIDE the
1914
+ // plan-mode hard ceiling. It can never add a tool to
1915
+ // the planning/approved capability set. The hard
1916
+ // shell-policy denylist also still applies.
1818
1917
  // No matching rule + no host policy → every existing layer runs unchanged
1819
1918
  // (default behaviour is byte-for-byte).
1820
1919
  const settingsVerdict = context.permissionRules
@@ -1845,18 +1944,10 @@ export async function executeTool(name, args, context = {}) {
1845
1944
  toolPolicies && typeof toolPolicies === "object"
1846
1945
  ? toolPolicies[name]
1847
1946
  : null;
1848
- const isExternalHostTool =
1849
- hostToolPolicy && !STATIC_AGENT_TOOL_NAMES.has(name);
1850
- const isExternalLocalTool =
1851
- localToolDescriptor && !STATIC_AGENT_TOOL_NAMES.has(name);
1852
1947
  const hostPolicyAllowsReadOnlyGit =
1853
1948
  name === "git" &&
1854
1949
  hostToolPolicy?.planModeBehavior === "readonly-conditional" &&
1855
1950
  isReadOnlyGitCommand(args.command);
1856
- const localReadOnlyAllowedInPlanMode =
1857
- isExternalLocalTool &&
1858
- planManager.isActive() &&
1859
- localToolDescriptor?.isReadOnly === true;
1860
1951
 
1861
1952
  // 2. host deny (a settings `allow` does not relax this)
1862
1953
  if (
@@ -1875,6 +1966,51 @@ export async function executeTool(name, args, context = {}) {
1875
1966
  };
1876
1967
  }
1877
1968
 
1969
+ // Plan mode is a capability ceiling, not another prompt/approval source.
1970
+ // Evaluate it before settings `ask`, sensitive-file confirmation, and every
1971
+ // other interactive gate so no `allow` or confirmed `ask` can widen the
1972
+ // planning tool set. Read-only git remains a built-in conditional capability.
1973
+ // External tools remain blocked until a host-owned, per-tool effect authority
1974
+ // exists; server annotations/descriptors cannot self-authorize Plan access.
1975
+ const executionLockActive = planManager.executionLock != null;
1976
+ const planReadOnlyFenceActive =
1977
+ planManager.isActive() && !executionLockActive;
1978
+ const externalToolBlockedDuringPlanning =
1979
+ planReadOnlyFenceActive && !STATIC_AGENT_TOOL_NAMES.has(name);
1980
+ context = { ...context, planReadOnlyFenceActive };
1981
+ if (
1982
+ planManager.isActive() &&
1983
+ !(name === "git" && isReadOnlyGitCommand(args.command)) &&
1984
+ (externalToolBlockedDuringPlanning || !planManager.isToolAllowed(name))
1985
+ ) {
1986
+ if (!executionLockActive) {
1987
+ planManager.addPlanItem({
1988
+ title: `${name}: ${formatToolArgs(name, args)}`,
1989
+ tool: name,
1990
+ params: args,
1991
+ estimatedImpact:
1992
+ name === "run_shell" ||
1993
+ name === "run_code" ||
1994
+ name === "git" ||
1995
+ localToolDescriptor?.riskLevel === "high"
1996
+ ? "high"
1997
+ : GUARDED_FILE_MUTATION_TOOLS.has(name) ||
1998
+ localToolDescriptor?.riskLevel === "medium"
1999
+ ? "medium"
2000
+ : "low",
2001
+ });
2002
+ }
2003
+ return {
2004
+ error: executionLockActive
2005
+ ? `[Plan Execution Lock] Tool "${name}" was not in the approved tool set. Request a plan revision before using it.`
2006
+ : `[Plan Mode] Tool "${name}" is blocked during planning. It has been added to the plan. Use /plan approve to execute.`,
2007
+ policy: {
2008
+ decision: "blocked",
2009
+ via: executionLockActive ? "plan-execution-lock" : "plan-mode",
2010
+ },
2011
+ };
2012
+ }
2013
+
1878
2014
  // 3 + 4. settings ask / allow (only reached when neither layer denied)
1879
2015
  let ruleAllowed = false;
1880
2016
  if (settingsVerdict.decision === "ask") {
@@ -2058,43 +2194,17 @@ export async function executeTool(name, args, context = {}) {
2058
2194
  }
2059
2195
  }
2060
2196
 
2061
- // Plan mode: settings/host allow rules may help exploration, but they cannot
2062
- // widen the immutable tool set issued when the user approved the plan.
2063
- const executionLockActive = planManager.executionLock != null;
2064
- if (
2065
- planManager.isActive() &&
2066
- (!ruleAllowed || executionLockActive) &&
2067
- !(name === "git" && isReadOnlyGitCommand(args.command)) &&
2068
- !planManager.isToolAllowed(name) &&
2069
- !(
2070
- !executionLockActive &&
2071
- isExternalHostTool &&
2072
- hostToolPolicy?.allowed === true
2073
- ) &&
2074
- !(!executionLockActive && localReadOnlyAllowedInPlanMode)
2075
- ) {
2076
- if (!executionLockActive) {
2077
- planManager.addPlanItem({
2078
- title: `${name}: ${formatToolArgs(name, args)}`,
2079
- tool: name,
2080
- params: args,
2081
- estimatedImpact:
2082
- name === "run_shell" ||
2083
- name === "run_code" ||
2084
- name === "git" ||
2085
- localToolDescriptor?.riskLevel === "high"
2086
- ? "high"
2087
- : GUARDED_FILE_MUTATION_TOOLS.has(name) ||
2088
- localToolDescriptor?.riskLevel === "medium"
2089
- ? "medium"
2090
- : "low",
2091
- });
2092
- }
2093
- return {
2094
- error: executionLockActive
2095
- ? `[Plan Execution Lock] Tool "${name}" was not in the approved tool set. Request a plan revision before using it.`
2096
- : `[Plan Mode] Tool "${name}" is blocked during planning. It has been added to the plan. Use /plan approve to execute.`,
2097
- };
2197
+ // Subtree rules are an authority input, so the first file mutation in a
2198
+ // subtree must observe them before any PreToolUse hook or filesystem effect.
2199
+ // Discovery+read commits the complete source/target batch atomically; this
2200
+ // call is intentionally deferred once and succeeds only on an explicit retry.
2201
+ if (GUARDED_FILE_MUTATION_TOOLS.has(name)) {
2202
+ const instructionPreflight = await _preflightMutationSubtreeInstructions(
2203
+ fileMutationPaths(name, args),
2204
+ cwd,
2205
+ context.subtreeInstructionScope || context.sessionId || "__legacy__",
2206
+ );
2207
+ if (instructionPreflight) return instructionPreflight;
2098
2208
  }
2099
2209
 
2100
2210
  // PreToolUse hooks. DB hooks (cc hook add) stay observe-only — a failure
@@ -2102,77 +2212,79 @@ export async function executeTool(name, args, context = {}) {
2102
2212
  // capable: a `block` (exit 2 / {decision:block}) stops the tool here, an
2103
2213
  // `ask` routes to the confirmer. Runs after permission resolution so a
2104
2214
  // settings deny / host deny short-circuits before any hook process spawns.
2105
- const hooksV2Pre = await executeHooksV2Event(
2106
- "PreToolUse",
2107
- {
2108
- schema_version: 1,
2109
- session_id: context.sessionId || null,
2110
- turn_id: context.turnId || null,
2111
- tool_use_id: context.toolCallId || null,
2112
- tool_name: name,
2113
- input_keys:
2114
- args && typeof args === "object" ? Object.keys(args).sort() : [],
2115
- cwd,
2116
- },
2117
- { failClosed: true },
2118
- );
2119
- if (hooksV2Pre.blocked || hooksV2Pre.decision === "block") {
2120
- return {
2121
- error: `[Hook v2] PreToolUse blocked "${name}".`,
2122
- policy: { decision: "block", via: "hooks-v2" },
2123
- };
2124
- }
2125
- if (hooksV2Pre.requiresApproval || hooksV2Pre.decision === "ask") {
2126
- const confirm = context.permissionConfirm || context.shellConfirm || null;
2127
- const approved =
2128
- typeof confirm === "function"
2129
- ? await confirm({
2130
- tool: name,
2131
- args,
2132
- reason: "Hooks v2 PreToolUse requested confirmation",
2133
- source: "hooks-v2",
2134
- })
2135
- : false;
2136
- if (!approved) {
2137
- emitHooksV2Event("PermissionDenied", {
2215
+ if (!planReadOnlyFenceActive) {
2216
+ const hooksV2Pre = await executeHooksV2Event(
2217
+ "PreToolUse",
2218
+ {
2138
2219
  schema_version: 1,
2139
2220
  session_id: context.sessionId || null,
2140
2221
  turn_id: context.turnId || null,
2141
2222
  tool_use_id: context.toolCallId || null,
2142
2223
  tool_name: name,
2143
- source: "hooks-v2",
2144
- });
2224
+ input_keys:
2225
+ args && typeof args === "object" ? Object.keys(args).sort() : [],
2226
+ cwd,
2227
+ },
2228
+ { failClosed: true },
2229
+ );
2230
+ if (hooksV2Pre.blocked || hooksV2Pre.decision === "block") {
2145
2231
  return {
2146
- error: `[Hook v2] PreToolUse confirmation denied for "${name}".`,
2147
- policy: { decision: "deny", via: "hooks-v2" },
2232
+ error: `[Hook v2] PreToolUse blocked "${name}".`,
2233
+ policy: { decision: "block", via: "hooks-v2" },
2148
2234
  };
2149
2235
  }
2150
- }
2151
- if (hookDb) {
2152
- try {
2153
- await executeHooks(hookDb, HookEvents.PreToolUse, {
2154
- tool: name,
2155
- args,
2156
- timestamp: new Date().toISOString(),
2157
- descriptor: runtimeDescriptor,
2158
- context: toolContext,
2159
- });
2160
- } catch (_err) {
2161
- // Hook failure should not block tool execution
2236
+ if (hooksV2Pre.requiresApproval || hooksV2Pre.decision === "ask") {
2237
+ const confirm = context.permissionConfirm || context.shellConfirm || null;
2238
+ const approved =
2239
+ typeof confirm === "function"
2240
+ ? await confirm({
2241
+ tool: name,
2242
+ args,
2243
+ reason: "Hooks v2 PreToolUse requested confirmation",
2244
+ source: "hooks-v2",
2245
+ })
2246
+ : false;
2247
+ if (!approved) {
2248
+ emitHooksV2Event("PermissionDenied", {
2249
+ schema_version: 1,
2250
+ session_id: context.sessionId || null,
2251
+ turn_id: context.turnId || null,
2252
+ tool_use_id: context.toolCallId || null,
2253
+ tool_name: name,
2254
+ source: "hooks-v2",
2255
+ });
2256
+ return {
2257
+ error: `[Hook v2] PreToolUse confirmation denied for "${name}".`,
2258
+ policy: { decision: "deny", via: "hooks-v2" },
2259
+ };
2260
+ }
2162
2261
  }
2163
- }
2164
- if (context.settingsHooks) {
2165
- const pre = await runSettingsPreToolUseHooks(name, args, context, cwd);
2166
- // A hook `ask` resolved by the IDE diff review: accepted → the IDE
2167
- // already wrote the file, return the synthetic result and skip the tool;
2168
- // rejected → the ide-diff deny shape (via:"ide-diff", not via:"hook").
2169
- if (pre.ideApplied) return pre.ideApplied;
2170
- if (pre.blocked) {
2171
- if (pre.ideResult) return pre.ideResult;
2172
- return {
2173
- error: `[Hook] PreToolUse blocked "${name}"${pre.reason ? ": " + pre.reason : ""}`,
2174
- policy: { decision: "block", via: "hook", hook: pre.hook || null },
2175
- };
2262
+ if (hookDb) {
2263
+ try {
2264
+ await executeHooks(hookDb, HookEvents.PreToolUse, {
2265
+ tool: name,
2266
+ args,
2267
+ timestamp: new Date().toISOString(),
2268
+ descriptor: runtimeDescriptor,
2269
+ context: toolContext,
2270
+ });
2271
+ } catch (error) {
2272
+ recordObserveHookIncident("PreToolUse", "database", error);
2273
+ }
2274
+ }
2275
+ if (context.settingsHooks) {
2276
+ const pre = await runSettingsPreToolUseHooks(name, args, context, cwd);
2277
+ // A hook `ask` resolved by the IDE diff review: accepted → the IDE
2278
+ // already wrote the file, return the synthetic result and skip the tool;
2279
+ // rejected → the ide-diff deny shape (via:"ide-diff", not via:"hook").
2280
+ if (pre.ideApplied) return pre.ideApplied;
2281
+ if (pre.blocked) {
2282
+ if (pre.ideResult) return pre.ideResult;
2283
+ return {
2284
+ error: `[Hook] PreToolUse blocked "${name}"${pre.reason ? ": " + pre.reason : ""}`,
2285
+ policy: { decision: "block", via: "hook", hook: pre.hook || null },
2286
+ };
2287
+ }
2176
2288
  }
2177
2289
  }
2178
2290
 
@@ -2197,10 +2309,18 @@ export async function executeTool(name, args, context = {}) {
2197
2309
  // 用量归因: shared per-run sink for child-loop (sub-agent / isolated
2198
2310
  // skill) token usage, drained by agentLoop as attributed events.
2199
2311
  subAgentUsageSink: context.subAgentUsageSink || null,
2312
+ planManager,
2313
+ permissionRules: context.permissionRules || null,
2314
+ effectiveAllowedToolNames: context.effectiveAllowedToolNames ?? null,
2200
2315
  hostManagedToolPolicy: context.hostManagedToolPolicy || null,
2201
2316
  externalToolDescriptors: context.externalToolDescriptors || null,
2202
2317
  externalToolExecutors: context.externalToolExecutors || null,
2203
2318
  mcpClient: context.mcpClient || null,
2319
+ mcpHostClient: context.mcpHostClient || context.mcpClient || null,
2320
+ mcpCallLedger: context.mcpCallLedger || null,
2321
+ mcpConflictScheduler: context.mcpConflictScheduler || null,
2322
+ subtreeInstructionScope:
2323
+ context.subtreeInstructionScope || context.sessionId || "__legacy__",
2204
2324
  shellPolicyOverrides: context.shellPolicyOverrides || null,
2205
2325
  approvalGate: context.approvalGate || null,
2206
2326
  shellConfirm: context.shellConfirm || null,
@@ -2210,6 +2330,7 @@ export async function executeTool(name, args, context = {}) {
2210
2330
  settingsVerdict,
2211
2331
  subAgentDepth: context.subAgentDepth || 0,
2212
2332
  subAgentBudget: context.subAgentBudget || null,
2333
+ sessionBudget: context.sessionBudget || null,
2213
2334
  // Effective contract of THIS loop (parent ceiling for a nested spawn) +
2214
2335
  // the MCP tool definitions this loop exposes (inheritable by a spawn).
2215
2336
  subAgentContract: context.subAgentContract || null,
@@ -2223,17 +2344,18 @@ export async function executeTool(name, args, context = {}) {
2223
2344
  backgroundSubAgents: context.backgroundSubAgents || null,
2224
2345
  toolAdmission: context.toolAdmission || null,
2225
2346
  unattendedActionPolicy: context.unattendedActionPolicy || null,
2347
+ managedCheckpoint: context.managedCheckpoint === true,
2226
2348
  });
2227
2349
  } catch (err) {
2228
- if (hookDb) {
2350
+ if (hookDb && !planReadOnlyFenceActive) {
2229
2351
  try {
2230
2352
  await executeHooks(hookDb, HookEvents.ToolError, {
2231
2353
  tool: name,
2232
2354
  args,
2233
2355
  error: err.message,
2234
2356
  });
2235
- } catch (_err) {
2236
- // Non-critical
2357
+ } catch (error) {
2358
+ recordObserveHookIncident("ToolError", "database", error);
2237
2359
  }
2238
2360
  }
2239
2361
  throw err;
@@ -2256,7 +2378,7 @@ export async function executeTool(name, args, context = {}) {
2256
2378
  }
2257
2379
 
2258
2380
  // PostToolUse hook
2259
- if (hookDb) {
2381
+ if (hookDb && !planReadOnlyFenceActive) {
2260
2382
  try {
2261
2383
  await executeHooks(hookDb, HookEvents.PostToolUse, {
2262
2384
  tool: name,
@@ -2268,13 +2390,18 @@ export async function executeTool(name, args, context = {}) {
2268
2390
  descriptor: runtimeDescriptor,
2269
2391
  context: toolContext,
2270
2392
  });
2271
- } catch (_err) {
2272
- // Non-critical
2393
+ } catch (error) {
2394
+ recordObserveHookIncident("PostToolUse", "database", error);
2273
2395
  }
2274
2396
  }
2275
2397
  // settings.json PostToolUse hooks: can't un-run the tool, but a `block`
2276
2398
  // reason is attached as `hookFeedback` to be surfaced back to the model.
2277
- if (context.settingsHooks && toolResult && typeof toolResult === "object") {
2399
+ if (
2400
+ !planReadOnlyFenceActive &&
2401
+ context.settingsHooks &&
2402
+ toolResult &&
2403
+ typeof toolResult === "object"
2404
+ ) {
2278
2405
  try {
2279
2406
  const matched = collectHooks(context.settingsHooks, "PostToolUse", name);
2280
2407
  if (matched && matched.length > 0) {
@@ -2309,6 +2436,20 @@ export async function executeTool(name, args, context = {}) {
2309
2436
  event: "PostToolUse",
2310
2437
  broker,
2311
2438
  });
2439
+ for (const hookResult of outcome.results || []) {
2440
+ if (
2441
+ hookResult?.nonBlockingError === true ||
2442
+ hookResult?.breakerOpen === true ||
2443
+ hookResult?.malformedDecision === true ||
2444
+ hookResult?.unsupportedDecision === true
2445
+ ) {
2446
+ recordObserveHookIncident(
2447
+ "PostToolUse",
2448
+ "settings-command",
2449
+ hookResult.reason || hookResult.error || "hook command failed",
2450
+ );
2451
+ }
2452
+ }
2312
2453
  if (outcome.decision === "block" && outcome.reason) {
2313
2454
  toolResult.hookFeedback = outcome.reason;
2314
2455
  }
@@ -2319,8 +2460,8 @@ export async function executeTool(name, args, context = {}) {
2319
2460
  context.hookSupervisor.dispatch(asyncHooks, payload, { cwd, broker });
2320
2461
  }
2321
2462
  }
2322
- } catch (_err) {
2323
- // PostToolUse hooks are best-effort
2463
+ } catch (error) {
2464
+ recordObserveHookIncident("PostToolUse", "settings-command", error);
2324
2465
  }
2325
2466
  }
2326
2467
 
@@ -2361,8 +2502,8 @@ export async function executeTool(name, args, context = {}) {
2361
2502
  ? `${toolResult.hookFeedback}\n${outcome.reason}`
2362
2503
  : outcome.reason;
2363
2504
  }
2364
- } catch (_err) {
2365
- // SubagentStop hooks are best-effort
2505
+ } catch (error) {
2506
+ recordObserveHookIncident("SubagentStop", "settings-command", error);
2366
2507
  }
2367
2508
  }
2368
2509
 
@@ -2380,7 +2521,7 @@ export async function executeTool(name, args, context = {}) {
2380
2521
  typeof toolResult === "object" &&
2381
2522
  !toolResult.error &&
2382
2523
  args?.path &&
2383
- context.mcpClient &&
2524
+ (context.mcpHostClient || context.mcpClient) &&
2384
2525
  context.externalToolExecutors
2385
2526
  ) {
2386
2527
  try {
@@ -2388,7 +2529,7 @@ export async function executeTool(name, args, context = {}) {
2388
2529
  await import("../lib/ide-context.js");
2389
2530
  const diags = await collectIdeDiagnostics(
2390
2531
  {
2391
- mcpClient: context.mcpClient,
2532
+ mcpClient: context.mcpHostClient || context.mcpClient,
2392
2533
  externalToolExecutors: context.externalToolExecutors,
2393
2534
  },
2394
2535
  path.resolve(cwd, args.path),
@@ -2400,6 +2541,14 @@ export async function executeTool(name, args, context = {}) {
2400
2541
  }
2401
2542
  }
2402
2543
 
2544
+ if (
2545
+ observeHookIncidents.length > 0 &&
2546
+ toolResult &&
2547
+ typeof toolResult === "object"
2548
+ ) {
2549
+ toolResult.hookIncidents = observeHookIncidents;
2550
+ }
2551
+
2403
2552
  return toolResult;
2404
2553
  }
2405
2554
 
@@ -2866,12 +3015,19 @@ async function _postEditDiagnostics(filePath, cwd, additionalDirectories) {
2866
3015
  }
2867
3016
 
2868
3017
  /** Merge post-edit diagnostics into a successful edit result (no-op if none). */
2869
- async function _withPostEditDiagnostics(
3018
+ export async function _withPostEditDiagnostics(
2870
3019
  result,
2871
3020
  filePath,
2872
3021
  cwd,
2873
3022
  additionalDirectories,
3023
+ managedCheckpoint = false,
2874
3024
  ) {
3025
+ // A cold language server is a long-lived child process. Starting one inside
3026
+ // a managed workspace transaction would keep a writer bound past tool
3027
+ // settlement and make commit/rollback unverifiable. Managed edits therefore
3028
+ // skip this best-effort enrichment; callers can request diagnostics after the
3029
+ // checkpoint has sealed.
3030
+ if (managedCheckpoint) return result;
2875
3031
  const newDiagnostics = await _postEditDiagnostics(
2876
3032
  filePath,
2877
3033
  cwd,
@@ -2886,15 +3042,20 @@ async function _withPostEditDiagnostics(
2886
3042
  // NOT loaded up front — they cost tokens for subtrees a run may never touch.
2887
3043
  // When a tool first ACCESSES a path inside such a subtree, we inject that
2888
3044
  // subtree's directory instructions into the tool result (the SAME channel as
2889
- // newDiagnostics), exactly once per subtree per process. A stateful
2890
- // SubtreeInstructionLoader per root remembers what it already injected so a
3045
+ // newDiagnostics), exactly once per subtree per agent session. A stateful
3046
+ // SubtreeInstructionLoader per root/session remembers what it already injected so a
2891
3047
  // second access to the same subtree is a no-op. Disable with
2892
3048
  // CC_SUBTREE_INSTRUCTIONS=0. Common case (no cc.md below cwd) → zero cost.
2893
- const _subtreeLoaderPool = new Map(); // root -> SubtreeInstructionLoader
3049
+ const _subtreeLoaderPool = new Map(); // root -> Map<session scope, loader>
2894
3050
 
2895
- async function _getSubtreeLoader(cwd) {
3051
+ async function _getSubtreeLoader(cwd, sessionScope = "__legacy__") {
2896
3052
  const root = path.resolve(cwd || process.cwd());
2897
- let loader = _subtreeLoaderPool.get(root);
3053
+ let scopedLoaders = _subtreeLoaderPool.get(root);
3054
+ if (!scopedLoaders) {
3055
+ scopedLoaders = new Map();
3056
+ _subtreeLoaderPool.set(root, scopedLoaders);
3057
+ }
3058
+ let loader = scopedLoaders.get(sessionScope);
2898
3059
  if (!loader) {
2899
3060
  const { SubtreeInstructionLoader } =
2900
3061
  await import("../lib/project-instructions.js");
@@ -2913,7 +3074,7 @@ async function _getSubtreeLoader(cwd) {
2913
3074
  baseDir: root,
2914
3075
  instructionExcludes,
2915
3076
  });
2916
- _subtreeLoaderPool.set(root, loader);
3077
+ scopedLoaders.set(sessionScope, loader);
2917
3078
  }
2918
3079
  return loader;
2919
3080
  }
@@ -2928,15 +3089,28 @@ export function _resetSubtreeInstructionLoaders() {
2928
3089
  * with their (capped) content read for inline injection — or null when the
2929
3090
  * subtree has no NEW cc.md/CLAUDE.md/AGENTS.md (the common case → zero cost).
2930
3091
  */
2931
- async function _subtreeInstructionsFor(accessedPath, cwd) {
3092
+ async function _prepareSubtreeInstructions(
3093
+ accessedPaths,
3094
+ cwd,
3095
+ sessionScope = "__legacy__",
3096
+ ) {
2932
3097
  if (process.env.CC_SUBTREE_INSTRUCTIONS === "0") return null;
2933
3098
  try {
2934
- const loader = await _getSubtreeLoader(cwd);
2935
- const fresh = loader.onAccess(accessedPath);
3099
+ const loader = await _getSubtreeLoader(cwd, sessionScope);
3100
+ const discovered = new Map();
3101
+ for (const accessedPath of Array.isArray(accessedPaths)
3102
+ ? accessedPaths
3103
+ : [accessedPaths]) {
3104
+ for (const candidate of loader.discover(accessedPath)) {
3105
+ discovered.set(candidate.identity, candidate);
3106
+ }
3107
+ }
3108
+ const fresh = [...discovered.values()];
2936
3109
  if (!fresh || !fresh.length) return null;
2937
3110
  const { DEFAULT_MAX_FILE_BYTES } =
2938
3111
  await import("../lib/project-instructions.js");
2939
3112
  const out = [];
3113
+ const errors = [];
2940
3114
  for (const f of fresh) {
2941
3115
  try {
2942
3116
  const buf = fs.readFileSync(f.path);
@@ -2950,23 +3124,84 @@ async function _subtreeInstructionsFor(accessedPath, cwd) {
2950
3124
  content,
2951
3125
  ...(truncated ? { truncated: true } : {}),
2952
3126
  });
2953
- } catch {
2954
- // discovered file vanished before we could read it — skip it
3127
+ } catch (err) {
3128
+ errors.push({ path: f.path, message: err.message });
2955
3129
  }
2956
3130
  }
2957
- return out.length ? out : null;
2958
- } catch {
2959
- return null; // fail-open: never break a tool because injection errored
3131
+ // Commit only after every candidate in the source/target batch has been
3132
+ // read. Any failure leaves the entire batch discoverable for a retry.
3133
+ if (!errors.length) loader.commit(fresh);
3134
+ return out.length || errors.length ? { instructions: out, errors } : null;
3135
+ } catch (err) {
3136
+ // Paths outside cwd are handled by the normal path/sandbox authority and
3137
+ // have no cwd-subtree rules. Other failures remain visible to mutation
3138
+ // preflight so they cannot silently widen authority.
3139
+ if (err?.code === "ERR_SUBTREE_INSTRUCTION_BOUNDARY") return null;
3140
+ return {
3141
+ instructions: [],
3142
+ errors: [{ path: null, message: err?.message || String(err) }],
3143
+ };
3144
+ }
3145
+ }
3146
+
3147
+ async function _subtreeInstructionsFor(accessedPath, cwd, sessionScope) {
3148
+ const prepared = await _prepareSubtreeInstructions(
3149
+ accessedPath,
3150
+ cwd,
3151
+ sessionScope,
3152
+ );
3153
+ return prepared?.instructions?.length ? prepared.instructions : null;
3154
+ }
3155
+
3156
+ async function _preflightMutationSubtreeInstructions(
3157
+ accessedPaths,
3158
+ cwd,
3159
+ sessionScope,
3160
+ ) {
3161
+ const prepared = await _prepareSubtreeInstructions(
3162
+ accessedPaths,
3163
+ cwd,
3164
+ sessionScope,
3165
+ );
3166
+ if (!prepared) return null;
3167
+ if (prepared.errors?.length) {
3168
+ return {
3169
+ error:
3170
+ "[Subtree Instructions] Mutation blocked because applicable instructions could not be loaded. No mutation was performed.",
3171
+ policy: { decision: "blocked", via: "subtree-instructions" },
3172
+ instructionLoadErrors: prepared.errors,
3173
+ mutationPerformed: false,
3174
+ ...(prepared.instructions?.length
3175
+ ? { subtreeInstructions: prepared.instructions }
3176
+ : {}),
3177
+ };
2960
3178
  }
3179
+ if (!prepared.instructions?.length) return null;
3180
+ return {
3181
+ error:
3182
+ "[Subtree Instructions] Mutation deferred before its first effect. Review these authoritative subtree rules, then retry the tool call.",
3183
+ policy: { decision: "deferred", via: "subtree-instructions" },
3184
+ subtreeInstructions: prepared.instructions,
3185
+ mutationPerformed: false,
3186
+ };
2961
3187
  }
2962
3188
 
2963
3189
  /**
2964
3190
  * Attach freshly-discovered subtree instructions to a SUCCESSFUL tool result
2965
3191
  * (no-op on an error result or when the subtree has nothing new).
2966
3192
  */
2967
- async function _withSubtreeInstructions(result, accessedPath, cwd) {
3193
+ async function _withSubtreeInstructions(
3194
+ result,
3195
+ accessedPath,
3196
+ cwd,
3197
+ sessionScope,
3198
+ ) {
2968
3199
  if (result && result.error) return result;
2969
- const subtreeInstructions = await _subtreeInstructionsFor(accessedPath, cwd);
3200
+ const subtreeInstructions = await _subtreeInstructionsFor(
3201
+ accessedPath,
3202
+ cwd,
3203
+ sessionScope,
3204
+ );
2970
3205
  return subtreeInstructions ? { ...result, subtreeInstructions } : result;
2971
3206
  }
2972
3207
 
@@ -3023,6 +3258,168 @@ async function promoteBrowserScreenshot(
3023
3258
  }
3024
3259
  }
3025
3260
 
3261
+ const MCP_LEDGER_EFFECTS = new Set(["read", "unknown", "write", "destructive"]);
3262
+
3263
+ /**
3264
+ * Reduce descriptor + managed-host metadata to the host-owned contract written
3265
+ * to the MCP ledger. A server's read-only declaration is never promoted to a
3266
+ * read authorization. Server declarations may only make the classification
3267
+ * stricter (write/destructive) when host authority is absent.
3268
+ */
3269
+ function mcpLedgerEffectContract(descriptor, hostPolicy) {
3270
+ const descriptorContract = descriptor?.effectContract || {};
3271
+ const hostContract = hostPolicy?.effectContract || {};
3272
+ const authorizedCandidate =
3273
+ hostContract.authorizedEffect || hostPolicy?.authorizedEffect;
3274
+ const authorizedEffect = MCP_LEDGER_EFFECTS.has(authorizedCandidate)
3275
+ ? authorizedCandidate
3276
+ : null;
3277
+ const declaredEffect = MCP_LEDGER_EFFECTS.has(
3278
+ descriptorContract.declaredEffect,
3279
+ )
3280
+ ? descriptorContract.declaredEffect
3281
+ : "unknown";
3282
+ const effect =
3283
+ authorizedEffect ||
3284
+ (declaredEffect === "destructive" || declaredEffect === "write"
3285
+ ? declaredEffect
3286
+ : "unknown");
3287
+ const annotations = descriptorContract.annotations || {};
3288
+
3289
+ return {
3290
+ effect,
3291
+ destructive:
3292
+ effect === "destructive" || annotations.destructiveHint === true,
3293
+ sideEffecting: effect === "write" || effect === "destructive",
3294
+ idempotent:
3295
+ typeof annotations.idempotentHint === "boolean"
3296
+ ? annotations.idempotentHint
3297
+ : null,
3298
+ openWorld:
3299
+ typeof annotations.openWorldHint === "boolean"
3300
+ ? annotations.openWorldHint
3301
+ : null,
3302
+ trusted:
3303
+ authorizedEffect != null &&
3304
+ (hostContract.trusted === true || hostPolicy?.sourceTrusted === true),
3305
+ source:
3306
+ hostContract.provenance ||
3307
+ descriptorContract.provenance ||
3308
+ descriptor?.source ||
3309
+ "mcp",
3310
+ };
3311
+ }
3312
+
3313
+ function mcpLedgerScopes(args) {
3314
+ const resourceScopes = [];
3315
+ const networkScopes = [];
3316
+ const visit = (value, key = "", depth = 0) => {
3317
+ if (depth > 3 || value == null) return;
3318
+ if (Array.isArray(value)) {
3319
+ value.slice(0, 32).forEach((entry) => visit(entry, key, depth + 1));
3320
+ return;
3321
+ }
3322
+ if (typeof value === "object") {
3323
+ Object.entries(value)
3324
+ .slice(0, 64)
3325
+ .forEach(([childKey, childValue]) =>
3326
+ visit(childValue, childKey, depth + 1),
3327
+ );
3328
+ return;
3329
+ }
3330
+ if (typeof value !== "string") return;
3331
+
3332
+ const normalizedKey = String(key).toLowerCase();
3333
+ const isNetworkScope = /url|uri|endpoint|origin|host/.test(normalizedKey);
3334
+ if (isNetworkScope) {
3335
+ networkScopes.push(value);
3336
+ }
3337
+ // URL/URI values can carry credentials, query secrets and private paths.
3338
+ // The network ledger normalizes them to origin only; never duplicate the
3339
+ // raw value into resourceScopes, whose identifiers are intentionally not
3340
+ // URL parsers. The input digest still binds the exact request at rest.
3341
+ if (
3342
+ !isNetworkScope &&
3343
+ /path|file|resource|repo|project|workspace/.test(normalizedKey)
3344
+ ) {
3345
+ resourceScopes.push(`${normalizedKey}:${value}`);
3346
+ }
3347
+ };
3348
+ visit(args || {});
3349
+ return { resourceScopes, networkScopes };
3350
+ }
3351
+
3352
+ const MCP_TRANSPORT_OUTCOME_UNKNOWN_CODE = "CC_MCP_TRANSPORT_OUTCOME_UNKNOWN";
3353
+ const MCP_PROTOCOL_RESULT_INVALID_CODE = "CC_MCP_PROTOCOL_RESULT_INVALID";
3354
+ const MCP_RESULT_PROJECTION_FAILED_CODE = "CC_MCP_RESULT_PROJECTION_FAILED";
3355
+
3356
+ function safeMcpProperty(value, property) {
3357
+ try {
3358
+ return value?.[property];
3359
+ } catch {
3360
+ return undefined;
3361
+ }
3362
+ }
3363
+
3364
+ function safeMcpErrorMessage(error) {
3365
+ const message = safeMcpProperty(error, "message");
3366
+ if (typeof message === "string" && message) return message;
3367
+ try {
3368
+ return String(error || "unknown error");
3369
+ } catch {
3370
+ return "unknown error";
3371
+ }
3372
+ }
3373
+
3374
+ function safeMcpErrorCode(error, fallback) {
3375
+ const code = safeMcpProperty(error, "code");
3376
+ return typeof code === "string" && code ? code : fallback;
3377
+ }
3378
+
3379
+ function invalidMcpProtocolResult(cause) {
3380
+ const error = new TypeError("MCP result could not be inspected safely", {
3381
+ cause,
3382
+ });
3383
+ error.code = MCP_PROTOCOL_RESULT_INVALID_CODE;
3384
+ return error;
3385
+ }
3386
+
3387
+ function mcpTransportOutcomeIsUnsafe(effectContract) {
3388
+ return !(
3389
+ effectContract?.effect === McpEffect.READ &&
3390
+ effectContract?.trusted === true
3391
+ );
3392
+ }
3393
+
3394
+ function mcpOutcomeUnknownPayload(
3395
+ ledger,
3396
+ ticket,
3397
+ { phase, reasonCode = MCP_OUTCOME_UNKNOWN_CODE } = {},
3398
+ ) {
3399
+ const stableReasonCode =
3400
+ typeof reasonCode === "string" && reasonCode
3401
+ ? reasonCode
3402
+ : MCP_OUTCOME_UNKNOWN_CODE;
3403
+ try {
3404
+ markMcpLedgerOutcomeUnknown(ledger, stableReasonCode);
3405
+ } catch {
3406
+ // The public result must remain deterministic even for a hostile ledger.
3407
+ }
3408
+ return {
3409
+ error:
3410
+ "MCP tool may have completed, but its outcome is unknown; do not retry automatically until durable recovery is adjudicated.",
3411
+ code: MCP_OUTCOME_UNKNOWN_CODE,
3412
+ status: "outcome_unknown",
3413
+ outcomeUnknown: true,
3414
+ retryable: false,
3415
+ mcpLedgerId: safeMcpProperty(ticket, "ledgerId") || null,
3416
+ mcpLedgerIncident: {
3417
+ phase: phase || "settled",
3418
+ code: stableReasonCode,
3419
+ },
3420
+ };
3421
+ }
3422
+
3026
3423
  async function executeToolInner(
3027
3424
  name,
3028
3425
  args,
@@ -3035,11 +3432,17 @@ async function executeToolInner(
3035
3432
  sessionId,
3036
3433
  turnId,
3037
3434
  toolCallId,
3435
+ planManager = null,
3436
+ permissionRules = null,
3437
+ effectiveAllowedToolNames = null,
3038
3438
  hostManagedToolPolicy,
3039
3439
  externalToolDescriptors,
3040
3440
  externalToolExecutors,
3041
3441
  extraToolDefinitions = null,
3042
3442
  mcpClient,
3443
+ mcpCallLedger = null,
3444
+ mcpConflictScheduler = null,
3445
+ subtreeInstructionScope = "__legacy__",
3043
3446
  memoryDb = null,
3044
3447
  permanentMemory = null,
3045
3448
  subAgentContract = null,
@@ -3054,6 +3457,7 @@ async function executeToolInner(
3054
3457
  settingsVerdict = null,
3055
3458
  subAgentDepth = 0,
3056
3459
  subAgentBudget = null,
3460
+ sessionBudget = null,
3057
3461
  interactiveApproval = false,
3058
3462
  settingsHooks = null,
3059
3463
  signal = null,
@@ -3061,6 +3465,7 @@ async function executeToolInner(
3061
3465
  subAgentUsageSink = null,
3062
3466
  toolAdmission = null,
3063
3467
  unattendedActionPolicy = null,
3468
+ managedCheckpoint = false,
3064
3469
  // Hook-envelope tracing: this run's trace id, threaded into child loops
3065
3470
  // (spawn_sub_agent / isolated run_skill) as their parent_id.
3066
3471
  hookTraceId = null,
@@ -3182,6 +3587,7 @@ async function executeToolInner(
3182
3587
  },
3183
3588
  filePath,
3184
3589
  cwd,
3590
+ subtreeInstructionScope,
3185
3591
  ),
3186
3592
  );
3187
3593
  }
@@ -3194,6 +3600,7 @@ async function executeToolInner(
3194
3600
  },
3195
3601
  filePath,
3196
3602
  cwd,
3603
+ subtreeInstructionScope,
3197
3604
  ),
3198
3605
  );
3199
3606
  }
@@ -3220,9 +3627,11 @@ async function executeToolInner(
3220
3627
  filePath,
3221
3628
  cwd,
3222
3629
  additionalDirectories,
3630
+ managedCheckpoint,
3223
3631
  ),
3224
3632
  filePath,
3225
3633
  cwd,
3634
+ subtreeInstructionScope,
3226
3635
  ),
3227
3636
  );
3228
3637
  }
@@ -3300,9 +3709,11 @@ async function executeToolInner(
3300
3709
  targetPath,
3301
3710
  cwd,
3302
3711
  additionalDirectories,
3712
+ managedCheckpoint,
3303
3713
  ),
3304
3714
  targetPath,
3305
3715
  cwd,
3716
+ subtreeInstructionScope,
3306
3717
  ),
3307
3718
  );
3308
3719
  }
@@ -3399,9 +3810,11 @@ async function executeToolInner(
3399
3810
  filePath,
3400
3811
  cwd,
3401
3812
  additionalDirectories,
3813
+ managedCheckpoint,
3402
3814
  ),
3403
3815
  filePath,
3404
3816
  cwd,
3817
+ subtreeInstructionScope,
3405
3818
  ),
3406
3819
  );
3407
3820
  }
@@ -3463,9 +3876,11 @@ async function executeToolInner(
3463
3876
  filePath,
3464
3877
  cwd,
3465
3878
  additionalDirectories,
3879
+ managedCheckpoint,
3466
3880
  ),
3467
3881
  filePath,
3468
3882
  cwd,
3883
+ subtreeInstructionScope,
3469
3884
  ),
3470
3885
  );
3471
3886
  }
@@ -4427,13 +4842,28 @@ async function executeToolInner(
4427
4842
  llmOptions,
4428
4843
  subAgentDepth,
4429
4844
  subAgentBudget,
4845
+ sessionBudget,
4430
4846
  subAgentContract,
4431
4847
  settingsHooks,
4848
+ // Immutable parent execution authority. The child may only tighten
4849
+ // these boundaries; it never reconstructs a fresh default policy.
4850
+ planManager,
4851
+ permissionRules,
4852
+ effectiveAllowedToolNames,
4853
+ hostManagedToolPolicy,
4854
+ sandbox,
4855
+ additionalDirectories,
4856
+ approvalGate,
4857
+ shellPolicyOverrides,
4858
+ classifyAllShell,
4859
+ unattendedActionPolicy,
4432
4860
  // Parent trace for the child's hook envelopes (parent_id).
4433
4861
  hookTraceId,
4434
4862
  // Parent MCP plumbing — a spawn can inherit these into the child,
4435
4863
  // filtered by the resolved contract's mcpServers allow-list.
4436
4864
  mcpClient,
4865
+ mcpCallLedger,
4866
+ mcpConflictScheduler,
4437
4867
  externalToolDescriptors,
4438
4868
  externalToolExecutors,
4439
4869
  extraToolDefinitions,
@@ -4505,14 +4935,31 @@ async function executeToolInner(
4505
4935
  case "todo_write": {
4506
4936
  try {
4507
4937
  const { writeTodos } = await import("../lib/todo-manager.js");
4508
- const result = writeTodos(sessionId, args.todos);
4938
+ const result = writeTodos(sessionId, args.todos, {
4939
+ ...(Number.isSafeInteger(args.expected_revision)
4940
+ ? { expectedRevision: args.expected_revision }
4941
+ : {}),
4942
+ });
4509
4943
  if (!result.success) {
4510
- return attachDescriptor({ error: result.error });
4944
+ return attachDescriptor({
4945
+ error: result.error,
4946
+ ...(result.code ? { code: result.code } : {}),
4947
+ ...(Number.isSafeInteger(result.expectedRevision)
4948
+ ? { expectedRevision: result.expectedRevision }
4949
+ : {}),
4950
+ ...(Number.isSafeInteger(result.actualRevision)
4951
+ ? { actualRevision: result.actualRevision }
4952
+ : {}),
4953
+ ...(result.recoveryStrategy
4954
+ ? { recoveryStrategy: result.recoveryStrategy }
4955
+ : {}),
4956
+ });
4511
4957
  }
4512
4958
  return attachDescriptor({
4513
4959
  success: true,
4514
4960
  count: result.count,
4515
4961
  summary: result.summary,
4962
+ revision: result.revision,
4516
4963
  });
4517
4964
  } catch (err) {
4518
4965
  return attachDescriptor({ error: `todo_write failed: ${err.message}` });
@@ -5201,6 +5648,7 @@ async function executeToolInner(
5201
5648
  },
5202
5649
  dirPath,
5203
5650
  cwd,
5651
+ subtreeInstructionScope,
5204
5652
  ),
5205
5653
  );
5206
5654
  }
@@ -5226,7 +5674,14 @@ async function executeToolInner(
5226
5674
  });
5227
5675
  }
5228
5676
  try {
5229
- if (typeof skillLoader.materializeSkill === "function") {
5677
+ if (typeof skillLoader.materializeSkillForExecution === "function") {
5678
+ match = await skillLoader.materializeSkillForExecution(match, {
5679
+ sessionId,
5680
+ turnId,
5681
+ loadedBecause: "run_skill",
5682
+ bodyIncluded: false,
5683
+ });
5684
+ } else if (typeof skillLoader.materializeSkill === "function") {
5230
5685
  match = skillLoader.materializeSkill(match, {
5231
5686
  sessionId,
5232
5687
  turnId,
@@ -5237,12 +5692,26 @@ async function executeToolInner(
5237
5692
  } catch (error) {
5238
5693
  return attachDescriptor({
5239
5694
  error: `Skill "${args.skill_name}" body could not be loaded: ${error.message}`,
5695
+ ...(error?.code ? { code: error.code } : {}),
5696
+ policy: {
5697
+ decision: "blocked",
5698
+ via: "skill-execution-boundary",
5699
+ },
5240
5700
  });
5241
5701
  }
5242
5702
 
5243
5703
  // Check if skill requests isolation (via SKILL.md frontmatter)
5244
5704
  const skillIsolation = match.isolation === true;
5245
5705
  if (skillIsolation) {
5706
+ const isolatedSkillTools = [
5707
+ "read_file",
5708
+ "search_files",
5709
+ "list_dir",
5710
+ ].filter(
5711
+ (toolName) =>
5712
+ !Array.isArray(effectiveAllowedToolNames) ||
5713
+ effectiveAllowedToolNames.includes(toolName),
5714
+ );
5246
5715
  // 用量归因: an isolated skill runs as a child loop whose real token
5247
5716
  // usage would otherwise be invisible — forward it into the parent
5248
5717
  // run's sink tagged origin:"skill" so `cc session usage --by skill`
@@ -5254,11 +5723,36 @@ async function executeToolInner(
5254
5723
  // Run skill through isolated sub-agent context
5255
5724
  const subCtx = SubAgentContext.create({
5256
5725
  role: `skill-${args.skill_name}`,
5257
- task: `Execute the "${args.skill_name}" skill with input: ${(args.input || "").substring(0, 200)}`,
5258
- allowedTools: ["read_file", "search_files", "list_dir"],
5726
+ task:
5727
+ `Execute the "${args.skill_name}" skill using only the approved tools.\n\n` +
5728
+ `Authoritative skill instructions:\n${String(match.body || "").substring(0, 48000)}\n\n` +
5729
+ `User input:\n${String(args.input || "").substring(0, 8000)}`,
5730
+ allowedTools: isolatedSkillTools,
5259
5731
  hookParentTraceId: hookTraceId || null,
5260
5732
  toolAdmission,
5261
5733
  cwd,
5734
+ llmOptions: llmOptions || null,
5735
+ ...(sessionBudget ? { sessionBudget } : {}),
5736
+ ...(permissionRules ? { permissionRules } : {}),
5737
+ ...(hostManagedToolPolicy
5738
+ ? {
5739
+ hostManagedToolPolicy: {
5740
+ ...hostManagedToolPolicy,
5741
+ toolDefinitions: [],
5742
+ },
5743
+ }
5744
+ : {}),
5745
+ ...(planManager ? { planManager } : {}),
5746
+ ...(sandbox ? { sandbox } : {}),
5747
+ ...(Array.isArray(additionalDirectories)
5748
+ ? { additionalDirectories: [...additionalDirectories] }
5749
+ : {}),
5750
+ ...(approvalGate ? { approvalGate } : {}),
5751
+ ...(shellPolicyOverrides ? { shellPolicyOverrides } : {}),
5752
+ ...(classifyAllShell ? { classifyAllShell: true } : {}),
5753
+ ...(unattendedActionPolicy ? { unattendedActionPolicy } : {}),
5754
+ ...(mcpCallLedger ? { mcpCallLedger } : {}),
5755
+ ...(mcpConflictScheduler ? { mcpConflictScheduler } : {}),
5262
5756
  onUsage: skillUsageSink
5263
5757
  ? (u) => {
5264
5758
  try {
@@ -5269,6 +5763,7 @@ async function executeToolInner(
5269
5763
  provider: u?.provider ?? null,
5270
5764
  model: u?.model ?? null,
5271
5765
  usage: u?.usage || null,
5766
+ ...(u?.source ? { source: u.source } : {}),
5272
5767
  attribution: {
5273
5768
  origin: "skill",
5274
5769
  skill: args.skill_name,
@@ -5287,6 +5782,25 @@ async function executeToolInner(
5287
5782
  skillSubRef = subCtx;
5288
5783
  try {
5289
5784
  const result = await subCtx.run(args.input);
5785
+ const resolvedFailure =
5786
+ subCtx.status === "failed" ||
5787
+ result?.success === false ||
5788
+ Boolean(result?.error);
5789
+ if (resolvedFailure) {
5790
+ const failureDetail =
5791
+ result?.error?.message ||
5792
+ result?.error ||
5793
+ result?.summary ||
5794
+ `child status ${subCtx.status || "failed"}`;
5795
+ return attachDescriptor({
5796
+ success: false,
5797
+ isolated: true,
5798
+ skill: args.skill_name,
5799
+ code: result?.code || "CC_SKILL_ISOLATED_EXECUTION_FAILED",
5800
+ error: `Isolated skill execution failed: ${failureDetail}`,
5801
+ ...(result?.summary ? { summary: result.summary } : {}),
5802
+ });
5803
+ }
5290
5804
  return attachDescriptor({
5291
5805
  success: true,
5292
5806
  isolated: true,
@@ -5296,79 +5810,24 @@ async function executeToolInner(
5296
5810
  });
5297
5811
  } catch (err) {
5298
5812
  return attachDescriptor({
5813
+ success: false,
5814
+ isolated: true,
5815
+ skill: args.skill_name,
5816
+ code: err?.code || "CC_SKILL_ISOLATED_EXECUTION_FAILED",
5299
5817
  error: `Isolated skill execution failed: ${err.message}`,
5300
5818
  });
5301
5819
  }
5302
5820
  }
5303
5821
 
5304
- // Skill-Embedded MCP: mount the skill's declared MCP servers for
5305
- // the duration of handler.execute, then unmount in finally. The
5306
- // handler may use them via taskContext.mcpClient. If mcpClient is
5307
- // null (no MCP set up for this session), skip silently.
5308
- let mountedMcpServers = [];
5309
- const hasSkillMcps =
5310
- Array.isArray(match.mcpServers) && match.mcpServers.length > 0;
5311
- if (hasSkillMcps && mcpClient) {
5312
- try {
5313
- const mountResult = await mountSkillMcpServers(mcpClient, match, {
5314
- onWarn: (msg) => {
5315
- // Non-fatal — logged as warning, skipped servers captured
5316
- // in mountResult.skipped.
5317
-
5318
- console.warn(msg);
5319
- },
5320
- });
5321
- mountedMcpServers = mountResult.mounted;
5322
- for (const s of mountedMcpServers) {
5323
- _activeMcpServers.add(typeof s === "string" ? s : s.name);
5324
- }
5325
- } catch (err) {
5326
- return attachDescriptor({
5327
- error: `Skill MCP mount failed: ${err.message}`,
5328
- });
5329
- }
5330
- }
5331
-
5332
- try {
5333
- const handlerPath = path.join(match.skillDir, "handler.js");
5334
- const imported = await import(
5335
- `file://${handlerPath.replace(/\\/g, "/")}`
5336
- );
5337
- const handler = imported.default || imported;
5338
- if (handler.init) await handler.init(match);
5339
- const task = {
5340
- params: { input: args.input },
5341
- input: args.input,
5342
- action: args.input,
5343
- };
5344
- const taskContext = {
5345
- projectRoot: cwd,
5346
- workspacePath: cwd,
5347
- processBroker: createSkillProcessBroker(match),
5348
- // Expose the MCP client + mounted servers so the skill handler
5349
- // can call MCP tools directly without going through the agent
5350
- // loop. Handlers that don't need MCP can ignore these.
5351
- mcpClient: mcpClient || null,
5352
- mountedMcpServers,
5353
- };
5354
- const result = await handler.execute(task, taskContext, match);
5355
- return attachDescriptor(result);
5356
- } catch (err) {
5357
- return attachDescriptor({
5358
- error: `Skill execution failed: ${err.message}`,
5359
- });
5360
- } finally {
5361
- if (mountedMcpServers.length > 0 && mcpClient) {
5362
- try {
5363
- await unmountSkillMcpServers(mcpClient, mountedMcpServers);
5364
- } catch (_err) {
5365
- // Non-critical — mount/unmount errors don't fail the skill
5366
- }
5367
- for (const s of mountedMcpServers) {
5368
- _activeMcpServers.delete(typeof s === "string" ? s : s.name);
5369
- }
5370
- }
5371
- }
5822
+ // Defense in depth: materializeSkill currently rejects this path before
5823
+ // reaching here. Keep the runtime fence explicit so a custom/legacy
5824
+ // loader can never re-enable arbitrary handler.js imports in the CLI
5825
+ // process or hand a Skill the raw MCP client/process broker.
5826
+ return attachDescriptor({
5827
+ error: `Skill "${args.skill_name}" cannot execute handler.js directly. Add isolation: true and use the controlled agent-tool path.`,
5828
+ code: "CC_SKILL_DIRECT_HANDLER_BLOCKED",
5829
+ policy: { decision: "blocked", via: "skill-execution-boundary" },
5830
+ });
5372
5831
  }
5373
5832
 
5374
5833
  case "list_skills": {
@@ -5484,21 +5943,268 @@ async function executeToolInner(
5484
5943
  return attachDescriptor(deferredGate);
5485
5944
  }
5486
5945
 
5946
+ let mcpWireInput;
5487
5947
  try {
5488
- const result = await mcpClient.callTool(
5489
- localToolExecutor.serverName,
5490
- localToolExecutor.toolName,
5491
- args || {},
5948
+ mcpWireInput = snapshotMcpJsonRpcInput(args || {});
5949
+ } catch (error) {
5950
+ return attachDescriptor({
5951
+ error:
5952
+ "MCP tool blocked because its input is not strict immutable JSON data",
5953
+ policy: {
5954
+ decision: "blocked",
5955
+ via: "mcp-wire-input",
5956
+ code: safeMcpErrorCode(error, "CC_MCP_WIRE_INPUT_INVALID"),
5957
+ },
5958
+ });
5959
+ }
5960
+
5961
+ const schedulerScopes = mcpLedgerScopes(mcpWireInput);
5962
+ const ledgerEffectContract = mcpLedgerEffectContract(
5963
+ localToolDescriptor,
5964
+ hostToolPolicy,
5965
+ );
5966
+ const schedulerEffectContract = ledgerEffectContract.trusted
5967
+ ? createHostOwnedMcpEffectContract(ledgerEffectContract)
5968
+ : ledgerEffectContract;
5969
+ const scheduler =
5970
+ mcpConflictScheduler || directMcpConflictScheduler(mcpClient);
5971
+ let schedulerLease;
5972
+ try {
5973
+ schedulerLease = await scheduler.acquire(
5974
+ {
5975
+ effectContract: schedulerEffectContract,
5976
+ ...schedulerScopes,
5977
+ },
5978
+ { signal },
5492
5979
  );
5493
- if (result && typeof result === "object") {
5494
- return attachDescriptor(result);
5495
- }
5496
- return attachDescriptor({ result });
5497
5980
  } catch (err) {
5498
5981
  return attachDescriptor({
5499
- error: `MCP tool execution failed: ${err.message}`,
5982
+ error: `MCP tool blocked by the effect conflict scheduler: ${err.message}`,
5983
+ policy: {
5984
+ decision: "blocked",
5985
+ via: "mcp-conflict-scheduler",
5986
+ code: err?.code || null,
5987
+ },
5500
5988
  });
5501
5989
  }
5990
+
5991
+ try {
5992
+ const ledger = mcpCallLedger || createMcpCallLedger();
5993
+ let ledgerTicket;
5994
+ try {
5995
+ ledgerTicket = await ledger.begin({
5996
+ sessionId,
5997
+ turnId,
5998
+ toolName: localToolExecutor.toolName,
5999
+ serverName: localToolExecutor.serverName,
6000
+ input: mcpWireInput,
6001
+ effectContract: ledgerEffectContract,
6002
+ ...schedulerScopes,
6003
+ });
6004
+ } catch (err) {
6005
+ return attachDescriptor({
6006
+ error: `MCP tool blocked because its call ledger prewrite failed: ${err.message}`,
6007
+ policy: {
6008
+ decision: "blocked",
6009
+ via: "mcp-ledger-prewrite",
6010
+ code: err?.code || null,
6011
+ ledgerId: err?.ledgerId || null,
6012
+ effect: err?.effect || null,
6013
+ blockMode: err?.blockMode || null,
6014
+ },
6015
+ });
6016
+ }
6017
+
6018
+ const transportFailure = async (callError) => {
6019
+ if (mcpTransportOutcomeIsUnsafe(ledgerEffectContract)) {
6020
+ return attachDescriptor(
6021
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6022
+ phase: "call",
6023
+ reasonCode: MCP_TRANSPORT_OUTCOME_UNKNOWN_CODE,
6024
+ }),
6025
+ );
6026
+ }
6027
+ try {
6028
+ await ledgerTicket.settle({
6029
+ status: "failed",
6030
+ error: callError,
6031
+ });
6032
+ } catch (ledgerError) {
6033
+ return attachDescriptor(
6034
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6035
+ phase: "settled",
6036
+ reasonCode: safeMcpErrorCode(
6037
+ ledgerError,
6038
+ "CC_MCP_LEDGER_SETTLE_FAILED",
6039
+ ),
6040
+ }),
6041
+ );
6042
+ }
6043
+ return attachDescriptor({
6044
+ error: `MCP tool execution failed: ${safeMcpErrorMessage(callError)}`,
6045
+ mcpLedgerId: safeMcpProperty(ledgerTicket, "ledgerId") || null,
6046
+ });
6047
+ };
6048
+
6049
+ let pendingResult;
6050
+ try {
6051
+ pendingResult = Reflect.apply(mcpClient.callTool, mcpClient, [
6052
+ localToolExecutor.serverName,
6053
+ localToolExecutor.toolName,
6054
+ mcpWireInput,
6055
+ ]);
6056
+ } catch (callError) {
6057
+ return await transportFailure(callError);
6058
+ }
6059
+
6060
+ let result;
6061
+ if (
6062
+ pendingResult !== null &&
6063
+ (typeof pendingResult === "object" ||
6064
+ typeof pendingResult === "function")
6065
+ ) {
6066
+ if (isProxy(pendingResult)) {
6067
+ return attachDescriptor(
6068
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6069
+ phase: "result",
6070
+ reasonCode: MCP_PROTOCOL_RESULT_INVALID_CODE,
6071
+ }),
6072
+ );
6073
+ }
6074
+
6075
+ let nativePromise;
6076
+ try {
6077
+ nativePromise = pendingResult instanceof Promise;
6078
+ } catch (inspectionError) {
6079
+ return attachDescriptor(
6080
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6081
+ phase: "result",
6082
+ reasonCode: safeMcpErrorCode(
6083
+ invalidMcpProtocolResult(inspectionError),
6084
+ MCP_PROTOCOL_RESULT_INVALID_CODE,
6085
+ ),
6086
+ }),
6087
+ );
6088
+ }
6089
+
6090
+ if (nativePromise) {
6091
+ try {
6092
+ result = await pendingResult;
6093
+ } catch (callError) {
6094
+ return await transportFailure(callError);
6095
+ }
6096
+ } else {
6097
+ let then;
6098
+ try {
6099
+ then = Reflect.get(pendingResult, "then", pendingResult);
6100
+ } catch (inspectionError) {
6101
+ return attachDescriptor(
6102
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6103
+ phase: "result",
6104
+ reasonCode: safeMcpErrorCode(
6105
+ invalidMcpProtocolResult(inspectionError),
6106
+ MCP_PROTOCOL_RESULT_INVALID_CODE,
6107
+ ),
6108
+ }),
6109
+ );
6110
+ }
6111
+ if (typeof then === "function") {
6112
+ try {
6113
+ result = await new Promise((resolve, reject) => {
6114
+ try {
6115
+ Reflect.apply(then, pendingResult, [resolve, reject]);
6116
+ } catch (thenError) {
6117
+ reject(thenError);
6118
+ }
6119
+ });
6120
+ } catch (thenError) {
6121
+ return attachDescriptor(
6122
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6123
+ phase: "result",
6124
+ reasonCode: safeMcpErrorCode(
6125
+ invalidMcpProtocolResult(thenError),
6126
+ MCP_PROTOCOL_RESULT_INVALID_CODE,
6127
+ ),
6128
+ }),
6129
+ );
6130
+ }
6131
+ } else {
6132
+ result = pendingResult;
6133
+ }
6134
+ }
6135
+ } else {
6136
+ result = pendingResult;
6137
+ }
6138
+
6139
+ let protocolError;
6140
+ try {
6141
+ if (
6142
+ result !== null &&
6143
+ (typeof result === "object" || typeof result === "function") &&
6144
+ isProxy(result)
6145
+ ) {
6146
+ throw invalidMcpProtocolResult();
6147
+ }
6148
+ protocolError = result?.isError === true;
6149
+ } catch (inspectionError) {
6150
+ return attachDescriptor(
6151
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6152
+ phase: "result",
6153
+ reasonCode: safeMcpErrorCode(
6154
+ invalidMcpProtocolResult(inspectionError),
6155
+ MCP_PROTOCOL_RESULT_INVALID_CODE,
6156
+ ),
6157
+ }),
6158
+ );
6159
+ }
6160
+
6161
+ try {
6162
+ await ledgerTicket.settle(
6163
+ protocolError
6164
+ ? {
6165
+ status: "failed",
6166
+ output: result,
6167
+ error: new Error("MCP server returned isError=true"),
6168
+ }
6169
+ : { status: "completed", output: result },
6170
+ );
6171
+ } catch (ledgerError) {
6172
+ return attachDescriptor(
6173
+ mcpOutcomeUnknownPayload(ledger, ledgerTicket, {
6174
+ phase: "settled",
6175
+ reasonCode: safeMcpErrorCode(
6176
+ ledgerError,
6177
+ "CC_MCP_LEDGER_SETTLE_FAILED",
6178
+ ),
6179
+ }),
6180
+ );
6181
+ }
6182
+
6183
+ const mcpLedgerId = safeMcpProperty(ledgerTicket, "ledgerId") || null;
6184
+ try {
6185
+ if (result && typeof result === "object") {
6186
+ return attachDescriptor({ ...result, mcpLedgerId });
6187
+ }
6188
+ return attachDescriptor({ result, mcpLedgerId });
6189
+ } catch (projectionError) {
6190
+ return attachDescriptor({
6191
+ error:
6192
+ "MCP tool completed, but its result could not be projected safely; do not retry automatically.",
6193
+ code: MCP_RESULT_PROJECTION_FAILED_CODE,
6194
+ retryable: false,
6195
+ mcpLedgerId,
6196
+ mcpLedgerIncident: {
6197
+ phase: "result",
6198
+ code: safeMcpErrorCode(
6199
+ projectionError,
6200
+ MCP_RESULT_PROJECTION_FAILED_CODE,
6201
+ ),
6202
+ },
6203
+ });
6204
+ }
6205
+ } finally {
6206
+ schedulerLease.release();
6207
+ }
5502
6208
  }
5503
6209
 
5504
6210
  if (
@@ -6173,11 +6879,41 @@ function* _drainSubAgentUsage(sink) {
6173
6879
  provider: u?.provider ?? null,
6174
6880
  model: u?.model ?? null,
6175
6881
  usage: u?.usage || {},
6882
+ ...(u?.source ? { source: u.source } : {}),
6176
6883
  attribution: u?.attribution || null,
6177
6884
  };
6178
6885
  }
6179
6886
  }
6180
6887
 
6888
+ /**
6889
+ * Build the bounded, deterministic parent-to-child handoff used when callers
6890
+ * do not supply explicit context. Keeping the same nine-field schema as
6891
+ * semantic compaction prevents decisions, tests, and unresolved side effects
6892
+ * from disappearing merely because work crosses a sub-agent boundary.
6893
+ */
6894
+ export function buildSubAgentHandoffContext(messages) {
6895
+ if (!Array.isArray(messages)) return null;
6896
+ const canonicalMessages = projectCanonicalResumeMessages(messages);
6897
+ const hasContent = canonicalMessages.some((message) => {
6898
+ if (!message || !["user", "assistant", "tool"].includes(message.role)) {
6899
+ return false;
6900
+ }
6901
+ if (typeof message.content === "string") {
6902
+ return message.content.trim().length > 0;
6903
+ }
6904
+ return message.content != null;
6905
+ });
6906
+ if (!hasContent) return null;
6907
+
6908
+ const handoff = buildExtractiveHandoff(canonicalMessages, {
6909
+ maxContentChars: 6000,
6910
+ maxItemsPerField: 6,
6911
+ maxItemChars: 500,
6912
+ maxFallbackSourceChars: 16000,
6913
+ });
6914
+ return `[Structured parent handoff v1]\n${formatStructuredHandoff(handoff)}`;
6915
+ }
6916
+
6181
6917
  async function _executeSpawnSubAgent(args, ctx) {
6182
6918
  // Nesting cap: refuse before any context/registry work.
6183
6919
  const currentDepth = ctx.subAgentDepth || 0;
@@ -6201,8 +6937,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6201
6937
  hardChildrenCap: ctx.subAgentBudget?.max ?? MAX_SUB_AGENTS_PER_RUN,
6202
6938
  });
6203
6939
  if (!recur.ok) return { error: `spawn_sub_agent: ${recur.reason}` };
6204
- } catch {
6205
- /* contract module unavailable — hard caps above still apply */
6940
+ } catch (err) {
6941
+ return {
6942
+ error: `spawn_sub_agent: parent contract enforcement failed closed (${err.message}).`,
6943
+ };
6206
6944
  }
6207
6945
  }
6208
6946
  // Breadth cap: a shared counter (one object for the whole tree) bounds the
@@ -6225,9 +6963,20 @@ async function _executeSpawnSubAgent(args, ctx) {
6225
6963
  role,
6226
6964
  task,
6227
6965
  context: inheritedContext,
6966
+ contextMode,
6228
6967
  tools: explicitTools,
6229
6968
  profile: profileName,
6230
6969
  } = args;
6970
+ // Compatibility bridge for callers that used the original overloaded
6971
+ // `context: fresh|fork` authority spelling. An explicit `contextMode` always
6972
+ // wins and makes `context` unambiguously prompt text.
6973
+ const legacyContextMode =
6974
+ contextMode == null &&
6975
+ (inheritedContext === "fresh" || inheritedContext === "fork")
6976
+ ? inheritedContext
6977
+ : null;
6978
+ if (legacyContextMode) inheritedContext = null;
6979
+ const requestedContextMode = contextMode ?? legacyContextMode;
6231
6980
  // Extended sub-agent contract (gap 2026-07-11 P1): per-spawn deny-list,
6232
6981
  // iteration cap and worktree isolation — spawn args win over the agent
6233
6982
  // file's frontmatter defaults.
@@ -6294,7 +7043,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6294
7043
  // effort, context inheritance); this child's contract becomes the ceiling for
6295
7044
  // ITS own nested spawns (threaded via SubAgentContext.subAgentContract).
6296
7045
  let effectiveContract = null;
6297
- let explicitContext = null;
7046
+ let explicitContextMode = null;
6298
7047
  let skillAllowlist = null;
6299
7048
  // MCP-server + hook allow-lists for child INHERITANCE. Default `[]` = inherit
6300
7049
  // NONE, which equals today's behavior (a spawned child gets zero MCP tools /
@@ -6309,10 +7058,23 @@ async function _executeSpawnSubAgent(args, ctx) {
6309
7058
  // = byte-identical.
6310
7059
  let permModeDriven = false;
6311
7060
  try {
6312
- const { resolveSubagentContract, normalizeSubagentContract } =
6313
- await import("../lib/subagent-contract.js");
6314
- const spawnContract = normalizeSubagentContract(args);
6315
- explicitContext = spawnContract.context ?? mdContract?.context ?? null;
7061
+ const {
7062
+ resolveSubagentContract,
7063
+ normalizeSubagentContract,
7064
+ assertValidSubagentContract,
7065
+ } = await import("../lib/subagent-contract.js");
7066
+ // `context` predates the authority contract and remains arbitrary prompt
7067
+ // text except for the narrow legacy spelling handled above. Map the
7068
+ // separate contextMode field onto the contract's canonical `context` key.
7069
+ const authorityArgs = { ...args };
7070
+ delete authorityArgs.context;
7071
+ delete authorityArgs.contextMode;
7072
+ if (requestedContextMode != null) {
7073
+ authorityArgs.context = requestedContextMode;
7074
+ }
7075
+ assertValidSubagentContract(authorityArgs);
7076
+ const spawnContract = normalizeSubagentContract(authorityArgs);
7077
+ explicitContextMode = spawnContract.context ?? mdContract?.context ?? null;
6316
7078
  effectiveContract = resolveSubagentContract({
6317
7079
  parent: ctx.subAgentContract || {},
6318
7080
  definition: mdContract,
@@ -6332,7 +7094,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6332
7094
  const skillsDriven =
6333
7095
  spawnContract.skills != null ||
6334
7096
  mdContract?.skills != null ||
6335
- explicitContext != null;
7097
+ explicitContextMode != null;
6336
7098
  skillAllowlist = skillsDriven ? (effectiveContract.skills ?? null) : null;
6337
7099
  // MCP/hooks work the OTHER way from skills: their pre-inheritance default is
6338
7100
  // "none", so the silent-`fresh`→[] resolution IS the safe current behavior —
@@ -6340,12 +7102,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6340
7102
  // into inheriting the corresponding parent capabilities.
6341
7103
  mcpAllow = effectiveContract.mcpServers ?? null;
6342
7104
  hookAllow = effectiveContract.hooks ?? null;
6343
- } catch {
6344
- effectiveContract = null; // contract resolution is best-effort
6345
- skillAllowlist = null;
6346
- mcpAllow = []; // inherit no MCP / hooks when resolution fails
6347
- hookAllow = [];
6348
- permModeDriven = false; // no gate when resolution fails
7105
+ } catch (err) {
7106
+ return {
7107
+ error: `spawn_sub_agent: authority contract resolution failed closed (${err.message}).`,
7108
+ };
6349
7109
  }
6350
7110
 
6351
7111
  // Filter the parent loop's live MCP plumbing + settings hooks down to what the
@@ -6366,9 +7126,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6366
7126
  mcpAllow,
6367
7127
  );
6368
7128
  inheritedHooks = filterInheritedHooks(ctx.settingsHooks || null, hookAllow);
6369
- } catch {
6370
- inheritedMcp = null; // inheritance is best-effort; never break the spawn
6371
- inheritedHooks = null;
7129
+ } catch (err) {
7130
+ return {
7131
+ error: `spawn_sub_agent: capability inheritance failed closed (${err.message}).`,
7132
+ };
6372
7133
  }
6373
7134
 
6374
7135
  // Memory INHERITANCE (contract `memory` boolean, tighten-only across depth):
@@ -6395,8 +7156,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6395
7156
  available: isGitRepo(ctx.cwd),
6396
7157
  });
6397
7158
  if (!iso.ok) return { error: `spawn_sub_agent: ${iso.reason}` };
6398
- } catch {
6399
- /* helper unavailable — sub-agent-context.js still fails closed at run() */
7159
+ } catch (err) {
7160
+ return {
7161
+ error: `spawn_sub_agent: isolation enforcement failed closed (${err.message}).`,
7162
+ };
6400
7163
  }
6401
7164
  }
6402
7165
 
@@ -6413,8 +7176,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6413
7176
  error: `Unknown sub-agent profile: "${profileName}". Valid: explorer|executor|design`,
6414
7177
  };
6415
7178
  }
6416
- } catch (_err) {
6417
- // profile module optional — proceed without
7179
+ } catch (err) {
7180
+ return {
7181
+ error: `spawn_sub_agent: requested profile resolution failed closed (${err.message}).`,
7182
+ };
6418
7183
  }
6419
7184
  }
6420
7185
 
@@ -6436,6 +7201,16 @@ async function _executeSpawnSubAgent(args, ctx) {
6436
7201
  allowedTools = base.filter((t) => !deny.has(t));
6437
7202
  }
6438
7203
 
7204
+ // A child can never regain a tool omitted from the parent's effective schema.
7205
+ // `[]` remains deny-all all the way into the child's execution-time fence.
7206
+ if (Array.isArray(ctx.effectiveAllowedToolNames)) {
7207
+ const parentCeiling = new Set(ctx.effectiveAllowedToolNames);
7208
+ const requested = Array.isArray(allowedTools)
7209
+ ? allowedTools
7210
+ : [...parentCeiling];
7211
+ allowedTools = requested.filter((tool) => parentCeiling.has(tool));
7212
+ }
7213
+
6439
7214
  // permissionMode enforcement into the child gate. Reuses the runner's own
6440
7215
  // resolvers (single-sourced, no drift); best-effort so it never breaks a spawn.
6441
7216
  // • `plan` → clamp to the read-only tool set (same rule as resolveEnabledTools),
@@ -6484,27 +7259,23 @@ async function _executeSpawnSubAgent(args, ctx) {
6484
7259
  defaultPolicy: perm.sessionPolicy,
6485
7260
  });
6486
7261
  }
6487
- } catch {
6488
- // Enforcement is best-effort — never break the spawn.
7262
+ } catch (err) {
7263
+ return {
7264
+ error: `spawn_sub_agent: permission-mode enforcement failed closed (${err.message}).`,
7265
+ };
6489
7266
  }
6490
7267
  }
6491
7268
 
6492
- // Auto-condense parent context if caller didn't provide explicit context.
6493
- // An explicit `context: fresh` contract suppresses this inheritance (the
6494
- // child starts clean); `fork` / unset keep the existing auto-condense.
7269
+ // Build a structured parent handoff if the caller did not provide explicit
7270
+ // An explicit `contextMode: fresh` contract suppresses this inheritance (the
7271
+ // child starts clean); `fork` / unset keep deterministic auto-inheritance.
6495
7272
  let resolvedContext = inheritedContext || null;
6496
7273
  if (
6497
7274
  !resolvedContext &&
6498
- explicitContext !== "fresh" &&
7275
+ explicitContextMode !== "fresh" &&
6499
7276
  Array.isArray(ctx.parentMessages)
6500
7277
  ) {
6501
- const recentMsgs = ctx.parentMessages
6502
- .filter((m) => m.role === "assistant" && typeof m.content === "string")
6503
- .slice(-3)
6504
- .map((m) => m.content.substring(0, 200));
6505
- if (recentMsgs.length > 0) {
6506
- resolvedContext = recentMsgs.join("\n---\n");
6507
- }
7278
+ resolvedContext = buildSubAgentHandoffContext(ctx.parentMessages);
6508
7279
  }
6509
7280
 
6510
7281
  // Link child to parent session so registry-scoped queries and
@@ -6540,8 +7311,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6540
7311
  ? `${resolvedContext}\n---\n${injected}`
6541
7312
  : injected;
6542
7313
  }
6543
- } catch (_err) {
6544
- // SubagentStart hooks are best-effort — never break the spawn.
7314
+ } catch (err) {
7315
+ return {
7316
+ error: `spawn_sub_agent: SubagentStart authority hook failed closed (${err.message}).`,
7317
+ };
6545
7318
  }
6546
7319
  }
6547
7320
 
@@ -6575,6 +7348,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6575
7348
  provider: u?.provider ?? null,
6576
7349
  model: u?.model ?? null,
6577
7350
  usage: u?.usage || null,
7351
+ ...(u?.source ? { source: u.source } : {}),
6578
7352
  attribution: {
6579
7353
  origin: "subagent",
6580
7354
  subagentId: subCtxRef?.id || null,
@@ -6609,11 +7383,23 @@ async function _executeSpawnSubAgent(args, ctx) {
6609
7383
  if (sparse) wtOpts.sparsePaths = sparse;
6610
7384
  if (symlink != null) wtOpts.symlinkDirectories = symlink;
6611
7385
  if (Object.keys(wtOpts).length) subWorktreeOptions = wtOpts;
6612
- } catch {
6613
- subWorktreeOptions = null; // best-effort → full checkout on any error
7386
+ } catch (err) {
7387
+ return {
7388
+ error: `spawn_sub_agent: worktree scope resolution failed closed (${err.message}).`,
7389
+ };
6614
7390
  }
6615
7391
  }
6616
7392
 
7393
+ // Preserve host deny/policy metadata, but do not implicitly inherit hosted
7394
+ // external definitions. MCP/host capabilities enter the child only through
7395
+ // the explicit contract-filtered plumbing above.
7396
+ const childHostManagedToolPolicy = ctx.hostManagedToolPolicy
7397
+ ? { ...ctx.hostManagedToolPolicy, toolDefinitions: [] }
7398
+ : null;
7399
+ // A parent gate is already an authority ceiling. Prefer it over a newly
7400
+ // derived child gate so an explicit child mode can never relax the parent.
7401
+ const effectiveChildApprovalGate = ctx.approvalGate || childApprovalGate;
7402
+
6617
7403
  const subCtx = SubAgentContext.create({
6618
7404
  role,
6619
7405
  task,
@@ -6622,7 +7408,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6622
7408
  // and THIS run's id as parent_id on every settings-hook payload it fires.
6623
7409
  hookParentTraceId: ctx.hookTraceId || null,
6624
7410
  inheritedContext: resolvedContext,
6625
- allowedTools: allowedTools || null,
7411
+ allowedTools: allowedTools ?? null,
6626
7412
  cwd: ctx.cwd,
6627
7413
  profile: profile || null,
6628
7414
  llmOptions: subLlmOptions,
@@ -6630,6 +7416,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6630
7416
  // Same shared counter object so the child's own spawns draw from the run's
6631
7417
  // single total-sub-agent pool (breadth cap spans the whole tree).
6632
7418
  subAgentBudget: ctx.subAgentBudget || null,
7419
+ ...(ctx.sessionBudget ? { sessionBudget: ctx.sessionBudget } : {}),
6633
7420
  onUsage,
6634
7421
  // Extended contract (gap 2026-07-11): per-agent iteration cap + opt-in
6635
7422
  // worktree isolation. undefined keeps the profile/flag defaults intact.
@@ -6657,6 +7444,10 @@ async function _executeSpawnSubAgent(args, ctx) {
6657
7444
  externalToolDescriptors: inheritedMcp.externalToolDescriptors,
6658
7445
  externalToolExecutors: inheritedMcp.externalToolExecutors,
6659
7446
  mcpClient: inheritedMcp.mcpClient,
7447
+ ...(ctx.mcpCallLedger ? { mcpCallLedger: ctx.mcpCallLedger } : {}),
7448
+ ...(ctx.mcpConflictScheduler
7449
+ ? { mcpConflictScheduler: ctx.mcpConflictScheduler }
7450
+ : {}),
6660
7451
  }
6661
7452
  : {}),
6662
7453
  ...(inheritedHooks ? { settingsHooks: inheritedHooks } : {}),
@@ -6679,7 +7470,27 @@ async function _executeSpawnSubAgent(args, ctx) {
6679
7470
  // permissionMode ApprovalGate (2026-07-13): a dedicated confirmer-less gate
6680
7471
  // seeded with the mode's tier gates the child's run_shell / browser_act;
6681
7472
  // absent (ungated) for a plain default spawn = byte-identical.
6682
- ...(childApprovalGate ? { approvalGate: childApprovalGate } : {}),
7473
+ ...(effectiveChildApprovalGate
7474
+ ? { approvalGate: effectiveChildApprovalGate }
7475
+ : {}),
7476
+ // Parent execution authority is inherited as a tighten-only bundle and is
7477
+ // re-enforced by the child's executeTool path on every provider tool call.
7478
+ ...(ctx.permissionRules ? { permissionRules: ctx.permissionRules } : {}),
7479
+ ...(childHostManagedToolPolicy
7480
+ ? { hostManagedToolPolicy: childHostManagedToolPolicy }
7481
+ : {}),
7482
+ ...(ctx.planManager ? { planManager: ctx.planManager } : {}),
7483
+ ...(ctx.sandbox ? { sandbox: ctx.sandbox } : {}),
7484
+ ...(Array.isArray(ctx.additionalDirectories)
7485
+ ? { additionalDirectories: [...ctx.additionalDirectories] }
7486
+ : {}),
7487
+ ...(ctx.shellPolicyOverrides
7488
+ ? { shellPolicyOverrides: ctx.shellPolicyOverrides }
7489
+ : {}),
7490
+ ...(ctx.classifyAllShell ? { classifyAllShell: true } : {}),
7491
+ ...(ctx.unattendedActionPolicy
7492
+ ? { unattendedActionPolicy: ctx.unattendedActionPolicy }
7493
+ : {}),
6683
7494
  ...(ctx.toolAdmission ? { toolAdmission: ctx.toolAdmission } : {}),
6684
7495
  });
6685
7496
  subCtxRef = subCtx;
@@ -6760,7 +7571,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6760
7571
  emit("sub-agent.started", {
6761
7572
  task: subCtx.task,
6762
7573
  background: true,
6763
- allowedTools: allowedTools || null,
7574
+ allowedTools: allowedTools ?? null,
6764
7575
  maxIterations: subCtx.maxIterations,
6765
7576
  createdAt: subCtx.createdAt,
6766
7577
  });
@@ -6837,7 +7648,7 @@ async function _executeSpawnSubAgent(args, ctx) {
6837
7648
 
6838
7649
  emit("sub-agent.started", {
6839
7650
  task: subCtx.task,
6840
- allowedTools: allowedTools || null,
7651
+ allowedTools: allowedTools ?? null,
6841
7652
  maxIterations: subCtx.maxIterations,
6842
7653
  createdAt: subCtx.createdAt,
6843
7654
  });
@@ -6853,6 +7664,24 @@ async function _executeSpawnSubAgent(args, ctx) {
6853
7664
  }
6854
7665
  }
6855
7666
 
7667
+ if (result?.budgetReason) {
7668
+ emit("sub-agent.failed", {
7669
+ status: subCtx.status,
7670
+ error: result.summary,
7671
+ budgetReason: result.budgetReason,
7672
+ completedAt: subCtx.completedAt,
7673
+ });
7674
+ return {
7675
+ error: result.summary,
7676
+ code: "ERR_SESSION_RESOURCE_BUDGET",
7677
+ budgetReason: result.budgetReason,
7678
+ subAgentId: subCtx.id,
7679
+ role: subCtx.role,
7680
+ parentSessionId,
7681
+ childBinding: subCtx.recoveryBinding(result),
7682
+ };
7683
+ }
7684
+
6856
7685
  emit("sub-agent.completed", {
6857
7686
  status: subCtx.status,
6858
7687
  summary: result.summary,
@@ -6907,6 +7736,26 @@ async function _executeSpawnSubAgent(args, ctx) {
6907
7736
 
6908
7737
  // ─── LLM chat with tools ─────────────────────────────────────────────────
6909
7738
 
7739
+ function getEffectiveToolDefinitions(options = {}) {
7740
+ const persona = _loadProjectPersona(options.cwd);
7741
+ // Merge every deny source before both schema projection and execution-time
7742
+ // enforcement. Keeping this in one helper prevents those two fences from
7743
+ // drifting apart.
7744
+ const mergedDisabledTools = [
7745
+ ...(Array.isArray(persona?.toolsDisabled) ? persona.toolsDisabled : []),
7746
+ ...(Array.isArray(options.disabledTools) ? options.disabledTools : []),
7747
+ ];
7748
+ return getAgentToolDefinitions({
7749
+ names: options.enabledToolNames,
7750
+ disabledTools: mergedDisabledTools,
7751
+ exactToolNames: options.exactToolNames === true,
7752
+ extraTools: [
7753
+ ...(options.hostManagedToolPolicy?.toolDefinitions || []),
7754
+ ...(options.extraToolDefinitions || []),
7755
+ ],
7756
+ });
7757
+ }
7758
+
6910
7759
  /**
6911
7760
  * Send a chat completion request with tool definitions.
6912
7761
  * Supports 8 providers: ollama, anthropic, openai, deepseek, dashscope, gemini, mistral, volcengine
@@ -6925,22 +7774,7 @@ export async function chatWithTools(rawMessages, options) {
6925
7774
  signal,
6926
7775
  } = options;
6927
7776
 
6928
- const persona = _loadProjectPersona(options.cwd);
6929
- // Merge the project-persona deny-list with any caller-supplied deny-list
6930
- // (e.g. headless `--disallowed-tools`). Without this merge the caller's
6931
- // deny-list is silently dropped and the tool stays callable.
6932
- const mergedDisabledTools = [
6933
- ...(Array.isArray(persona?.toolsDisabled) ? persona.toolsDisabled : []),
6934
- ...(Array.isArray(options.disabledTools) ? options.disabledTools : []),
6935
- ];
6936
- const tools = getAgentToolDefinitions({
6937
- names: options.enabledToolNames,
6938
- disabledTools: mergedDisabledTools,
6939
- extraTools: [
6940
- ...(options.hostManagedToolPolicy?.toolDefinitions || []),
6941
- ...(options.extraToolDefinitions || []),
6942
- ],
6943
- });
7777
+ const tools = getEffectiveToolDefinitions(options);
6944
7778
 
6945
7779
  const lastUserMsg = [...rawMessages].reverse().find((m) => m.role === "user");
6946
7780
  const messages = ce
@@ -6969,7 +7803,14 @@ export async function chatWithTools(rawMessages, options) {
6969
7803
  () =>
6970
7804
  _chatOllamaStreaming(
6971
7805
  apiUrl,
6972
- { model, messages: ollamaMessages, tools },
7806
+ {
7807
+ model,
7808
+ messages: ollamaMessages,
7809
+ tools,
7810
+ ...(options.maxOutputTokens
7811
+ ? { options: { num_predict: options.maxOutputTokens } }
7812
+ : {}),
7813
+ },
6973
7814
  options.onToken,
6974
7815
  signal,
6975
7816
  options.onStall,
@@ -6996,6 +7837,9 @@ export async function chatWithTools(rawMessages, options) {
6996
7837
  messages: ollamaMessages,
6997
7838
  tools,
6998
7839
  stream: false,
7840
+ ...(options.maxOutputTokens
7841
+ ? { options: { num_predict: options.maxOutputTokens } }
7842
+ : {}),
6999
7843
  }),
7000
7844
  });
7001
7845
  if (!response.ok) {
@@ -7054,7 +7898,9 @@ export async function chatWithTools(rawMessages, options) {
7054
7898
  );
7055
7899
  const body = {
7056
7900
  model: effModel,
7057
- max_tokens: anthropicMaxTokens || 8192,
7901
+ max_tokens: options.maxOutputTokens
7902
+ ? Math.min(anthropicMaxTokens || 8192, options.maxOutputTokens)
7903
+ : anthropicMaxTokens || 8192,
7058
7904
  // Convert cc's internal OpenAI-shaped history (role:"tool" results,
7059
7905
  // assistant tool_calls[]) into Anthropic content blocks. Without this,
7060
7906
  // multi-turn tool use 400s on turn 2 (Anthropic rejects role:"tool" and
@@ -7213,6 +8059,9 @@ export async function chatWithTools(rawMessages, options) {
7213
8059
  tools,
7214
8060
  stream: true,
7215
8061
  stream_options: { include_usage: true },
8062
+ ...(options.maxOutputTokens
8063
+ ? { max_tokens: options.maxOutputTokens }
8064
+ : {}),
7216
8065
  },
7217
8066
  key,
7218
8067
  options.onToken,
@@ -7245,6 +8094,9 @@ export async function chatWithTools(rawMessages, options) {
7245
8094
  model: model || defaultModels[provider] || "gpt-4o-mini",
7246
8095
  messages,
7247
8096
  tools,
8097
+ ...(options.maxOutputTokens
8098
+ ? { max_tokens: options.maxOutputTokens }
8099
+ : {}),
7248
8100
  }),
7249
8101
  });
7250
8102
 
@@ -8172,6 +9024,55 @@ async function _autoCheckpointBeforeTool(toolContext, toolName, toolArgs) {
8172
9024
  }
8173
9025
  }
8174
9026
 
9027
+ function _managedCheckpointUncoveredWriterReason(toolContext) {
9028
+ if (
9029
+ Array.isArray(toolContext?.additionalDirectories) &&
9030
+ toolContext.additionalDirectories.length > 0
9031
+ ) {
9032
+ return "additional_workspace_roots_not_transactional";
9033
+ }
9034
+ if (
9035
+ toolContext?.mcpClient?.servers instanceof Map &&
9036
+ toolContext.mcpClient.servers.size > 0
9037
+ ) {
9038
+ return "ambient_mcp_server_writer_not_quiescent";
9039
+ }
9040
+ const workspaceRoot = path.resolve(toolContext?.cwd || process.cwd());
9041
+ const hasOverlappingCodeIntel = [..._codeIntelPool.keys()].some(
9042
+ (candidate) => {
9043
+ const lspRoot = path.resolve(candidate);
9044
+ const workspaceToLsp = path.relative(workspaceRoot, lspRoot);
9045
+ const lspToWorkspace = path.relative(lspRoot, workspaceRoot);
9046
+ const isInside = (relative) =>
9047
+ relative === "" ||
9048
+ (relative !== ".." &&
9049
+ !relative.startsWith(`..${path.sep}`) &&
9050
+ !path.isAbsolute(relative));
9051
+ return isInside(workspaceToLsp) || isInside(lspToWorkspace);
9052
+ },
9053
+ );
9054
+ if (hasOverlappingCodeIntel) {
9055
+ return "ambient_lsp_writer_not_quiescent";
9056
+ }
9057
+ if (
9058
+ [..._backgroundShellTasks.values()].some(
9059
+ (task) => task?.status === "running",
9060
+ )
9061
+ ) {
9062
+ return "ambient_background_shell_writer_not_quiescent";
9063
+ }
9064
+ if (
9065
+ toolContext?.backgroundSubAgents instanceof Map &&
9066
+ toolContext.backgroundSubAgents.size > 0
9067
+ ) {
9068
+ return "ambient_background_agent_writer_not_quiescent";
9069
+ }
9070
+ if (toolContext?.hookSupervisor && toolContext?.settingsHooks) {
9071
+ return "asynchronous_hook_writer_not_quiescent";
9072
+ }
9073
+ return null;
9074
+ }
9075
+
8175
9076
  /**
8176
9077
  * Async generator that drives the agentic tool-use loop.
8177
9078
  *
@@ -8201,9 +9102,45 @@ async function _getAutoCompactor(options) {
8201
9102
  if (feature("PROMPT_COMPRESSOR")) {
8202
9103
  const { PromptCompressor } =
8203
9104
  await import("../harness/prompt-compressor.js");
9105
+ const llmQuery =
9106
+ typeof options.compactionLlmQuery === "function"
9107
+ ? options.compactionLlmQuery
9108
+ : options.chatFn
9109
+ ? null
9110
+ : async (prompt) => {
9111
+ const maxOutputTokens = Math.min(
9112
+ 4096,
9113
+ Math.max(
9114
+ 256,
9115
+ Number(options.compactionMaxOutputTokens) || 2048,
9116
+ ),
9117
+ );
9118
+ const response = await chatWithTools(
9119
+ [{ role: "user", content: prompt }],
9120
+ {
9121
+ ...options,
9122
+ contextEngine: null,
9123
+ enabledToolNames: [],
9124
+ extraToolDefinitions: [],
9125
+ hostManagedToolPolicy: null,
9126
+ onToken: undefined,
9127
+ onStall: undefined,
9128
+ onStreamRetry: undefined,
9129
+ maxOutputTokens,
9130
+ },
9131
+ );
9132
+ return {
9133
+ summary: response?.message?.content || "",
9134
+ usage: response?.usage || null,
9135
+ provider: options.provider || null,
9136
+ model: options.model || null,
9137
+ };
9138
+ };
8204
9139
  compressor = new PromptCompressor({
8205
9140
  model: options.model,
8206
9141
  provider: options.provider,
9142
+ llmQuery,
9143
+ summaryInputMaxChars: options.compactionInputMaxChars,
8207
9144
  });
8208
9145
  }
8209
9146
  } catch {
@@ -8217,6 +9154,21 @@ async function _getAutoCompactor(options) {
8217
9154
  return compressor;
8218
9155
  }
8219
9156
 
9157
+ function _compactionTokenUsage(stats) {
9158
+ const summaryUsage = stats?.summaryUsage;
9159
+ if (!summaryUsage || typeof summaryUsage !== "object") return null;
9160
+ const tokenCount = (value) => {
9161
+ const number = Number(value);
9162
+ return Number.isFinite(number) && number > 0 ? Math.trunc(number) : 0;
9163
+ };
9164
+ return {
9165
+ input_tokens: tokenCount(summaryUsage.inputTokens),
9166
+ output_tokens: tokenCount(summaryUsage.outputTokens),
9167
+ cache_read_input_tokens: tokenCount(summaryUsage.cacheReadTokens),
9168
+ cache_creation_input_tokens: tokenCount(summaryUsage.cacheCreationTokens),
9169
+ };
9170
+ }
9171
+
8220
9172
  /**
8221
9173
  * Run `fn` inside an OpenTelemetry span when `options.recorder` is attached,
8222
9174
  * else run it bare (zero overhead on the un-instrumented path). `onResult`
@@ -8324,6 +9276,15 @@ export async function* agentLoop(messages, options) {
8324
9276
  options.runId ||
8325
9277
  `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8326
9278
 
9279
+ const effectiveAllowedToolNames = Object.freeze(
9280
+ getEffectiveToolDefinitions(options).map((tool) => tool.function.name),
9281
+ );
9282
+ const mcpCallLedger =
9283
+ options.mcpCallLedger ||
9284
+ createMcpCallLedger({ sink: options.mcpLedgerSink || null });
9285
+ const mcpConflictScheduler =
9286
+ options.mcpConflictScheduler || createMcpConflictScheduler();
9287
+
8327
9288
  const toolContext = {
8328
9289
  hookDb: options.hookDb || null,
8329
9290
  skillLoader: options.skillLoader || _defaultSkillLoader,
@@ -8338,6 +9299,7 @@ export async function* agentLoop(messages, options) {
8338
9299
  // unrestricted; [] = none; a list restricts run_skill/list_skills to those
8339
9300
  // ids/dirNames. Set by the spawn path from the resolved subagent contract.
8340
9301
  skillAllowlist: options.skillAllowlist ?? null,
9302
+ effectiveAllowedToolNames,
8341
9303
  cwd: options.cwd || process.cwd(),
8342
9304
  planManager: options.planManager || null,
8343
9305
  sessionId: options.sessionId || null,
@@ -8359,6 +9321,14 @@ export async function* agentLoop(messages, options) {
8359
9321
  // contract's mcpServers allow-list). Otherwise consumed only at agentLoop.
8360
9322
  extraToolDefinitions: options.extraToolDefinitions || null,
8361
9323
  mcpClient: options.mcpClient || null,
9324
+ mcpHostClient: options.mcpHostClient || options.mcpClient || null,
9325
+ mcpCallLedger,
9326
+ mcpConflictScheduler,
9327
+ // A loop-local identity prevents one session's lazy instruction commits
9328
+ // from suppressing first-access delivery in another session at the same
9329
+ // cwd. Hosts may inject a stable identity across resumed turns.
9330
+ subtreeInstructionScope:
9331
+ options.subtreeInstructionScope || options.sessionId || Symbol(runId),
8362
9332
  // Parent memory source — a spawn can inherit the parent's hierarchical
8363
9333
  // memory DB into the child ONLY when the resolved contract grants memory
8364
9334
  // (context:fork from a memory-bearing parent, or explicit memory:true).
@@ -8399,6 +9369,13 @@ export async function* agentLoop(messages, options) {
8399
9369
  autoCheckpoint: options.autoCheckpoint || false,
8400
9370
  checkpointSession:
8401
9371
  options.checkpointSession || options.sessionId || "agent",
9372
+ managedCheckpoint: options.managedCheckpoint === true,
9373
+ managedCheckpointStateDir: options.managedCheckpointStateDir || null,
9374
+ managedCheckpointExclusions: Array.isArray(
9375
+ options.managedCheckpointExclusions,
9376
+ )
9377
+ ? [...options.managedCheckpointExclusions]
9378
+ : [],
8402
9379
  // Sub-agent nesting level (0 = main loop); spawn_sub_agent caps at
8403
9380
  // MAX_SUB_AGENT_DEPTH using this.
8404
9381
  subAgentDepth: options.subAgentDepth || 0,
@@ -8409,6 +9386,10 @@ export async function* agentLoop(messages, options) {
8409
9386
  spawned: 0,
8410
9387
  max: MAX_SUB_AGENTS_PER_RUN,
8411
9388
  },
9389
+ // Optional local adapter for a host-created SessionResourceBudget. The
9390
+ // CLI root does not create one yet; when supplied, every nested child sees
9391
+ // the same object and cannot reset concurrency/spawn/depth totals.
9392
+ sessionBudget: options.sessionBudget || null,
8412
9393
  // This loop's EFFECTIVE subagent contract (set when this loop IS a spawned
8413
9394
  // sub-agent). Threaded so a nested spawn_sub_agent sees it as the parent
8414
9395
  // ceiling (tighten-only). null at the top level (no ceiling).
@@ -8511,7 +9492,7 @@ export async function* agentLoop(messages, options) {
8511
9492
  // line) when provided; otherwise fall back to a clear stderr notice.
8512
9493
  const message =
8513
9494
  reason === "env-key"
8514
- ? `"${from}" 鉴权失败,已临时切换到不同厂商 "${to}"(请检查 ${from} 的 API key:cc config set llm.apiKey …)。`
9495
+ ? `"${from}" 鉴权失败,已临时切换到不同厂商 "${to}"(请检查 ${from} 的 API key:cc config set-secret llm.apiKey)。`
8515
9496
  : reason === "model-mismatch"
8516
9497
  ? `模型 "${fromModel}" 不属于 ${from},已改用其默认模型 "${toModel}"(用 cc config set llm.model 设置正确的 ${from} 模型)。`
8517
9498
  : `provider 配置与 baseUrl 不一致,已按 baseUrl 切换到 "${to}"。`;
@@ -8692,6 +9673,16 @@ export async function* agentLoop(messages, options) {
8692
9673
  preserveToolPairs: true,
8693
9674
  ...pinOpts,
8694
9675
  });
9676
+ const compactionUsage = _compactionTokenUsage(stats);
9677
+ if (stats.degraded === true) {
9678
+ yield {
9679
+ type: "compaction-degraded",
9680
+ runId,
9681
+ reason: stats.degradedReason || "semantic-summary-degraded",
9682
+ summaryMode: stats.summaryMode || "extractive-fallback",
9683
+ stats,
9684
+ };
9685
+ }
8695
9686
  if (stats.saved > 0 && compacted.length < messages.length) {
8696
9687
  messages.splice(0, messages.length, ...compacted);
8697
9688
  // Persist the compaction so a later --resume rebuilds from the
@@ -8733,10 +9724,31 @@ export async function* agentLoop(messages, options) {
8733
9724
  });
8734
9725
  yield { type: "compaction", stats, runId };
8735
9726
  }
9727
+ if (compactionUsage) {
9728
+ // PromptCompressor calls the provider directly, outside the main
9729
+ // chat request. Apply/persist the resulting compaction and surface
9730
+ // any degraded fallback before yielding billable usage: a
9731
+ // headless consumer may stop the generator as soon as its cost cap
9732
+ // is exceeded. Usage still arrives exactly once and before the
9733
+ // next model call, without entering the normal response path.
9734
+ yield {
9735
+ type: "token-usage",
9736
+ provider: stats.summaryProvider || options.provider || null,
9737
+ model: stats.summaryModel || options.model || null,
9738
+ usage: compactionUsage,
9739
+ source: "semantic-compaction",
9740
+ runId,
9741
+ };
9742
+ }
8736
9743
  }
8737
9744
  } catch (_e) {
8738
9745
  if (isAbortError(_e) || signal?.aborted) throw _e;
8739
- // Compaction is best-effort — proceed with the uncompacted messages.
9746
+ yield {
9747
+ type: "compaction-degraded",
9748
+ runId,
9749
+ reason: `compaction_failed:${_e?.message || String(_e)}`,
9750
+ summaryMode: "none",
9751
+ };
8740
9752
  }
8741
9753
  }
8742
9754
 
@@ -9230,136 +10242,307 @@ export async function* agentLoop(messages, options) {
9230
10242
  turn_id: `${runId}:t${budget.consumed}`,
9231
10243
  };
9232
10244
 
9233
- yield {
9234
- type: "tool-executing",
9235
- tool: toolName,
9236
- args: toolArgs,
9237
- tool_use_id: call.id,
9238
- turn_id: `${runId}:t${budget.consumed}`,
9239
- };
10245
+ let managedCheckpointHandle = null;
10246
+ let managedCheckpointPreparationError = null;
10247
+ try {
10248
+ managedCheckpointHandle = beginManagedToolCheckpoint({
10249
+ enabled: toolContext.managedCheckpoint === true,
10250
+ broker,
10251
+ workspaceRoot: toolContext.cwd || process.cwd(),
10252
+ stateDir: toolContext.managedCheckpointStateDir || undefined,
10253
+ runId,
10254
+ taskKey: `${runId}:t${budget.consumed}:${call.id}:${toolName}`,
10255
+ toolName,
10256
+ toolArgs,
10257
+ externalToolExecutor:
10258
+ toolContext.externalToolExecutors?.[toolName] || null,
10259
+ unmanagedWriterReason:
10260
+ _managedCheckpointUncoveredWriterReason(toolContext),
10261
+ exclusions: toolContext.managedCheckpointExclusions || [],
10262
+ });
10263
+ } catch (error) {
10264
+ managedCheckpointPreparationError = error;
10265
+ yield {
10266
+ type: "managed-checkpoint-error",
10267
+ phase: "prepare",
10268
+ tool: toolName,
10269
+ error: error.message,
10270
+ code: error.code || null,
10271
+ coverage: "none",
10272
+ tool_use_id: call.id,
10273
+ turn_id: `${runId}:t${budget.consumed}`,
10274
+ };
10275
+ }
10276
+ let managedCheckpointSettled = managedCheckpointHandle?.skipped === true;
10277
+ let managedCheckpointSettlementAttempted = false;
10278
+ try {
10279
+ if (managedCheckpointHandle) {
10280
+ yield {
10281
+ type: "managed-checkpoint",
10282
+ phase: managedCheckpointHandle.skipped ? "unavailable" : "prepared",
10283
+ id: managedCheckpointHandle.checkpointId || null,
10284
+ transaction_id: managedCheckpointHandle.transactionId || null,
10285
+ tool: toolName,
10286
+ coverage: managedCheckpointHandle.skipped
10287
+ ? managedCheckpointHandle.coverage
10288
+ : managedCheckpointHandle.prepared?.coverage || "partial",
10289
+ reason: managedCheckpointHandle.reason || null,
10290
+ tool_use_id: call.id,
10291
+ turn_id: `${runId}:t${budget.consumed}`,
10292
+ };
10293
+ }
9240
10294
 
9241
- let toolResult;
9242
- let toolError = null;
9243
- // Per-span unified ids (P2 observability): a tool span carries its turn.id
9244
- // (correlating with the model span of the same iteration), the provider's
9245
- // tool_use.id (so a tool-result event can be tied back to its call), and —
9246
- // when auto-checkpoint fired before a mutating tool — the checkpoint.id the
9247
- // user could restore to. All normalized through buildTelemetryAttributes.
9248
- // tool_arguments CONTENT is opt-in (--otlp-content): the alias key is only
9249
- // present when explicitly enabled, so by default the field is omitted
9250
- // entirely (byte-identical default OTLP), and even opted-in it's length-
9251
- // capped by redactContent. Mirrors the run-level content.prompt opt-in.
9252
- const toolContentOptIn = options.otlpIncludeContent === true;
9253
- const toolIdAttrs = recorder
9254
- ? buildTelemetryAttributes(
9255
- {
9256
- turnId: `${runId}:t${budget.consumed}`,
9257
- toolUseId: call.id,
9258
- checkpointId: cpId || undefined,
9259
- ...(toolContentOptIn ? { toolArguments: toolArgs } : {}),
10295
+ // A preparation failure is a strict admission failure: the tool never
10296
+ // starts, so do not emit the observationally stronger `tool-executing`
10297
+ // event. Consumers use that event to bind hooks, telemetry and turns to
10298
+ // an actual invocation.
10299
+ if (!managedCheckpointPreparationError) {
10300
+ yield {
10301
+ type: "tool-executing",
10302
+ tool: toolName,
10303
+ args: toolArgs,
10304
+ tool_use_id: call.id,
10305
+ turn_id: `${runId}:t${budget.consumed}`,
10306
+ };
10307
+ }
10308
+
10309
+ let toolResult;
10310
+ let toolError = null;
10311
+ // Per-span unified ids (P2 observability): a tool span carries its turn.id
10312
+ // (correlating with the model span of the same iteration), the provider's
10313
+ // tool_use.id (so a tool-result event can be tied back to its call), and —
10314
+ // when auto-checkpoint fired before a mutating tool — the checkpoint.id the
10315
+ // user could restore to. All normalized through buildTelemetryAttributes.
10316
+ // tool_arguments CONTENT is opt-in (--otlp-content): the alias key is only
10317
+ // present when explicitly enabled, so by default the field is omitted
10318
+ // entirely (byte-identical default OTLP), and even opted-in it's length-
10319
+ // capped by redactContent. Mirrors the run-level content.prompt opt-in.
10320
+ const toolContentOptIn = options.otlpIncludeContent === true;
10321
+ const toolIdAttrs = recorder
10322
+ ? buildTelemetryAttributes(
10323
+ {
10324
+ turnId: `${runId}:t${budget.consumed}`,
10325
+ toolUseId: call.id,
10326
+ checkpointId: cpId || undefined,
10327
+ ...(toolContentOptIn ? { toolArguments: toolArgs } : {}),
10328
+ },
10329
+ { includeContent: toolContentOptIn },
10330
+ )
10331
+ : null;
10332
+ if (managedCheckpointPreparationError) {
10333
+ toolError = managedCheckpointPreparationError.message;
10334
+ toolResult = {
10335
+ error: `[Managed checkpoint] Preparation failed; "${toolName}" was blocked before execution: ${managedCheckpointPreparationError.message}`,
10336
+ managedCheckpoint: {
10337
+ status: "not_started",
10338
+ coverage: "none",
10339
+ code: managedCheckpointPreparationError.code || null,
9260
10340
  },
9261
- { includeContent: toolContentOptIn },
9262
- )
9263
- : null;
9264
- try {
9265
- toolResult = await _withSpan(
9266
- recorder,
9267
- "agent.tool",
9268
- { "tool.name": toolName, ...(toolIdAttrs || {}) },
9269
- () =>
9270
- executeTool(toolName, toolArgs, {
9271
- ...toolContext,
9272
- toolCallId: call.id,
9273
- turnId: `${runId}:t${budget.consumed}`,
9274
- }),
9275
- (span, r) => {
9276
- span.setAttribute(
9277
- "tool.is_error",
9278
- !!(r && typeof r === "object" && r.error),
9279
- );
9280
- // permission.decision_id (P2): a GATED tool result carries a
9281
- // `policy` (deny / ask-fail / host-block / sandbox); allow-path
9282
- // tools execute with no distinct decision. Stamp a stable id
9283
- // (derived from the call + gate, so it's recomputable from the
9284
- // tool-result's policy + tool_call_id) plus the low-cardinality
9285
- // decision, letting a blocked tool span be tied to its decision.
9286
- const decision =
9287
- r && typeof r === "object"
9288
- ? permissionDecision(call.id, toolName, r)
9289
- : null;
9290
- if (decision?.id) {
9291
- const permAttrs = buildTelemetryAttributes({
9292
- decisionId: decision.id,
9293
- "permission.decision": decision.decision,
9294
- });
9295
- if (permAttrs["permission.decision_id"]) {
9296
- span.setAttribute(
9297
- "permission.decision_id",
9298
- permAttrs["permission.decision_id"],
9299
- );
9300
- }
9301
- if (permAttrs["permission.decision"]) {
10341
+ };
10342
+ } else {
10343
+ try {
10344
+ toolResult = await _withSpan(
10345
+ recorder,
10346
+ "agent.tool",
10347
+ { "tool.name": toolName, ...(toolIdAttrs || {}) },
10348
+ () =>
10349
+ executeTool(toolName, toolArgs, {
10350
+ ...toolContext,
10351
+ toolCallId: call.id,
10352
+ turnId: `${runId}:t${budget.consumed}`,
10353
+ }),
10354
+ (span, r) => {
9302
10355
  span.setAttribute(
9303
- "permission.decision",
9304
- permAttrs["permission.decision"],
10356
+ "tool.is_error",
10357
+ !!(r && typeof r === "object" && r.error),
9305
10358
  );
9306
- }
10359
+ // permission.decision_id (P2): a GATED tool result carries a
10360
+ // `policy` (deny / ask-fail / host-block / sandbox); allow-path
10361
+ // tools execute with no distinct decision. Stamp a stable id
10362
+ // (derived from the call + gate, so it's recomputable from the
10363
+ // tool-result's policy + tool_call_id) plus the low-cardinality
10364
+ // decision, letting a blocked tool span be tied to its decision.
10365
+ const decision =
10366
+ r && typeof r === "object"
10367
+ ? permissionDecision(call.id, toolName, r)
10368
+ : null;
10369
+ if (decision?.id) {
10370
+ const permAttrs = buildTelemetryAttributes({
10371
+ decisionId: decision.id,
10372
+ "permission.decision": decision.decision,
10373
+ });
10374
+ if (permAttrs["permission.decision_id"]) {
10375
+ span.setAttribute(
10376
+ "permission.decision_id",
10377
+ permAttrs["permission.decision_id"],
10378
+ );
10379
+ }
10380
+ if (permAttrs["permission.decision"]) {
10381
+ span.setAttribute(
10382
+ "permission.decision",
10383
+ permAttrs["permission.decision"],
10384
+ );
10385
+ }
10386
+ }
10387
+ },
10388
+ "tool_error",
10389
+ );
10390
+ } catch (err) {
10391
+ toolResult = { error: err.message };
10392
+ toolError = err.message;
10393
+ }
10394
+ }
10395
+ if (recorder) recorder.counter("agent.tool.calls", 1);
10396
+
10397
+ if (managedCheckpointHandle) {
10398
+ const interrupted = signal?.aborted === true;
10399
+ const toolSucceeded =
10400
+ !interrupted &&
10401
+ !toolError &&
10402
+ !(toolResult && typeof toolResult === "object" && toolResult.error);
10403
+ try {
10404
+ managedCheckpointSettlementAttempted = true;
10405
+ const managedCheckpoint = settleManagedToolCheckpoint(
10406
+ managedCheckpointHandle,
10407
+ {
10408
+ success: toolSucceeded,
10409
+ reason: interrupted
10410
+ ? "agent tool interrupted"
10411
+ : toolError ||
10412
+ (toolResult && typeof toolResult === "object"
10413
+ ? toolResult.error
10414
+ : null) ||
10415
+ "agent tool failed",
10416
+ },
10417
+ );
10418
+ managedCheckpointSettled = true;
10419
+ if (toolResult && typeof toolResult === "object") {
10420
+ toolResult.managedCheckpoint = managedCheckpoint;
9307
10421
  }
9308
- },
9309
- "tool_error",
9310
- );
9311
- } catch (err) {
9312
- toolResult = { error: err.message };
9313
- toolError = err.message;
9314
- }
9315
- if (recorder) recorder.counter("agent.tool.calls", 1);
10422
+ yield {
10423
+ type: "managed-checkpoint-settled",
10424
+ phase: managedCheckpoint?.skipped
10425
+ ? "unavailable"
10426
+ : toolSucceeded
10427
+ ? "committed"
10428
+ : "rolled_back",
10429
+ id: managedCheckpoint?.checkpointId || null,
10430
+ transaction_id: managedCheckpoint?.transactionId || null,
10431
+ evidence_digest:
10432
+ managedCheckpoint?.evidence?.evidenceDigest || null,
10433
+ coverage: managedCheckpoint?.coverage || "none",
10434
+ file_coverage: managedCheckpoint?.fileCoverage || "none",
10435
+ reason: managedCheckpoint?.reason || null,
10436
+ tool: toolName,
10437
+ tool_use_id: call.id,
10438
+ turn_id: `${runId}:t${budget.consumed}`,
10439
+ };
10440
+ } catch (checkpointError) {
10441
+ toolError = checkpointError.message;
10442
+ toolResult = {
10443
+ error: `[Managed checkpoint] ${checkpointError.message}. Manual recovery/adjudication is required before this workspace is reused.`,
10444
+ managedCheckpoint: {
10445
+ status: "recovery_required",
10446
+ coverage: "none",
10447
+ code: checkpointError.code || null,
10448
+ transactionId: checkpointError.transactionId || null,
10449
+ checkpointId: checkpointError.checkpointId || null,
10450
+ settlement: checkpointError.settlement || null,
10451
+ originalToolError:
10452
+ toolResult && typeof toolResult === "object"
10453
+ ? toolResult.error || null
10454
+ : null,
10455
+ },
10456
+ };
10457
+ yield {
10458
+ type: "managed-checkpoint-error",
10459
+ phase: checkpointError.settlement || "settle",
10460
+ tool: toolName,
10461
+ error: checkpointError.message,
10462
+ code: checkpointError.code || null,
10463
+ transaction_id: checkpointError.transactionId || null,
10464
+ checkpoint_id: checkpointError.checkpointId || null,
10465
+ coverage: "none",
10466
+ recovery_required: true,
10467
+ tool_use_id: call.id,
10468
+ turn_id: `${runId}:t${budget.consumed}`,
10469
+ };
10470
+ }
10471
+ }
9316
10472
 
9317
- throwIfAborted(signal);
10473
+ throwIfAborted(signal);
9318
10474
 
9319
- // Append budget warning to tool result so the LLM sees it
9320
- const warningMsg = budget.toWarningMessage();
9321
- // Cap an individual tool result so one giant output can't blow the
9322
- // context — but tell the model when we cut it (no more silent
9323
- // mid-content slice). See MAX_TOOL_RESULT_CHARS / capToolResultString.
9324
- const resultStr = capToolResultString(
9325
- safeStringifyToolResult(toolResult),
9326
- );
9327
- const toolContent = warningMsg
9328
- ? `${resultStr}\n\n${warningMsg}`
9329
- : resultStr;
10475
+ // Append budget warning to tool result so the LLM sees it
10476
+ const warningMsg = budget.toWarningMessage();
10477
+ // Cap an individual tool result so one giant output can't blow the
10478
+ // context — but tell the model when we cut it (no more silent
10479
+ // mid-content slice). See MAX_TOOL_RESULT_CHARS / capToolResultString.
10480
+ const resultStr = capToolResultString(
10481
+ safeStringifyToolResult(toolResult),
10482
+ );
10483
+ const toolContent = warningMsg
10484
+ ? `${resultStr}\n\n${warningMsg}`
10485
+ : resultStr;
9330
10486
 
9331
- const decision = permissionDecision(call.id, toolName, toolResult);
9332
- yield {
9333
- type: "tool-result",
9334
- tool: toolName,
9335
- result: toolResult,
9336
- error: toolError,
9337
- tool_use_id: call.id,
9338
- turn_id: `${runId}:t${budget.consumed}`,
9339
- permission_decision_id: decision?.id || null,
9340
- permission_decision: decision,
9341
- };
10487
+ const decision = permissionDecision(call.id, toolName, toolResult);
10488
+ yield {
10489
+ type: "tool-result",
10490
+ tool: toolName,
10491
+ result: toolResult,
10492
+ error: toolError,
10493
+ tool_use_id: call.id,
10494
+ turn_id: `${runId}:t${budget.consumed}`,
10495
+ permission_decision_id: decision?.id || null,
10496
+ permission_decision: decision,
10497
+ };
9342
10498
 
9343
- messages.push({
9344
- role: "tool",
9345
- content: toolContent,
9346
- tool_call_id: call.id,
9347
- });
9348
- const failed = emitToolHookLifecycle({
9349
- tool: toolName,
9350
- args: toolArgs,
9351
- result: toolResult,
9352
- error: toolError,
9353
- sessionId: options.sessionId || null,
9354
- turnId,
9355
- toolUseId: call.id,
9356
- cwd: options.cwd || process.cwd(),
9357
- });
9358
- toolBatchRecords.push({
9359
- tool: toolName,
9360
- toolUseId: call.id,
9361
- failed,
9362
- });
10499
+ messages.push({
10500
+ role: "tool",
10501
+ content: toolContent,
10502
+ tool_call_id: call.id,
10503
+ });
10504
+ const failed = emitToolHookLifecycle({
10505
+ tool: toolName,
10506
+ args: toolArgs,
10507
+ result: toolResult,
10508
+ error: toolError,
10509
+ sessionId: options.sessionId || null,
10510
+ turnId,
10511
+ toolUseId: call.id,
10512
+ cwd: options.cwd || process.cwd(),
10513
+ });
10514
+ toolBatchRecords.push({
10515
+ tool: toolName,
10516
+ toolUseId: call.id,
10517
+ failed,
10518
+ });
10519
+ } finally {
10520
+ if (
10521
+ managedCheckpointHandle &&
10522
+ !managedCheckpointHandle.skipped &&
10523
+ !managedCheckpointSettled &&
10524
+ !managedCheckpointSettlementAttempted
10525
+ ) {
10526
+ try {
10527
+ managedCheckpointSettlementAttempted = true;
10528
+ settleManagedToolCheckpoint(managedCheckpointHandle, {
10529
+ success: false,
10530
+ reason:
10531
+ "agent event consumer closed before managed tool settlement",
10532
+ });
10533
+ managedCheckpointSettled = true;
10534
+ } catch (abandonError) {
10535
+ // Async-generator return() executes this finally. Propagate a
10536
+ // settlement failure so cancellation cannot silently strand a
10537
+ // PREPARED transaction or advertise recoverable/full evidence.
10538
+ abandonError.message = `managed checkpoint cancellation rollback failed: ${abandonError.message}`;
10539
+ // Intentionally override the generator's pending return(): a failed
10540
+ // rollback is security-relevant and must remain observable.
10541
+ // eslint-disable-next-line no-unsafe-finally
10542
+ throw abandonError;
10543
+ }
10544
+ }
10545
+ }
9363
10546
  }
9364
10547
  emitToolBatchHookLifecycle({
9365
10548
  records: toolBatchRecords,