chainlesschain 0.166.143 → 0.166.145

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 (208) hide show
  1. package/README.md +63 -10
  2. package/package.json +2 -2
  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 +3 -3
  155. package/src/commands/agent.js +44 -61
  156. package/src/commands/goal.js +79 -0
  157. package/src/commands/mcp-tasks.js +206 -0
  158. package/src/commands/mcp.js +34 -2
  159. package/src/commands/session-show.js +36 -1
  160. package/src/data/changelog.json +26 -0
  161. package/src/harness/jsonl-session-store.js +6 -0
  162. package/src/harness/mcp-client.js +431 -6
  163. package/src/harness/session-list-index.js +11 -58
  164. package/src/host/README.md +43 -0
  165. package/src/host/project-goal-graph.js +57 -0
  166. package/src/lib/codex-app-server-adapter.js +20 -0
  167. package/src/lib/codex-app-server-support.js +2 -2
  168. package/src/lib/context-memory-kernel/memory-query-control.js +5 -1
  169. package/src/lib/context-memory-kernel/memory-query-index.js +37 -1
  170. package/src/lib/context-memory-kernel/message-adapter.js +27 -5
  171. package/src/lib/context-memory-kernel/provider-context.js +196 -14
  172. package/src/lib/context-memory-kernel/segmented-memory-port.js +26 -1
  173. package/src/lib/evolution/agent-evolution-ingress.js +55 -1
  174. package/src/lib/evolution/skill-candidate-registry.js +3 -1
  175. package/src/lib/formal-budget-provider-scope.js +29 -7
  176. package/src/lib/formal-budget-transport.js +36 -5
  177. package/src/lib/goal-store.js +219 -0
  178. package/src/lib/graph-kernel/graph-runtime-surfaces.json +30 -0
  179. package/src/lib/graph-kernel/production-source-evidence.js +3 -3
  180. package/src/lib/graph-kernel/runtime-surface-manifest.js +46 -9
  181. package/src/lib/graph-kernel/runtime.js +12 -1
  182. package/src/lib/mcp-call-ledger-projection.js +1026 -0
  183. package/src/lib/mcp-call-ledger-store.js +19 -1024
  184. package/src/lib/mcp-ledger-recovery-admission.js +25 -0
  185. package/src/lib/mcp-task-delivery-contract.js +190 -0
  186. package/src/lib/mcp-task-delivery.js +113 -0
  187. package/src/lib/mcp-task-journal-projection.js +450 -0
  188. package/src/lib/mcp-task-journal.js +57 -0
  189. package/src/lib/mcp-task-runtime.js +480 -0
  190. package/src/lib/mcp-tasks.js +193 -0
  191. package/src/lib/model-input-diagnostics.js +265 -0
  192. package/src/lib/model-input-source-mapping.js +343 -0
  193. package/src/lib/openai-responses.js +32 -9
  194. package/src/lib/provider-request-admission.js +181 -0
  195. package/src/lib/public-ide-capability-manifest.js +2 -0
  196. package/src/lib/scheduler-kernel/graph-authority-adapter.js +140 -15
  197. package/src/lib/session-generation-authority.js +58 -0
  198. package/src/lib/session-host-snapshot.js +6 -0
  199. package/src/lib/session-model-input-diagnostics.js +262 -0
  200. package/src/lib/session-transcript-history.js +6 -0
  201. package/src/lib/session-transcript-page.js +7 -1
  202. package/src/lib/session-transcript-structure.js +38 -0
  203. package/src/lib/sub-agent-context.js +7 -3
  204. package/src/repl/agent-repl.js +178 -230
  205. package/src/runtime/agent-core.js +267 -140
  206. package/src/runtime/headless-runner.js +57 -69
  207. package/src/assets/web-panel/assets/index-DruOFzuF.js +0 -1
  208. package/src/assets/web-panel/assets/index-hhOrZ6HO.js +0 -1
