chainlesschain 0.166.143 → 0.166.146

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 (235) hide show
  1. package/README.md +108 -10
  2. package/package.json +3 -3
  3. package/src/assets/linux-subreaper/linux-arm64/manifest.json +1 -1
  4. package/src/assets/linux-subreaper/linux-x64/manifest.json +1 -1
  5. package/src/assets/web-panel/.build-hash +1 -1
  6. package/src/assets/web-panel/assets/{AIOps-DNySV2Kf.js → AIOps-BjBY1txq.js} +1 -1
  7. package/src/assets/web-panel/assets/{ActionButton-ByFuxJsa.js → ActionButton-CS2ov4iK.js} +1 -1
  8. package/src/assets/web-panel/assets/{Analytics-ETbdywk5.js → Analytics-C9LS7ahG.js} +1 -1
  9. package/src/assets/web-panel/assets/{AppLayout-CuHekZaP.js → AppLayout-4_s9gBVg.js} +2 -2
  10. package/src/assets/web-panel/assets/{Artifacts-BJJq2BDq.js → Artifacts-CwS17ayg.js} +1 -1
  11. package/src/assets/web-panel/assets/{Audit-DXrietv8.js → Audit-D3QMRsd-.js} +1 -1
  12. package/src/assets/web-panel/assets/{BackgroundAgents-CFB1fxsr.js → BackgroundAgents-Bxau9H9Q.js} +1 -1
  13. package/src/assets/web-panel/assets/{Backup-VLtflRmp.js → Backup--YSJyAuP.js} +1 -1
  14. package/src/assets/web-panel/assets/{BaseInput-BbqBaS2r.js → BaseInput-DZolkmdu.js} +1 -1
  15. package/src/assets/web-panel/assets/{Chat-t0g7BXL8.js → Chat-DA-7fNKq.js} +1 -1
  16. package/src/assets/web-panel/assets/{ChatBubbleRenderer-JNFsjV0j.js → ChatBubbleRenderer-DniEWT5j.js} +1 -1
  17. package/src/assets/web-panel/assets/{Checkbox-BCSclHQb.js → Checkbox-B4hgbnOB.js} +1 -1
  18. package/src/assets/web-panel/assets/{Codegen-BcyINEHT.js → Codegen-BQ3HSq9S.js} +1 -1
  19. package/src/assets/web-panel/assets/{Col-C-0WNlwS.js → Col-DJwxq_Wu.js} +1 -1
  20. package/src/assets/web-panel/assets/{Community-DxZeoORX.js → Community-DZYVM_iz.js} +1 -1
  21. package/src/assets/web-panel/assets/{Compact-BNnX4jpz.js → Compact-1Yq5o53N.js} +1 -1
  22. package/src/assets/web-panel/assets/{Compliance-KnjHtn9C.js → Compliance-52Per8mR.js} +1 -1
  23. package/src/assets/web-panel/assets/{Cowork-CDyCrhbX.js → Cowork-BaCNxzo7.js} +1 -1
  24. package/src/assets/web-panel/assets/{Cron-DxpS3D1G.js → Cron-DADTMPPr.js} +1 -1
  25. package/src/assets/web-panel/assets/{Crosschain-BSzTZYyc.js → Crosschain-CS3rx96X.js} +1 -1
  26. package/src/assets/web-panel/assets/{DID-Bfj9Vdne.js → DID-B8eatIvd.js} +1 -1
  27. package/src/assets/web-panel/assets/{Dashboard-CcERVdgo.js → Dashboard-0vsurC1X.js} +2 -2
  28. package/src/assets/web-panel/assets/{Dropdown-BtYXAz6E.js → Dropdown-BULy3ccq.js} +1 -1
  29. package/src/assets/web-panel/assets/{EmailListRenderer-fdCMeGXU.js → EmailListRenderer-CcwgCUpu.js} +1 -1
  30. package/src/assets/web-panel/assets/{EvolutionSettings-LHxhcuF2.js → EvolutionSettings-DLs_6II3.js} +1 -1
  31. package/src/assets/web-panel/assets/{FamilyGuardDashboard-MIgtLsos.js → FamilyGuardDashboard-DpUpWwQP.js} +1 -1
  32. package/src/assets/web-panel/assets/{Federation-9-TOztwa.js → Federation-6hx8MMYA.js} +1 -1
  33. package/src/assets/web-panel/assets/{FormItemContext-BKcwEE6w.js → FormItemContext-CsdE-ZR5.js} +1 -1
  34. package/src/assets/web-panel/assets/{GenericCardRenderer-DJBPVUK2.js → GenericCardRenderer-DzXneQPV.js} +1 -1
  35. package/src/assets/web-panel/assets/{Git-C_XYISjG.js → Git-D_ThKL1Q.js} +1 -1
  36. package/src/assets/web-panel/assets/{Governance-DWsbPrwq.js → Governance-BFBSlr-9.js} +1 -1
  37. package/src/assets/web-panel/assets/{Inference-D0_bYket.js → Inference-BAI0b1Jl.js} +1 -1
  38. package/src/assets/web-panel/assets/{KnowledgeGraph-BoA3VQlw.js → KnowledgeGraph-CpO6Bdtr.js} +1 -1
  39. package/src/assets/web-panel/assets/{Logs-LEGItChf.js → Logs-BcRaS_HC.js} +1 -1
  40. package/src/assets/web-panel/assets/{MarkdownRenderer-DOHVc-Uw.js → MarkdownRenderer-CmZaA7Ct.js} +1 -1
  41. package/src/assets/web-panel/assets/{Marketplace-BKovl9NH.js → Marketplace-BpHBn0Nw.js} +1 -1
  42. package/src/assets/web-panel/assets/{McpTools-D61ktoGb.js → McpTools-auVxEYSE.js} +1 -1
  43. package/src/assets/web-panel/assets/{Memory-CllorS0l.js → Memory-DpCyb656.js} +1 -1
  44. package/src/assets/web-panel/assets/{MobileBridge-D-dJ78bk.js → MobileBridge-CEIGi769.js} +1 -1
  45. package/src/assets/web-panel/assets/{MobileProjects-CaxMKkd3.js → MobileProjects-pphH0a8n.js} +1 -1
  46. package/src/assets/web-panel/assets/{Mtc-qEc62Qsx.js → Mtc-CMJXBEp1.js} +1 -1
  47. package/src/assets/web-panel/assets/{MtcAudit-BY68jOZJ.js → MtcAudit-BI25yvzM.js} +1 -1
  48. package/src/assets/web-panel/assets/{Multisig-eCCR8ELt.js → Multisig-BhMDExsQ.js} +1 -1
  49. package/src/assets/web-panel/assets/{NLProgramming-VtGv8pky.js → NLProgramming-CatOR9Ez.js} +1 -1
  50. package/src/assets/web-panel/assets/{Notes-CPkYQySe.js → Notes-BHG6SBpu.js} +1 -1
  51. package/src/assets/web-panel/assets/{NotificationSettings-BuAvlHUu.js → NotificationSettings-BB-m0AbL.js} +1 -1
  52. package/src/assets/web-panel/assets/{OrderTableRenderer-CLf_HAGv.js → OrderTableRenderer-W-WReAih.js} +1 -1
  53. package/src/assets/web-panel/assets/{Organization-DjujhMbD.js → Organization-BkQCgon_.js} +1 -1
  54. package/src/assets/web-panel/assets/{Overflow-RznznTS4.js → Overflow-kCTwPrIc.js} +1 -1
  55. package/src/assets/web-panel/assets/{P2P-DSa5ot0t.js → P2P-CvOF8whc.js} +1 -1
  56. package/src/assets/web-panel/assets/{PdhVaultBrowser-oSEh6vkf.js → PdhVaultBrowser-DYkTzn6u.js} +2 -2
  57. package/src/assets/web-panel/assets/{Permissions-CdOZguX9.js → Permissions-F-UzeWVt.js} +1 -1
  58. package/src/assets/web-panel/assets/{PersonalDataHub-B4--6iEF.js → PersonalDataHub-BURpZBb6.js} +1 -1
  59. package/src/assets/web-panel/assets/{Pipeline-BnI57jE8.js → Pipeline-lZYx_7qc.js} +1 -1
  60. package/src/assets/web-panel/assets/{Privacy-C8MId3ad.js → Privacy-DdfYgt1_.js} +1 -1
  61. package/src/assets/web-panel/assets/{ProjectInit-DPGyYO8a.js → ProjectInit-DbMBCojn.js} +1 -1
  62. package/src/assets/web-panel/assets/{ProjectSettings-qBMqaJaO.js → ProjectSettings-DPGbzkyi.js} +1 -1
  63. package/src/assets/web-panel/assets/{Projects-Bq87Syce.js → Projects-B9-t2ofM.js} +1 -1
  64. package/src/assets/web-panel/assets/{Providers-CVuG9Ugf.js → Providers-q9dSBLsP.js} +1 -1
  65. package/src/assets/web-panel/assets/{QrScannerModal-C94c8m3q.js → QrScannerModal-BIth1Lij.js} +1 -1
  66. package/src/assets/web-panel/assets/{QuickAsk-BvfsXZ8s.js → QuickAsk-C928WbdK.js} +1 -1
  67. package/src/assets/web-panel/assets/{Recommend-CoezBYH9.js → Recommend-CzDNsNPZ.js} +1 -1
  68. package/src/assets/web-panel/assets/{RemoteSession-CcYC4v3u.js → RemoteSession-CedjOslI.js} +1 -1
  69. package/src/assets/web-panel/assets/{Reputation-diDbL4cO.js → Reputation-B8ggKVtj.js} +1 -1
  70. package/src/assets/web-panel/assets/{Row-5qp3_fNS.js → Row-Cx167nF6.js} +1 -1
  71. package/src/assets/web-panel/assets/{RssFeed-BCsMvpV4.js → RssFeed-Cj8hwiLP.js} +1 -1
  72. package/src/assets/web-panel/assets/{Search-Br9nVxOp.js → Search-Dsyrkogu.js} +1 -1
  73. package/src/assets/web-panel/assets/{Security-BdOUzRfA.js → Security-DfOcWFt-.js} +1 -1
  74. package/src/assets/web-panel/assets/{Services-Cp9TqzyN.js → Services-CSyv-JgS.js} +1 -1
  75. package/src/assets/web-panel/assets/{Skeleton-DSdWsUMR.js → Skeleton-B0chhFP5.js} +1 -1
  76. package/src/assets/web-panel/assets/{Skills-DRczAMTe.js → Skills-B_jrR_AF.js} +1 -1
  77. package/src/assets/web-panel/assets/{Sla-B6G_Vd8N.js → Sla-krP10aUI.js} +1 -1
  78. package/src/assets/web-panel/assets/{SpeechSettings-BCcLx5x4.js → SpeechSettings-Cm_Cjvf2.js} +1 -1
  79. package/src/assets/web-panel/assets/{SyncSettings-BFhwtxCp.js → SyncSettings-Cmb-KoqG.js} +1 -1
  80. package/src/assets/web-panel/assets/{Tasks-DGRE6VHO.js → Tasks-DUOiwTxY.js} +1 -1
  81. package/src/assets/web-panel/assets/{Templates-CJkJRFzd.js → Templates-DcEPspsP.js} +1 -1
  82. package/src/assets/web-panel/assets/{Tenant-CAOv6p00.js → Tenant-Dw93LtrE.js} +1 -1
  83. package/src/assets/web-panel/assets/{Terminal-CDrwwrKj.js → Terminal-B04i0AIG.js} +1 -1
  84. package/src/assets/web-panel/assets/{TimelineRenderer-DI0YE2SN.js → TimelineRenderer-C-aAORNK.js} +1 -1
  85. package/src/assets/web-panel/assets/{Tokens-DmqWTZSG.js → Tokens-W1RBfDKb.js} +1 -1
  86. package/src/assets/web-panel/assets/{Trigger-CkXkhmjk.js → Trigger-BuuH9sMn.js} +1 -1
  87. package/src/assets/web-panel/assets/{Trust-U8YJLcoJ.js → Trust-Bma-Vz-f.js} +1 -1
  88. package/src/assets/web-panel/assets/{UkeySign-BLTozMmr.js → UkeySign-CqWw3_ha.js} +1 -1
  89. package/src/assets/web-panel/assets/{VideoEditing-DHKyFlZa.js → VideoEditing-6NYmQRUe.js} +1 -1
  90. package/src/assets/web-panel/assets/{Wallet-DapBxIQt.js → Wallet-CTUuBxsr.js} +1 -1
  91. package/src/assets/web-panel/assets/{WebAuthn-CkvG3yOr.js → WebAuthn-D8mN5UQU.js} +1 -1
  92. package/src/assets/web-panel/assets/{WorkflowEditor-cNLsinXP.js → WorkflowEditor-DOB46XMH.js} +1 -1
  93. package/src/assets/web-panel/assets/{chat-BzgkgfMC.js → chat-BPNlNLwi.js} +1 -1
  94. package/src/assets/web-panel/assets/{colors-BPpVKQsb.js → colors-D-LNng0Q.js} +1 -1
  95. package/src/assets/web-panel/assets/{compact-item-zepznuTv.js → compact-item-Vkl3KOAb.js} +1 -1
  96. package/src/assets/web-panel/assets/{createContext-BRto-SQH.js → createContext-CFsJ9Bmp.js} +1 -1
  97. package/src/assets/web-panel/assets/{hasIn-CqsmU_n6.js → hasIn-C1v7eiIB.js} +1 -1
  98. package/src/assets/web-panel/assets/{index-DKa_jSfj.js → index-0oRhV07J.js} +1 -1
  99. package/src/assets/web-panel/assets/{index-wbvZayBb.js → index-5oK4ICcR.js} +1 -1
  100. package/src/assets/web-panel/assets/{index-CwkhrUmw.js → index-9JeeBF92.js} +1 -1
  101. package/src/assets/web-panel/assets/{index-B0Z6rfV-.js → index-BGyhWFpc.js} +1 -1
  102. package/src/assets/web-panel/assets/{index-DUclk35X.js → index-BH5PxoVq.js} +1 -1
  103. package/src/assets/web-panel/assets/{index-Z6DBe2RU.js → index-BMcTUbpz.js} +1 -1
  104. package/src/assets/web-panel/assets/{index-DXkw-nt5.js → index-BMsRfvkp.js} +1 -1
  105. package/src/assets/web-panel/assets/{index-BeBxP1M6.js → index-BObyCZ2w.js} +1 -1
  106. package/src/assets/web-panel/assets/{index-D_asIcU7.js → index-BPwv3l6X.js} +1 -1
  107. package/src/assets/web-panel/assets/{index-BeSzdB7x.js → index-BQr5mmyc.js} +1 -1
  108. package/src/assets/web-panel/assets/{index-w36TkwyO.js → index-BVHaJNpn.js} +1 -1
  109. package/src/assets/web-panel/assets/{index-D_-w4KkD.js → index-BefXafSw.js} +1 -1
  110. package/src/assets/web-panel/assets/{index-DvGttIXQ.js → index-BgvrlrtJ.js} +1 -1
  111. package/src/assets/web-panel/assets/{index-LVvzNdPa.js → index-BiPmMm38.js} +1 -1
  112. package/src/assets/web-panel/assets/{index-CdHXVSZ4.js → index-BoZnaD3Q.js} +1 -1
  113. package/src/assets/web-panel/assets/{index-Q5sAV7wp.js → index-BxJC59QT.js} +1 -1
  114. package/src/assets/web-panel/assets/{index-BGHd4D8F.js → index-CD8egQCF.js} +1 -1
  115. package/src/assets/web-panel/assets/index-CLafGdQC.js +1 -0
  116. package/src/assets/web-panel/assets/{index-JrVhUwyh.js → index-CaJvbmCw.js} +1 -1
  117. package/src/assets/web-panel/assets/{index-CTk9gY88.js → index-CfVl0Oqt.js} +1 -1
  118. package/src/assets/web-panel/assets/{index-DJSn3owP.js → index-ChGe005u.js} +1 -1
  119. package/src/assets/web-panel/assets/{index-DDPmr5Yr.js → index-Cjxxw-1P.js} +1 -1
  120. package/src/assets/web-panel/assets/{index-BEXKES7V.js → index-CmkppTkH.js} +1 -1
  121. package/src/assets/web-panel/assets/{index-CmPnDXx4.js → index-DFErisPY.js} +1 -1
  122. package/src/assets/web-panel/assets/{index-B_l6gfDh.js → index-DVfUt2bK.js} +1 -1
  123. package/src/assets/web-panel/assets/index-DYHw3Xoi.js +1 -0
  124. package/src/assets/web-panel/assets/{index-CnezE05k.js → index-DZ16Oxcu.js} +1 -1
  125. package/src/assets/web-panel/assets/{index-faHHtBKj.js → index-DbmhJVc3.js} +1 -1
  126. package/src/assets/web-panel/assets/{index-CzoKAiyT.js → index-Dd0OgZmt.js} +3 -3
  127. package/src/assets/web-panel/assets/{index-B-bNzvdU.js → index-DgYmI2pD.js} +1 -1
  128. package/src/assets/web-panel/assets/{index-B9_jRD2e.js → index-DmUZGqe2.js} +1 -1
  129. package/src/assets/web-panel/assets/{index-BuBnM6Kz.js → index-Dq9SDl82.js} +1 -1
  130. package/src/assets/web-panel/assets/{index-BLwY9y0X.js → index-DuIfomtv.js} +1 -1
  131. package/src/assets/web-panel/assets/{index-S8fkzbQ_.js → index-MGJzHAw_.js} +1 -1
  132. package/src/assets/web-panel/assets/{index-Df_CY0We.js → index-PCe8NA3J.js} +1 -1
  133. package/src/assets/web-panel/assets/{index-DEbAW3Ec.js → index-PiL6D-FC.js} +1 -1
  134. package/src/assets/web-panel/assets/{index-CBI-7Q3W.js → index-a_H30VZX.js} +1 -1
  135. package/src/assets/web-panel/assets/{index-Dnvj_XU-.js → index-hBzgHVea.js} +1 -1
  136. package/src/assets/web-panel/assets/{index-Bz7pG8z3.js → index-uDSUo2y2.js} +1 -1
  137. package/src/assets/web-panel/assets/{initDefaultProps-BlhbrsQk.js → initDefaultProps-CCYgHcTH.js} +1 -1
  138. package/src/assets/web-panel/assets/{motion-UZx12NPM.js → motion-4Yr4ZkjE.js} +1 -1
  139. package/src/assets/web-panel/assets/{move-BTby5W4q.js → move-ZP90E-ji.js} +1 -1
  140. package/src/assets/web-panel/assets/{mtc-parser-BOOaGiCg.js → mtc-parser-s0N3WyRA.js} +1 -1
  141. package/src/assets/web-panel/assets/{omit-BVylGzEr.js → omit-BZ6gx9Kf.js} +1 -1
  142. package/src/assets/web-panel/assets/{pickAttrs-Cp3Nflbr.js → pickAttrs-DxUtFOOQ.js} +1 -1
  143. package/src/assets/web-panel/assets/{placementArrow-BVXYvwH2.js → placementArrow-Btzjn1hK.js} +1 -1
  144. package/src/assets/web-panel/assets/{responsiveObserve-C67SbpBN.js → responsiveObserve-DYcoe1XJ.js} +1 -1
  145. package/src/assets/web-panel/assets/{slide-CnBvM22R.js → slide-BiBewdr4.js} +1 -1
  146. package/src/assets/web-panel/assets/{statusUtils-T8fy53tf.js → statusUtils-D9vt0dkG.js} +1 -1
  147. package/src/assets/web-panel/assets/{styleChecker-Bf7i4nlm.js → styleChecker-BXsm_vG0.js} +1 -1
  148. package/src/assets/web-panel/assets/{useFlexGapSupport-BUKk7jqw.js → useFlexGapSupport-CIG8zET4.js} +1 -1
  149. package/src/assets/web-panel/assets/{useFs-T5lg6SpD.js → useFs-ChFPF8GI.js} +1 -1
  150. package/src/assets/web-panel/assets/{usePersonalDataHub-Brvye8Tg.js → usePersonalDataHub-D4CzWJhY.js} +1 -1
  151. package/src/assets/web-panel/assets/{vnode-CK992ojP.js → vnode-6V5tphk5.js} +1 -1
  152. package/src/assets/web-panel/assets/{zoom-CcABB_97.js → zoom-B2H_VwfU.js} +1 -1
  153. package/src/assets/web-panel/index.html +1 -1
  154. package/src/command-help-index.json +4 -4
  155. package/src/commands/agent.js +64 -62
  156. package/src/commands/goal.js +79 -0
  157. package/src/commands/mcp-tasks.js +239 -0
  158. package/src/commands/mcp.js +58 -2
  159. package/src/commands/memory.js +131 -7
  160. package/src/commands/session-show.js +36 -1
  161. package/src/data/changelog.json +39 -0
  162. package/src/generated/cc-agent-protocol.schema.json +175 -69
  163. package/src/harness/jsonl-session-store.js +10 -0
  164. package/src/harness/mcp-client.js +701 -51
  165. package/src/harness/prompt-compressor.js +1 -0
  166. package/src/harness/session-index.js +8 -0
  167. package/src/harness/session-list-index.js +13 -58
  168. package/src/host/README.md +43 -0
  169. package/src/host/project-goal-graph.js +57 -0
  170. package/src/lib/agent-session-export.js +19 -0
  171. package/src/lib/app-server/context-memory-notifications.js +11 -2
  172. package/src/lib/app-server/server.js +1 -0
  173. package/src/lib/background-launch-profile.js +38 -6
  174. package/src/lib/codex-app-server-adapter.js +20 -0
  175. package/src/lib/codex-app-server-support.js +2 -2
  176. package/src/lib/context-memory-kernel/local-semantic-source.js +426 -0
  177. package/src/lib/context-memory-kernel/local-semantic-worker.py +109 -0
  178. package/src/lib/context-memory-kernel/memory-query-control.js +5 -1
  179. package/src/lib/context-memory-kernel/memory-query-index.js +37 -1
  180. package/src/lib/context-memory-kernel/memory-service.js +35 -2
  181. package/src/lib/context-memory-kernel/message-adapter.js +27 -5
  182. package/src/lib/context-memory-kernel/provider-context.js +197 -15
  183. package/src/lib/context-memory-kernel/runtime.js +40 -0
  184. package/src/lib/context-memory-kernel/segmented-memory-port.js +26 -1
  185. package/src/lib/evolution/agent-evolution-ingress.js +55 -1
  186. package/src/lib/evolution/evolution-artifact-ports.js +36 -1
  187. package/src/lib/evolution/skill-candidate-registry.js +3 -1
  188. package/src/lib/formal-budget-authority.js +56 -3
  189. package/src/lib/formal-budget-contract.js +90 -5
  190. package/src/lib/formal-budget-provider-scope.js +29 -7
  191. package/src/lib/formal-budget-transport.js +36 -5
  192. package/src/lib/goal-store.js +219 -0
  193. package/src/lib/graph-kernel/graph-runtime-surfaces.json +30 -0
  194. package/src/lib/graph-kernel/production-source-evidence.js +3 -3
  195. package/src/lib/graph-kernel/runtime-surface-manifest.js +46 -9
  196. package/src/lib/graph-kernel/runtime.js +12 -1
  197. package/src/lib/mcp-call-ledger-projection.js +1026 -0
  198. package/src/lib/mcp-call-ledger-store.js +19 -1024
  199. package/src/lib/mcp-client.js +1 -0
  200. package/src/lib/mcp-ledger-recovery-admission.js +25 -0
  201. package/src/lib/mcp-stateless-protocol.js +158 -0
  202. package/src/lib/mcp-task-continuation-contract.js +129 -0
  203. package/src/lib/mcp-task-continuation.js +147 -0
  204. package/src/lib/mcp-task-delivery-contract.js +190 -0
  205. package/src/lib/mcp-task-delivery.js +113 -0
  206. package/src/lib/mcp-task-journal-projection.js +495 -0
  207. package/src/lib/mcp-task-journal.js +57 -0
  208. package/src/lib/mcp-task-runtime.js +627 -0
  209. package/src/lib/mcp-tasks.js +217 -0
  210. package/src/lib/model-input-diagnostics.js +265 -0
  211. package/src/lib/model-input-source-mapping.js +343 -0
  212. package/src/lib/openai-responses.js +32 -9
  213. package/src/lib/provider-request-admission.js +181 -0
  214. package/src/lib/public-ide-capability-manifest.js +2 -0
  215. package/src/lib/scheduler-kernel/graph-authority-adapter.js +140 -15
  216. package/src/lib/session-generation-authority.js +58 -0
  217. package/src/lib/session-host-snapshot.js +37 -0
  218. package/src/lib/session-input-lifecycle.js +147 -0
  219. package/src/lib/session-input-receipt.js +64 -0
  220. package/src/lib/session-message-provenance.js +6 -5
  221. package/src/lib/session-model-input-diagnostics.js +262 -0
  222. package/src/lib/session-model-usage-recovery.js +115 -0
  223. package/src/lib/session-transcript-history.js +9 -0
  224. package/src/lib/session-transcript-page.js +7 -1
  225. package/src/lib/session-transcript-structure.js +45 -0
  226. package/src/lib/storage-failure-cause-codes.js +79 -0
  227. package/src/lib/sub-agent-context.js +7 -3
  228. package/src/repl/agent-repl.js +526 -253
  229. package/src/runtime/agent-core.js +296 -151
  230. package/src/runtime/headless-runner.js +58 -69
  231. package/src/runtime/headless-stream.js +40 -33
  232. package/src/runtime/mcp-config.js +5 -3
  233. package/src/runtime/policies/agent-policy.js +1 -0
  234. package/src/assets/web-panel/assets/index-DruOFzuF.js +0 -1
  235. package/src/assets/web-panel/assets/index-hhOrZ6HO.js +0 -1