@@ -1,3 +1,11 @@
1
+ import {
2
+ withModelInputDiagnostics,
3
+ recordLogicalModelInput,
4
+ MODEL_INPUT_PLAN,
5
+ MODEL_INPUT_TOOLS,
6
+ registerModelInputProtocol,
7
+ MODEL_INPUT_USAGE_CALL,
8
+ } from "../lib/model-input-diagnostics.js";
1
9
  import {
2
10
  projectMessagesWithTaskBinding,
3
11
  getTaskCompactionBindings,
@@ -7,6 +15,7 @@ import {
7
15
  requireUnscopedToolExecution,
8
16
  } from "../lib/formal-budget-provider-scope.js";
9
17
  import { isFormalBudgetError } from "../lib/formal-budget-errors.js";
18
+ import { withProviderRequestAdmission } from "../lib/provider-request-admission.js";
10
19
  import {
11
20
  FORMAL_QUALITY_ALLOWED_FILES_ENV,
12
21
  FORMAL_QUALITY_FILE_TOOLS,
@@ -121,7 +130,10 @@ import os from "os";
121
130
  import { createHash, randomUUID } from "node:crypto";
122
131
  import skillInvocationReceipt from "@chainlesschain/session-core/skill-invocation-receipt";
123
132
  import { isProxy } from "node:util/types";
124
- import { captureAgentEvolutionIngress } from "../lib/evolution/agent-evolution-ingress.js";
133
+ import {
134
+ captureAgentEvolutionIngress,
135
+ getAgentModelRequestReceipt,
136
+ } from "../lib/evolution/agent-evolution-ingress.js";
125
137
  import {
126
138
  assertSkillRuntimeAdmission,
127
139
  captureSkillRuntimeDependencies,
@@ -1618,19 +1630,18 @@ function filesystemIdentity(stats) {
1618
1630
  function sameFilesystemObjectIdentity(left, right) {
1619
1631
  return Boolean(
1620
1632
  left &&
1621
- right &&
1622
- left.dev === right.dev &&
1623
- left.ino === right.ino &&
1624
- left.type === right.type,
1633
+ right &&
1634
+ left.dev === right.dev &&
1635
+ left.ino === right.ino &&
1636
+ left.type === right.type,
1625
1637
  );
1626
1638
  }
1627
1639
 
1628
1640
  function sameFilesystemIdentity(left, right, { content = false } = {}) {
1629
1641
  return Boolean(
1630
1642
  sameFilesystemObjectIdentity(left, right) &&
1631
- left.nlink === right.nlink &&
1632
- (!content ||
1633
- (left.size === right.size && left.mtimeNs === right.mtimeNs)),
1643
+ left.nlink === right.nlink &&
1644
+ (!content || (left.size === right.size && left.mtimeNs === right.mtimeNs)),
1634
1645
  );
1635
1646
  }
1636
1647
 
@@ -3522,9 +3533,8 @@ export async function executeTool(name, args, context = {}) {
3522
3533
  GUARDED_FILE_MUTATION_TOOLS.has(name) &&
3523
3534
  settingsVerdict.decision !== "allow"
3524
3535
  ) {
3525
- const { sensitiveFileReason, autoExecConfigReason } = await import(
3526
- "../lib/sensitive-file-guard.js"
3527
- );
3536
+ const { sensitiveFileReason, autoExecConfigReason } =
3537
+ await import("../lib/sensitive-file-guard.js");
3528
3538
  const guarded = fileMutationPaths(name, args)
3529
3539
  .map((candidatePath) => ({
3530
3540
  path: candidatePath,
@@ -3559,9 +3569,8 @@ export async function executeTool(name, args, context = {}) {
3559
3569
  GUARDED_FILE_MUTATION_TOOLS.has(name) &&
3560
3570
  settingsVerdict.decision !== "allow"
3561
3571
  ) {
3562
- const { sessionStorePathReason } = await import(
3563
- "../lib/session-store-guard.js"
3564
- );
3572
+ const { sessionStorePathReason } =
3573
+ await import("../lib/session-store-guard.js");
3565
3574
  const guarded = fileMutationPaths(name, args)
3566
3575
  .map((candidatePath) => ({
3567
3576
  path: candidatePath,
@@ -4308,9 +4317,8 @@ export async function executeTool(name, args, context = {}) {
4308
4317
  context.externalToolExecutors
4309
4318
  ) {
4310
4319
  try {
4311
- const { collectIdeDiagnostics, formatIdeDiagnostics } = await import(
4312
- "../lib/ide-context.js"
4313
- );
4320
+ const { collectIdeDiagnostics, formatIdeDiagnostics } =
4321
+ await import("../lib/ide-context.js");
4314
4322
  const diags = await collectIdeDiagnostics(
4315
4323
  {
4316
4324
  mcpClient: context.mcpHostClient || context.mcpClient,
@@ -4852,9 +4860,8 @@ export async function _getSharedCodeIntel(cwd) {
4852
4860
  const root = path.resolve(cwd || process.cwd());
4853
4861
  let entry = _codeIntelPool.get(root);
4854
4862
  if (!entry) {
4855
- const { CodeIntelligence } = await import(
4856
- "../lib/lsp/code-intelligence.js"
4857
- );
4863
+ const { CodeIntelligence } =
4864
+ await import("../lib/lsp/code-intelligence.js");
4858
4865
  // Re-check AFTER the await: two concurrent callers (the parallel read-only
4859
4866
  // batch runs several `code_intelligence` calls at once) both observed an
4860
4867
  // empty pool before this `await import`, so without this guard both would
@@ -4943,9 +4950,8 @@ async function _postEditDiagnostics(filePath, cwd, additionalDirectories) {
4943
4950
  }
4944
4951
  let hasServer = false;
4945
4952
  try {
4946
- const { languageIdForFile, resolveServer } = await import(
4947
- "../lib/lsp/lsp-server-registry.js"
4948
- );
4953
+ const { languageIdForFile, resolveServer } =
4954
+ await import("../lib/lsp/lsp-server-registry.js");
4949
4955
  const languageId = languageIdForFile(filePath);
4950
4956
  if (!languageId) return null; // unsupported file type — no LSP, no cost
4951
4957
  hasServer = Boolean(resolveServer(languageId, root));
@@ -4968,9 +4974,8 @@ async function _postEditDiagnostics(filePath, cwd, additionalDirectories) {
4968
4974
  // the model sees the most severe diagnostics first and can't be flooded by
4969
4975
  // a pathological diagnostics dump. Budget is overridable via
4970
4976
  // CC_EDIT_DIAGNOSTICS_TOKENS (default 2000).
4971
- const { capDiagnostics } = await import(
4972
- "../lib/lsp/diagnostics-scheduler.js"
4973
- );
4977
+ const { capDiagnostics } =
4978
+ await import("../lib/lsp/diagnostics-scheduler.js");
4974
4979
  const budget = Number(process.env.CC_EDIT_DIAGNOSTICS_TOKENS) || 2000;
4975
4980
  const { kept } = capDiagnostics(diags, { maxTokens: budget });
4976
4981
  return kept.length ? kept : null;
@@ -5028,9 +5033,8 @@ export async function _withPostEditDiagnostics(
5028
5033
  workspaceRootsFor(cwd, additionalDirectories),
5029
5034
  );
5030
5035
  if (root) {
5031
- const { collectFileImportDiagnostics } = await import(
5032
- "../lib/file-import-diagnostics.js"
5033
- );
5036
+ const { collectFileImportDiagnostics } =
5037
+ await import("../lib/file-import-diagnostics.js");
5034
5038
  const checked = collectFileImportDiagnostics({
5035
5039
  filePath,
5036
5040
  content: writtenContent,
@@ -5102,14 +5106,12 @@ async function _getSubtreeLoader(cwd, sessionScope = "__legacy__") {
5102
5106
  }
5103
5107
  let loader = scopedLoaders.get(sessionScope);
5104
5108
  if (!loader) {
5105
- const { SubtreeInstructionLoader } = await import(
5106
- "../lib/project-instructions.js"
5107
- );
5109
+ const { SubtreeInstructionLoader } =
5110
+ await import("../lib/project-instructions.js");
5108
5111
  let instructionExcludes;
5109
5112
  try {
5110
- const { readStringArraySetting } = await import(
5111
- "../lib/settings-loader.cjs"
5112
- );
5113
+ const { readStringArraySetting } =
5114
+ await import("../lib/settings-loader.cjs");
5113
5115
  instructionExcludes = readStringArraySetting("instructionExcludes", {
5114
5116
  cwd: root,
5115
5117
  });
@@ -5154,9 +5156,8 @@ async function _prepareSubtreeInstructions(
5154
5156
  }
5155
5157
  const fresh = [...discovered.values()];
5156
5158
  if (!fresh || !fresh.length) return null;
5157
- const { DEFAULT_MAX_FILE_BYTES } = await import(
5158
- "../lib/project-instructions.js"
5159
- );
5159
+ const { DEFAULT_MAX_FILE_BYTES } =
5160
+ await import("../lib/project-instructions.js");
5160
5161
  const out = [];
5161
5162
  const errors = [];
5162
5163
  for (const f of fresh) {
@@ -5263,9 +5264,8 @@ async function _withSubtreeInstructions(
5263
5264
  async function filterSkillsByCwd(skills, cwd) {
5264
5265
  try {
5265
5266
  if (!Array.isArray(skills) || skills.every((s) => !s?.paths)) return skills;
5266
- const { filterSkillsByRelCwd, relCwdForCwd } = await import(
5267
- "../lib/skill-path-scope.js"
5268
- );
5267
+ const { filterSkillsByRelCwd, relCwdForCwd } =
5268
+ await import("../lib/skill-path-scope.js");
5269
5269
  const { findProjectRoot } = await import("../lib/project-detector.js");
5270
5270
  const root = (cwd && findProjectRoot(cwd)) || cwd || "";
5271
5271
  return filterSkillsByRelCwd(skills, relCwdForCwd(cwd, root));
@@ -5280,9 +5280,8 @@ async function promoteBrowserGeneratedArtifact(
5280
5280
  ) {
5281
5281
  if (!filePath) return { artifact: null, error: null };
5282
5282
  try {
5283
- const { ArtifactStore, publicArtifactMetadata } = await import(
5284
- "../lib/artifact-store.js"
5285
- );
5283
+ const { ArtifactStore, publicArtifactMetadata } =
5284
+ await import("../lib/artifact-store.js");
5286
5285
  const entry = new ArtifactStore().publish({
5287
5286
  filePath,
5288
5287
  title,
@@ -5335,9 +5334,8 @@ async function promoteBrowserDownload(
5335
5334
  async function publishBrowserEvidence(envelope, sessionId) {
5336
5335
  if (!envelope?.envelopeDigest) return { artifact: null, error: null };
5337
5336
  try {
5338
- const { ArtifactStore, publicArtifactMetadata } = await import(
5339
- "../lib/artifact-store.js"
5340
- );
5337
+ const { ArtifactStore, publicArtifactMetadata } =
5338
+ await import("../lib/artifact-store.js");
5341
5339
  const {
5342
5340
  browserEvidenceDigest,
5343
5341
  canonicalBrowserEvidenceJson,
@@ -5400,9 +5398,8 @@ async function publishBrowserEvidence(envelope, sessionId) {
5400
5398
  }
5401
5399
 
5402
5400
  async function resolveBrowserUploadArtifact(artifactId, sessionId) {
5403
- const { ArtifactStore, publicArtifactMetadata } = await import(
5404
- "../lib/artifact-store.js"
5405
- );
5401
+ const { ArtifactStore, publicArtifactMetadata } =
5402
+ await import("../lib/artifact-store.js");
5406
5403
  const store = new ArtifactStore();
5407
5404
  return store.withIndexSnapshot((entries) => {
5408
5405
  const matches = entries.filter((entry) => entry.id === artifactId);
@@ -6406,9 +6403,8 @@ async function executeToolInner(
6406
6403
  // through PowerShell via explicit argv (`powershell.exe -NoProfile
6407
6404
  // [-ExecutionPolicy <p>] -Command <cmd>`). The unconfigured path keeps
6408
6405
  // the historical default shell byte-identical (useDefaultShell=true).
6409
- const { resolveShellInvocation } = await import(
6410
- "../lib/shell-selector.cjs"
6411
- );
6406
+ const { resolveShellInvocation } =
6407
+ await import("../lib/shell-selector.cjs");
6412
6408
  let shellInv = resolveShellInvocation({
6413
6409
  command: args.command,
6414
6410
  requested: args.shell,
@@ -7181,9 +7177,8 @@ async function executeToolInner(
7181
7177
  let removeSettingsAuthorityListener = null;
7182
7178
  if (needsEgress) {
7183
7179
  try {
7184
- const { startEgressProxyWorker } = await import(
7185
- "../lib/sandbox-egress-worker.js"
7186
- );
7180
+ const { startEgressProxyWorker } =
7181
+ await import("../lib/sandbox-egress-worker.js");
7187
7182
  if (dockerEgress) {
7188
7183
  privateSocketDir = fs.mkdtempSync(
7189
7184
  path.join(os.tmpdir(), "cc-egress-"),
@@ -7224,9 +7219,8 @@ async function executeToolInner(
7224
7219
  // Proxy startup and dynamic imports are asynchronous. Re-read the
7225
7220
  // live authority after they settle and before sandbox dispatch.
7226
7221
  if (dockerEgress && proxyHandle?.socketPath) {
7227
- const { createDockerEgressAuthorityMonitor } = await import(
7228
- "../lib/sandbox-egress-authority-monitor.js"
7229
- );
7222
+ const { createDockerEgressAuthorityMonitor } =
7223
+ await import("../lib/sandbox-egress-authority-monitor.js");
7230
7224
  authorityMonitor = createDockerEgressAuthorityMonitor({
7231
7225
  sessionId: sessionId || null,
7232
7226
  policyVersion:
@@ -7848,9 +7842,8 @@ async function executeToolInner(
7848
7842
  !ruleAllowed &&
7849
7843
  typeof approvalGate.decide === "function"
7850
7844
  ) {
7851
- const { APPROVAL_RISK, APPROVAL_DECISION } = await import(
7852
- "@chainlesschain/session-core"
7853
- );
7845
+ const { APPROVAL_RISK, APPROVAL_DECISION } =
7846
+ await import("@chainlesschain/session-core");
7854
7847
  const gate = await approvalGate.decide({
7855
7848
  sessionId,
7856
7849
  riskLevel: APPROVAL_RISK.HIGH,
@@ -8064,9 +8057,8 @@ async function executeToolInner(
8064
8057
 
8065
8058
  case "slash_command": {
8066
8059
  try {
8067
- const { getCommand, expandCommand, discoverCommands } = await import(
8068
- "../lib/slash-commands.js"
8069
- );
8060
+ const { getCommand, expandCommand, discoverCommands } =
8061
+ await import("../lib/slash-commands.js");
8070
8062
  const raw = String(args.command || "").trim();
8071
8063
  if (!raw) {
8072
8064
  return attachDescriptor({
@@ -8277,9 +8269,8 @@ async function executeToolInner(
8277
8269
 
8278
8270
  case "notify": {
8279
8271
  try {
8280
- const { sendAgentNotification } = await import(
8281
- "../lib/agent-notify.js"
8282
- );
8272
+ const { sendAgentNotification } =
8273
+ await import("../lib/agent-notify.js");
8283
8274
  const outcome = await sendAgentNotification({
8284
8275
  title: args.title,
8285
8276
  body: args.body,
@@ -8301,9 +8292,8 @@ async function executeToolInner(
8301
8292
  if (refusal) return attachDescriptor(refusal);
8302
8293
  }
8303
8294
  try {
8304
- const { AgentScheduleStore } = await import(
8305
- "../lib/agent-schedule-store.js"
8306
- );
8295
+ const { AgentScheduleStore } =
8296
+ await import("../lib/agent-schedule-store.js");
8307
8297
  const { parseDuration } = await import("../lib/loop.js");
8308
8298
  const store = new AgentScheduleStore();
8309
8299
  const action = String(args.action || "").toLowerCase();
@@ -8426,9 +8416,8 @@ async function executeToolInner(
8426
8416
  // Only METADATA returns to the conversation (the transcript never
8427
8417
  // carries the file body); `cc artifacts` lists/inspects/cleans.
8428
8418
  try {
8429
- const { ArtifactStore, publicArtifactMetadata } = await import(
8430
- "../lib/artifact-store.js"
8431
- );
8419
+ const { ArtifactStore, publicArtifactMetadata } =
8420
+ await import("../lib/artifact-store.js");
8432
8421
  const store = new ArtifactStore();
8433
8422
  const entry = store.publish({
8434
8423
  filePath: path.resolve(cwd, String(args.path || "")),
@@ -8518,9 +8507,8 @@ async function executeToolInner(
8518
8507
  !ruleAllowed &&
8519
8508
  typeof approvalGate.decide === "function"
8520
8509
  ) {
8521
- const { APPROVAL_RISK, APPROVAL_DECISION } = await import(
8522
- "@chainlesschain/session-core"
8523
- );
8510
+ const { APPROVAL_RISK, APPROVAL_DECISION } =
8511
+ await import("@chainlesschain/session-core");
8524
8512
  const summary = Array.isArray(args.actions)
8525
8513
  ? args.actions
8526
8514
  .map((a) => a?.type)
@@ -8645,9 +8633,8 @@ async function executeToolInner(
8645
8633
  case "search_files": {
8646
8634
  if (typeof args.path === "string" && args.path.length > 0) {
8647
8635
  const file = path.resolve(cwd, args.path);
8648
- const { credentialFileReason } = await import(
8649
- "../lib/credential-guard.js"
8650
- );
8636
+ const { credentialFileReason } =
8637
+ await import("../lib/credential-guard.js");
8651
8638
  const reason =
8652
8639
  credentialFileReason(file) ||
8653
8640
  (fs.existsSync(file)
@@ -11072,9 +11059,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11072
11059
  // the breadth counter increments so spawnedCount is this-spawn-exclusive.
11073
11060
  if (ctx.subAgentContract) {
11074
11061
  try {
11075
- const { enforceRecursionLimits } = await import(
11076
- "../lib/subagent-contract.js"
11077
- );
11062
+ const { enforceRecursionLimits } =
11063
+ await import("../lib/subagent-contract.js");
11078
11064
  const recur = enforceRecursionLimits({
11079
11065
  depth: currentDepth,
11080
11066
  spawnedCount: ctx.subAgentBudget?.spawned || 0,
@@ -11267,9 +11253,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11267
11253
  let inheritedMcp = null;
11268
11254
  let inheritedHooks = null;
11269
11255
  try {
11270
- const { filterInheritedMcp, filterInheritedHooks } = await import(
11271
- "../lib/subagent-inheritance.js"
11272
- );
11256
+ const { filterInheritedMcp, filterInheritedHooks } =
11257
+ await import("../lib/subagent-inheritance.js");
11273
11258
  inheritedMcp = filterInheritedMcp(
11274
11259
  {
11275
11260
  extraToolDefinitions: ctx.extraToolDefinitions,
@@ -11302,9 +11287,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11302
11287
  // repo, refuse the spawn instead of silently running in the parent checkout.
11303
11288
  if (subIsolation === "worktree") {
11304
11289
  try {
11305
- const { resolveIsolationFailClosed } = await import(
11306
- "../lib/subagent-contract.js"
11307
- );
11290
+ const { resolveIsolationFailClosed } =
11291
+ await import("../lib/subagent-contract.js");
11308
11292
  const { isGitRepo } = await import("../lib/git-integration.js");
11309
11293
  const iso = resolveIsolationFailClosed({
11310
11294
  requested: "worktree",
@@ -11323,9 +11307,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11323
11307
  let profile = null;
11324
11308
  if (profileName) {
11325
11309
  try {
11326
- const { getSubAgentProfile } = await import(
11327
- "../lib/sub-agent-profiles.js"
11328
- );
11310
+ const { getSubAgentProfile } =
11311
+ await import("../lib/sub-agent-profiles.js");
11329
11312
  profile = getSubAgentProfile(profileName);
11330
11313
  if (!profile) {
11331
11314
  return {
@@ -11396,9 +11379,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11396
11379
  let childApprovalGate = null;
11397
11380
  if (effectiveContract?.permissionMode) {
11398
11381
  try {
11399
- const { resolvePermissionMode, resolveEnabledTools } = await import(
11400
- "./headless-runner.js"
11401
- );
11382
+ const { resolvePermissionMode, resolveEnabledTools } =
11383
+ await import("./headless-runner.js");
11402
11384
  const perm = resolvePermissionMode(effectiveContract.permissionMode);
11403
11385
  if (perm.readOnly) {
11404
11386
  allowedTools = resolveEnabledTools({ allowedTools, readOnly: true });
@@ -11433,9 +11415,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11433
11415
  !(Array.isArray(mcpAllow) && mcpAllow.length === 0)
11434
11416
  ) {
11435
11417
  try {
11436
- const { createInheritedMcpToolCatalog } = await import(
11437
- "../lib/subagent-inheritance.js"
11438
- );
11418
+ const { createInheritedMcpToolCatalog } =
11419
+ await import("../lib/subagent-inheritance.js");
11439
11420
  childMcpCatalog = createInheritedMcpToolCatalog(
11440
11421
  ctx,
11441
11422
  mcpAllow,
@@ -11682,9 +11663,8 @@ async function _executeSpawnSubAgent(args, ctx) {
11682
11663
  let subWorktreeOptions = null;
11683
11664
  if (subIsolation === "worktree") {
11684
11665
  try {
11685
- const { normalizeSparsePaths } = await import(
11686
- "../lib/worktree-sparse.js"
11687
- );
11666
+ const { normalizeSparsePaths } =
11667
+ await import("../lib/worktree-sparse.js");
11688
11668
  const sparse = normalizeSparsePaths(
11689
11669
  args.sparsePaths ?? mdSparsePaths ?? null,
11690
11670
  );
@@ -11888,11 +11868,10 @@ async function _executeSpawnSubAgent(args, ctx) {
11888
11868
 
11889
11869
  // Resolve the registry ONCE before the try so the failure path can also move
11890
11870
  // the sub-agent out of `_active` (the success path does this via complete()).
11891
- const { SubAgentRegistry } = await import(
11892
- "../lib/sub-agent-registry.js"
11893
- ).catch(() => ({
11894
- SubAgentRegistry: null,
11895
- }));
11871
+ const { SubAgentRegistry } =
11872
+ await import("../lib/sub-agent-registry.js").catch(() => ({
11873
+ SubAgentRegistry: null,
11874
+ }));
11896
11875
  let registry = null;
11897
11876
  if (SubAgentRegistry) {
11898
11877
  try {
@@ -12273,6 +12252,33 @@ function _openAIProviderRequestReceipt(response, data, clientRequestId) {
12273
12252
  * @returns {Promise<object>} response with .message
12274
12253
  */
12275
12254
  export async function chatWithTools(rawMessages, options) {
12255
+ return withModelInputDiagnostics(options, () =>
12256
+ chatWithToolsDiagnosed(rawMessages, options),
12257
+ );
12258
+ }
12259
+
12260
+ async function chatWithToolsDiagnosed(rawMessages, options) {
12261
+ let prepared = null;
12262
+ let destination = { provider: options.provider || "ollama" };
12263
+ return withProviderRequestAdmission(
12264
+ {
12265
+ validate: (target, controls) =>
12266
+ prepared?.assertCurrent?.(target, controls),
12267
+ enabled: () => prepared?.admissionEnabled === true,
12268
+ check: (target, controls) =>
12269
+ prepared?.assertDispatchOpen?.(target, controls),
12270
+ resource: () => prepared?.dispatchResource,
12271
+ target: () => destination,
12272
+ },
12273
+ () =>
12274
+ chatWithToolsAdmitted(rawMessages, options, (context, provider) => {
12275
+ if (context) prepared = context;
12276
+ if (provider) destination = { provider };
12277
+ }),
12278
+ );
12279
+ }
12280
+
12281
+ async function chatWithToolsAdmitted(rawMessages, options, captureAdmission) {
12276
12282
  rawMessages = projectRejectedToolArguments(rawMessages);
12277
12283
  if (options.serviceTier != null) {
12278
12284
  resolveModelServiceTier(
@@ -12300,13 +12306,29 @@ export async function chatWithTools(rawMessages, options) {
12300
12306
  contextEngine: ce,
12301
12307
  signal,
12302
12308
  } = { ...options, ...connection };
12309
+ captureAdmission(null, provider);
12303
12310
 
12304
12311
  const providerRequestId = _normalizeProviderRequestId(
12305
12312
  options.providerRequestId,
12306
12313
  );
12307
12314
 
12308
12315
  let tools = getProviderToolDefinitions(options);
12309
- if (Array.isArray(options.contextMemorySelectedToolNames)) {
12316
+ const selectExactTools = async (definitions, selectedDefinitions) => {
12317
+ const { canonicalDigest } =
12318
+ await import("@chainlesschain/context-memory-kernel");
12319
+ const schemaDigest = (definition) =>
12320
+ canonicalDigest(definition, "chainlesschain.cli-tool-schema/v1");
12321
+ const remaining = selectedDefinitions.map(schemaDigest);
12322
+ return definitions.filter((definition) => {
12323
+ const index = remaining.indexOf(schemaDigest(definition));
12324
+ if (index < 0) return false;
12325
+ remaining.splice(index, 1);
12326
+ return true;
12327
+ });
12328
+ };
12329
+ if (Array.isArray(options[MODEL_INPUT_TOOLS])) {
12330
+ tools = await selectExactTools(tools, options[MODEL_INPUT_TOOLS]);
12331
+ } else if (Array.isArray(options.contextMemorySelectedToolNames)) {
12310
12332
  const selected = new Set(options.contextMemorySelectedToolNames);
12311
12333
  tools = tools.filter((tool) => selected.has(tool?.function?.name));
12312
12334
  }
@@ -12317,18 +12339,20 @@ export async function chatWithTools(rawMessages, options) {
12317
12339
  options.contextMemoryPreplanned !== true &&
12318
12340
  options.contextMemorySkipPlanning !== true
12319
12341
  ) {
12320
- const { prepareCanonicalProviderContext } = await import(
12321
- "../lib/context-memory-kernel/provider-context.js"
12322
- );
12342
+ const { prepareCanonicalProviderContext } =
12343
+ await import("../lib/context-memory-kernel/provider-context.js");
12323
12344
  const prepared = await prepareCanonicalProviderContext(rawMessages, {
12324
12345
  ...options,
12346
+ provider,
12347
+ model,
12348
+ baseUrl,
12325
12349
  contextMemoryToolDefinitions: tools,
12326
12350
  });
12351
+ captureAdmission(prepared, provider);
12327
12352
  providerMessages = prepared.messages;
12328
12353
  canonicalPlan = prepared.plan;
12329
12354
  if (canonicalPlan) {
12330
- const selected = new Set(prepared.selectedToolNames);
12331
- tools = tools.filter((tool) => selected.has(tool?.function?.name));
12355
+ tools = await selectExactTools(tools, prepared.selectedToolDefinitions);
12332
12356
  }
12333
12357
  }
12334
12358
  const lastUserMsg = [...providerMessages]
@@ -12341,15 +12365,39 @@ export async function chatWithTools(rawMessages, options) {
12341
12365
  })
12342
12366
  : providerMessages;
12343
12367
 
12368
+ const diagnosticPlan = canonicalPlan || options[MODEL_INPUT_PLAN];
12369
+ let sourceRows = null;
12370
+ let preProjection = null;
12371
+ if (typeof options.onModelInputDiagnostic === "function") {
12372
+ const { getCanonicalProviderSourceMapping } =
12373
+ await import("../lib/context-memory-kernel/provider-context.js");
12374
+ preProjection = JSON.parse(JSON.stringify({ messages, tools }));
12375
+ sourceRows = getCanonicalProviderSourceMapping(
12376
+ diagnosticPlan,
12377
+ preProjection,
12378
+ );
12379
+ }
12380
+ let modelInputReceipt = null;
12344
12381
  if (evolutionIngress !== null) {
12345
12382
  const projected = await evolutionIngress.prepareModelRequest({
12346
12383
  messages,
12347
12384
  tools,
12348
12385
  });
12386
+ modelInputReceipt = getAgentModelRequestReceipt(projected);
12349
12387
  messages = projected.messages;
12350
12388
  tools = projected.tools;
12351
12389
  }
12352
12390
 
12391
+ ({ messages, tools } = await recordLogicalModelInput({
12392
+ messages,
12393
+ tools,
12394
+ plan: diagnosticPlan,
12395
+ receipt: modelInputReceipt,
12396
+ sourceRows,
12397
+ preProjection,
12398
+ projectionExpected: evolutionIngress !== null,
12399
+ }));
12400
+
12353
12401
  if (options[READ_FILE_REQUEST_CONTEXT]) {
12354
12402
  options[READ_FILE_REQUEST_CONTEXT].messages = messages;
12355
12403
  }
@@ -12369,6 +12417,15 @@ export async function chatWithTools(rawMessages, options) {
12369
12417
  const ollamaMessages = hasImageContent(messages)
12370
12418
  ? toOllamaMessages(messages)
12371
12419
  : messages;
12420
+ registerModelInputProtocol(
12421
+ "ollama-chat",
12422
+ {
12423
+ messages: ollamaMessages,
12424
+ tools,
12425
+ },
12426
+ {},
12427
+ { messages, tools },
12428
+ );
12372
12429
  // Real-time token deltas (Claude-Code `--include-partial-messages`): when
12373
12430
  // the caller supplies an onToken hook, stream the response and forward each
12374
12431
  // content chunk as it arrives. Tool calls + usage are accumulated and the
@@ -12487,6 +12544,10 @@ export async function chatWithTools(rawMessages, options) {
12487
12544
  model: effModel,
12488
12545
  maxOutputTokens: options.maxOutputTokens,
12489
12546
  });
12547
+ const otherIndexes = messages.flatMap((message, index) =>
12548
+ message.role !== "system" ? [index] : [],
12549
+ );
12550
+ const anthropicMessagePaths = messages.map(() => []);
12490
12551
  const body = {
12491
12552
  model: effModel,
12492
12553
  max_tokens: anthropicOutputBudget.requestMaxOutputTokens,
@@ -12494,7 +12555,9 @@ export async function chatWithTools(rawMessages, options) {
12494
12555
  // assistant tool_calls[]) into Anthropic content blocks. Without this,
12495
12556
  // multi-turn tool use 400s on turn 2 (Anthropic rejects role:"tool" and
12496
12557
  // assistant `tool_calls`). Also replays preserved thinking blocks.
12497
- messages: _toAnthropicMessages(otherMsgs),
12558
+ messages: _toAnthropicMessages(otherMsgs, (index, paths) => {
12559
+ anthropicMessagePaths[otherIndexes[index]] = paths;
12560
+ }),
12498
12561
  tools: anthropicTools,
12499
12562
  };
12500
12563
  if (
@@ -12529,6 +12592,28 @@ export async function chatWithTools(rawMessages, options) {
12529
12592
  : systemText;
12530
12593
  }
12531
12594
 
12595
+ let systemOffset = 0;
12596
+ for (let index = 0; index < messages.length; index++) {
12597
+ if (messages[index].role !== "system") continue;
12598
+ const text = String(messages[index].content ?? "");
12599
+ anthropicMessagePaths[index] = [
12600
+ {
12601
+ path: cacheEnabled ? "/system/0/text" : "/system",
12602
+ start: systemOffset,
12603
+ end: systemOffset + text.length,
12604
+ },
12605
+ ];
12606
+ systemOffset += text.length + 1;
12607
+ }
12608
+ registerModelInputProtocol(
12609
+ "anthropic-messages",
12610
+ body,
12611
+ {
12612
+ messages: anthropicMessagePaths,
12613
+ },
12614
+ { messages, tools },
12615
+ );
12616
+
12532
12617
  const url = normalizeProviderBaseUrl(baseUrl);
12533
12618
 
12534
12619
  // Real token streaming (--include-partial-messages): stream the SSE response
@@ -12652,6 +12737,8 @@ export async function chatWithTools(rawMessages, options) {
12652
12737
  modelProfile.runtimeProtocol === "openai-responses";
12653
12738
 
12654
12739
  if (useOpenAIResponses) {
12740
+ const responseMessagePaths = messages.map(() => []);
12741
+ const responseToolPaths = tools.map(() => []);
12655
12742
  const responseBody = createOpenAIResponsesBody({
12656
12743
  model: effectiveModel,
12657
12744
  messages,
@@ -12661,7 +12748,22 @@ export async function chatWithTools(rawMessages, options) {
12661
12748
  stream: typeof options.onToken === "function",
12662
12749
  modelProfile,
12663
12750
  serviceTier: options.serviceTier,
12751
+ onMessageMapping: (index, paths) => {
12752
+ responseMessagePaths[index] = paths;
12753
+ },
12754
+ onToolMapping: (index, paths) => {
12755
+ responseToolPaths[index] = paths;
12756
+ },
12664
12757
  });
12758
+ registerModelInputProtocol(
12759
+ "openai-responses",
12760
+ responseBody,
12761
+ {
12762
+ messages: responseMessagePaths,
12763
+ tools: responseToolPaths,
12764
+ },
12765
+ { messages, tools },
12766
+ );
12665
12767
  if (typeof options.onToken === "function") {
12666
12768
  return await _retryStreamingChat(
12667
12769
  (attempt = 0) =>
@@ -12768,6 +12870,13 @@ export async function chatWithTools(rawMessages, options) {
12768
12870
  );
12769
12871
  }
12770
12872
 
12873
+ registerModelInputProtocol(
12874
+ "openai-chat",
12875
+ { messages, tools },
12876
+ {},
12877
+ { messages, tools },
12878
+ );
12879
+
12771
12880
  // Real token streaming (--include-partial-messages) for every OpenAI-compatible
12772
12881
  // provider (openai / deepseek / dashscope / mistral / gemini / volcengine):
12773
12882
  // stream the SSE response, forward content deltas live, and reassemble the
@@ -13678,18 +13787,27 @@ async function _chatOpenAIResponsesStreaming(
13678
13787
  * are replayed FIRST in the assistant turn (the API requires them ahead of
13679
13788
  * tool_use when continuing a thinking+tool turn). Exported for tests.
13680
13789
  */
13681
- export function _toAnthropicMessages(msgs) {
13790
+ export function _toAnthropicMessages(msgs, onMapping = null) {
13682
13791
  const out = [];
13683
13792
  let pendingResults = [];
13793
+ let pendingIndexes = [];
13794
+ const point = (path) => ({ path, start: null, end: null });
13684
13795
  const flush = () => {
13685
13796
  if (pendingResults.length) {
13797
+ pendingIndexes.forEach((index, position) =>
13798
+ onMapping?.(index, [
13799
+ point("/messages/" + out.length + "/content/" + position),
13800
+ ]),
13801
+ );
13686
13802
  out.push({ role: "user", content: pendingResults });
13687
13803
  pendingResults = [];
13804
+ pendingIndexes = [];
13688
13805
  }
13689
13806
  };
13690
- for (const m of msgs || []) {
13807
+ for (const [sourceIndex, m] of (msgs || []).entries()) {
13691
13808
  if (!m) continue;
13692
13809
  if (m.role === "tool") {
13810
+ pendingIndexes.push(sourceIndex);
13693
13811
  pendingResults.push({
13694
13812
  type: "tool_result",
13695
13813
  tool_use_id: m.tool_call_id,
@@ -13701,6 +13819,7 @@ export function _toAnthropicMessages(msgs) {
13701
13819
  continue;
13702
13820
  }
13703
13821
  flush();
13822
+ onMapping?.(sourceIndex, [point("/messages/" + out.length)]);
13704
13823
  if (m.role === "assistant") {
13705
13824
  const blocks = [];
13706
13825
  if (Array.isArray(m._thinkingBlocks)) {
@@ -14603,9 +14722,8 @@ async function _getAutoCompactor(options) {
14603
14722
  let canonicalRequired = false;
14604
14723
  try {
14605
14724
  const { feature } = await import("../lib/feature-flags.js");
14606
- const { resolveCliContextMemoryCutover } = await import(
14607
- "../lib/context-memory-kernel/authority.js"
14608
- );
14725
+ const { resolveCliContextMemoryCutover } =
14726
+ await import("../lib/context-memory-kernel/authority.js");
14609
14727
  const cutover = resolveCliContextMemoryCutover({
14610
14728
  env: options.contextMemoryEnv || process.env,
14611
14729
  scopeKey: options.sessionId
@@ -14614,9 +14732,8 @@ async function _getAutoCompactor(options) {
14614
14732
  });
14615
14733
  canonicalRequired = cutover.canonical;
14616
14734
  if (feature("PROMPT_COMPRESSOR") || cutover.canonical) {
14617
- const { PromptCompressor } = await import(
14618
- "../harness/prompt-compressor.js"
14619
- );
14735
+ const { PromptCompressor } =
14736
+ await import("../harness/prompt-compressor.js");
14620
14737
  const llmQuery =
14621
14738
  typeof options.compactionLlmQuery === "function"
14622
14739
  ? options.compactionLlmQuery
@@ -14669,9 +14786,8 @@ async function _getAutoCompactor(options) {
14669
14786
  compressor = _instrumentAutoCompactorUsage(compressor, options);
14670
14787
  if (cutover.canonical) {
14671
14788
  const compatibilitySummarizer = compressor;
14672
- const { compactLiveMessagesCanonical } = await import(
14673
- "../lib/context-memory-kernel/live-compaction.js"
14674
- );
14789
+ const { compactLiveMessagesCanonical } =
14790
+ await import("../lib/context-memory-kernel/live-compaction.js");
14675
14791
  compressor = {
14676
14792
  canonicalKernel: true,
14677
14793
  shouldAutoCompact: (messages) =>
@@ -15109,9 +15225,8 @@ export async function* agentLoop(messages, options) {
15109
15225
  : captureAgentEvolutionIngress(options.evolutionIngress);
15110
15226
  let llmCall = configuredChatFn || chatWithTools;
15111
15227
  if (evolutionIngress !== null && configuredChatFn) {
15112
- const { captureCanonicalFallbackChatFn } = await import(
15113
- "./fallback-model.js"
15114
- );
15228
+ const { captureCanonicalFallbackChatFn } =
15229
+ await import("./fallback-model.js");
15115
15230
  llmCall = captureCanonicalFallbackChatFn(
15116
15231
  configuredChatFn,
15117
15232
  evolutionIngress,
@@ -15120,9 +15235,8 @@ export async function* agentLoop(messages, options) {
15120
15235
  // Shared iteration budget — replaces hardcoded MAX_ITERATIONS.
15121
15236
  // When options.iterationBudget is provided (e.g. from parent agent),
15122
15237
  // the same budget instance is shared, so parent+child consume from one pool.
15123
- const { IterationBudget, WarningLevel } = await import(
15124
- "../lib/iteration-budget.js"
15125
- );
15238
+ const { IterationBudget, WarningLevel } =
15239
+ await import("../lib/iteration-budget.js");
15126
15240
  const budget = options.iterationBudget || new IterationBudget();
15127
15241
  const { HostResourceBudget } = await import("../lib/host-resource-budget.js");
15128
15242
  const hostResourceBudget =
@@ -15581,9 +15695,8 @@ export async function* agentLoop(messages, options) {
15581
15695
  options.strictUsageTelemetry !== true &&
15582
15696
  workflowEffectId == null
15583
15697
  ) {
15584
- const { makeRunnableProviderFallback } = await import(
15585
- "../lib/runnable-provider.js"
15586
- );
15698
+ const { makeRunnableProviderFallback } =
15699
+ await import("../lib/runnable-provider.js");
15587
15700
  llmCall = makeRunnableProviderFallback(llmCall, {
15588
15701
  onFallback: ({ from, to, reason, fromModel, toModel }) => {
15589
15702
  // Telemetry: a provider/model fallback is a reliability signal — count
@@ -16353,9 +16466,8 @@ export async function* agentLoop(messages, options) {
16353
16466
  }
16354
16467
  compactionUsageCall =
16355
16468
  compactionUsageCall || compactionUsageState?.calls?.at(-1) || null;
16356
- const { getRejectedCompactionUsage } = await import(
16357
- "../lib/context-memory-kernel/live-compaction.js"
16358
- );
16469
+ const { getRejectedCompactionUsage } =
16470
+ await import("../lib/context-memory-kernel/live-compaction.js");
16359
16471
  const rejectedUsage = getRejectedCompactionUsage(_e);
16360
16472
  const returnedUsage = compactionUsageCall?.returnedUsage;
16361
16473
  const providerReceipt = _takeCompactionProviderReceipt(
@@ -16836,13 +16948,13 @@ export async function* agentLoop(messages, options) {
16836
16948
  // the run-level ids (turn.id correlates with the agent.iteration counter).
16837
16949
  let canonicalProviderContext = null;
16838
16950
  if (options.contextMemorySkipPlanning !== true) {
16839
- const { prepareCanonicalProviderContext } = await import(
16840
- "../lib/context-memory-kernel/provider-context.js"
16841
- );
16951
+ const { prepareCanonicalProviderContext } =
16952
+ await import("../lib/context-memory-kernel/provider-context.js");
16842
16953
  canonicalProviderContext = await prepareCanonicalProviderContext(
16843
16954
  callMessages,
16844
16955
  {
16845
16956
  ...options,
16957
+ provider: options.provider || "ollama",
16846
16958
  ...(independentReviewContext?.active
16847
16959
  ? { contextMemoryRecall: false }
16848
16960
  : {}),
@@ -16919,6 +17031,9 @@ export async function* agentLoop(messages, options) {
16919
17031
  // projection. Commit visibility only after a successful model response.
16920
17032
  const readFileRequestContext = { messages: callMessages };
16921
17033
  const providerCallOptions = {
17034
+ [MODEL_INPUT_PLAN]: canonicalProviderContext?.plan || null,
17035
+ [MODEL_INPUT_TOOLS]:
17036
+ canonicalProviderContext?.selectedToolDefinitions || null,
16922
17037
  [READ_FILE_REQUEST_CONTEXT]: readFileRequestContext,
16923
17038
  ...(evolutionIngress !== null
16924
17039
  ? { ...requestOptions, evolutionIngress }
@@ -16956,6 +17071,7 @@ export async function* agentLoop(messages, options) {
16956
17071
  }
16957
17072
  : {}),
16958
17073
  };
17074
+ providerCallOptions[MODEL_INPUT_USAGE_CALL] = modelUsageCall.callId;
16959
17075
  // Resolve before dispatch, including compatibility/skip-planning runs.
16960
17076
  // The panel and persisted transcript use this same request configuration.
16961
17077
  const requestContextWindow =
@@ -17001,7 +17117,18 @@ export async function* agentLoop(messages, options) {
17001
17117
  "agent.iteration": budget.consumed,
17002
17118
  ...(modelIdAttrs || {}),
17003
17119
  },
17004
- () => llmCall(callMessages, providerCallOptions),
17120
+ () =>
17121
+ canonicalProviderContext?.admissionEnabled === true
17122
+ ? withProviderRequestAdmission(
17123
+ {
17124
+ validate: canonicalProviderContext.assertCurrent,
17125
+ check: canonicalProviderContext.assertDispatchOpen,
17126
+ resource: canonicalProviderContext.dispatchResource,
17127
+ target: { provider: options.provider || "ollama" },
17128
+ },
17129
+ () => llmCall(callMessages, providerCallOptions),
17130
+ )
17131
+ : llmCall(callMessages, providerCallOptions),
17005
17132
  (span, r) => {
17006
17133
  const t = _usageTokens(r?.usage);
17007
17134
  if (t) {