@@ -1,3 +1,6 @@
1
+ import { formatSessionModelUsageRecoveryNotice } from "../lib/session-model-usage-recovery.js";
2
+ import { createPersistedModelInputObserver } from "../lib/session-model-input-diagnostics.js";
3
+ import { summarizeMcpPayload } from "../lib/mcp-call-ledger.js";
1
4
  /**
2
5
  * Agentic REPL - Claude Code / Codex style
3
6
  *
@@ -107,6 +110,10 @@ import {
107
110
  persistSideEffectLedger,
108
111
  } from "../lib/side-effect-ledger-store.js";
109
112
  import { operationIdempotencyKey } from "../lib/idempotency.js";
113
+ import {
114
+ appendSessionInputAcceptance,
115
+ appendSessionInputSettlement,
116
+ } from "../lib/session-input-receipt.js";
110
117
  import { collectToolResourceIdentifiers } from "../lib/permission-side-effect-center.js";
111
118
  import {
112
119
  preserveDurableSystemMessageProvenance,
@@ -439,9 +446,9 @@ export async function runReplDirectToolWithLedger({
439
446
  tool,
440
447
  isError: Boolean(
441
448
  executionFailed ||
442
- result?.error ||
443
- result?.is_error ||
444
- result?.isError,
449
+ result?.error ||
450
+ result?.is_error ||
451
+ result?.isError,
445
452
  ),
446
453
  skill: tool === "run_skill" ? args?.skill_name : undefined,
447
454
  ...extractPluginUsageAttribution(result),
@@ -531,9 +538,8 @@ async function _fireNotification(message, type = "info", session = null) {
531
538
  // Fire settings.json observe hooks first (best-effort)
532
539
  if (_settingsHooks) {
533
540
  try {
534
- const { runObserveHooks } = await import(
535
- "../lib/settings-hook-events.js"
536
- );
541
+ const { runObserveHooks } =
542
+ await import("../lib/settings-hook-events.js");
537
543
  await runObserveHooks(
538
544
  _settingsHooks,
539
545
  "Notification",
@@ -722,6 +728,16 @@ export async function agentLoop(messages, options) {
722
728
  );
723
729
  }
724
730
  : undefined);
731
+ const onModelInputDiagnostic =
732
+ options.persistUsageTelemetry === true && options.sessionId
733
+ ? createPersistedModelInputObserver({
734
+ append: (type, data) =>
735
+ persistRuntimeLedger(() =>
736
+ persistBoundary(options.sessionId, type, data),
737
+ ),
738
+ observe: options.onModelInputDiagnostic,
739
+ })
740
+ : options.onModelInputDiagnostic;
725
741
  const childToolExecs = new Map();
726
742
  const onToolCallBoundary =
727
743
  options.onToolCallBoundary ||
@@ -783,6 +799,7 @@ export async function agentLoop(messages, options) {
783
799
  onUsageSettlement,
784
800
  onToolCallBoundary,
785
801
  onToolCallSettlement,
802
+ onModelInputDiagnostic,
786
803
  onProviderFallback,
787
804
  })) {
788
805
  if (evolutionIngress !== null) {
@@ -2059,7 +2076,7 @@ function collapseValidatedPlainReplTailInPlace(messages) {
2059
2076
  return true;
2060
2077
  }
2061
2078
 
2062
- function normalizeReplReplayMessages(rebuiltMessages) {
2079
+ function normalizeReplReplayMessages(rebuiltMessages, referenceDigests = []) {
2063
2080
  // Validate the immutable raw snapshot before any normalization. In
2064
2081
  // particular, never let a same-role merge hide malformed tool authority.
2065
2082
  validateRawReplReplayMessages(rebuiltMessages);
@@ -2076,9 +2093,25 @@ function normalizeReplReplayMessages(rebuiltMessages) {
2076
2093
  );
2077
2094
  let phase = "expect-initial-conversation-message";
2078
2095
  let pendingToolCallIds = null;
2096
+ let previousConversation = null;
2097
+ const references = new Set(referenceDigests);
2079
2098
 
2080
2099
  for (let index = 0; index < conversationMessages.length; index += 1) {
2081
2100
  const message = conversationMessages[index];
2101
+ // External references are neither model answers nor tool exchanges. Only
2102
+ // exact commitments from this same verified transcript may be transparent
2103
+ // to alternation; a peer-chosen name or prefix cannot grant this exception.
2104
+ if (
2105
+ message.role === "assistant" &&
2106
+ message.name === "mcp_task_result" &&
2107
+ references.has(summarizeMcpPayload(message).sha256)
2108
+ )
2109
+ continue;
2110
+ const samePlainRun =
2111
+ previousConversation?.role === message.role &&
2112
+ isPlainReplMergeMessage(previousConversation) &&
2113
+ isPlainReplMergeMessage(message);
2114
+ previousConversation = message;
2082
2115
  const hasToolCalls = Object.prototype.hasOwnProperty.call(
2083
2116
  message,
2084
2117
  "tool_calls",
@@ -2102,7 +2135,8 @@ function normalizeReplReplayMessages(rebuiltMessages) {
2102
2135
  if (message.role === "user") {
2103
2136
  if (
2104
2137
  phase !== "expect-user" &&
2105
- phase !== "expect-initial-conversation-message"
2138
+ phase !== "expect-initial-conversation-message" &&
2139
+ !samePlainRun
2106
2140
  ) {
2107
2141
  throw invalidReplRecovery(
2108
2142
  `REPL session user message[${index}] breaks role alternation`,
@@ -2116,7 +2150,8 @@ function normalizeReplReplayMessages(rebuiltMessages) {
2116
2150
  if (
2117
2151
  phase !== "expect-assistant" &&
2118
2152
  phase !== "expect-assistant-after-tools" &&
2119
- phase !== "expect-initial-conversation-message"
2153
+ phase !== "expect-initial-conversation-message" &&
2154
+ !samePlainRun
2120
2155
  ) {
2121
2156
  throw invalidReplRecovery(
2122
2157
  `REPL session assistant message[${index}] breaks role alternation`,
@@ -2252,7 +2287,27 @@ export function prepareReplJsonlResumeCandidate(sessionId, dependencies = {}) {
2252
2287
  const rebuiltMessages = snapshotReplMessages(
2253
2288
  projectCanonicalResumeMessages(rawRebuiltMessages),
2254
2289
  );
2255
- const normalizedReplay = normalizeReplReplayMessages(rebuiltMessages);
2290
+ const referenceDigests = snapshotReplMessageValue(
2291
+ dataDescriptorValue(
2292
+ stateDescriptors,
2293
+ "mcpTaskReferenceDigests",
2294
+ "REPL session host resume state",
2295
+ { required: false, fallback: [] },
2296
+ ),
2297
+ "MCP task reference commitments",
2298
+ );
2299
+ if (
2300
+ !Array.isArray(referenceDigests) ||
2301
+ !referenceDigests.every(
2302
+ (value) =>
2303
+ typeof value === "string" && /^sha256:[a-f0-9]{64}$/u.test(value),
2304
+ )
2305
+ )
2306
+ throw invalidReplRecovery("Invalid MCP task reference commitments");
2307
+ const normalizedReplay = normalizeReplReplayMessages(
2308
+ rebuiltMessages,
2309
+ referenceDigests,
2310
+ );
2256
2311
  const mcp = createReplMcpRecoveryCandidate(
2257
2312
  sessionId,
2258
2313
  dataDescriptorValue(
@@ -2289,10 +2344,20 @@ export function prepareReplJsonlResumeCandidate(sessionId, dependencies = {}) {
2289
2344
  "REPL session budget declaration",
2290
2345
  ),
2291
2346
  );
2347
+ const modelUsageRecovery = snapshotReplMessageValue(
2348
+ dataDescriptorValue(
2349
+ stateDescriptors,
2350
+ "modelUsageRecovery",
2351
+ "REPL local usage recovery",
2352
+ { required: false },
2353
+ ) ?? null,
2354
+ "REPL local usage recovery",
2355
+ );
2292
2356
  return brandedFrozenCandidate(REPL_JSONL_RESUME_CANDIDATES, {
2293
2357
  ok: true,
2294
2358
  sessionId,
2295
2359
  sessionBudgetRoot,
2360
+ modelUsageRecovery,
2296
2361
  rebuiltMessages,
2297
2362
  replayMessages: normalizedReplay.replayMessages,
2298
2363
  canonicalSystemMessages: normalizedReplay.canonicalSystemMessages,
@@ -3137,6 +3202,9 @@ async function startAgentReplInWorkspaceOwned(
3137
3202
  startupAdmission,
3138
3203
  outputScope,
3139
3204
  ) {
3205
+ // Keep the user's session-wide recall choice across model switches, direct
3206
+ // judges and resumed turns; canonical per-request planning also needs it.
3207
+ const recallMemory = options.recallMemory !== false;
3140
3208
  // The compressor captures this session's ingress and metering callbacks.
3141
3209
  // A later REPL instance must not replace another session's authority.
3142
3210
  let _compressor = null;
@@ -3271,6 +3339,10 @@ async function startAgentReplInWorkspaceOwned(
3271
3339
  let _processingLine = false;
3272
3340
  let _lineSettled = null;
3273
3341
  const _activeBtwCalls = new Set();
3342
+ const _mcpTaskTrackers = new Map();
3343
+ const _mcpTaskAutoWakeQueue = [];
3344
+ let _mcpTaskAutoWakeRunning = false;
3345
+ const _mcpTaskAutoWakeSentinel = Symbol("mcp-task-auto-wake");
3274
3346
  const _pendingLines = [];
3275
3347
  const _runtimeLedgerTerminalLatch = createReplRuntimeLedgerTerminalLatch({
3276
3348
  onTrip: (terminalError) => {
@@ -3535,9 +3607,8 @@ async function startAgentReplInWorkspaceOwned(
3535
3607
  // Initialize prompt compressor (adaptive to model's context window). A
3536
3608
  // canonical cutover cannot disable the Kernel writer by toggling the legacy
3537
3609
  // compressor feature flag; the compressor remains only its summarizer.
3538
- const { resolveCliContextMemoryCutover } = await import(
3539
- "../lib/context-memory-kernel/authority.js"
3540
- );
3610
+ const { resolveCliContextMemoryCutover } =
3611
+ await import("../lib/context-memory-kernel/authority.js");
3541
3612
  const contextMemoryCutover = resolveCliContextMemoryCutover({
3542
3613
  env: options.contextMemoryEnv || process.env,
3543
3614
  scopeKey: sessionId ? `cli:session:${sessionId}` : "cli:repl",
@@ -3559,6 +3630,7 @@ async function startAgentReplInWorkspaceOwned(
3559
3630
  includeLedgerMetadata: true,
3560
3631
  call: ({ signal }) =>
3561
3632
  chatWithTools([{ role: "user", content: prompt }], {
3633
+ contextMemoryRecall: recallMemory,
3562
3634
  ...(evolutionIngress === null ? {} : { evolutionIngress }),
3563
3635
  provider,
3564
3636
  model,
@@ -3585,9 +3657,8 @@ async function startAgentReplInWorkspaceOwned(
3585
3657
  });
3586
3658
  if (contextMemoryCutover.canonical) {
3587
3659
  const compatibilitySummarizer = _compressor;
3588
- const { compactLiveMessagesCanonical } = await import(
3589
- "../lib/context-memory-kernel/live-compaction.js"
3590
- );
3660
+ const { compactLiveMessagesCanonical } =
3661
+ await import("../lib/context-memory-kernel/live-compaction.js");
3591
3662
  _compressor = {
3592
3663
  canonicalKernel: true,
3593
3664
  maxTokens: compatibilitySummarizer.maxTokens,
@@ -3645,7 +3716,11 @@ async function startAgentReplInWorkspaceOwned(
3645
3716
  // Non-critical
3646
3717
  }
3647
3718
 
3648
- contextEngine = new CLIContextEngineering({ db, permanentMemory });
3719
+ contextEngine = new CLIContextEngineering({
3720
+ db,
3721
+ permanentMemory,
3722
+ memoryEnabled: recallMemory,
3723
+ });
3649
3724
 
3650
3725
  // Initialize autonomous agent
3651
3726
  const autonomousAgent = new CLIAutonomousAgent();
@@ -3682,9 +3757,8 @@ async function startAgentReplInWorkspaceOwned(
3682
3757
  // MEDIUM/HIGH-risk commands against the session's policy tier
3683
3758
  // (strict / trusted / autopilot).
3684
3759
  try {
3685
- const { getApprovalGate } = await import(
3686
- "../lib/session-core-singletons.js"
3687
- );
3760
+ const { getApprovalGate } =
3761
+ await import("../lib/session-core-singletons.js");
3688
3762
  _approvalGate = await getApprovalGate();
3689
3763
  _approvalGate =
3690
3764
  _approvalGate?.createSessionScope?.(
@@ -3970,14 +4044,12 @@ async function startAgentReplInWorkspaceOwned(
3970
4044
  // project plugins get a process spawned. Reaped in the SessionEnd cleanup +
3971
4045
  // a process-exit backstop, so no monitor outlives the session.
3972
4046
  try {
3973
- const { collectPluginMonitors } = await import(
3974
- "../lib/plugin-runtime/monitors.js"
3975
- );
4047
+ const { collectPluginMonitors } =
4048
+ await import("../lib/plugin-runtime/monitors.js");
3976
4049
  const monitors = collectPluginMonitors({ cwd: process.cwd() });
3977
4050
  if (monitors.length > 0) {
3978
- const { PluginMonitorSupervisor } = await import(
3979
- "../lib/plugin-monitor-supervisor.js"
3980
- );
4051
+ const { PluginMonitorSupervisor } =
4052
+ await import("../lib/plugin-monitor-supervisor.js");
3981
4053
  _pluginMonitors = new PluginMonitorSupervisor();
3982
4054
  const started = _pluginMonitors.start(monitors);
3983
4055
  if (started.length > 0) {
@@ -4009,9 +4081,8 @@ async function startAgentReplInWorkspaceOwned(
4009
4081
  // Apply trusted plugins' default env vars (Phase 3.3o) — only for env keys the
4010
4082
  // user/system didn't already set; restored at SessionEnd.
4011
4083
  try {
4012
- const { applyPluginSettingsEnv } = await import(
4013
- "../lib/plugin-runtime/settings.js"
4014
- );
4084
+ const { applyPluginSettingsEnv } =
4085
+ await import("../lib/plugin-runtime/settings.js");
4015
4086
  const res = applyPluginSettingsEnv({ cwd: process.cwd() });
4016
4087
  _pluginSettingsRestore = res.restore;
4017
4088
  if (res.added.length > 0) {
@@ -4082,9 +4153,8 @@ async function startAgentReplInWorkspaceOwned(
4082
4153
  let _sessionMgr = null;
4083
4154
  let _sessionHandle = null;
4084
4155
  try {
4085
- const { getSessionManager } = await import(
4086
- "../lib/session-core-singletons.js"
4087
- );
4156
+ const { getSessionManager } =
4157
+ await import("../lib/session-core-singletons.js");
4088
4158
  // Keep durable lifecycle sidecars on the same launch-authoritative Claude
4089
4159
  // project bucket as the JSONL transcript. Project settings may not switch
4090
4160
  // this map/path after the REPL has admitted its launch environment.
@@ -4133,9 +4203,8 @@ async function startAgentReplInWorkspaceOwned(
4133
4203
  error.code = "CC_REMOTE_APPROVAL_GATE_UNAVAILABLE";
4134
4204
  throw error;
4135
4205
  }
4136
- const { startHeadlessRemoteApproval } = await import(
4137
- "../lib/remote-approval-bridge.js"
4138
- );
4206
+ const { startHeadlessRemoteApproval } =
4207
+ await import("../lib/remote-approval-bridge.js");
4139
4208
  const started = await startHeadlessRemoteApproval({
4140
4209
  agentSessionId:
4141
4210
  sessionId || `repl-${process.pid}-${Date.now().toString(36)}`,
@@ -4377,6 +4446,7 @@ async function startAgentReplInWorkspaceOwned(
4377
4446
  // the first prompt turn of a persistable (JSONL) session. This is Critical
4378
4447
  // recovery state: a failure blocks subsequent model/tool turns.
4379
4448
  let _turnBindingProducer = null;
4449
+ let _sessionInputAccepted = null;
4380
4450
  let _turnBindingCriticalError = null;
4381
4451
  // Apply --output-style or the settings.json `outputStyle` default at startup.
4382
4452
  try {
@@ -4398,9 +4468,8 @@ async function startAgentReplInWorkspaceOwned(
4398
4468
  // project memory is off or no hook is registered.
4399
4469
  if (_settingsHooks && _loadedReplInstructions) {
4400
4470
  try {
4401
- const { runInstructionsLoadedHooks } = await import(
4402
- "../lib/settings-hook-events.js"
4403
- );
4471
+ const { runInstructionsLoadedHooks } =
4472
+ await import("../lib/settings-hook-events.js");
4404
4473
  const ctx = (
4405
4474
  await runInstructionsLoadedHooks(_settingsHooks, {
4406
4475
  files: _loadedReplInstructions.files,
@@ -4417,9 +4486,8 @@ async function startAgentReplInWorkspaceOwned(
4417
4486
  // settings.json SessionStart hooks → inject session context (observe-only).
4418
4487
  if (_settingsHooks) {
4419
4488
  try {
4420
- const { runSessionStartHooks } = await import(
4421
- "../lib/settings-hook-events.js"
4422
- );
4489
+ const { runSessionStartHooks } =
4490
+ await import("../lib/settings-hook-events.js");
4423
4491
  const ctx = (
4424
4492
  await runSessionStartHooks(_settingsHooks, {
4425
4493
  source: "startup",
@@ -4487,18 +4555,15 @@ async function startAgentReplInWorkspaceOwned(
4487
4555
  };
4488
4556
  if (options.bundlePath) {
4489
4557
  try {
4490
- const { loadBundle } = await import(
4491
- "@chainlesschain/session-core/agent-bundle-loader"
4492
- );
4493
- const { parseUserMdSeed, resolveBundle } = await import(
4494
- "@chainlesschain/session-core/agent-bundle-resolver"
4495
- );
4558
+ const { loadBundle } =
4559
+ await import("@chainlesschain/session-core/agent-bundle-loader");
4560
+ const { parseUserMdSeed, resolveBundle } =
4561
+ await import("@chainlesschain/session-core/agent-bundle-resolver");
4496
4562
  const bundle = loadBundle(options.bundlePath);
4497
4563
  if (contextMemoryCutover.canonical) {
4498
4564
  _bundleResolved = resolveBundle(bundle);
4499
- const { createCliCanonicalMemoryService } = await import(
4500
- "../lib/context-memory-kernel/memory-service.js"
4501
- );
4565
+ const { createCliCanonicalMemoryService } =
4566
+ await import("../lib/context-memory-kernel/memory-service.js");
4502
4567
  const memoryService = createCliCanonicalMemoryService({
4503
4568
  env: options.contextMemoryEnv || process.env,
4504
4569
  });
@@ -4540,9 +4605,8 @@ async function startAgentReplInWorkspaceOwned(
4540
4605
  }
4541
4606
  _bundleResolved.seedResult = { seeded, skipped };
4542
4607
  } else {
4543
- const { getMemoryStore } = await import(
4544
- "../lib/session-core-singletons.js"
4545
- );
4608
+ const { getMemoryStore } =
4609
+ await import("../lib/session-core-singletons.js");
4546
4610
  _bundleResolved = resolveBundle(bundle, {
4547
4611
  memoryStore: getMemoryStore(),
4548
4612
  seedOptions: {
@@ -4800,9 +4864,8 @@ async function startAgentReplInWorkspaceOwned(
4800
4864
  // when there are no extra roots. Best-effort.
4801
4865
  if (additionalDirectories.length > 0) {
4802
4866
  try {
4803
- const { workspaceRootDirs, notifyMcpRootsChanged } = await import(
4804
- "./add-dir.js"
4805
- );
4867
+ const { workspaceRootDirs, notifyMcpRootsChanged } =
4868
+ await import("./add-dir.js");
4806
4869
  notifyMcpRootsChanged(
4807
4870
  [_adhocMcp?.mcpClient, _bundleMcpClient],
4808
4871
  workspaceRootDirs(process.cwd(), additionalDirectories),
@@ -4853,11 +4916,10 @@ async function startAgentReplInWorkspaceOwned(
4853
4916
  // Phase G #5 — inject top-K memory recall into system prompt for new sessions
4854
4917
  // Skip on resume (existing context already reflects prior work) and when
4855
4918
  // --no-recall-memory is passed.
4856
- if (!options.sessionId && options.recallMemory !== false) {
4919
+ if (!options.sessionId && recallMemory && !contextMemoryCutover.canonical) {
4857
4920
  try {
4858
- const { buildMemoryInjection } = await import(
4859
- "../lib/memory-injection.js"
4860
- );
4921
+ const { buildMemoryInjection } =
4922
+ await import("../lib/memory-injection.js");
4861
4923
  const injection = buildMemoryInjection({
4862
4924
  agentId: options.agentId || null,
4863
4925
  query: options.recallQuery || "",
@@ -4907,6 +4969,11 @@ async function startAgentReplInWorkspaceOwned(
4907
4969
  error.code = "CC_REPL_SESSION_RESUME_NOT_PREPARED";
4908
4970
  throw error;
4909
4971
  }
4972
+ const usageRecoveryNotice = formatSessionModelUsageRecoveryNotice(
4973
+ sessionId,
4974
+ prepared.modelUsageRecovery,
4975
+ );
4976
+ if (usageRecoveryNotice) logger.warn(usageRecoveryNotice);
4910
4977
  messages.push(...prepared.canonicalSystemMessages);
4911
4978
  if (_startupReplSideEffects.noticeMessage) {
4912
4979
  messages.push(_startupReplSideEffects.noticeMessage);
@@ -4959,9 +5026,8 @@ async function startAgentReplInWorkspaceOwned(
4959
5026
  // Observe-only, best-effort — never blocks entering the REPL.
4960
5027
  if (_settingsHooks && _startupResumeCommitted) {
4961
5028
  try {
4962
- const { runObserveHooks } = await import(
4963
- "../lib/settings-hook-events.js"
4964
- );
5029
+ const { runObserveHooks } =
5030
+ await import("../lib/settings-hook-events.js");
4965
5031
  await runObserveHooks(
4966
5032
  _settingsHooks,
4967
5033
  "SessionResume",
@@ -4999,9 +5065,8 @@ async function startAgentReplInWorkspaceOwned(
4999
5065
  // transcript snapshot and ZERO tools. Compact call/outcome metadata shares
5000
5066
  // the session hash chain, while advice text itself is never persisted.
5001
5067
  try {
5002
- const { createConfiguredAdvisorRuntime } = await import(
5003
- "../lib/advisor-runtime.js"
5004
- );
5068
+ const { createConfiguredAdvisorRuntime } =
5069
+ await import("../lib/advisor-runtime.js");
5005
5070
  const advisorOverrides = {};
5006
5071
  if (options.advisorEnabled !== undefined) {
5007
5072
  advisorOverrides.enabled = options.advisorEnabled === true;
@@ -5229,6 +5294,7 @@ async function startAgentReplInWorkspaceOwned(
5229
5294
  "/ide",
5230
5295
  "/init",
5231
5296
  "/mcp",
5297
+ "/mcp-watch",
5232
5298
  "/memory",
5233
5299
  "/microcompact",
5234
5300
  "/model",
@@ -5370,9 +5436,8 @@ async function startAgentReplInWorkspaceOwned(
5370
5436
  return;
5371
5437
  }
5372
5438
  try {
5373
- const { defaultOpenBrowser } = await import(
5374
- "../lib/mcp-oauth.js"
5375
- );
5439
+ const { defaultOpenBrowser } =
5440
+ await import("../lib/mcp-oauth.js");
5376
5441
  const opened = defaultOpenBrowser(request.url);
5377
5442
  resolve(opened ? { action: "accept" } : { action: "cancel" });
5378
5443
  } catch {
@@ -5415,9 +5480,8 @@ async function startAgentReplInWorkspaceOwned(
5415
5480
  let _channels = null;
5416
5481
  if (options.channels) {
5417
5482
  try {
5418
- const { startChannels, formatChannelEvent } = await import(
5419
- "../lib/channels/channel-manager.js"
5420
- );
5483
+ const { startChannels, formatChannelEvent } =
5484
+ await import("../lib/channels/channel-manager.js");
5421
5485
  let channelsConfig = {};
5422
5486
  try {
5423
5487
  channelsConfig =
@@ -5710,9 +5774,8 @@ async function startAgentReplInWorkspaceOwned(
5710
5774
  const _notifyVersionSkew = async () => {
5711
5775
  if (_versionSkewNotified) return;
5712
5776
  try {
5713
- const { detectVersionSkew, versionSkewMessage } = await import(
5714
- "../lib/version-skew.js"
5715
- );
5777
+ const { detectVersionSkew, versionSkewMessage } =
5778
+ await import("../lib/version-skew.js");
5716
5779
  const skew = detectVersionSkew();
5717
5780
  if (skew) {
5718
5781
  _versionSkewNotified = true;
@@ -5866,7 +5929,83 @@ async function startAgentReplInWorkspaceOwned(
5866
5929
  // continuation backslash keeps the prompt open; `_mlBuffer` accumulates the
5867
5930
  // pieces and the whole block submits when a line does not continue.
5868
5931
  const _mlBuffer = [];
5932
+ const kickMcpTaskAutoWake = () => {
5933
+ if (
5934
+ _processingLine ||
5935
+ _mcpTaskAutoWakeRunning ||
5936
+ _replClosing ||
5937
+ _mlBuffer.length > 0 ||
5938
+ (_replRl?.line || "").length > 0 ||
5939
+ _mcpTaskAutoWakeQueue.length === 0
5940
+ ) {
5941
+ return;
5942
+ }
5943
+ _mcpTaskAutoWakeRunning = true;
5944
+ _processingLine = true;
5945
+ let settleLine;
5946
+ _lineSettled = new Promise((resolve) => {
5947
+ settleLine = resolve;
5948
+ });
5949
+ void (async () => {
5950
+ try {
5951
+ await handleLine(_mcpTaskAutoWakeSentinel);
5952
+ if (!(await _waitForReplOutput())) return;
5953
+ while (
5954
+ _pendingLines.length &&
5955
+ !_replClosing &&
5956
+ !_runtimeLedgerTerminalLatch.isTripped()
5957
+ ) {
5958
+ const next = _pendingLines.shift();
5959
+ await handleLine(next);
5960
+ if (!(await _waitForReplOutput())) return;
5961
+ }
5962
+ } finally {
5963
+ _processingLine = false;
5964
+ settleLine();
5965
+ _lineSettled = null;
5966
+ _mcpTaskAutoWakeRunning = false;
5967
+ kickMcpTaskAutoWake();
5968
+ }
5969
+ })();
5970
+ };
5971
+ const scheduleMcpTaskAutoWake = (delivery) => {
5972
+ if (process.env.CC_MCP_TASK_AUTOWAKE !== "1" || !delivery?.message) {
5973
+ return false;
5974
+ }
5975
+ if (_mcpTaskAutoWakeQueue.length >= 8) {
5976
+ logger.warn(
5977
+ "[mcp-watch] auto-wake queue is full; delivery remains available in the session",
5978
+ );
5979
+ return false;
5980
+ }
5981
+ _mcpTaskAutoWakeQueue.push(delivery);
5982
+ kickMcpTaskAutoWake();
5983
+ return true;
5984
+ };
5869
5985
  const handleLine = async (input) => {
5986
+ let mcpAutoWakeDelivery =
5987
+ input === _mcpTaskAutoWakeSentinel
5988
+ ? _mcpTaskAutoWakeQueue.shift() || null
5989
+ : null;
5990
+ let mcpContinuationStarted = null;
5991
+ if (mcpAutoWakeDelivery) {
5992
+ try {
5993
+ if (mcpAutoWakeDelivery.sessionId !== sessionId)
5994
+ throw new Error("MCP continuation belongs to another session");
5995
+ const { beginMcpTaskContinuation } =
5996
+ await import("../lib/mcp-task-continuation.js");
5997
+ mcpContinuationStarted = beginMcpTaskContinuation(
5998
+ sessionId,
5999
+ mcpAutoWakeDelivery.localId,
6000
+ );
6001
+ mcpAutoWakeDelivery = mcpContinuationStarted.delivery;
6002
+ input = `Continue the existing user task using the verified external MCP reference (deliveryId: ${mcpAutoWakeDelivery.deliveryId}). This host continuation does not add user instructions or grant any new permissions.`;
6003
+ } catch (error) {
6004
+ logger.warn(`[mcp-watch] continuation not started: ${error.message}`);
6005
+ prompt();
6006
+ return;
6007
+ }
6008
+ }
5870
6009
  // Backslash continuation — accumulate and re-prompt without firing a turn.
5871
6010
  const _cont = analyzeContinuation(input);
5872
6011
  if (_cont.continued) {
@@ -5887,9 +6026,8 @@ async function startAgentReplInWorkspaceOwned(
5887
6026
  // to the model verbatim — the same fall-through an unmatched slash line
5888
6027
  // already takes. /exit and /quit stay live so the session can be closed.
5889
6028
  // Predicate + sentinel are pure (lib/slash-dispatch.js, unit-tested).
5890
- const { slashDispatchBypassed, slashBypassSentinel } = await import(
5891
- "../lib/slash-dispatch.js"
5892
- );
6029
+ const { slashDispatchBypassed, slashBypassSentinel } =
6030
+ await import("../lib/slash-dispatch.js");
5893
6031
  const _slashBypassed = slashDispatchBypassed(
5894
6032
  rawLine,
5895
6033
  _slashCommandsDisabled,
@@ -5918,9 +6056,8 @@ async function startAgentReplInWorkspaceOwned(
5918
6056
  // no LLM round-trip — and fold the output into the conversation context.
5919
6057
  if (trimmed.startsWith("!") && trimmed.slice(1).trim()) {
5920
6058
  try {
5921
- const { runBangCommand, shouldRespondToBashCommands } = await import(
5922
- "../lib/repl-bang-memorize.js"
5923
- );
6059
+ const { runBangCommand, shouldRespondToBashCommands } =
6060
+ await import("../lib/repl-bang-memorize.js");
5924
6061
  const res = runBangCommand(trimmed, { cwd: process.cwd() });
5925
6062
  logger.log(chalk.gray(`$ ${res.cmd}`));
5926
6063
  if (res.stdout)
@@ -5957,9 +6094,8 @@ async function startAgentReplInWorkspaceOwned(
5957
6094
  // cc.md (auto-loaded next session) and keep it active in this one.
5958
6095
  if (trimmed.startsWith("#") && trimmed.slice(1).trim()) {
5959
6096
  try {
5960
- const { appendMemoryNote } = await import(
5961
- "../lib/repl-bang-memorize.js"
5962
- );
6097
+ const { appendMemoryNote } =
6098
+ await import("../lib/repl-bang-memorize.js");
5963
6099
  const res = appendMemoryNote(trimmed, { cwd: process.cwd() });
5964
6100
  messages.push({
5965
6101
  role: "system",
@@ -6344,9 +6480,8 @@ async function startAgentReplInWorkspaceOwned(
6344
6480
  if (trimmed === "/init" || trimmed.startsWith("/init ")) {
6345
6481
  const force = /(^|\s)(--force|-f)(\s|$)/.test(trimmed);
6346
6482
  try {
6347
- const { inventoryProject, renderMemoryFile } = await import(
6348
- "../lib/project-inventory.js"
6349
- );
6483
+ const { inventoryProject, renderMemoryFile } =
6484
+ await import("../lib/project-inventory.js");
6350
6485
  const initCwd = process.cwd();
6351
6486
  const target = path.join(initCwd, "cc.md");
6352
6487
  if (fs.existsSync(target) && !force) {
@@ -6390,12 +6525,10 @@ async function startAgentReplInWorkspaceOwned(
6390
6525
  try {
6391
6526
  const { parseAgentsCommand, formatAgentsList, formatAgentDetail } =
6392
6527
  await import("./agents-status.js");
6393
- const { discoverAgents, getAgent, scaffoldAgent } = await import(
6394
- "../lib/agents.js"
6395
- );
6396
- const { listSubAgentProfiles } = await import(
6397
- "../lib/sub-agent-profiles.js"
6398
- );
6528
+ const { discoverAgents, getAgent, scaffoldAgent } =
6529
+ await import("../lib/agents.js");
6530
+ const { listSubAgentProfiles } =
6531
+ await import("../lib/sub-agent-profiles.js");
6399
6532
  const cmd = parseAgentsCommand(trimmed);
6400
6533
  if (cmd.action === "help") {
6401
6534
  logger.log(
@@ -6451,9 +6584,8 @@ async function startAgentReplInWorkspaceOwned(
6451
6584
 
6452
6585
  if (trimmed === "/sub-agents" || trimmed === "/subagents") {
6453
6586
  try {
6454
- const { SubAgentRegistry } = await import(
6455
- "../lib/sub-agent-registry.js"
6456
- );
6587
+ const { SubAgentRegistry } =
6588
+ await import("../lib/sub-agent-registry.js");
6457
6589
  const registry = SubAgentRegistry.getInstance();
6458
6590
  const active = registry.getActive();
6459
6591
  const history = registry.getHistory();
@@ -6505,9 +6637,8 @@ async function startAgentReplInWorkspaceOwned(
6505
6637
  // user could silently switch to a retired id and only learn of it when
6506
6638
  // the next turn fails with an opaque "model not found".
6507
6639
  try {
6508
- const { maybeWarnDeprecatedModel } = await import(
6509
- "../lib/model-deprecation.js"
6510
- );
6640
+ const { maybeWarnDeprecatedModel } =
6641
+ await import("../lib/model-deprecation.js");
6511
6642
  maybeWarnDeprecatedModel({ model });
6512
6643
  } catch {
6513
6644
  // deprecation notice is best-effort
@@ -6602,9 +6733,8 @@ async function startAgentReplInWorkspaceOwned(
6602
6733
  // One-shot advice is queued as an ephemeral prepareCall suffix, requiring
6603
6734
  // the main agent to validate it locally on its next model/tool turn.
6604
6735
  {
6605
- const { parseAdvisorCommand, executeAdvisorCommand } = await import(
6606
- "./advisor-command.js"
6607
- );
6736
+ const { parseAdvisorCommand, executeAdvisorCommand } =
6737
+ await import("./advisor-command.js");
6608
6738
  const advisorCommand = parseAdvisorCommand(trimmed);
6609
6739
  if (advisorCommand) {
6610
6740
  const result = await executeAdvisorCommand(advisorCommand, {
@@ -6643,9 +6773,8 @@ async function startAgentReplInWorkspaceOwned(
6643
6773
  // Stash the conversation first so `/rewind clear` can restore it
6644
6774
  // (Claude-Code 2.1.191). A no-op /clear (nothing to stash) keeps any
6645
6775
  // existing restorable snapshot.
6646
- const { snapshotClearedConversation } = await import(
6647
- "../lib/repl-rewind.js"
6648
- );
6776
+ const { snapshotClearedConversation } =
6777
+ await import("../lib/repl-rewind.js");
6649
6778
  const snap = snapshotClearedConversation(messages, _checkpointMarks);
6650
6779
  if (snap) _clearedConversation = snap;
6651
6780
  messages.length = 1; // Keep system prompt
@@ -6666,9 +6795,8 @@ async function startAgentReplInWorkspaceOwned(
6666
6795
  ) {
6667
6796
  try {
6668
6797
  const arg = trimmed.slice("/terminal-setup".length).trim();
6669
- const { runTerminalSetup } = await import(
6670
- "../commands/terminal-setup.js"
6671
- );
6798
+ const { runTerminalSetup } =
6799
+ await import("../commands/terminal-setup.js");
6672
6800
  const res = runTerminalSetup({ apply: arg === "--apply" });
6673
6801
  for (const l of res.lines) logger.log(l);
6674
6802
  } catch (err) {
@@ -6972,9 +7100,8 @@ async function startAgentReplInWorkspaceOwned(
6972
7100
  if (trimmed === "/output-style" || trimmed.startsWith("/output-style ")) {
6973
7101
  const arg = trimmed.slice("/output-style".length).trim();
6974
7102
  try {
6975
- const { discoverOutputStyles, getOutputStyle } = await import(
6976
- "../lib/output-styles.js"
6977
- );
7103
+ const { discoverOutputStyles, getOutputStyle } =
7104
+ await import("../lib/output-styles.js");
6978
7105
  if (!arg) {
6979
7106
  logger.log(chalk.bold("Output styles:"));
6980
7107
  for (const s of discoverOutputStyles(process.cwd())) {
@@ -7042,15 +7169,13 @@ async function startAgentReplInWorkspaceOwned(
7042
7169
  // (byte-unchanged) without a registered CwdChanged hook.
7043
7170
  if (_settingsHooks && oldCwd !== newCwd) {
7044
7171
  try {
7045
- const { runCwdChangedHooks, dispatchAsyncHooks } = await import(
7046
- "../lib/settings-hook-events.js"
7047
- );
7172
+ const { runCwdChangedHooks, dispatchAsyncHooks } =
7173
+ await import("../lib/settings-hook-events.js");
7048
7174
  const payload = { oldCwd, newCwd, sessionId };
7049
7175
  await runCwdChangedHooks(_settingsHooks, payload);
7050
7176
  if (!_asyncHookSupervisor) {
7051
- const { AsyncHookSupervisor } = await import(
7052
- "../lib/async-hook-supervisor.js"
7053
- );
7177
+ const { AsyncHookSupervisor } =
7178
+ await import("../lib/async-hook-supervisor.js");
7054
7179
  _asyncHookSupervisor = new AsyncHookSupervisor({
7055
7180
  persistStats: true,
7056
7181
  });
@@ -7110,9 +7235,8 @@ async function startAgentReplInWorkspaceOwned(
7110
7235
  (parsed.command === "turn" || parsed.command === "branch")
7111
7236
  ) {
7112
7237
  try {
7113
- const { loadTurnBindingLog } = await import(
7114
- "../lib/turn-binding-store.js"
7115
- );
7238
+ const { loadTurnBindingLog } =
7239
+ await import("../lib/turn-binding-store.js");
7116
7240
  _persistedBinding = loadTurnBindingLog(sessionId);
7117
7241
  } catch {
7118
7242
  /* marks-only fallback */
@@ -7171,9 +7295,8 @@ async function startAgentReplInWorkspaceOwned(
7171
7295
  logger.error("Could not plan a branch from that turn.");
7172
7296
  } else {
7173
7297
  try {
7174
- const { createBranchSession } = await import(
7175
- "../harness/jsonl-session-store.js"
7176
- );
7298
+ const { createBranchSession } =
7299
+ await import("../harness/jsonl-session-store.js");
7177
7300
  const res = createBranchSession({
7178
7301
  branchSessionId: plan.branchSessionId,
7179
7302
  parentSessionId: sessionId,
@@ -7307,9 +7430,8 @@ async function startAgentReplInWorkspaceOwned(
7307
7430
  .toLowerCase();
7308
7431
  if (ans === "" || ans === "y" || ans === "yes") {
7309
7432
  try {
7310
- const { rewindTo } = await import(
7311
- "../lib/checkpoint-store.js"
7312
- );
7433
+ const { rewindTo } =
7434
+ await import("../lib/checkpoint-store.js");
7313
7435
  const r = rewindTo(process.cwd(), cp.id, {
7314
7436
  session: sessionId,
7315
7437
  });
@@ -7359,9 +7481,8 @@ async function startAgentReplInWorkspaceOwned(
7359
7481
  // window. Reuses the same categorizer + estimator as the archived view.
7360
7482
  try {
7361
7483
  const { categorizeContext } = await import("../commands/context.js");
7362
- const { estimateTokens } = await import(
7363
- "../harness/prompt-compressor.js"
7364
- );
7484
+ const { estimateTokens } =
7485
+ await import("../harness/prompt-compressor.js");
7365
7486
  const { buckets, counts, total } = categorizeContext(
7366
7487
  messages,
7367
7488
  estimateTokens,
@@ -7394,9 +7515,8 @@ async function startAgentReplInWorkspaceOwned(
7394
7515
  : ""
7395
7516
  }`,
7396
7517
  );
7397
- const { default: sourceLedger } = await import(
7398
- "../lib/context-source-ledger.js"
7399
- );
7518
+ const { default: sourceLedger } =
7519
+ await import("../lib/context-source-ledger.js");
7400
7520
  const attribution = sourceLedger.getTokenReport({ sessionId });
7401
7521
  if (attribution.entries) {
7402
7522
  logger.log(
@@ -7417,9 +7537,8 @@ async function startAgentReplInWorkspaceOwned(
7417
7537
  // `messages`, so it's invisible to the role buckets above. Show the
7418
7538
  // per-server schema cost + tool-search state + optimization advice.
7419
7539
  if (_adhocMcp?.extraToolDefinitions?.length) {
7420
- const { describeMcpToolContext } = await import(
7421
- "../runtime/mcp-tool-search.js"
7422
- );
7540
+ const { describeMcpToolContext } =
7541
+ await import("../runtime/mcp-tool-search.js");
7423
7542
  const info = describeMcpToolContext(_adhocMcp, {
7424
7543
  estimate: estimateTokens,
7425
7544
  model,
@@ -7893,19 +8012,16 @@ async function startAgentReplInWorkspaceOwned(
7893
8012
  if (trimmed === "/reload-plugins") {
7894
8013
  try {
7895
8014
  const cwd = process.cwd();
7896
- const { reloadPluginRuntime } = await import(
7897
- "../lib/plugin-runtime/reload.js"
7898
- );
8015
+ const { reloadPluginRuntime } =
8016
+ await import("../lib/plugin-runtime/reload.js");
7899
8017
  const sum = reloadPluginRuntime({ cwd });
7900
8018
 
7901
8019
  // Re-merge plugin hooks onto the user's settings hooks (live session).
7902
8020
  try {
7903
- const { loadHooks, attachAuthorityErrors } = await import(
7904
- "../lib/settings-hooks.cjs"
7905
- );
7906
- const { mergePluginHooks } = await import(
7907
- "../lib/plugin-runtime/hooks.js"
7908
- );
8021
+ const { loadHooks, attachAuthorityErrors } =
8022
+ await import("../lib/settings-hooks.cjs");
8023
+ const { mergePluginHooks } =
8024
+ await import("../lib/plugin-runtime/hooks.js");
7909
8025
  const loaded = loadHooks({ cwd });
7910
8026
  const merged = mergePluginHooks(
7911
8027
  attachAuthorityErrors(loaded.hooks, loaded.authorityErrors),
@@ -7934,9 +8050,8 @@ async function startAgentReplInWorkspaceOwned(
7934
8050
  // react (e.g. re-audit the newly-trusted config). Best-effort.
7935
8051
  if (_settingsHooks) {
7936
8052
  try {
7937
- const { runObserveHooks, dispatchAsyncHooks } = await import(
7938
- "../lib/settings-hook-events.js"
7939
- );
8053
+ const { runObserveHooks, dispatchAsyncHooks } =
8054
+ await import("../lib/settings-hook-events.js");
7940
8055
  const payload = {
7941
8056
  session_id: sessionId || null,
7942
8057
  source: "reload-plugins",
@@ -7945,9 +8060,8 @@ async function startAgentReplInWorkspaceOwned(
7945
8060
  cwd,
7946
8061
  });
7947
8062
  if (!_asyncHookSupervisor) {
7948
- const { AsyncHookSupervisor } = await import(
7949
- "../lib/async-hook-supervisor.js"
7950
- );
8063
+ const { AsyncHookSupervisor } =
8064
+ await import("../lib/async-hook-supervisor.js");
7951
8065
  _asyncHookSupervisor = new AsyncHookSupervisor({
7952
8066
  persistStats: true,
7953
8067
  });
@@ -7963,18 +8077,16 @@ async function startAgentReplInWorkspaceOwned(
7963
8077
 
7964
8078
  // Restart background monitors with the fresh, trust-gated set.
7965
8079
  try {
7966
- const { collectPluginMonitors } = await import(
7967
- "../lib/plugin-runtime/monitors.js"
7968
- );
8080
+ const { collectPluginMonitors } =
8081
+ await import("../lib/plugin-runtime/monitors.js");
7969
8082
  if (_pluginMonitors) {
7970
8083
  _pluginMonitors.stopAll();
7971
8084
  _pluginMonitors = null;
7972
8085
  }
7973
8086
  const monitors = collectPluginMonitors({ cwd });
7974
8087
  if (monitors.length > 0) {
7975
- const { PluginMonitorSupervisor } = await import(
7976
- "../lib/plugin-monitor-supervisor.js"
7977
- );
8088
+ const { PluginMonitorSupervisor } =
8089
+ await import("../lib/plugin-monitor-supervisor.js");
7978
8090
  _pluginMonitors = new PluginMonitorSupervisor();
7979
8091
  _pluginMonitors.start(monitors);
7980
8092
  }
@@ -7984,9 +8096,8 @@ async function startAgentReplInWorkspaceOwned(
7984
8096
 
7985
8097
  // Re-apply legacy plugin bin PATH; strict bins remain direct-only.
7986
8098
  try {
7987
- const { applyPluginBinPath } = await import(
7988
- "../lib/plugin-runtime/bin.js"
7989
- );
8099
+ const { applyPluginBinPath } =
8100
+ await import("../lib/plugin-runtime/bin.js");
7990
8101
  if (_pluginBinRestore) _pluginBinRestore();
7991
8102
  const res = applyPluginBinPath({ cwd });
7992
8103
  _pluginBinRestore = res.restore;
@@ -7996,9 +8107,8 @@ async function startAgentReplInWorkspaceOwned(
7996
8107
 
7997
8108
  // Re-apply plugin default env vars (a newly-trusted plugin's settings).
7998
8109
  try {
7999
- const { applyPluginSettingsEnv } = await import(
8000
- "../lib/plugin-runtime/settings.js"
8001
- );
8110
+ const { applyPluginSettingsEnv } =
8111
+ await import("../lib/plugin-runtime/settings.js");
8002
8112
  if (_pluginSettingsRestore) _pluginSettingsRestore();
8003
8113
  const res = applyPluginSettingsEnv({ cwd });
8004
8114
  _pluginSettingsRestore = res.restore;
@@ -8031,9 +8141,8 @@ async function startAgentReplInWorkspaceOwned(
8031
8141
  // cwd so it follows `/cd`, using this session's provider/model.
8032
8142
  if (trimmed === "/review" || trimmed.startsWith("/review ")) {
8033
8143
  const rest = trimmed.slice("/review".length).trim();
8034
- const { parseReviewReplArgs, describeReviewArgs } = await import(
8035
- "./review-args.js"
8036
- );
8144
+ const { parseReviewReplArgs, describeReviewArgs } =
8145
+ await import("./review-args.js");
8037
8146
  const { opts: reviewOpts, errors } = parseReviewReplArgs(rest);
8038
8147
  if (errors.length) {
8039
8148
  for (const e of errors) logger.error(chalk.red(`/review: ${e}`));
@@ -8244,9 +8353,8 @@ async function startAgentReplInWorkspaceOwned(
8244
8353
  logger.log("");
8245
8354
  } else if (subCmd === "debate" && coworkInput) {
8246
8355
  try {
8247
- const { startDebate } = await import(
8248
- "../lib/cowork/debate-review-cli.js"
8249
- );
8356
+ const { startDebate } =
8357
+ await import("../lib/cowork/debate-review-cli.js");
8250
8358
  let code = coworkInput;
8251
8359
  let targetLabel = coworkInput;
8252
8360
  const resolved = path.resolve(coworkInput);
@@ -8296,9 +8404,8 @@ async function startAgentReplInWorkspaceOwned(
8296
8404
  }
8297
8405
  } else if (subCmd === "compare" && coworkInput) {
8298
8406
  try {
8299
- const { compare } = await import(
8300
- "../lib/cowork/ab-comparator-cli.js"
8301
- );
8407
+ const { compare } =
8408
+ await import("../lib/cowork/ab-comparator-cli.js");
8302
8409
  process.stdout.write(chalk.gray("\n Generating variants...\n"));
8303
8410
  const result = await compare({
8304
8411
  prompt: coworkInput,
@@ -8330,9 +8437,8 @@ async function startAgentReplInWorkspaceOwned(
8330
8437
  }
8331
8438
  } else if (subCmd === "graph" && coworkInput) {
8332
8439
  try {
8333
- const { buildKnowledgeGraph } = await import(
8334
- "../lib/cowork/code-knowledge-graph-cli.js"
8335
- );
8440
+ const { buildKnowledgeGraph } =
8441
+ await import("../lib/cowork/code-knowledge-graph-cli.js");
8336
8442
  process.stdout.write(chalk.gray("\n Analyzing code graph...\n"));
8337
8443
  const result = await buildKnowledgeGraph({
8338
8444
  targetPath: path.resolve(coworkInput),
@@ -8369,9 +8475,8 @@ async function startAgentReplInWorkspaceOwned(
8369
8475
  }
8370
8476
  } else if (subCmd === "decision" && coworkInput) {
8371
8477
  try {
8372
- const { extractDecisions } = await import(
8373
- "../lib/cowork/decision-kb-cli.js"
8374
- );
8478
+ const { extractDecisions } =
8479
+ await import("../lib/cowork/decision-kb-cli.js");
8375
8480
  process.stdout.write(chalk.gray("\n Analyzing decisions...\n"));
8376
8481
  const result = await extractDecisions({
8377
8482
  targetPath: path.resolve(coworkInput),
@@ -8637,9 +8742,8 @@ async function startAgentReplInWorkspaceOwned(
8637
8742
  { messages, signal: _turnAbort?.signal || null },
8638
8743
  );
8639
8744
  if (result.ok) {
8640
- const { renderAdvisorAdvice } = await import(
8641
- "./advisor-command.js"
8642
- );
8745
+ const { renderAdvisorAdvice } =
8746
+ await import("./advisor-command.js");
8643
8747
  logger.log(renderAdvisorAdvice(result));
8644
8748
  } else if (result.effect !== "disabled") {
8645
8749
  logger.warn(result.error);
@@ -8741,12 +8845,10 @@ async function startAgentReplInWorkspaceOwned(
8741
8845
  const planRequest =
8742
8846
  subCmd.slice(11).trim() || "Help me with the current task";
8743
8847
  try {
8744
- const { CLIInteractivePlanner } = await import(
8745
- "../lib/interactive-planner.js"
8746
- );
8747
- const { TerminalInteractionAdapter } = await import(
8748
- "../lib/interaction-adapter.js"
8749
- );
8848
+ const { CLIInteractivePlanner } =
8849
+ await import("../lib/interactive-planner.js");
8850
+ const { TerminalInteractionAdapter } =
8851
+ await import("../lib/interaction-adapter.js");
8750
8852
  const chatFn = createChatFn({
8751
8853
  ...(evolutionIngress === null ? {} : { evolutionIngress }),
8752
8854
  provider,
@@ -8825,9 +8927,8 @@ async function startAgentReplInWorkspaceOwned(
8825
8927
  // a note) and `cc memory recall` (scoped store).
8826
8928
  if (trimmed === "/memory" || trimmed.startsWith("/memory ")) {
8827
8929
  try {
8828
- const { loadProjectInstructions } = await import(
8829
- "../lib/project-instructions.js"
8830
- );
8930
+ const { loadProjectInstructions } =
8931
+ await import("../lib/project-instructions.js");
8831
8932
  const { renderMemoryFiles } = await import("./memory-status.js");
8832
8933
  const loaded = loadProjectInstructions({ cwd: process.cwd() });
8833
8934
  logger.log(
@@ -8843,6 +8944,88 @@ async function startAgentReplInWorkspaceOwned(
8843
8944
  }
8844
8945
 
8845
8946
  // `/mcp` — overview of connected MCP servers' resources + prompts.
8947
+ // `/mcp-watch [local-id]` starts explicit, lease-bound durable task
8948
+ // tracking in this REPL. Delivery remains an external reference event;
8949
+ // it never becomes an implicit user prompt or model instruction.
8950
+ if (trimmed === "/mcp-watch" || trimmed.startsWith("/mcp-watch ")) {
8951
+ try {
8952
+ if (!sessionId || !useJsonl || !_sessionHostLeaseScope?.lease) {
8953
+ throw new Error(
8954
+ "MCP task tracking requires an active canonical session lease",
8955
+ );
8956
+ }
8957
+ const hostMcp = _getReplHostMcp();
8958
+ if (!hostMcp?.mcpClient) {
8959
+ throw new Error("No connected MCP client is available");
8960
+ }
8961
+ const { listDurableMcpTasks, createDurableMcpTaskRuntime } =
8962
+ await import("../lib/mcp-task-runtime.js");
8963
+ const { readMcpTaskJournal } =
8964
+ await import("../lib/mcp-task-journal.js");
8965
+ const requested = trimmed.slice("/mcp-watch".length).trim();
8966
+ const journal = readMcpTaskJournal(sessionId);
8967
+ const { records: durableRecords } = listDurableMcpTasks(sessionId);
8968
+ const records = durableRecords.filter(
8969
+ (record) =>
8970
+ (!requested || record.localId === requested) &&
8971
+ !_mcpTaskTrackers.has(record.localId) &&
8972
+ !journal.continuations.some(
8973
+ (item) => item.localId === record.localId,
8974
+ ) &&
8975
+ (!record.delivered || process.env.CC_MCP_TASK_AUTOWAKE === "1"),
8976
+ );
8977
+ if (
8978
+ requested &&
8979
+ !records.some((record) => record.localId === requested)
8980
+ ) {
8981
+ throw new Error("No pending durable MCP task matches that local id");
8982
+ }
8983
+ for (const record of records) {
8984
+ const runtime = createDurableMcpTaskRuntime({
8985
+ client: hostMcp.mcpClient,
8986
+ sessionId,
8987
+ lease: _sessionHostLeaseScope.lease,
8988
+ });
8989
+ const tracker = runtime.startTracking(record.localId, {
8990
+ deliver: true,
8991
+ onUpdate: (update) => {
8992
+ logger.verbose(
8993
+ `[mcp-watch] ${record.localId}: ${
8994
+ update.remoteStatus || update.phase
8995
+ }`,
8996
+ );
8997
+ },
8998
+ onDelivery: (receipt, delivery) => {
8999
+ const scheduled = scheduleMcpTaskAutoWake(delivery);
9000
+ logger.log(
9001
+ chalk.green(
9002
+ `✓ MCP task ${receipt.localId} delivered as external reference; ${scheduled ? "continuation queued." : "submit a prompt to continue."}`,
9003
+ ),
9004
+ );
9005
+ },
9006
+ });
9007
+ _mcpTaskTrackers.set(record.localId, tracker);
9008
+ void tracker.promise
9009
+ .catch((error) => {
9010
+ if (error?.code !== "CC_MCP_TASK_TRACKING_STOPPED") {
9011
+ logger.warn(
9012
+ `[mcp-watch] ${record.localId} stopped: ${error.message}`,
9013
+ );
9014
+ }
9015
+ })
9016
+ .finally(() => _mcpTaskTrackers.delete(record.localId));
9017
+ }
9018
+ logger.log(
9019
+ records.length
9020
+ ? `MCP task tracking started for ${records.length} task(s).`
9021
+ : "No pending durable MCP tasks require tracking.",
9022
+ );
9023
+ } catch (error) {
9024
+ logger.error(chalk.red(`/mcp-watch failed: ${error.message}`));
9025
+ }
9026
+ prompt();
9027
+ return;
9028
+ }
8846
9029
  if (trimmed === "/mcp" || trimmed.startsWith("/mcp ")) {
8847
9030
  const mcpClient = _getReplHostMcp()?.mcpClient;
8848
9031
  logger.log(renderMcpSurface(mcpClient));
@@ -8919,9 +9102,8 @@ async function startAgentReplInWorkspaceOwned(
8919
9102
  } catch (_err) {
8920
9103
  // config read is best-effort; checks degrade gracefully
8921
9104
  }
8922
- const { buildDoctorChecks, renderDoctor } = await import(
8923
- "./doctor-status.js"
8924
- );
9105
+ const { buildDoctorChecks, renderDoctor } =
9106
+ await import("./doctor-status.js");
8925
9107
  const { ideToolNames } = await import("./ide-status.js");
8926
9108
  const checks = buildDoctorChecks({
8927
9109
  config,
@@ -9342,10 +9524,12 @@ async function startAgentReplInWorkspaceOwned(
9342
9524
  // Fire UserPromptSubmit hook with rewrite/abort support.
9343
9525
  // Hooks may emit {"rewrittenPrompt": "..."} or {"abort": true, "reason": "..."}
9344
9526
  // via stdout JSON. Failures fall through to the original prompt.
9345
- const promptDirective = await fireUserPromptSubmit(_hookDb, promptText, {
9346
- sessionId,
9347
- messageCount: messages.length,
9348
- });
9527
+ const promptDirective = mcpContinuationStarted
9528
+ ? { prompt: promptText }
9529
+ : await fireUserPromptSubmit(_hookDb, promptText, {
9530
+ sessionId,
9531
+ messageCount: messages.length,
9532
+ });
9349
9533
  if (promptDirective.abort) {
9350
9534
  logger.info(
9351
9535
  chalk.yellow(
@@ -9392,11 +9576,10 @@ async function startAgentReplInWorkspaceOwned(
9392
9576
 
9393
9577
  // settings.json UserPromptSubmit hooks (decision-capable; the DB hook above
9394
9578
  // is observe-only). block → abort the turn; context → inject before the turn.
9395
- if (_settingsHooks) {
9579
+ if (_settingsHooks && !mcpContinuationStarted) {
9396
9580
  try {
9397
- const { runUserPromptSubmitHooks } = await import(
9398
- "../lib/settings-hook-events.js"
9399
- );
9581
+ const { runUserPromptSubmitHooks } =
9582
+ await import("../lib/settings-hook-events.js");
9400
9583
  const ups = await runUserPromptSubmitHooks(_settingsHooks, {
9401
9584
  prompt: userContent,
9402
9585
  cwd: process.cwd(),
@@ -9418,13 +9601,11 @@ async function startAgentReplInWorkspaceOwned(
9418
9601
  // long-running check (background tests, CI status) runs ALONGSIDE this
9419
9602
  // turn without blocking it; its result/rewake surfaces on a later turn
9420
9603
  // via the async-hook drain below. Lazily create the supervisor.
9421
- const { dispatchAsyncHooks } = await import(
9422
- "../lib/settings-hook-events.js"
9423
- );
9604
+ const { dispatchAsyncHooks } =
9605
+ await import("../lib/settings-hook-events.js");
9424
9606
  if (!_asyncHookSupervisor) {
9425
- const { AsyncHookSupervisor } = await import(
9426
- "../lib/async-hook-supervisor.js"
9427
- );
9607
+ const { AsyncHookSupervisor } =
9608
+ await import("../lib/async-hook-supervisor.js");
9428
9609
  _asyncHookSupervisor = new AsyncHookSupervisor({
9429
9610
  persistStats: true,
9430
9611
  });
@@ -9512,9 +9693,8 @@ async function startAgentReplInWorkspaceOwned(
9512
9693
  // Ephemeral: persistence stores effectivePrompt, not this snapshot.
9513
9694
  // Best-effort; CC_IDE_CONTEXT=0 disables.
9514
9695
  try {
9515
- const { buildIdePromptContext, expandIdeMentions } = await import(
9516
- "../lib/ide-context.js"
9517
- );
9696
+ const { buildIdePromptContext, expandIdeMentions } =
9697
+ await import("../lib/ide-context.js");
9518
9698
  const hostMcp = _getReplHostMcp();
9519
9699
  const ideCtx = await buildIdePromptContext(hostMcp);
9520
9700
  if (ideCtx) userContent += `\n\n${ideCtx}`;
@@ -9579,7 +9759,9 @@ async function startAgentReplInWorkspaceOwned(
9579
9759
  // Explicit clipboard attachment chips are consumed only when a real model
9580
9760
  // turn is about to start. They compose with auto-detected path images and
9581
9761
  // enter the same provider-neutral multimodal message/vision override.
9582
- const clipboardImageChips = _promptInteractions.takeClipboardImageChips();
9762
+ const clipboardImageChips = mcpContinuationStarted
9763
+ ? []
9764
+ : _promptInteractions.takeClipboardImageChips();
9583
9765
  const clipboardMerge = mergeClipboardImageChips(
9584
9766
  _userMessageContent,
9585
9767
  clipboardImageChips,
@@ -9608,8 +9790,22 @@ async function startAgentReplInWorkspaceOwned(
9608
9790
 
9609
9791
  // Add user message (keep the object ref so /note-next can be injected for
9610
9792
  // this turn's model call and then stripped before persistence).
9611
- const _userMsg = { role: "user", content: _userMessageContent };
9612
- messages.push(_userMsg);
9793
+ if (mcpAutoWakeDelivery?.message) {
9794
+ const reference = mcpAutoWakeDelivery.message;
9795
+ if (
9796
+ !messages.some(
9797
+ (item) =>
9798
+ item.role === reference.role &&
9799
+ item.name === reference.name &&
9800
+ item.content === reference.content,
9801
+ )
9802
+ )
9803
+ messages.push({ ...reference });
9804
+ }
9805
+ const _userMsg = mcpContinuationStarted
9806
+ ? null
9807
+ : { role: "user", content: _userMessageContent };
9808
+ if (_userMsg) messages.push(_userMsg);
9613
9809
 
9614
9810
  // P1 turn→checkpoint binding: anchor this turn in the explicit table at
9615
9811
  // `conversationOffset = messages.length` measured just AFTER the user
@@ -9620,9 +9816,8 @@ async function startAgentReplInWorkspaceOwned(
9620
9816
  if (sessionId && useJsonl) {
9621
9817
  try {
9622
9818
  if (!_turnBindingProducer) {
9623
- const { createReplTurnBindingProducer } = await import(
9624
- "./repl-turn-binding.js"
9625
- );
9819
+ const { createReplTurnBindingProducer } =
9820
+ await import("./repl-turn-binding.js");
9626
9821
  _turnBindingProducer = createReplTurnBindingProducer({
9627
9822
  sessionId,
9628
9823
  onError: (error, phase) => {
@@ -9652,13 +9847,12 @@ async function startAgentReplInWorkspaceOwned(
9652
9847
  try {
9653
9848
  const { CLISlotFiller } = await import("../lib/slot-filler.js");
9654
9849
  const intent = CLISlotFiller.detectIntent(promptText);
9655
- if (intent) {
9850
+ if (intent && !mcpContinuationStarted) {
9656
9851
  const defs = CLISlotFiller.getSlotDefinitions(intent.type);
9657
9852
  const missing = defs.required.filter((s) => !intent.entities[s]);
9658
9853
  if (missing.length > 0) {
9659
- const { TerminalInteractionAdapter } = await import(
9660
- "../lib/interaction-adapter.js"
9661
- );
9854
+ const { TerminalInteractionAdapter } =
9855
+ await import("../lib/interaction-adapter.js");
9662
9856
  const interaction = new TerminalInteractionAdapter();
9663
9857
  const filler = new CLISlotFiller({ interaction });
9664
9858
  const result = await filler.fillSlots(intent, {
@@ -9695,7 +9889,7 @@ async function startAgentReplInWorkspaceOwned(
9695
9889
  // get a 401). Runnable-first: keep the configured (working) model instead.
9696
9890
  let activeModel = model;
9697
9891
  const taskDetection = detectTaskType(promptText);
9698
- if (taskDetection.confidence > 0.3) {
9892
+ if (taskDetection.confidence > 0.3 && !mcpContinuationStarted) {
9699
9893
  const recommended = selectModelForTask(provider, taskDetection.taskType);
9700
9894
  const switchTo = runnableTaskModel({
9701
9895
  provider,
@@ -9738,6 +9932,28 @@ async function startAgentReplInWorkspaceOwned(
9738
9932
  }
9739
9933
 
9740
9934
  try {
9935
+ // Durable REPL input admission is a hard boundary: persist the exact
9936
+ // effective prompt before any provider dispatch. The acceptance event is
9937
+ // intentionally excluded from replay history; only a later settled event
9938
+ // publishes the user/assistant pair. Legacy and non-JSONL sessions keep
9939
+ // their existing best-effort behavior.
9940
+ _sessionInputAccepted = null;
9941
+ if (sessionId && useJsonl && !mcpContinuationStarted) {
9942
+ try {
9943
+ _sessionInputAccepted = appendSessionInputAcceptance(sessionId, {
9944
+ inputId: `repl-${randomUUID()}`,
9945
+ turnId: `${sessionId}:turn-${_turnCount + 1}`,
9946
+ prompt: effectivePrompt,
9947
+ });
9948
+ } catch (error) {
9949
+ const persistenceError = markRuntimeLedgerPersistenceError(error);
9950
+ logger.error(
9951
+ `[recovery] refusing provider dispatch because input acceptance was not persisted: ${persistenceError.message}`,
9952
+ );
9953
+ prompt();
9954
+ return;
9955
+ }
9956
+ }
9741
9957
  process.stdout.write("\n");
9742
9958
  const iterationBudget = new IterationBudget({ owner: sessionId });
9743
9959
  // Bind a cross-session goal (cc goal) into this run, if one resolves.
@@ -9747,9 +9963,8 @@ async function startAgentReplInWorkspaceOwned(
9747
9963
  const { resolveActiveGoal } = await import("../lib/goal-store.js");
9748
9964
  const boundGoal = resolveActiveGoal({ sessionId });
9749
9965
  if (boundGoal) {
9750
- const { goalPrepareCall, composePrepareCall } = await import(
9751
- "../lib/goal-context.js"
9752
- );
9966
+ const { goalPrepareCall, composePrepareCall } =
9967
+ await import("../lib/goal-context.js");
9753
9968
  prepareCall = composePrepareCall([
9754
9969
  defaultPrepareCall,
9755
9970
  goalPrepareCall(boundGoal),
@@ -9758,6 +9973,13 @@ async function startAgentReplInWorkspaceOwned(
9758
9973
  } catch (_e) {
9759
9974
  /* goal binding is best-effort — fall back to defaultPrepareCall */
9760
9975
  }
9976
+ if (mcpContinuationStarted) {
9977
+ const { composePrepareCall } = await import("../lib/goal-context.js");
9978
+ prepareCall = composePrepareCall([
9979
+ prepareCall,
9980
+ () => ({ systemSuffix: input }),
9981
+ ]);
9982
+ }
9761
9983
  _turnAbort = new AbortController();
9762
9984
  if (_advisorRuntime) {
9763
9985
  _advisorRuntime.beginTurn(
@@ -9775,9 +9997,8 @@ async function startAgentReplInWorkspaceOwned(
9775
9997
  }
9776
9998
  return;
9777
9999
  }
9778
- const { renderAdvisorAdvice } = await import(
9779
- "./advisor-command.js"
9780
- );
10000
+ const { renderAdvisorAdvice } =
10001
+ await import("./advisor-command.js");
9781
10002
  process.stderr.write(`\n${renderAdvisorAdvice(result)}\n`);
9782
10003
  },
9783
10004
  });
@@ -9819,7 +10040,7 @@ async function startAgentReplInWorkspaceOwned(
9819
10040
  // persisted (saveMessages/JSONL) or carried into later turns. Consumed on
9820
10041
  // send (cleared now) so a thrown turn doesn't re-inject next time; the
9821
10042
  // submit-start backstop restores if agentLoop throws before we get back.
9822
- if (pendingBtw.length > 0) {
10043
+ if (pendingBtw.length > 0 && !mcpContinuationStarted) {
9823
10044
  const block = buildAsideBlock(pendingBtw);
9824
10045
  if (block) {
9825
10046
  _btwRestore = { msg: _userMsg, content: _userMsg.content };
@@ -9838,9 +10059,8 @@ async function startAgentReplInWorkspaceOwned(
9838
10059
  // hooks (fired inside the loop, per tool call) can be dispatched
9839
10060
  // fire-and-forget; their results/rewakes drain into the next turn above.
9840
10061
  if (_settingsHooks && !_asyncHookSupervisor) {
9841
- const { AsyncHookSupervisor } = await import(
9842
- "../lib/async-hook-supervisor.js"
9843
- );
10062
+ const { AsyncHookSupervisor } =
10063
+ await import("../lib/async-hook-supervisor.js");
9844
10064
  _asyncHookSupervisor = new AsyncHookSupervisor({
9845
10065
  persistStats: true,
9846
10066
  });
@@ -9853,6 +10073,7 @@ async function startAgentReplInWorkspaceOwned(
9853
10073
  usageEvents,
9854
10074
  thinking: reasoning,
9855
10075
  } = await agentLoop(messages, {
10076
+ contextMemoryRecall: recallMemory,
9856
10077
  contextMemoryModelWindowTokens: options.contextMemoryModelWindowTokens,
9857
10078
  ...captureSkillRuntimeDependencies(options),
9858
10079
  ...liveOpts,
@@ -9912,6 +10133,7 @@ async function startAgentReplInWorkspaceOwned(
9912
10133
  model: _visionLlm ? _visionLlm.model : activeModel,
9913
10134
  thinking: turnThinking,
9914
10135
  thinkingBudget,
10136
+ maxOutputTokens: options.maxOutputTokens,
9915
10137
  baseUrl: _visionLlm ? _visionLlm.baseUrl : baseUrl,
9916
10138
  apiKey: _visionLlm ? _visionLlm.apiKey : apiKey,
9917
10139
  serviceTier: options.serviceTier,
@@ -9954,6 +10176,7 @@ async function startAgentReplInWorkspaceOwned(
9954
10176
  // previous absent ceiling also yielded "default").
9955
10177
  subAgentContract: {
9956
10178
  permissionMode: permissionModeForTier(_sessionTier),
10179
+ ...(recallMemory ? {} : { memory: false }),
9957
10180
  },
9958
10181
  prepareCall,
9959
10182
  approvalGate: _approvalGate,
@@ -10029,9 +10252,8 @@ async function startAgentReplInWorkspaceOwned(
10029
10252
  const fsMod = await import("node:fs");
10030
10253
  const judge = async (cond, { finalText }) => {
10031
10254
  const { chatWithTools } = await import("../runtime/agent-core.js");
10032
- const { firstBalancedJson } = await import(
10033
- "../lib/json-schema-output.js"
10034
- );
10255
+ const { firstBalancedJson } =
10256
+ await import("../lib/json-schema-output.js");
10035
10257
  const p =
10036
10258
  `Judge whether this coding session met a completion condition.\n` +
10037
10259
  `Condition: ${cond.text || cond.source}\n\n` +
@@ -10043,6 +10265,7 @@ async function startAgentReplInWorkspaceOwned(
10043
10265
  source: "model",
10044
10266
  call: ({ signal }) =>
10045
10267
  chatWithTools([{ role: "user", content: p }], {
10268
+ contextMemoryRecall: recallMemory,
10046
10269
  ...(evolutionIngress === null ? {} : { evolutionIngress }),
10047
10270
  model: activeModel,
10048
10271
  provider,
@@ -10133,9 +10356,8 @@ async function startAgentReplInWorkspaceOwned(
10133
10356
  } else {
10134
10357
  // Phase G #2 — route through StreamRouter so REPL / WS / future
10135
10358
  // streaming providers share one StreamEvent protocol.
10136
- const { streamAgentResponse } = await import(
10137
- "../lib/agent-stream.js"
10138
- );
10359
+ const { streamAgentResponse } =
10360
+ await import("../lib/agent-stream.js");
10139
10361
  process.stdout.write("\n");
10140
10362
  const noStream = options.noStream === true;
10141
10363
  const streamResult = await streamAgentResponse(effectiveResponse, {
@@ -10174,24 +10396,66 @@ async function startAgentReplInWorkspaceOwned(
10174
10396
  if (sessionId) {
10175
10397
  try {
10176
10398
  if (useJsonl) {
10177
- // Append incremental events (user + assistant)
10178
- appendUserMessage(sessionId, effectivePrompt);
10179
- _replCompactPersistence.record({
10180
- role: "user",
10181
- content: effectivePrompt,
10182
- });
10183
- if (effectiveResponse) {
10399
+ // A settled lifecycle event is the only replayable representation
10400
+ // of this REPL turn. The accepted prompt remains private pending
10401
+ // evidence until this append succeeds.
10402
+ if (mcpContinuationStarted) {
10403
+ const { settleMcpTaskContinuation } =
10404
+ await import("../lib/mcp-task-continuation.js");
10405
+ settleMcpTaskContinuation(
10406
+ sessionId,
10407
+ mcpContinuationStarted,
10408
+ effectiveResponse || "",
10409
+ );
10410
+ _replCompactPersistence.record({
10411
+ role: "assistant",
10412
+ content: effectiveResponse || "",
10413
+ });
10414
+ } else if (_sessionInputAccepted) {
10415
+ appendSessionInputSettlement(
10416
+ sessionId,
10417
+ _sessionInputAccepted,
10418
+ effectiveResponse || "",
10419
+ );
10420
+ } else {
10421
+ // This branch is retained for older injected hosts that do not
10422
+ // use the durable input lifecycle.
10423
+ appendUserMessage(sessionId, effectivePrompt);
10424
+ }
10425
+ if (!mcpContinuationStarted)
10426
+ _replCompactPersistence.record({
10427
+ role: "user",
10428
+ content: effectivePrompt,
10429
+ });
10430
+ if (
10431
+ effectiveResponse &&
10432
+ !_sessionInputAccepted &&
10433
+ !mcpContinuationStarted
10434
+ ) {
10184
10435
  appendAssistantMessage(sessionId, effectiveResponse);
10185
10436
  _replCompactPersistence.record({
10186
10437
  role: "assistant",
10187
10438
  content: effectiveResponse,
10188
10439
  });
10189
10440
  }
10441
+ if (_sessionInputAccepted) {
10442
+ _replCompactPersistence.record({
10443
+ role: "assistant",
10444
+ content: effectiveResponse || "",
10445
+ });
10446
+ }
10190
10447
  } else if (db) {
10191
10448
  saveMessages(db, sessionId, messages);
10192
10449
  }
10193
10450
  } catch (_e) {
10194
- // Non-critical
10451
+ if (useJsonl && (_sessionInputAccepted || mcpContinuationStarted)) {
10452
+ const terminalError = _runtimeLedgerTerminalLatch.trip(
10453
+ markRuntimeLedgerPersistenceError(_e),
10454
+ );
10455
+ if (terminalError) _reportRuntimeLedgerTerminal();
10456
+ throw _e;
10457
+ }
10458
+ // Legacy persistence remains best-effort.
10195
10459
  }
10196
10460
  }
10197
10461
  // Persist the explicit turn-binding table for this settled turn,
@@ -10293,9 +10557,8 @@ async function startAgentReplInWorkspaceOwned(
10293
10557
  // drain above). Best-effort — never break turn completion.
10294
10558
  if (_settingsHooks) {
10295
10559
  try {
10296
- const { runObserveHooks, dispatchAsyncHooks } = await import(
10297
- "../lib/settings-hook-events.js"
10298
- );
10560
+ const { runObserveHooks, dispatchAsyncHooks } =
10561
+ await import("../lib/settings-hook-events.js");
10299
10562
  await runObserveHooks(
10300
10563
  _settingsHooks,
10301
10564
  "Stop",
@@ -10303,9 +10566,8 @@ async function startAgentReplInWorkspaceOwned(
10303
10566
  { cwd: process.cwd() },
10304
10567
  );
10305
10568
  if (!_asyncHookSupervisor) {
10306
- const { AsyncHookSupervisor } = await import(
10307
- "../lib/async-hook-supervisor.js"
10308
- );
10569
+ const { AsyncHookSupervisor } =
10570
+ await import("../lib/async-hook-supervisor.js");
10309
10571
  _asyncHookSupervisor = new AsyncHookSupervisor({
10310
10572
  persistStats: true,
10311
10573
  });
@@ -10422,14 +10684,24 @@ async function startAgentReplInWorkspaceOwned(
10422
10684
  _processingLine = false;
10423
10685
  settleLine();
10424
10686
  _lineSettled = null;
10687
+ kickMcpTaskAutoWake();
10425
10688
  }
10426
10689
  });
10427
10690
 
10691
+ // Opt-in restart recovery: with auto-wake enabled, scan the canonical
10692
+ // journal after the line listener is live and resume pending task trackers.
10693
+ if (process.env.CC_MCP_TASK_AUTOWAKE === "1") {
10694
+ setImmediate(() => {
10695
+ if (!_replClosing) rl.emit("line", "/mcp-watch");
10696
+ });
10697
+ }
10698
+
10428
10699
  rl.on("close", async () => {
10429
10700
  if (_replCleanupStarted) return;
10430
10701
  _replCleanupStarted = true;
10431
10702
  _replClosing = true;
10432
10703
  _pendingLines.length = 0;
10704
+ _mcpTaskAutoWakeQueue.length = 0;
10433
10705
  // Do not certify a Run while its model/tool or auxiliary usage settlement
10434
10706
  // is still in flight. EOF during a main turn cancels and leaves it incomplete.
10435
10707
  if (_turnAbort !== null) {
@@ -10442,6 +10714,8 @@ async function startAgentReplInWorkspaceOwned(
10442
10714
  if (_evolutionSession !== null) _replOutputFailure ||= error;
10443
10715
  _turnAbort.abort(error);
10444
10716
  }
10717
+ for (const tracker of _mcpTaskTrackers.values()) tracker.stop();
10718
+ _mcpTaskTrackers.clear();
10445
10719
  _promptInteractions.dispose();
10446
10720
  // Autonomous goals outlive the input line that submitted them. Cancel
10447
10721
  // their next-step execution and wait for any current call to settle too.
@@ -10490,9 +10764,8 @@ async function startAgentReplInWorkspaceOwned(
10490
10764
  // settings.json SessionEnd hooks (observe-only) when the REPL exits.
10491
10765
  if (_settingsHooks) {
10492
10766
  try {
10493
- const { runObserveHooks } = await import(
10494
- "../lib/settings-hook-events.js"
10495
- );
10767
+ const { runObserveHooks } =
10768
+ await import("../lib/settings-hook-events.js");
10496
10769
  await runObserveHooks(
10497
10770
  _settingsHooks,
10498
10771
  "SessionEnd",