nolo-cli 0.213.0 → 0.220.0

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 (271) hide show
  1. package/README.md +3 -2
  2. package/{_executeModel-CUJLCFWR.js → _executeModel-BNEMFCAO.js} +125 -96
  3. package/{accountResolver-4LKIHEKL.js → accountResolver-QETKNC7T.js} +4 -4
  4. package/{action-DF5UYSJF.js → action-GDZDXPMB.js} +14 -13
  5. package/{addContentAction-WERAONNY.js → addContentAction-7RO4AMRI.js} +21 -20
  6. package/{addDialogAgentAction-7VI7YRML.js → addDialogAgentAction-EVYBGTXB.js} +26 -25
  7. package/{agentDeleteCommand-XJORXPGU.js → agentDeleteCommand-7QTQNFCO.js} +145 -137
  8. package/{agentEmailCommands-XTYYFR6Z.js → agentEmailCommands-I7SHOSD6.js} +146 -139
  9. package/{agentFavoriteCommands-EDK743YA.js → agentFavoriteCommands-7LOP3HUD.js} +11 -12
  10. package/{agentGrantCommands-RQWK2TEV.js → agentGrantCommands-L6O2HVJI.js} +9 -9
  11. package/{agentListCommands-OBLRBLHS.js → agentListCommands-GUGMORTK.js} +180 -103
  12. package/{agentMachineCommands-5FMT3OT5.js → agentMachineCommands-UMDKILU3.js} +75 -66
  13. package/{agentProviderCommands-Q5O33MED.js → agentProviderCommands-STI3DQ6A.js} +8 -8
  14. package/{agentPullCommand-6EM3URVK.js → agentPullCommand-KHV4EELF.js} +11 -11
  15. package/agentRecordCommands-YTAMTHOY.js +175 -0
  16. package/agentRunCommand-DBM6YNO6.js +207 -0
  17. package/{agentRunControl-TAMHJQSR.js → agentRunControl-MBG4U6SL.js} +40 -19
  18. package/{agentRuntimeLocal-SOO2OPJG.js → agentRuntimeLocal-TU4LA353.js} +55 -48
  19. package/{agentSlice-CHR6KOZN.js → agentSlice-DPG7Q7IA.js} +24 -23
  20. package/{appDeleteCommands-GUP6P5YE.js → appDeleteCommands-JWP3XPUA.js} +67 -58
  21. package/{appDeployCommands-MH2FX4O5.js → appDeployCommands-6E4TQCWI.js} +67 -58
  22. package/{appDeployStatusCommands-SUHN3HPJ.js → appDeployStatusCommands-ALU4SADG.js} +67 -58
  23. package/{appGetCommands-YWDEX6Z4.js → appGetCommands-JEY4L6L4.js} +67 -58
  24. package/{appListCommands-ZQVMLPAY.js → appListCommands-PCAVHU7M.js} +67 -58
  25. package/{authCommand-PWX2ZNUP.js → authCommand-CGRIIOOV.js} +37 -33
  26. package/{authCommands-HV3EAU3V.js → authCommands-55OGQGCR.js} +16 -12
  27. package/{builtinSkillRegistry-2QETTQPM.js → builtinSkillRegistry-BAE2LDXF.js} +11 -13
  28. package/{chromeCommands-REEAH4SX.js → chromeCommands-G5UDKVSV.js} +3 -3
  29. package/{chromeOpsCommands-DIVM2K3T.js → chromeOpsCommands-WAA45NCS.js} +23 -13
  30. package/{chunk-VNYYOX3V.js → chunk-262R3XNN.js} +157 -50
  31. package/chunk-2MCB7CD7.js +98 -0
  32. package/{chunk-CTPXME7U.js → chunk-2NPD3FTX.js} +30 -7
  33. package/{chunk-YB3YZK56.js → chunk-2WZXXAQD.js} +1 -67
  34. package/{chunk-HRMJUN5J.js → chunk-2X7WFDT6.js} +1 -1
  35. package/chunk-2YGBI2XB.js +30 -0
  36. package/{chunk-TY3TIUJK.js → chunk-324FWHUA.js} +85 -3
  37. package/{chunk-KFLT5KAD.js → chunk-3NNXR7EH.js} +20 -20
  38. package/{chunk-ZRSNONOB.js → chunk-3P54D2E4.js} +8 -3
  39. package/{chunk-7OCO4TDT.js → chunk-3U44JB3O.js} +1 -1
  40. package/{chunk-TX5EYMGT.js → chunk-44J7Z5AQ.js} +34 -258
  41. package/chunk-4D4QD7FT.js +201 -0
  42. package/chunk-4I2MXV5Q.js +275 -0
  43. package/{chunk-MYOH447Z.js → chunk-4JVNURX4.js} +1 -1
  44. package/{chunk-COFEN36Z.js → chunk-4ZGPHFLE.js} +3 -3
  45. package/{chunk-ZXOUUDCG.js → chunk-53MFERZ3.js} +3869 -362
  46. package/chunk-547ENH5T.js +226 -0
  47. package/{chunk-YDH3FDFQ.js → chunk-5FUN7EG4.js} +1 -1
  48. package/{chunk-6DWMYIUY.js → chunk-5WKDR7HS.js} +14 -9
  49. package/chunk-5ZUOVCKT.js +32 -0
  50. package/{chunk-T43B7LB2.js → chunk-62HXNQVV.js} +1 -1
  51. package/{chunk-ZC3CMUKU.js → chunk-6OVNSQHN.js} +84 -2
  52. package/{chunk-IXNGOHV5.js → chunk-6QHKRARD.js} +12 -153
  53. package/{chunk-4T2WNOY7.js → chunk-6RDBLXVQ.js} +28 -17
  54. package/{chunk-EYLGAEB4.js → chunk-6XRPBZRS.js} +134 -0
  55. package/{chunk-KIM6CLW5.js → chunk-7JGMNKKG.js} +57 -26
  56. package/{chunk-P5L7CXOC.js → chunk-7Z6EW7AH.js} +3 -2
  57. package/chunk-AGYPUBFW.js +686 -0
  58. package/{chunk-Y63ZSOR6.js → chunk-AL3TYDIF.js} +1 -1
  59. package/{chunk-NOKUNJON.js → chunk-ALAES342.js} +75 -94
  60. package/{chunk-4I7ERB7F.js → chunk-ATEKLSLR.js} +2 -2
  61. package/{chunk-CRHOO2ZR.js → chunk-AUAJTAFM.js} +8 -8
  62. package/{chunk-LLRPJECG.js → chunk-AWIL6EHN.js} +15 -157
  63. package/chunk-BIDSIRTS.js +307 -0
  64. package/chunk-BIWI5M4E.js +62 -0
  65. package/{chunk-4VJAC32I.js → chunk-BNMPUQW6.js} +3 -2
  66. package/{chunk-RLBNLZVC.js → chunk-BP5ZJ6B4.js} +1 -1
  67. package/{chunk-NBTY7YJF.js → chunk-BR3GT6MR.js} +1 -0
  68. package/{chunk-7RFNTILS.js → chunk-BUDVRYES.js} +2 -2
  69. package/{chunk-SVYO6AO7.js → chunk-BV3FLP2L.js} +41 -1
  70. package/{chunk-ZL5RAEEB.js → chunk-CBUZ6DKA.js} +3 -3
  71. package/{chunk-SM3NSZJV.js → chunk-CD3RU7XL.js} +36 -2
  72. package/chunk-CMMI3DAT.js +1621 -0
  73. package/{chunk-J2NHJ7WX.js → chunk-CYWNWA77.js} +6 -6
  74. package/{chunk-MOIJOHA5.js → chunk-D6YNCNM6.js} +35 -21
  75. package/{chunk-H2TJUNCH.js → chunk-DBUR22G5.js} +16 -16
  76. package/chunk-DEA37IUY.js +271 -0
  77. package/{chunk-O2TZF4AI.js → chunk-DGYCDA6W.js} +4 -4
  78. package/{chunk-YWSEPJ7C.js → chunk-DUUDXSLX.js} +21 -7
  79. package/{chunk-KFHREHUQ.js → chunk-DXWGFL2Z.js} +89 -1
  80. package/{chunk-H5HF7TJA.js → chunk-EEOOBRA7.js} +6 -6
  81. package/{chunk-Y6ORVLSS.js → chunk-EVGU5P4U.js} +1 -1
  82. package/chunk-EWQ3HGNZ.js +90 -0
  83. package/{chunk-6VLJ6YA7.js → chunk-F6Z6ZCUV.js} +9 -9
  84. package/{chunk-75XIDFBW.js → chunk-FJ23FZXF.js} +72 -28
  85. package/chunk-FJSNBZXR.js +142 -0
  86. package/{chunk-WRYQ35LQ.js → chunk-G7IUT2V3.js} +860 -57
  87. package/{chunk-PCLE46CE.js → chunk-GBWGPTA7.js} +2 -1
  88. package/{chunk-H7PPIYWP.js → chunk-GPOV42YM.js} +19 -19
  89. package/{chunk-W4S457LU.js → chunk-GUXZK7SE.js} +42 -6
  90. package/{chunk-QHPRUL4O.js → chunk-GV6PRJBU.js} +4 -4
  91. package/{chunk-YUA6OAH5.js → chunk-HBRDSQ3M.js} +2 -2
  92. package/{chunk-G7MLNNEX.js → chunk-HHFGE2WF.js} +7 -7
  93. package/{chunk-OQPKUBPB.js → chunk-HSSBDZLD.js} +19 -7
  94. package/{chunk-EHSZD5OI.js → chunk-HXER7YJF.js} +4 -4
  95. package/{chunk-TAKB25RM.js → chunk-HYLRQDEE.js} +6 -6
  96. package/{chunk-LOEO7LRC.js → chunk-ILHQ2AXT.js} +10 -8
  97. package/{chunk-BBJ22CLB.js → chunk-JJMR2EA3.js} +64 -34
  98. package/{chunk-G2BQWAVT.js → chunk-JLAMNSBC.js} +4 -4
  99. package/{chunk-RSHTSUEG.js → chunk-JUSHVFNF.js} +2133 -622
  100. package/{chunk-YJAFKXMU.js → chunk-KHVFJSVE.js} +54 -49
  101. package/{chunk-X7SDOJUM.js → chunk-KRI6N5QZ.js} +16 -16
  102. package/{chunk-7BT37FK3.js → chunk-L32W3PRP.js} +675 -128
  103. package/chunk-LKA64WH4.js +227 -0
  104. package/{chunk-HUBHAQK2.js → chunk-LMRRCEDE.js} +31 -31
  105. package/chunk-M4SFKP5L.js +675 -0
  106. package/{chunk-MDB67IWP.js → chunk-MSMHU36U.js} +12 -12
  107. package/{chunk-7Y4YTDQF.js → chunk-MXKWTPUM.js} +288 -166
  108. package/{chunk-WYDI6TGM.js → chunk-MXRUXMZ3.js} +94 -135
  109. package/{chunk-AZMYUSVF.js → chunk-N5Z2V73W.js} +1 -1
  110. package/{chunk-QG4AOSON.js → chunk-NHY322ZU.js} +154 -32
  111. package/{chunk-UHJGXRJ4.js → chunk-OBIC6EG7.js} +6 -6
  112. package/{chunk-GOO6G4PY.js → chunk-OBSEKCVK.js} +123 -70
  113. package/{chunk-WMTBPBMP.js → chunk-OG6MQOQG.js} +130 -60
  114. package/{chunk-XJWWBO34.js → chunk-OJKUU3LP.js} +5 -7
  115. package/{chunk-ALQ3657A.js → chunk-OOJNQK6V.js} +21 -1
  116. package/{chunk-NSAPDIN2.js → chunk-OWKNSIXL.js} +679 -74
  117. package/{chunk-6XIE5ZGI.js → chunk-PDCV7P5W.js} +1 -1
  118. package/{chunk-A7TFUNZO.js → chunk-PPJYZRSQ.js} +6 -2
  119. package/{chunk-F6UUQOG6.js → chunk-Q3IVPFVO.js} +4 -4
  120. package/{chunk-VO4WSAVP.js → chunk-QBZCGP34.js} +3 -3
  121. package/chunk-QCB42576.js +13 -0
  122. package/chunk-QHEN7NZ7.js +46 -0
  123. package/{chunk-3UKL3HPD.js → chunk-QJTZ76CP.js} +32 -84
  124. package/{chunk-V5Y3R6BT.js → chunk-QRGDJA4B.js} +215 -212
  125. package/{chunk-4KB6WQUL.js → chunk-QYB23WUH.js} +1 -1
  126. package/{chunk-ZNWI6OVT.js → chunk-R44TU3MZ.js} +85 -11
  127. package/{chunk-PYRUW7XN.js → chunk-R6Z5S5GA.js} +139 -57
  128. package/{chunk-VL5KOY2C.js → chunk-R7XWZDOH.js} +125 -29
  129. package/{chunk-R5O4QAWG.js → chunk-RBPUNSG5.js} +11 -77
  130. package/{chunk-NJLL224W.js → chunk-RG2DGNL6.js} +3 -3
  131. package/{chunk-C6KNNXWU.js → chunk-RGQ4UUWZ.js} +25 -2
  132. package/{chunk-TCZHTTUU.js → chunk-RTHFJZ6M.js} +11 -11
  133. package/{chunk-RZOV7OMV.js → chunk-RYOLWYBK.js} +146 -200
  134. package/{chunk-OWYYDMGJ.js → chunk-S2NTVGA2.js} +4 -2
  135. package/{chunk-XHQC4PXX.js → chunk-S5NA3C52.js} +488 -226
  136. package/{secretCommands-LXDWOLZ6.js → chunk-S6FDXXZV.js} +190 -15
  137. package/chunk-S6K5F3KP.js +99 -0
  138. package/{chunk-INN4LTAJ.js → chunk-SRCCSTIM.js} +8 -8
  139. package/{chunk-JY5NGFFH.js → chunk-SYTHYBMI.js} +5 -5
  140. package/{chunk-UYD5HQ6T.js → chunk-SZVMASJ2.js} +3300 -1396
  141. package/{chunk-FUGMREBO.js → chunk-TGNIKIHR.js} +3 -3
  142. package/{chunk-HPFCI4SK.js → chunk-TI2EPRHE.js} +4 -4
  143. package/chunk-TLE77UJ5.js +230 -0
  144. package/chunk-TSPMLCWI.js +364 -0
  145. package/{chunk-YGILMZ7N.js → chunk-TUSTONB3.js} +1 -1
  146. package/{chunk-4VNS5WPM.js → chunk-U67V476Y.js} +1 -8
  147. package/{chunk-F7CI2ZC5.js → chunk-UAIHKQIA.js} +2 -1
  148. package/{chunk-WPORQFYN.js → chunk-UVLYNWIE.js} +2 -2
  149. package/{chunk-H4UOTUOX.js → chunk-VMJVAJ6W.js} +152 -19
  150. package/{chunk-KC4XDTT3.js → chunk-VS276URX.js} +4 -4
  151. package/{chunk-YTF4WH7J.js → chunk-WWTSEBDF.js} +1 -1
  152. package/{chunk-E2BESSAW.js → chunk-X4O7FJF5.js} +2 -0
  153. package/{chunk-RPQXPZZF.js → chunk-XSW4EXQV.js} +976 -17
  154. package/{chunk-7QTZCMKL.js → chunk-XTETTSKN.js} +3036 -2468
  155. package/{chunk-J5JTMQIA.js → chunk-YFLVRVYK.js} +1 -1
  156. package/chunk-YKY4OVOX.js +1141 -0
  157. package/{chunk-MMA3LZ3W.js → chunk-YNIYE47Z.js} +1 -1
  158. package/chunk-YZMNK53S.js +68 -0
  159. package/{chunk-FY7F4Q6X.js → chunk-Z4PCXPUE.js} +2 -2
  160. package/{chunk-INUFILG6.js → chunk-ZH3KXFHS.js} +11 -3
  161. package/chunk-ZOHO6MOF.js +376 -0
  162. package/{cliAgentConfigHelpers-WJBZQTLW.js → cliAgentConfigHelpers-BTRHMPW2.js} +18 -19
  163. package/{cliAuthorityBrokerClient-PM3U6Q6J.js → cliAuthorityBrokerClient-XHH7MH2P.js} +1 -1
  164. package/{cliAuthorityStoreDriver-TKLXNNTG.js → cliAuthorityStoreDriver-6FE3BJNB.js} +1 -1
  165. package/{cliEnvHelpers-BVYTMUPJ.js → cliEnvHelpers-CNMP3RDX.js} +3 -3
  166. package/{cliExecutor-BWBF2MTI.js → cliExecutor-K6FDZTQ2.js} +4 -2
  167. package/cliLocalAgentRecordReader-M3F76NIP.js +90 -0
  168. package/{commandRegistry-W63CYRZJ.js → commandRegistry-T3UBK6OA.js} +105 -97
  169. package/{contentThunks-U7PL5MQD.js → contentThunks-YEPZAHXU.js} +53 -48
  170. package/{cooldownCommands-TIGUHXTD.js → cooldownCommands-YB5H5BBK.js} +5 -4
  171. package/{createAgentAutomationAction-OLBQDD6R.js → createAgentAutomationAction-TBIIO5WT.js} +51 -48
  172. package/{createDialogAction-SVH6B3SB.js → createDialogAction-KBKMYFTQ.js} +52 -53
  173. package/{createPageAction-F4DIWZ2Z.js → createPageAction-3FGAPLJO.js} +56 -53
  174. package/{cursorProvider-YGGNMVWX.js → cursorProvider-2RACMEMF.js} +1 -1
  175. package/{db-HUCI5R4G.js → db-M7FU2GNK.js} +10 -7
  176. package/{dbSlice-BVH2YZPQ.js → dbSlice-XRUZOGSU.js} +20 -19
  177. package/{deleteFile-5YOEKV4U.js → deleteFile-6URDHYRB.js} +12 -12
  178. package/{desktopFolderProjects-SFY5EZS3.js → desktopFolderProjects-4POAMVJN.js} +2 -2
  179. package/{dialogCommands-KHIEPY3M.js → dialogCommands-NRLCOPJR.js} +71 -64
  180. package/dialogNotifyCommand-SHGPCU22.js +36 -0
  181. package/{dialogSlice-ZCTDV2PZ.js → dialogSlice-DP2WTMNO.js} +48 -45
  182. package/{dialogUsageCommand-7KCPYGHG.js → dialogUsageCommand-W2WCSGKF.js} +11 -10
  183. package/{docCreateCommands-DPMZI7G5.js → docCreateCommands-YJRDA3RX.js} +66 -59
  184. package/{docDeleteCommands-IRQQLUBT.js → docDeleteCommands-A5QIHZNF.js} +69 -62
  185. package/{docReadCommands-LK37XH6L.js → docReadCommands-CF2LTMYH.js} +66 -59
  186. package/{docStore-V2KECILA.js → docStore-NDY3K3PK.js} +25 -24
  187. package/{docUpdateCommands-O6T3HJHH.js → docUpdateCommands-QRKV4ZXE.js} +69 -62
  188. package/{fetchMessages-NR4KNQLO.js → fetchMessages-TQEUZD7H.js} +8 -7
  189. package/{getPricing-2MNMXEVG.js → getPricing-LF5C4XSI.js} +7 -7
  190. package/{handleSendMessageAction-2PE25WM3.js → handleSendMessageAction-IUGVVJ43.js} +206 -314
  191. package/{hostCredentialCreate-S233UMAP.js → hostCredentialCreate-X2ZFRXDR.js} +132 -124
  192. package/index.js +65 -27
  193. package/{keys-BEGDOTRL.js → keys-RWF7UCB4.js} +5 -4
  194. package/legacyMigration-TF4SYJCZ.js +19 -0
  195. package/{lib-5KKIBFIT.js → lib-OT5OTXRU.js} +7087 -6664
  196. package/{localDialogRead-7NNDVVF7.js → localDialogRead-CCOCVGAP.js} +3 -3
  197. package/{localFirstLog-DHNOY2NA.js → localFirstLog-OIETGK66.js} +1 -1
  198. package/localRecall-BDYKXB46.js +17 -0
  199. package/{localRuntimeAdapter-KY6WXNBR.js → localRuntimeAdapter-KAG3T4LF.js} +138 -130
  200. package/{localRuntimeAuthority-OYH4AE4G.js → localRuntimeAuthority-IBJAT62G.js} +1 -1
  201. package/{localRuntimeDb-VBIMCWUC.js → localRuntimeDb-N7KHDXS2.js} +2 -2
  202. package/{machineCommands-Q6HA3IXF.js → machineCommands-6NIQJE2A.js} +143 -135
  203. package/{machineInfo-UKPTZO5Y.js → machineInfo-LWHTEBHJ.js} +1 -1
  204. package/machineWsRunDispatch-RA5NOSGG.js +190 -0
  205. package/{memberThunks-7EDJADWU.js → memberThunks-7Y3OYSJQ.js} +30 -29
  206. package/{memoryCommands-ASCE5STX.js → memoryCommands-BC6REPQB.js} +7 -7
  207. package/models-H5NNZRLH.js +9 -0
  208. package/{oauthTokenStore-OEERZFUC.js → oauthTokenStore-RUYNYALS.js} +1 -1
  209. package/{offlineMarxistsAgentCommand-2QTHJCHV.js → offlineMarxistsAgentCommand-XVXUE6G5.js} +6 -6
  210. package/overlay-BBQZXGYI.js +13 -0
  211. package/package.json +2 -2
  212. package/{pdf-U6KSUEZZ.js → pdf-KE3QI2V7.js} +1 -1
  213. package/{processSpawn-ZU5QFM43.js → processSpawn-6GEO77KV.js} +1 -1
  214. package/{profileConfig-KN3N2BLF.js → profileConfig-KOWK4HOG.js} +1 -1
  215. package/{projectArchive-DRTDIMEV.js → projectArchive-OIUP63MV.js} +59 -56
  216. package/{providerPresetApply-YXGV6NXB.js → providerPresetApply-WHAMP2D5.js} +20 -13
  217. package/{providerRegistry-S6UL6UNA.js → providerRegistry-ZI2KORJ7.js} +11 -11
  218. package/{read-4V2RMG7N.js → read-TYMBGEXO.js} +13 -13
  219. package/{readDocTool-BH6ATGQO.js → readDocTool-SKQVHBLO.js} +2 -2
  220. package/{readlineWorkspace-2W4WRCOU.js → readlineWorkspace-ZGC4KSXG.js} +7760 -6499
  221. package/{removeDialogAgentAction-LYAZGNKW.js → removeDialogAgentAction-F5QE2O2B.js} +29 -28
  222. package/{runAgentClientLoop-J2VQBS2Z.js → runAgentClientLoop-NKUW2DSJ.js} +94 -88
  223. package/{runtimeDoctorCommands-QAI3MBKQ.js → runtimeDoctorCommands-RRKPBGVO.js} +19 -19
  224. package/{runtimeModeArgs-2Y7BALTO.js → runtimeModeArgs-X7DL7PUN.js} +1 -1
  225. package/secretCommands-KZWBZIYS.js +24 -0
  226. package/{setDialogExtraReferencesAction-OCRPGPYH.js → setDialogExtraReferencesAction-72L27ERM.js} +25 -24
  227. package/{setPrimaryDialogAgentAction-HFJDQIBU.js → setPrimaryDialogAgentAction-GJJDUSGJ.js} +29 -28
  228. package/{settingThunks-RAMHMTGM.js → settingThunks-ZRGWVGZD.js} +99 -90
  229. package/{skillDiscovery-XKHROSH2.js → skillDiscovery-I37M5KJC.js} +4 -4
  230. package/{skillSummaryMarker-42HKSXYY.js → skillSummaryMarker-62UW7HI7.js} +1 -1
  231. package/{slateToRenderMarkdown-Y5IYN73U.js → slateToRenderMarkdown-R3X74MCX.js} +1 -1
  232. package/{slateUtils-NGV2NMKM.js → slateUtils-ESQAJ6RN.js} +1 -1
  233. package/{spaceCommands-KVJZVKVO.js → spaceCommands-MEH3HJBC.js} +66 -57
  234. package/store-Z53ICFL3.js +48 -0
  235. package/{streamAgentChatTurn-GHBMJJ6S.js → streamAgentChatTurn-FJTUUXHJ.js} +886 -668
  236. package/{switchDialogAgentAction-EBRMW3RA.js → switchDialogAgentAction-IIJBPND3.js} +26 -25
  237. package/{tableCommands-MP6VFSVT.js → tableCommands-FTAOCBTX.js} +13 -13
  238. package/tombstones-FQQMEDOW.js +32 -0
  239. package/{toolApiClient-HGNO53TC.js → toolApiClient-OGQEBQVX.js} +4 -4
  240. package/{tools-EWKCPKMS.js → tools-ZXHIAOSP.js} +82 -81
  241. package/tuiRestart-2IL37YIB.js +41 -0
  242. package/tuiSummaryLlmCaller-W2QN4VAC.js +44 -0
  243. package/{updateCommands-ZQYU6SCI.js → updateCommands-CPATDG6J.js} +11 -7
  244. package/{updateDialogTitleAction-5GGMBTDF.js → updateDialogTitleAction-JMKLKL4P.js} +54 -51
  245. package/{usageCommand-F4IPVMIZ.js → usageCommand-2BF74MKF.js} +11 -10
  246. package/{usageRebuildCommand-HAW2AD5N.js → usageRebuildCommand-UHB55BQM.js} +12 -11
  247. package/userDataMerge-HT2ZVHBJ.js +13 -0
  248. package/{windowsSelfUpdate-257DV2T6.js → windowsSelfUpdate-ZFD6J5HF.js} +3 -3
  249. package/{workloadLifecycle-4C42SVBD.js → workloadLifecycle-HFJIN5IZ.js} +4 -4
  250. package/agentRecordCommands-ZQ7SVYGG.js +0 -167
  251. package/agentRunCommand-WS7IGO2W.js +0 -196
  252. package/chunk-3CGG2PAL.js +0 -594
  253. package/chunk-5MQRBSMW.js +0 -862
  254. package/chunk-5XBUWM6I.js +0 -89
  255. package/chunk-CJEIOP3E.js +0 -0
  256. package/chunk-EHGEOAHI.js +0 -636
  257. package/chunk-FW6YHHLI.js +0 -842
  258. package/chunk-GPVRUGGY.js +0 -115
  259. package/chunk-HSVBJRF4.js +0 -339
  260. package/chunk-LEC5ALIN.js +0 -91
  261. package/chunk-WACI5I6V.js +0 -147
  262. package/chunk-WJZOQR2J.js +0 -151
  263. package/chunk-ZCWRMUWT.js +0 -89
  264. package/dist-M676ULYG.js +0 -7314
  265. package/machineWsRunDispatch-WWJQ6WR3.js +0 -182
  266. package/models-PJBE6JDV.js +0 -9
  267. package/tuiSummaryLlmCaller-ALQYUUWB.js +0 -189
  268. package/{chunk-AGP3YSEC.js → chunk-4N6G2CKP.js} +3 -3
  269. package/{chunk-BLVSFYQ3.js → chunk-LISC7BD4.js} +3 -3
  270. package/{chunk-2QHFH3DR.js → chunk-USGHJSGO.js} +3 -3
  271. package/{chunk-AETZ7AD6.js → chunk-W6RFEDN4.js} +3 -3
@@ -1,3 +1,15 @@
1
+ import {
2
+ DEVIN_CONNECT_URL,
3
+ parseSseDataLineJson,
4
+ parseSseDataLineObject
5
+ } from "./chunk-2NPD3FTX.js";
6
+ import {
7
+ EXECUTION_BACKEND_KINDS
8
+ } from "./chunk-PWTNI4N7.js";
9
+ import {
10
+ formatImageSummary,
11
+ readLocalImage
12
+ } from "./chunk-AL3TYDIF.js";
1
13
  import {
2
14
  applyChatCompletionDelta,
3
15
  applyResponsesToolEvent,
@@ -6,12 +18,7 @@ import {
6
18
  flushChatCompletionStream,
7
19
  providerHttpFailure,
8
20
  throwIfChatCompletionStreamFailed
9
- } from "./chunk-OQPKUBPB.js";
10
- import {
11
- DEVIN_CONNECT_URL,
12
- parseSseDataLineJson,
13
- parseSseDataLineObject
14
- } from "./chunk-CTPXME7U.js";
21
+ } from "./chunk-HSSBDZLD.js";
15
22
  import {
16
23
  readSseFrames
17
24
  } from "./chunk-HNUWUO75.js";
@@ -20,16 +27,22 @@ import {
20
27
  summarizeToolArguments
21
28
  } from "./chunk-CHOZJMJS.js";
22
29
  import {
23
- EXECUTION_BACKEND_KINDS
24
- } from "./chunk-PWTNI4N7.js";
25
- import {
26
- formatImageSummary,
27
- readLocalImage
28
- } from "./chunk-Y63ZSOR6.js";
29
- import {
30
+ evaluateRequestBudget,
30
31
  hasImageInRuntimeMessages,
31
32
  stripImagePartsFromMessages
32
- } from "./chunk-W4S457LU.js";
33
+ } from "./chunk-GUXZK7SE.js";
34
+ import {
35
+ resolveToolExecutionContract
36
+ } from "./chunk-LKA64WH4.js";
37
+ import {
38
+ clipToolText,
39
+ resolveHistoricalToolContentCap,
40
+ resolveToolOutputProfile
41
+ } from "./chunk-2WZXXAQD.js";
42
+ import {
43
+ resolveAgentImageInputSupport,
44
+ resolveToolImagePolicy
45
+ } from "./chunk-DUUDXSLX.js";
33
46
  import {
34
47
  applyShapingCounts,
35
48
  attachProjectionFacts,
@@ -40,7 +53,7 @@ import {
40
53
  projectUserPartForModel,
41
54
  resolveOutboundDiagnosticSink,
42
55
  writeThinkingFacts
43
- } from "./chunk-4KB6WQUL.js";
56
+ } from "./chunk-QYB23WUH.js";
44
57
  import {
45
58
  createThinkParserState,
46
59
  createToolCallAccumulator,
@@ -66,7 +79,7 @@ import {
66
79
  hashStablePrefixContent,
67
80
  resolveResponseGuidelines,
68
81
  resolveToolGuidedSections
69
- } from "./chunk-5MQRBSMW.js";
82
+ } from "./chunk-AGYPUBFW.js";
70
83
  import {
71
84
  classifyUnparsableToolArgs,
72
85
  collectStablePromptPrefix,
@@ -90,7 +103,7 @@ import {
90
103
  toOpenAiCompatibleMessages,
91
104
  toResponsesTools,
92
105
  transferDowngradedToolTurnOrigin
93
- } from "./chunk-H5HF7TJA.js";
106
+ } from "./chunk-EEOOBRA7.js";
94
107
  import {
95
108
  TOOL_HAD_IMAGES,
96
109
  TOOL_IMAGES,
@@ -103,39 +116,31 @@ import {
103
116
  toolImageDelivery,
104
117
  toolImages,
105
118
  withoutToolImages
106
- } from "./chunk-E2BESSAW.js";
119
+ } from "./chunk-X4O7FJF5.js";
107
120
  import {
108
121
  BRIDGE_STREAM_MAX_CHARS,
109
122
  CLI_NOLO_WORKSPACE_TOOL_NAMES,
110
123
  DEFAULT_READ_DIALOG_MAX_RESPONSE_CHARS,
111
- DEFAULT_SUBTASK_MAX_TOOL_CALLS,
112
- DEFAULT_SUBTASK_MAX_WALL_CLOCK_MS,
113
124
  NOLO_WORKSPACE_TOOL_NAMES,
114
125
  buildDialogReadEnvelope,
115
126
  buildNoloWorkspaceCommandArgs,
116
127
  buildNoloWorkspaceOpenAiTools,
117
- buildSubtaskBudgetExhaustedContent,
118
128
  createStreamingDialogReadProjector,
119
- createSubtaskBudgetTracker,
120
129
  noloPositiveIntegerString,
121
130
  noloStringArg,
122
131
  parseNoloWorkspaceToolArguments,
123
132
  readTextStreamUpToChars,
124
133
  resolveNoloDialogInput
125
- } from "./chunk-RZOV7OMV.js";
134
+ } from "./chunk-RYOLWYBK.js";
126
135
  import {
127
136
  applyToolSurfaceConstraints
128
- } from "./chunk-KC4XDTT3.js";
137
+ } from "./chunk-VS276URX.js";
129
138
  import {
130
- clipToolText,
131
- planContextUsage,
132
- resolveHistoricalToolContentCap,
133
- resolveToolOutputProfile
134
- } from "./chunk-YB3YZK56.js";
139
+ isQuotaExhaustedError
140
+ } from "./chunk-TLE77UJ5.js";
135
141
  import {
136
- resolveAgentImageInputSupport,
137
- resolveToolImagePolicy
138
- } from "./chunk-YWSEPJ7C.js";
142
+ isAgentSkillDisabled
143
+ } from "./chunk-FJSNBZXR.js";
139
144
  import {
140
145
  buildDialogFallbackTitleFromUserInput
141
146
  } from "./chunk-2MBTWINN.js";
@@ -143,29 +148,35 @@ import {
143
148
  EMPTY_ASSISTANT_REPAIR_PROMPT,
144
149
  extractReferenceKeysFromMessage,
145
150
  hasAssistantVisibleOutput,
146
- normalizeUsage,
147
- readCacheCreationInputTokens,
148
- readCacheReadInputTokens,
149
151
  resolveAgentContextWindow,
150
152
  resolveEmptyAssistantFallbackMessage,
151
153
  resolveEmptyAssistantOutcome,
152
154
  resolveTruncatedReasoningTailLog
153
- } from "./chunk-V5Y3R6BT.js";
155
+ } from "./chunk-QRGDJA4B.js";
154
156
  import {
155
157
  COMPACTION_SUMMARY_SCHEMA_VERSION,
156
158
  COMPACTION_SUMMARY_SYSTEM_PROMPT,
157
159
  buildBoundedCompactionRequest,
158
160
  buildCompactionMetricsFromPlan,
161
+ buildSummarySourceDiagnostics,
162
+ classifySummaryError,
159
163
  computeSummarySourceMetadata,
164
+ createSummaryBudget,
160
165
  formatCompactionMetricsLog,
161
166
  getMessageTokenCount,
162
167
  getModelContextWindow,
168
+ isTruncatedCompletion,
169
+ normalizeUsage,
163
170
  planCompression,
171
+ readCacheCreationInputTokens,
172
+ readCacheReadInputTokens,
164
173
  resolveCompressionTriggerRatio,
165
174
  resolveEffectiveCompactionBudgets,
175
+ runSummaryWithContract,
166
176
  sha256Hex,
177
+ summaryCompletionTokens,
167
178
  truncateToolOutputForContext
168
- } from "./chunk-7BT37FK3.js";
179
+ } from "./chunk-L32W3PRP.js";
169
180
  import {
170
181
  createProviderCallTimingTracker,
171
182
  finalizeProviderCallTiming,
@@ -176,31 +187,27 @@ import {
176
187
  import {
177
188
  clipCompactText
178
189
  } from "./chunk-5MMAK75Q.js";
179
- import {
180
- assertCredentialRef
181
- } from "./chunk-OQHIVPG4.js";
182
190
  import {
183
191
  asRecordOrEmpty
184
192
  } from "./chunk-KX6YBIHG.js";
193
+ import {
194
+ assertCredentialRef
195
+ } from "./chunk-OQHIVPG4.js";
185
196
  import {
186
197
  isAbortError
187
198
  } from "./chunk-7DPNBQSV.js";
188
199
  import {
189
- buildDialogSummaryLayer
190
- } from "./chunk-ZRSNONOB.js";
191
- import {
192
- buildUserResponseLanguageContext
193
- } from "./chunk-4VJAC32I.js";
194
- import {
195
- canonicalizeToolName,
196
- canonicalizeToolNames
197
- } from "./chunk-ZCWRMUWT.js";
200
+ isLevelNotFoundError
201
+ } from "./chunk-OW765XBU.js";
198
202
  import {
203
+ TOOL_OUTPUT_SPILL_BYTES,
204
+ TOOL_OUTPUT_SPILL_LINES,
199
205
  buildInteractiveCommandBlockedResult,
200
206
  buildProcessTaskResultCapsule,
201
207
  buildWorkspaceShellCommand,
202
208
  buildWorkspaceShellEscapeBlockedResult,
203
209
  buildWorkspaceShellPlan,
210
+ countLines,
204
211
  createGlob,
205
212
  deriveLabel,
206
213
  extractActivity,
@@ -209,56 +216,74 @@ import {
209
216
  formatToolOverflowMarker,
210
217
  getProcessRegistry,
211
218
  isProcessTaskTerminalStatus,
219
+ isSpilledToolOutput,
212
220
  reportedTaskStatus,
213
221
  resolveExecShellTimeoutMs,
214
222
  resolveExecutableOnPath,
215
223
  runWorkspaceCommand,
216
224
  spawnToWebStreams,
225
+ spillLargeToolOutput,
217
226
  spillToolOutput,
218
227
  toProcessTaskView,
219
228
  truncateToolOutput
220
- } from "./chunk-H4UOTUOX.js";
229
+ } from "./chunk-VMJVAJ6W.js";
221
230
  import {
222
231
  estimateTokenCount
223
232
  } from "./chunk-PSCNXBYA.js";
224
- import {
225
- buildProviderAuthHeaders,
226
- buildProviderExecutionPlan
227
- } from "./chunk-TCZHTTUU.js";
228
- import {
229
- toErrorMessage
230
- } from "./chunk-HNMXYYJR.js";
231
- import {
232
- isRecord
233
- } from "./chunk-KUG52IAP.js";
234
- import {
235
- asTrimmedLowercaseString
236
- } from "./chunk-QSJ3HFEF.js";
237
- import {
238
- normalizeServerOrigin
239
- } from "./chunk-CF7PE763.js";
240
233
  import {
241
234
  resolveNoloStateDir
242
235
  } from "./chunk-6UBGXX2W.js";
236
+ import {
237
+ WORKTREE_ISOLATION_PRELUDE
238
+ } from "./chunk-G7IUT2V3.js";
239
+ import {
240
+ canonicalizeToolName,
241
+ canonicalizeToolNames
242
+ } from "./chunk-6OVNSQHN.js";
243
243
  import {
244
244
  dialogMessageKey,
245
245
  dialogMessageRange
246
- } from "./chunk-XJWWBO34.js";
246
+ } from "./chunk-OJKUU3LP.js";
247
247
  import {
248
248
  asTrimmedNonEmptyStringArray
249
249
  } from "./chunk-I42VC5KR.js";
250
250
  import {
251
251
  asOptionalPositiveFiniteNumber
252
252
  } from "./chunk-U6VC4MU4.js";
253
+ import {
254
+ buildDialogSummaryLayer
255
+ } from "./chunk-3P54D2E4.js";
256
+ import {
257
+ buildUserResponseLanguageContext
258
+ } from "./chunk-BNMPUQW6.js";
259
+ import {
260
+ buildProviderAuthHeaders,
261
+ buildProviderExecutionPlan
262
+ } from "./chunk-RTHFJZ6M.js";
263
+ import {
264
+ toErrorMessage
265
+ } from "./chunk-HNMXYYJR.js";
253
266
  import {
254
267
  asTrimmedString
255
268
  } from "./chunk-3EUW3WEO.js";
269
+ import {
270
+ isRecord
271
+ } from "./chunk-KUG52IAP.js";
256
272
  import {
257
273
  asOptionalTrimmedString
258
274
  } from "./chunk-G3SUCT4W.js";
275
+ import {
276
+ normalizeServerOrigin
277
+ } from "./chunk-CF7PE763.js";
278
+ import {
279
+ PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL
280
+ } from "./chunk-OBSEKCVK.js";
281
+ import {
282
+ asTrimmedLowercaseString
283
+ } from "./chunk-QSJ3HFEF.js";
259
284
  import {
260
285
  __export
261
- } from "./chunk-4VNS5WPM.js";
286
+ } from "./chunk-U67V476Y.js";
262
287
 
263
288
  // packages/agent-runtime/actionGate.ts
264
289
  function readCommandActionGatePayload(payload) {
@@ -302,6 +327,72 @@ function readTitleParams(value) {
302
327
  return Object.fromEntries(entries);
303
328
  }
304
329
 
330
+ // packages/agent-runtime/dialogHistoryOrder.ts
331
+ import { decodeTime } from "ulid";
332
+ function orderDialogHistory(messages) {
333
+ const time = (message) => {
334
+ if (Number.isFinite(message.cliHistoryOrder)) return message.cliHistoryOrder;
335
+ const id = message.id ?? message.cliMessageId;
336
+ if (!id) return Infinity;
337
+ const timestamp = /^(\d+)-/.exec(id);
338
+ if (timestamp) return Number(timestamp[1]);
339
+ if (/^[0-9A-HJKMNP-TV-Z]{26}$/.test(id)) {
340
+ try {
341
+ return decodeTime(id);
342
+ } catch {
343
+ }
344
+ }
345
+ return Number.isFinite(message.createdAt) ? message.createdAt : -Infinity;
346
+ };
347
+ const identity2 = (message) => message.id ?? message.cliMessageId;
348
+ return messages.map((message, index) => ({ message, index, time: time(message) })).sort((a, b) => {
349
+ if (a.time !== b.time) return a.time < b.time ? -1 : 1;
350
+ const left = identity2(a.message), right = identity2(b.message);
351
+ if (left && right && left !== right) return left < right ? -1 : 1;
352
+ return a.index - b.index;
353
+ }).map(({ message }) => message);
354
+ }
355
+ function dialogTurnUserMessageId(turnId, index) {
356
+ if (typeof turnId !== "string" || !/^turn-[0-9A-HJKMNP-TV-Z]{26}$/.test(turnId)) return void 0;
357
+ return `${decodeTime(turnId.slice(5))}-${String(index + 1).padStart(3, "0")}-${turnId}`;
358
+ }
359
+
360
+ // packages/agent-runtime/contextRefusal.ts
361
+ var machineIdentifier = (value) => value && /^[A-Z][A-Z0-9_]{0,63}$/.test(value) ? value : void 0;
362
+ function classifyContextRefusal(args2) {
363
+ const { outcome, historyTokens, budget, droppedCount } = args2;
364
+ const largest = args2.largestMessageTokens;
365
+ const numbersKnown = Number.isFinite(historyTokens) && historyTokens >= 0 && Number.isFinite(budget) && budget >= 0 && largest !== void 0 && Number.isFinite(largest) && largest >= 0;
366
+ const base = { historyTokens, budget, droppedCount, largestMessageTokens: largest ?? -1 };
367
+ const result4 = (reason, detail) => ({ ...base, reason, detail });
368
+ if (!numbersKnown) return result4("unknown", "input-estimate-unavailable");
369
+ if (largest >= budget) return result4("single-message-too-large", "largest-message-at-or-above-budget");
370
+ const compacted = outcome?.result;
371
+ const decision = compacted?.decision;
372
+ const failure = outcome?.error ?? compacted?.failure;
373
+ if (failure || compacted?.failureReason || decision?.outcome === "failed") {
374
+ const code = machineIdentifier(failure?.code);
375
+ const errorType = failure?.errorType;
376
+ const status = failure?.status;
377
+ if (code === "PROVIDER_UNAVAILABLE" || code === "SUMMARY_PROVIDER_UNAVAILABLE") {
378
+ return result4("no-compactable-content", `code=${code}`);
379
+ }
380
+ const busy = status === 503 || status === 429 || !!code && /BUSY|RATE_LIMIT|CAPACITY|OVERLOAD|RESOURCE_EXHAUSTED/.test(code) || !!errorType && /^(?:capacity|overloaded|rate_limit)(?:_error)?$/.test(errorType);
381
+ const detail = [
382
+ status !== void 0 && Number.isInteger(status) && status >= 100 && status <= 599 ? `status=${status}` : "",
383
+ code ? `code=${code}` : "",
384
+ failure ? `category=${failure.category}` : `failure=${compacted?.failureReason ?? (decision?.outcome === "failed" ? decision.reason : "provider-error")}`
385
+ ].filter(Boolean).join(" ");
386
+ return result4(busy ? "summary-provider-busy" : "summary-failed", detail);
387
+ }
388
+ if (decision?.outcome === "skipped") {
389
+ if (decision.skipReason === "summary-empty") return result4("summary-failed", "summary-empty");
390
+ const bounded3 = decision.skipReason === "bounded-request-blocked" ? /\b(no-budget|invalid-window|empty-input|no-safe-group|group-too-large)\b/.exec(decision.detail ?? "")?.[1] : void 0;
391
+ return result4("no-compactable-content", `skip=${decision.skipReason}${bounded3 ? ` detail=${bounded3}` : ""}`);
392
+ }
393
+ return result4("unknown", decision ? "no-refusal-decision" : "compaction-not-evaluated");
394
+ }
395
+
305
396
  // node_modules/effect/dist/Pipeable.js
306
397
  var pipeArguments = (self, args2) => {
307
398
  switch (args2.length) {
@@ -13125,6 +13216,30 @@ function createLoopTiming() {
13125
13216
  return { mark, flush: flush2 };
13126
13217
  }
13127
13218
 
13219
+ // packages/agent-runtime/toolExecutionFailure.ts
13220
+ function isToolExecutionFailure(args2) {
13221
+ const metadata = args2.metadata;
13222
+ if (metadata) {
13223
+ if (metadata.error) return true;
13224
+ const exitCode = metadata.exitCode;
13225
+ if (typeof exitCode === "number" && Number.isFinite(exitCode) && exitCode !== 0) return true;
13226
+ if (typeof exitCode === "string" && exitCode.trim() !== "") {
13227
+ const parsedExitCode = Number(exitCode);
13228
+ if (Number.isFinite(parsedExitCode) && parsedExitCode !== 0) return true;
13229
+ }
13230
+ if (metadata.timedOut === true) return true;
13231
+ }
13232
+ if (typeof args2.content !== "string" || !args2.content.trim()) return false;
13233
+ try {
13234
+ const parsed = JSON.parse(args2.content);
13235
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
13236
+ const record2 = parsed;
13237
+ return Boolean(record2.error) || record2.ok === false || record2.success === false || record2.status === "error";
13238
+ } catch {
13239
+ return false;
13240
+ }
13241
+ }
13242
+
13128
13243
  // packages/agent-runtime/toolCallPairing.ts
13129
13244
  function readToolCallId(message) {
13130
13245
  if (typeof message.tool_call_id === "string" && message.tool_call_id) {
@@ -13483,7 +13598,7 @@ var OBSERVATION_ONLY_METADATA_KEYS = /* @__PURE__ */ new Set([
13483
13598
  ]);
13484
13599
  function formatToolMessageContent(args2) {
13485
13600
  const sanitizedContent = sanitizeToolOutputText(args2.content ?? "");
13486
- const scrubbedContent = scrubSecrets(sanitizedContent).cleaned;
13601
+ const scrubbedContent = spillLargeToolOutput(scrubSecrets(sanitizedContent).cleaned, args2.toolName, args2.workspaceRoot);
13487
13602
  if (args2.toolName !== "globFiles" && args2.toolName !== "codeSearch" && args2.toolName !== "readFile" || !args2.metadata || Object.keys(args2.metadata).length === 0) {
13488
13603
  return scrubbedContent;
13489
13604
  }
@@ -13499,7 +13614,7 @@ function formatToolMessageContent(args2) {
13499
13614
  [tool metadata]
13500
13615
  ${JSON.stringify(visible)}`;
13501
13616
  }
13502
- function blocksToOpenAiMessages(blocks) {
13617
+ function blocksToOpenAiMessages(blocks, workspaceRoot) {
13503
13618
  const out = [];
13504
13619
  let text2 = "";
13505
13620
  let reasoning = "";
@@ -13520,6 +13635,7 @@ function blocksToOpenAiMessages(blocks) {
13520
13635
  role: "tool",
13521
13636
  content: formatToolMessageContent({
13522
13637
  toolName: tc.function.name,
13638
+ workspaceRoot,
13523
13639
  content: res?.content ?? "",
13524
13640
  ...res?.metadata ? { metadata: res.metadata } : {}
13525
13641
  }),
@@ -13586,42 +13702,6 @@ var TOOL_METADATA_KEYS = [
13586
13702
  "pasteId",
13587
13703
  "source"
13588
13704
  ];
13589
- function trimHistoryToContextBudget(history, model, contextWindowOverride) {
13590
- if (history.length === 0) return { history, droppedCount: 0 };
13591
- const { rawMessageBudget } = planContextUsage({
13592
- contextWindow: contextWindowOverride ?? getModelContextWindow(model ?? ""),
13593
- summaryTokens: 0,
13594
- // localLoop 没有 web 端的负载分档器;medium 是中性默认值,
13595
- // 不为了省几个 token 在这里复制一份分类逻辑。
13596
- recentLoad: "medium"
13597
- });
13598
- const messageTokens = (message) => {
13599
- const toolCalls = message.tool_calls;
13600
- return estimateTokenCount(contentAsText(message.content)) + (Array.isArray(toolCalls) ? estimateTokenCount(JSON.stringify(toolCalls)) : 0);
13601
- };
13602
- let used = 0;
13603
- let start = history.length;
13604
- for (let i = history.length - 1; i >= 0; i -= 1) {
13605
- const cost = messageTokens(history[i]);
13606
- if (used + cost > rawMessageBudget && start < history.length) break;
13607
- used += cost;
13608
- start = i;
13609
- }
13610
- if (start === 0) return { history, droppedCount: 0 };
13611
- return {
13612
- history: sanitizeToolCallPairing(history.slice(start)),
13613
- droppedCount: start
13614
- };
13615
- }
13616
- function contentAsText(content) {
13617
- if (typeof content === "string") return content;
13618
- if (!Array.isArray(content)) return "";
13619
- return content.map((part) => {
13620
- if (part?.type === "text") return part.text;
13621
- if (part?.type === "image_url") return part.image_url.url;
13622
- return "";
13623
- }).join("\n");
13624
- }
13625
13705
  function contentCharCount(content) {
13626
13706
  if (typeof content === "string") return content.length;
13627
13707
  if (!Array.isArray(content)) return 0;
@@ -13655,6 +13735,7 @@ function projectToolContentForProvider(args2) {
13655
13735
  const rawContent = args2.content;
13656
13736
  const content = typeof rawContent === "string" ? sanitizeToolOutputText(rawContent) : rawContent;
13657
13737
  if (typeof content !== "string") return content;
13738
+ if (isSpilledToolOutput(content)) return content;
13658
13739
  const metadataText = compactToolMetadata(args2.metadata);
13659
13740
  const embeddedMetadataIndex = metadataText ? content.indexOf("\n\n[tool metadata]\n") : -1;
13660
13741
  const contentForProjection = embeddedMetadataIndex >= 0 ? content.slice(0, embeddedMetadataIndex) : content;
@@ -13686,7 +13767,7 @@ ${metadataText}` : "";
13686
13767
  content: contentForProjection,
13687
13768
  toolName: args2.toolName
13688
13769
  });
13689
- spillNote = `; spillFile=${spill.displayPath}; totalLines=${spill.totalLines}; hint=read full output via readFile`;
13770
+ spillNote = `; spillFile=${spill.displayPath}; totalLines=${spill.totalLines}; hint=read a range, not the whole spill (readFile lines=A-B or sed -n 'A,Bp'); a full read re-injects ${spill.totalChars} chars`;
13690
13771
  } catch {
13691
13772
  }
13692
13773
  }
@@ -13896,6 +13977,29 @@ ${args2.input}` : [
13896
13977
  } : {}
13897
13978
  };
13898
13979
  }
13980
+ function estimateLocalRequestInput(messages, toolSchemaTokens = 0) {
13981
+ return messages.reduce((sum2, message) => sum2 + getMessageTokenCount(message), 0) + toolSchemaTokens;
13982
+ }
13983
+ function evaluateLocalRequestBudget(args2) {
13984
+ const estimate = estimateLocalRequestInput(args2.messages, args2.descriptor?.toolSchemaTokens ?? 0);
13985
+ const ratio = Math.max(1, args2.calibrationRatio ?? 1);
13986
+ const output = args2.descriptor?.output ?? { semantics: "unknown", fallbackReserveTokens: 8192 };
13987
+ const boundedOutput = output.semantics === "unknown" ? { ...output, fallbackReserveTokens: Math.min(
13988
+ output.fallbackReserveTokens,
13989
+ Math.min(8192, Math.max(1, Math.floor(args2.contextWindow / 4)))
13990
+ ) } : output;
13991
+ return evaluateRequestBudget({
13992
+ contextWindow: args2.contextWindow,
13993
+ messageTokens: Math.ceil(estimate * ratio),
13994
+ toolSchemaTokens: 0,
13995
+ // already included in the calibrated full-input estimate
13996
+ protocolReserveTokens: 0,
13997
+ output: boundedOutput
13998
+ });
13999
+ }
14000
+ function updateLocalRequestCalibration(previous, actual, estimated) {
14001
+ return Number.isFinite(actual) && actual > 0 && Number.isFinite(estimated) && estimated > 0 ? Math.max(1, actual / estimated) : previous;
14002
+ }
13899
14003
 
13900
14004
  // packages/agent-runtime/toolArgsTruncationPolicy.ts
13901
14005
  import { createHash } from "node:crypto";
@@ -14736,12 +14840,13 @@ function detectExecShellSynchronousWarnings(command, shell) {
14736
14840
  }
14737
14841
 
14738
14842
  // packages/agent-runtime/capabilities/execShellCapability.ts
14843
+ var WINDOWS_SHELL_NOTE = process.platform === "win32" ? ` On Windows the runtime prefers pwsh (PowerShell 7+): it is resolved first (PATH, then the WindowsApps alias), and powershell.exe 5.1 is only a fallback when pwsh is absent. Read metadata.shellKind from the result \u2014 "pwsh" supports '&&'/'||' and $PSStyle, "powershell5" does not (join with ';' or split calls). Match the syntax to the kind you actually got; never assume the version.` : "";
14739
14844
  function buildExecShellToolDefinition(toolName = "execShell") {
14740
14845
  return {
14741
14846
  type: "function",
14742
14847
  function: {
14743
14848
  name: toolName,
14744
- description: `Execute a shell command from the workspace root. Prefer one compound command (e.g. 'git status && git diff --stat') to perform complete verification in one step instead of multiple small roundtrips. Do not cd into guessed paths; commands already run from the workspace root. Commands block until exit. Long-running commands (sleep over ${IMMEDIATE_DETACH_SLEEP_THRESHOLD_SECONDS}s, dev servers, watchers) automatically detach to background returning {detached: true, pid, label}; for persistent services, prefer launchProcess. On Windows the resolved shell may be Windows PowerShell 5.1 (metadata.shellKind="powershell5"): it does not support '&&'/'||' or $PSStyle \u2014 join commands with ';' or split into multiple calls. metadata.shellKind="pwsh" means PowerShell 7+ with full syntax. Read resolvedShell/shellKind from any execShell result before writing Windows-specific syntax. LIFECYCLE CONTRACT (misreading this contract silenced a real dialog for 10 hours): (1) A normal command waits synchronously for at most 120 seconds; if it ends inside that window the call IS finished \u2014 a result containing exitCode means the command has already completed, never "still running"; parse it immediately (no later event will remind you). (2) Only a result with metadata.detached === true AND a taskId represents a tracked background task that may trigger completion wake-up (terminal completion turn carrying a bounded result capsule); that handle produces a completion notification when finished; to read its output without waiting for the wake-up, read the result file for that taskId with readFile (a launchProcess taskId only yields a notice on your next real turn, never a new turn). Note that sleep commands exceeding the detach threshold will detach and trigger a completion wake-up upon exit \u2014 do not run standalone sleep commands purely to pause execution. (3) Text the command itself prints (LAUNCHED, STARTED, BACKGROUND, ...) is plain stdout with zero lifecycle meaning \u2014 never read it as a platform receipt. (4) Shell-level backgrounding (\`&\`, nohup, disown, setsid, self-daemonizing scripts, PowerShell Start-Process) is NOT tracked: those descendants produce no completion notification, and the outer shell finishing tells you nothing about them. Use background: true to turn a finite job into a tracked background task immediately. When a synchronous result's core output was redirected to a file, read that file in the SAME turn ("read it later" means it is lost) \u2014 never end the turn promising a later automatic report without a taskId.`,
14849
+ description: `Execute a shell command from the workspace root. Prefer one compound command (e.g. 'git status && git diff --stat') to perform complete verification in one step instead of multiple small roundtrips. Do not cd into guessed paths; commands already run from the workspace root. Commands block until exit. Long-running commands (sleep over ${IMMEDIATE_DETACH_SLEEP_THRESHOLD_SECONDS}s, dev servers, watchers) automatically detach to background returning {detached: true, pid, label}; for persistent services, prefer launchProcess.${WINDOWS_SHELL_NOTE} LIFECYCLE CONTRACT: (1) A normal command waits synchronously for at most 120 seconds; if it ends inside that window the call IS finished \u2014 a result carrying exitCode means the command has already completed: parse it immediately, never read it as "still running" (no later event will remind you). (2) Only a result with metadata.detached === true AND a taskId can deliver an automatic completion turn; that taskId is an opaque handle, NOT a file path and NOT a result file \u2014 never search for, guess or readFile a path from it, and never rerun the command just to obtain its output. That terminal turn delivers the result inline as a bounded capsule; when the capsule was truncated it also carries a real full-output path in its overflow marker \u2014 read that actual path with readFile only when it is present. While waiting for that terminal notification, continue independent work on other parts of the task. A launchProcess taskId is a tracked task too, but it only yields a notice on your next real turn. (3) Text the command itself prints (LAUNCHED, STARTED, ...) is plain stdout with zero lifecycle meaning \u2014 never read it as a platform receipt. (4) Shell-level backgrounding (&, nohup, disown, setsid, self-daemonizing scripts, PowerShell Start-Process) is NOT tracked: those descendants produce no completion notification, and the outer shell finishing tells you nothing about them. Use background: true to turn a finite job into a tracked background task. Do not run standalone sleep commands purely to pause execution. When a synchronous result's core output was redirected to a file, read that file in the SAME turn ("read it later" means it is lost) \u2014 never end the turn promising a later automatic report without a taskId.`,
14745
14850
  parameters: {
14746
14851
  type: "object",
14747
14852
  properties: {
@@ -14759,7 +14864,7 @@ function buildExecShellToolDefinition(toolName = "execShell") {
14759
14864
  },
14760
14865
  label: {
14761
14866
  type: "string",
14762
- description: "Optional human-readable label for the resulting background task, shown in the task list and completion notices. Defaults to the command's last token, which is unhelpful for pipelines (e.g. '| tail -25' yields '-25')."
14867
+ description: "Optional human-readable label for the resulting background task, shown in task lists and completion notices. Defaults to the last token."
14763
14868
  }
14764
14869
  }
14765
14870
  }
@@ -15317,6 +15422,52 @@ import { homedir } from "node:os";
15317
15422
  import { dirname as dirname2, relative as relative4, resolve as resolve4, sep as sep2 } from "node:path";
15318
15423
  import { spawn as spawnChildProcess2 } from "node:child_process";
15319
15424
 
15425
+ // packages/agent-runtime/runResultReadProjection.ts
15426
+ import { basename } from "node:path";
15427
+ function projectRunResultRead(path, content, raw = false) {
15428
+ const unchanged = { content, projected: false };
15429
+ if (raw || !basename(path).endsWith(".result.md") || !content.startsWith("---\n")) return unchanged;
15430
+ const end3 = content.indexOf("\n---\n", 4);
15431
+ if (end3 < 0) return unchanged;
15432
+ const header = content.slice(0, end3).split("\n");
15433
+ const runLine = header.find((line) => line.startsWith("runId: "));
15434
+ const index = header.findIndex((line) => line.startsWith("acceptance: "));
15435
+ if (!runLine || index < 0) return unchanged;
15436
+ try {
15437
+ const runId = JSON.parse(runLine.slice(7));
15438
+ if (typeof runId !== "string" || basename(path) !== `${runId}.result.md`) return unchanged;
15439
+ const encoded = JSON.parse(header[index].slice(12));
15440
+ if (typeof encoded !== "string") return unchanged;
15441
+ const acceptance = JSON.parse(encoded);
15442
+ if (!isRecord(acceptance) || acceptance.schemaVersion !== 1 || acceptance.source !== "local-runtime" || !isRecord(acceptance.checks) || !Array.isArray(acceptance.checks.observations)) return unchanged;
15443
+ const { observations, ...checks } = acceptance.checks;
15444
+ let exitZero = 0;
15445
+ let exitNonzero = 0;
15446
+ let exitUnknown = 0;
15447
+ for (const observation of observations) {
15448
+ const code = isRecord(observation) ? observation.exitCode : void 0;
15449
+ if (code === 0) exitZero++;
15450
+ else if (typeof code === "number" && Number.isInteger(code)) exitNonzero++;
15451
+ else exitUnknown++;
15452
+ }
15453
+ const projected = { ...acceptance, checks: { ...checks, observationSummary: {
15454
+ count: observations.length,
15455
+ exitZero,
15456
+ exitNonzero,
15457
+ exitUnknown,
15458
+ evidence: "#/acceptance/checks/observations",
15459
+ readOriginal: "readFile with raw:true (force:true if already read)",
15460
+ limitation: "Exit counts are observations, not version-bound test or review approval."
15461
+ } } };
15462
+ const line = `acceptance: ${JSON.stringify(JSON.stringify(projected))}`;
15463
+ if (line.length >= header[index].length) return unchanged;
15464
+ header[index] = line;
15465
+ return { content: header.join("\n") + content.slice(end3), projected: true };
15466
+ } catch {
15467
+ return unchanged;
15468
+ }
15469
+ }
15470
+
15320
15471
  // packages/core/readRangeLedger.ts
15321
15472
  function filterRetainedLedgerRecords(records, retainedCap) {
15322
15473
  return records.filter((record2) => record2.chars <= retainedCap);
@@ -15351,15 +15502,27 @@ function isLineRangeCovered(request3, covered) {
15351
15502
 
15352
15503
  // packages/agent-runtime/fileTextSearch.ts
15353
15504
  import { readdir, readFile as readFile3, stat as stat3 } from "node:fs/promises";
15354
- import { basename, relative as relative2, resolve as resolve2 } from "node:path";
15505
+ import { basename as basename2, relative as relative2, resolve as resolve2 } from "node:path";
15355
15506
  import { spawn as spawnChildProcess } from "node:child_process";
15356
15507
 
15357
15508
  // packages/agent-runtime/gitignore.ts
15358
15509
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
15359
15510
  import { resolve } from "node:path";
15511
+ function isIgnorableFsError(err) {
15512
+ if (err && typeof err === "object" && "code" in err) {
15513
+ const code = err.code;
15514
+ return code === "ENOENT" || code === "ENOTDIR";
15515
+ }
15516
+ return false;
15517
+ }
15360
15518
  async function readRootGitignorePatterns(workspaceRoot) {
15361
- const content = await readFile2(resolve(workspaceRoot, ".gitignore"), "utf8").catch(() => null);
15362
- if (content === null) return [];
15519
+ let content;
15520
+ try {
15521
+ content = await readFile2(resolve(workspaceRoot, ".gitignore"), "utf8");
15522
+ } catch (err) {
15523
+ if (isIgnorableFsError(err)) return [];
15524
+ throw err;
15525
+ }
15363
15526
  return content.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#") && !line.startsWith("!")).flatMap((line) => {
15364
15527
  const unanchored = line.replace(/^\//, "");
15365
15528
  if (unanchored.endsWith("/")) return [`${unanchored}**`];
@@ -15371,14 +15534,15 @@ async function hasRootGitignore(workspaceRoot) {
15371
15534
  try {
15372
15535
  await stat2(resolve(workspaceRoot, ".gitignore"));
15373
15536
  return true;
15374
- } catch {
15375
- return false;
15537
+ } catch (err) {
15538
+ if (isIgnorableFsError(err)) return false;
15539
+ throw err;
15376
15540
  }
15377
15541
  }
15378
15542
 
15379
15543
  // packages/agent-runtime/fileTextSearch.ts
15380
15544
  var normalizePath = (value) => value.replaceAll("\\", "/");
15381
- var pathFor = (root, file, absolute = false) => absolute ? normalizePath(file) : normalizePath(relative2(root, file) || basename(file));
15545
+ var pathFor = (root, file, absolute = false) => absolute ? normalizePath(file) : normalizePath(relative2(root, file) || basename2(file));
15382
15546
  var COMMAND_LIMIT_HEADROOM = 1;
15383
15547
  async function runCommand(binary, args2, cwd, maxResults) {
15384
15548
  const recordLimit = maxResults === void 0 ? 0 : Math.max(0, maxResults) + COMMAND_LIMIT_HEADROOM;
@@ -15404,6 +15568,17 @@ async function runCommand(binary, args2, cwd, maxResults) {
15404
15568
  }
15405
15569
  });
15406
15570
  }
15571
+ function extractGrepExcludeDir(pattern) {
15572
+ const p = pattern.replaceAll("\\", "/");
15573
+ if (!p) return null;
15574
+ if (!/\/(\*{1,2})?$/.test(p)) return null;
15575
+ const clean = p.replace(/\/(\*{1,2})?$/, "");
15576
+ if (!clean || clean.includes("/") || /[*?{}[\]]/.test(clean)) return null;
15577
+ return clean;
15578
+ }
15579
+ function isGrepExpressibleExclude(pattern) {
15580
+ return extractGrepExcludeDir(pattern) !== null;
15581
+ }
15407
15582
  function commandArgs(o, binary, target) {
15408
15583
  const args2 = binary === "rg" ? ["--line-number", "--no-heading", "--color", "never", "--null"] : ["-RIn", "--binary-files=without-match", "--null"];
15409
15584
  if (binary === "rg") args2.push("--no-require-git");
@@ -15416,8 +15591,8 @@ function commandArgs(o, binary, target) {
15416
15591
  if (o.include) args2.push("--glob", o.include);
15417
15592
  } else {
15418
15593
  for (const x of o.exclude ?? []) {
15419
- const clean = x.replace(/\/\*\*$/, "");
15420
- if (clean && !clean.includes("/")) args2.push("--exclude-dir", clean);
15594
+ const clean = extractGrepExcludeDir(x);
15595
+ if (clean) args2.push("--exclude-dir", clean);
15421
15596
  }
15422
15597
  if (o.include) args2.push("--include", o.include);
15423
15598
  }
@@ -15465,7 +15640,7 @@ function globMatch(pattern, value) {
15465
15640
  else source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
15466
15641
  }
15467
15642
  const r = new RegExp(`^${source}$`);
15468
- return r.test(value) || r.test(basename(value));
15643
+ return r.test(value) || r.test(basename2(value));
15469
15644
  }
15470
15645
  var defaultReadTextFile = (filePath) => readFile3(filePath, "utf8").catch(() => "");
15471
15646
  async function jsSearch(o, targetPath) {
@@ -15513,6 +15688,23 @@ async function jsSearch(o, targetPath) {
15513
15688
  }
15514
15689
  return { matches: out, totalMatches: out.length, truncated: false, engine: "js" };
15515
15690
  }
15691
+ async function canGrepFulfillOptions(o) {
15692
+ if (!o.includeIgnored) {
15693
+ const gitignorePatterns = await readRootGitignorePatterns(o.root);
15694
+ if (gitignorePatterns.length > 0) return false;
15695
+ }
15696
+ if (o.include) {
15697
+ if (o.include.includes("/") || o.include.includes("\\") || o.include.includes("**") || /[{}[\]]/.test(o.include)) {
15698
+ return false;
15699
+ }
15700
+ }
15701
+ if (o.exclude && o.exclude.length > 0) {
15702
+ for (const pattern of o.exclude) {
15703
+ if (!isGrepExpressibleExclude(pattern)) return false;
15704
+ }
15705
+ }
15706
+ return true;
15707
+ }
15516
15708
  var COMMAND_ENGINES = [
15517
15709
  { engine: "ripgrep", binaryOption: "resolveRipgrepBinary", binaryName: "rg", argsKey: "rg" },
15518
15710
  { engine: "grep", binaryOption: "resolveGrepBinary", binaryName: "grep", argsKey: "grep" }
@@ -15524,6 +15716,7 @@ async function searchFileTextMatches(o) {
15524
15716
  if (targetStat.isFile()) return jsSearch(o, targetPath);
15525
15717
  const run2 = o.runCommand ?? runCommand, max4 = o.maxResults;
15526
15718
  for (const entry of COMMAND_ENGINES) {
15719
+ if (entry.engine === "grep" && !await canGrepFulfillOptions(o)) continue;
15527
15720
  const injectedResolver = o[entry.binaryOption];
15528
15721
  const binary = injectedResolver ? injectedResolver() : resolveExecutableOnPath(entry.binaryName);
15529
15722
  if (!binary) continue;
@@ -15708,13 +15901,15 @@ function runTaskLogs(args2) {
15708
15901
  const allEvents = registry.getTaskEvents(taskId, 0);
15709
15902
  const terminal = lastTerminalEvent(allEvents);
15710
15903
  const status = terminal ? reportedTaskStatus(terminal.type, terminal.exitCode) : record2 ? statusOf(record2) : "running";
15904
+ const hint = events.length === 0 && !isProcessTaskTerminalStatus(status) ? `no new events since cursor ${cursor}; the task is still running and there is nothing more to read right now. Don't re-read the same cursor immediately: later events are returned once they exist. Where the host reports completions, wait for that signal; otherwise use taskWait with an explicit budget.` : void 0;
15711
15905
  return {
15712
15906
  outcome: "ok",
15713
15907
  taskId,
15714
15908
  cursor: registry.latestTaskSeq(taskId),
15715
15909
  events,
15716
15910
  status,
15717
- terminal: isProcessTaskTerminalStatus(status)
15911
+ terminal: isProcessTaskTerminalStatus(status),
15912
+ ...hint ? { hint } : {}
15718
15913
  };
15719
15914
  }
15720
15915
  function formatTaskLogsContent(result4, options) {
@@ -15865,7 +16060,7 @@ function buildReadWorkspaceParameters() {
15865
16060
  const path = buildWorkspacePathProperty();
15866
16061
  const lines = {
15867
16062
  type: "string",
15868
- description: 'Line slice: "40-120" (range, 1-based, inclusive), "120-" (from line to end), "-50" (tail N lines), "50" (head N lines). Omit to read full file.'
16063
+ description: 'Line slice: "40-120" (range, 1-based, inclusive), "120-" (from line to end), "-50" (tail N lines), "50" (head N lines). Omit to read from the start; large results return a bounded window. Continue from metadata endLine + 1.'
15869
16064
  };
15870
16065
  const force = {
15871
16066
  type: "boolean",
@@ -15876,7 +16071,11 @@ function buildReadWorkspaceParameters() {
15876
16071
  properties: {
15877
16072
  path,
15878
16073
  lines,
15879
- force
16074
+ force,
16075
+ raw: {
16076
+ type: "boolean",
16077
+ description: "Read original bytes including full runtime acceptance observations in *.result.md. Default compacts only machine observations; report text and physical line numbers are unchanged."
16078
+ }
15880
16079
  },
15881
16080
  required: ["path"]
15882
16081
  };
@@ -16201,7 +16400,7 @@ function filterDeclaredWorkspaceToolNames(args2) {
16201
16400
  // packages/agent-runtime/workspacePathGuard.ts
16202
16401
  import { constants as fsConstants } from "node:fs";
16203
16402
  import { lstat, mkdir, open, readlink, realpath as realpath2 } from "node:fs/promises";
16204
- import { basename as basename2, dirname, isAbsolute as isAbsolute2, join as join2, relative as relative3, resolve as resolve3, sep } from "node:path";
16403
+ import { basename as basename3, dirname, isAbsolute as isAbsolute2, join as join2, relative as relative3, resolve as resolve3, sep } from "node:path";
16205
16404
  function isPathInsideRoot(root, targetPath) {
16206
16405
  const rel = relative3(resolve3(root), resolve3(targetPath));
16207
16406
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute2(rel);
@@ -16224,7 +16423,7 @@ async function realpathAllowMissing(targetPath) {
16224
16423
  if (!isNotFoundError(error)) return null;
16225
16424
  const parent = dirname(current);
16226
16425
  if (parent === current) return null;
16227
- tail.push(basename2(current));
16426
+ tail.push(basename3(current));
16228
16427
  current = parent;
16229
16428
  }
16230
16429
  }
@@ -16418,7 +16617,7 @@ async function createMissingDirectoryChain(guard) {
16418
16617
  }
16419
16618
  try {
16420
16619
  for (const target of missing.slice().reverse()) {
16421
- const name = basename2(target);
16620
+ const name = basename3(target);
16422
16621
  if (!name || name === "." || name === "..") {
16423
16622
  throw workspacePathGuardError({
16424
16623
  ok: false,
@@ -16650,7 +16849,6 @@ function readExpectedReplacementCount(args2) {
16650
16849
  }
16651
16850
  return value;
16652
16851
  }
16653
- var READ_FILE_SLICE_FALLBACK_LINES = 200;
16654
16852
  function isAbsentArg(value) {
16655
16853
  return value === void 0 || value === null;
16656
16854
  }
@@ -16662,6 +16860,9 @@ function describeRejectedArgValue(value) {
16662
16860
  if (Array.isArray(value)) return "an array";
16663
16861
  return `a value of type ${typeof value}`;
16664
16862
  }
16863
+ function clipMarkerValue(text2, max4 = 60) {
16864
+ return text2.length <= max4 ? text2 : `${text2.slice(0, max4)}\u2026(${text2.length} chars)`;
16865
+ }
16665
16866
  function readIntegerArg(args2) {
16666
16867
  if (isAbsentArg(args2.value)) return {};
16667
16868
  const min4 = args2.min ?? 1;
@@ -16719,17 +16920,9 @@ function parseLinesArg(value) {
16719
16920
  return { slice: { startLine, endLine } };
16720
16921
  }
16721
16922
  function readFileSliceArgs(args2) {
16722
- const warnings = [];
16723
- const withFallback = (slice2) => {
16724
- warnings.push(
16725
- `No usable line range remained; returned the first ${READ_FILE_SLICE_FALLBACK_LINES} lines instead of the whole file.`
16726
- );
16727
- return { ...slice2, maxLines: READ_FILE_SLICE_FALLBACK_LINES, warnings };
16728
- };
16729
- if (isAbsentArg(args2.lines)) return { warnings };
16923
+ if (isAbsentArg(args2.lines) || args2.lines === "") return {};
16730
16924
  const { slice, warning } = parseLinesArg(args2.lines);
16731
- if (warning) warnings.push(warning);
16732
- return slice ? { ...slice, warnings } : withFallback({});
16925
+ return slice ? { slice } : { error: clipMarkerValue(warning ?? "Invalid line range", 240) };
16733
16926
  }
16734
16927
  function buildReadFileSliceHint(totalLines) {
16735
16928
  return `File has ${totalLines} lines. Use lines: ${LINES_ARG_SYNTAX}, or omit it for the whole file.`;
@@ -16998,7 +17191,15 @@ var READ_FILE_LEDGER_MAX_KEYS = 256;
16998
17191
  async function readFileTool(args2) {
16999
17192
  const parsed = parseWorkspaceToolArguments(args2.call.arguments);
17000
17193
  const requestedPath = requireWorkspaceToolPath(parsed);
17001
- const { warnings, ...sliceArgs } = readFileSliceArgs(parsed);
17194
+ const parsedSlice = readFileSliceArgs(parsed);
17195
+ if (parsedSlice.error) {
17196
+ return {
17197
+ content: `[readFile] Invalid lines: ${parsedSlice.error} No file content was read. Use lines: ${LINES_ARG_SYNTAX}, or omit lines.`,
17198
+ metadata: { status: "invalid-arguments", tool: "readFile" }
17199
+ };
17200
+ }
17201
+ const sliceArgs = parsedSlice.slice ?? {};
17202
+ const warnings = [];
17002
17203
  const approval = await resolveLocalWorkspaceToolApproval({
17003
17204
  workspaceRoot: args2.workspaceRoot,
17004
17205
  requestedPath,
@@ -17006,42 +17207,97 @@ async function readFileTool(args2) {
17006
17207
  ...args2.confirmExternalFileAccess ? { confirmExternalFileAccess: args2.confirmExternalFileAccess } : {}
17007
17208
  });
17008
17209
  const absolutePath = approval.path;
17009
- const content = await readGuardApprovedFile(approval);
17210
+ const originalContent = await readGuardApprovedFile(approval);
17211
+ const projection = projectRunResultRead(absolutePath, originalContent, parsed.raw === true);
17212
+ const content = projection.content;
17010
17213
  const activity = extractActivity(parsed);
17011
17214
  const sliced = sliceReadFileContent({
17012
17215
  content,
17013
17216
  ...sliceArgs
17014
17217
  });
17015
- const truncatedRead = defensivelyTruncateReadFile({
17016
- content: sliced.content,
17017
- totalLines: sliced.totalLines
17018
- });
17019
- const isTruncated = sliced.truncated || truncatedRead.truncatedByCharLimit;
17020
17218
  const relativePath = normalizeWorkspaceRelativePath({
17021
17219
  workspaceRoot: resolve4(args2.workspaceRoot),
17022
17220
  targetPath: absolutePath
17023
17221
  });
17222
+ const cap = resolveHistoricalToolContentCap("readFile", 0);
17223
+ const selectedLines = splitTextLines(sliced.content);
17224
+ const makeMetadata = (body, endLine, windowed2, partialLine) => ({
17225
+ path: relativePath,
17226
+ bytes: Buffer.byteLength(body),
17227
+ totalBytes: Buffer.byteLength(originalContent),
17228
+ ...projection.projected ? {
17229
+ projection: "run-result-observations",
17230
+ projectedTotalBytes: Buffer.byteLength(content),
17231
+ rawReadHint: "readFile raw:true reads original evidence; line numbers are unchanged."
17232
+ } : {},
17233
+ startLine: sliced.startLine,
17234
+ ...partialLine ? { partialLine: true } : { endLine },
17235
+ totalLines: sliced.totalLines,
17236
+ truncated: sliced.truncated || windowed2,
17237
+ ...windowed2 ? { truncatedByByteLimit: true, truncatedByCharLimit: true } : {},
17238
+ ...sliceArgs.maxLines ? { maxLines: sliceArgs.maxLines } : {},
17239
+ ...sliceArgs.tailLines ? { tailLines: sliceArgs.tailLines } : {},
17240
+ ...activity ? { activity } : {}
17241
+ });
17242
+ const fits = (body, endLine, windowed2) => {
17243
+ if (Buffer.byteLength(body) > TOOL_OUTPUT_SPILL_BYTES || countLines(body) > TOOL_OUTPUT_SPILL_LINES) return false;
17244
+ const metadata2 = makeMetadata(body, endLine, windowed2, false);
17245
+ return formatToolMessageContent({ toolName: "readFile", content: body, metadata: metadata2 }).length <= cap;
17246
+ };
17247
+ let deliveredCount = selectedLines.length;
17248
+ let finalContent = sliced.content;
17249
+ let windowed = false;
17250
+ if (!fits(finalContent, sliced.endLine, false)) {
17251
+ let low = 0;
17252
+ let high = selectedLines.length;
17253
+ while (low < high) {
17254
+ const mid = Math.ceil((low + high) / 2);
17255
+ const candidate = selectedLines.slice(0, mid).join("\n");
17256
+ if (fits(candidate, sliced.startLine + mid - 1, true)) low = mid;
17257
+ else high = mid - 1;
17258
+ }
17259
+ deliveredCount = low;
17260
+ windowed = true;
17261
+ finalContent = selectedLines.slice(0, deliveredCount).join("\n");
17262
+ }
17263
+ const oversizedLine = windowed && deliveredCount === 0;
17264
+ if (oversizedLine) {
17265
+ let low = 0;
17266
+ let high = Math.min(sliced.content.length, cap);
17267
+ while (low < high) {
17268
+ const mid = Math.ceil((low + high) / 2);
17269
+ const candidate = defensivelyTruncateReadFile({ content: sliced.content, totalLines: sliced.totalLines, limit: mid }).content;
17270
+ const metadata2 = makeMetadata(candidate, sliced.startLine, true, true);
17271
+ const fitsPreview = Buffer.byteLength(candidate) <= TOOL_OUTPUT_SPILL_BYTES && countLines(candidate) <= TOOL_OUTPUT_SPILL_LINES && formatToolMessageContent({ toolName: "readFile", content: candidate, metadata: metadata2 }).length <= cap;
17272
+ if (fitsPreview) low = mid;
17273
+ else high = mid - 1;
17274
+ }
17275
+ finalContent = low > 0 ? defensivelyTruncateReadFile({ content: sliced.content, totalLines: sliced.totalLines, limit: low }).content : "[readFile] Line exceeds the delivery budget; use codeSearch or another tool to inspect it.";
17276
+ }
17277
+ const deliveredEndLine = windowed && !oversizedLine ? sliced.startLine + deliveredCount - 1 : sliced.endLine;
17278
+ const metadata = makeMetadata(finalContent, deliveredEndLine, windowed, oversizedLine);
17024
17279
  const force = parsed.force === true;
17025
17280
  const ledger = args2.readLedger;
17026
- const requestRange = { startLine: sliced.startLine, endLine: sliced.endLine };
17027
- const fingerprint = createHash3("sha1").update(content).digest("hex").slice(0, 20);
17281
+ const deliveredRange = { startLine: sliced.startLine, endLine: deliveredEndLine };
17282
+ const fingerprint = createHash3("sha1").update(originalContent).update(parsed.raw === true ? "\0raw" : "\0default").digest("hex").slice(0, 20);
17028
17283
  let entry = ledger?.get(relativePath);
17029
17284
  if (entry && entry.fingerprint !== fingerprint) {
17030
17285
  entry = void 0;
17031
17286
  ledger?.delete(relativePath);
17032
17287
  }
17033
- if (!force && entry && ledger) {
17288
+ if (!force && entry && ledger && !oversizedLine) {
17034
17289
  const retainedCap = resolveHistoricalToolContentCap("readFile", 0);
17035
17290
  const retained = filterRetainedLedgerRecords(entry.records, retainedCap);
17036
- if (retained.length > 0 && isLineRangeCovered(requestRange, retained)) {
17291
+ if (retained.length > 0 && isLineRangeCovered(deliveredRange, retained)) {
17037
17292
  ledger.delete(relativePath);
17038
17293
  ledger.set(relativePath, entry);
17039
17294
  return {
17040
- content: `[readFile] ${relativePath} lines ${requestRange.startLine}-${requestRange.endLine} were already delivered earlier and the file is unchanged; not resending. Pass force:true to refetch.`,
17295
+ content: `[readFile] ${relativePath} lines ${deliveredRange.startLine}-${deliveredRange.endLine} were already delivered earlier and the file is unchanged; not resending. Pass force:true to refetch.` + (windowed ? ` Continue with lines=${deliveredEndLine + 1}-.` : ""),
17041
17296
  metadata: {
17042
17297
  path: relativePath,
17043
- startLine: requestRange.startLine,
17044
- endLine: requestRange.endLine,
17298
+ startLine: deliveredRange.startLine,
17299
+ endLine: deliveredRange.endLine,
17300
+ ...windowed ? { truncated: true } : {},
17045
17301
  totalLines: sliced.totalLines,
17046
17302
  deduped: true,
17047
17303
  ...warnings.length ? { warnings: [...warnings, buildReadFileSliceHint(sliced.totalLines)] } : {},
@@ -17050,24 +17306,10 @@ async function readFileTool(args2) {
17050
17306
  };
17051
17307
  }
17052
17308
  }
17053
- const metadata = {
17054
- path: relativePath,
17055
- bytes: Buffer.byteLength(truncatedRead.content),
17056
- totalBytes: Buffer.byteLength(content),
17057
- startLine: sliced.startLine,
17058
- endLine: sliced.endLine,
17059
- totalLines: sliced.totalLines,
17060
- truncated: isTruncated,
17061
- ...truncatedRead.truncatedByCharLimit ? { truncatedByByteLimit: true, truncatedByCharLimit: true } : {},
17062
- ...sliceArgs.maxLines ? { maxLines: sliceArgs.maxLines } : {},
17063
- ...sliceArgs.tailLines ? { tailLines: sliceArgs.tailLines } : {},
17064
- ...warnings.length ? { warnings: [...warnings, buildReadFileSliceHint(sliced.totalLines)] } : {},
17065
- ...activity ? { activity } : {}
17066
- };
17067
- if (!isTruncated && ledger) {
17068
- const persistedChars = truncatedRead.content.length + "\n\n[tool metadata]\n".length + JSON.stringify(metadata).length;
17309
+ if (!oversizedLine && ledger) {
17310
+ const persistedChars = formatToolMessageContent({ toolName: "readFile", content: finalContent, metadata }).length;
17069
17311
  const records = entry?.records ?? [];
17070
- records.push({ ...requestRange, chars: persistedChars });
17312
+ records.push({ ...deliveredRange, chars: persistedChars });
17071
17313
  ledger.delete(relativePath);
17072
17314
  ledger.set(relativePath, {
17073
17315
  fingerprint,
@@ -17079,7 +17321,7 @@ async function readFileTool(args2) {
17079
17321
  ledger.delete(oldestKey);
17080
17322
  }
17081
17323
  }
17082
- return { content: truncatedRead.content, metadata };
17324
+ return { content: finalContent, metadata };
17083
17325
  }
17084
17326
  async function ensureGuardedParentDirectory(args2) {
17085
17327
  const directoryGuard = await resolveWorkspaceSafePath({
@@ -17978,7 +18220,8 @@ function createLocalWorkspaceToolExecutors(args2) {
17978
18220
  if (!Array.isArray(paths) || paths.length === 0 || paths.some((path) => typeof path !== "string" || !path.trim())) {
17979
18221
  throw new Error("read_image: paths must contain 1 to 4 non-empty string paths (maximum 4 images)");
17980
18222
  }
17981
- const results2 = await Promise.all(paths.map(async (path) => {
18223
+ const imagePaths = paths.filter((path) => typeof path === "string");
18224
+ const results2 = await Promise.all(imagePaths.map(async (path) => {
17982
18225
  try {
17983
18226
  const absolutePath = await resolveLocalWorkspaceToolPath({
17984
18227
  workspaceRoot: args2.workspaceRoot,
@@ -18225,6 +18468,13 @@ function getAgentRuntimeToolParametersIndex() {
18225
18468
  }
18226
18469
 
18227
18470
  // packages/agent-runtime/localToolPolicy.ts
18471
+ var shellLifecycles = /* @__PURE__ */ new WeakMap();
18472
+ function registerLocalShellLifecycle(executor, lifecycle) {
18473
+ shellLifecycles.set(executor, lifecycle);
18474
+ }
18475
+ function getLocalShellLifecycle(executor) {
18476
+ return executor ? shellLifecycles.get(executor) : void 0;
18477
+ }
18228
18478
  var NEVER_LOCAL_TOOLS = /* @__PURE__ */ new Set([
18229
18479
  "deleteSpaces",
18230
18480
  "updateAgent",
@@ -18338,12 +18588,13 @@ async function runExecShellGates(args2) {
18338
18588
  return { kind: "pass", opts };
18339
18589
  }
18340
18590
  if (args2.execShellApproval) {
18341
- const result4 = await invokeCapability("execShell", args2.callArguments, {
18591
+ const execute = () => invokeCapability("execShell", args2.callArguments, {
18342
18592
  ...opts,
18343
18593
  workspaceRoot: args2.workspaceRoot,
18344
18594
  commandOutputLimit: args2.commandOutputLimit,
18345
18595
  execShellApproval: args2.execShellApproval
18346
18596
  });
18597
+ const result4 = await (args2.shellLifecycle ? args2.shellLifecycle(execute, args2.abortSignal) : execute());
18347
18598
  return { kind: "handled", result: result4 };
18348
18599
  }
18349
18600
  let parsedInput = args2.callArguments;
@@ -18387,6 +18638,7 @@ async function executeLocalToolWithPolicy(args2) {
18387
18638
  const gate = await runExecShellGates({
18388
18639
  toolName: decision.toolName,
18389
18640
  callArguments: args2.call.arguments,
18641
+ shellLifecycle: getLocalShellLifecycle(executor),
18390
18642
  execShellApproval: args2.execShellApproval,
18391
18643
  workspaceRoot: args2.workspaceRoot,
18392
18644
  commandOutputLimit: args2.commandOutputLimit,
@@ -18407,7 +18659,41 @@ async function executeLocalToolWithPolicy(args2) {
18407
18659
  );
18408
18660
  }
18409
18661
 
18662
+ // packages/agent-runtime/credentialSinkPolicy.ts
18663
+ var CREDENTIAL_REF_ALLOWED_SINKS = /* @__PURE__ */ new Set();
18664
+ function classifyCredentialRefSink(toolName, allowlist = CREDENTIAL_REF_ALLOWED_SINKS) {
18665
+ if (isCommandExecutingTool(toolName)) return "command";
18666
+ if (allowlist.has(toolName)) return "allow";
18667
+ return "confirm";
18668
+ }
18669
+ function buildCredentialSinkPermissionRequest(toolName) {
18670
+ return {
18671
+ id: `permission-credential-sink-${toolName}`,
18672
+ tool: toolName,
18673
+ action: "credential_unwrap_tool_use",
18674
+ title: "\u786E\u8BA4\u5728\u5DE5\u5177\u53C2\u6570\u4E2D\u4F7F\u7528\u51ED\u636E",
18675
+ body: `\u8BE5\u5DE5\u5177\uFF08${toolName}\uFF09\u7684\u53C2\u6570\u8981\u643A\u5E26\u51ED\u636E\uFF0C\u786E\u8BA4\u540E\u4EC5\u672C\u6B21\u8C03\u7528\u89E3\u5305\uFF1B\u660E\u6587\u4E0D\u4F1A\u5199\u5165\u5386\u53F2\u6216\u8BB0\u5F55\u3002`,
18676
+ suggestedRule: {
18677
+ scope: "once",
18678
+ pattern: { capability: "credential_use", target: "tool_arguments" }
18679
+ }
18680
+ };
18681
+ }
18682
+
18410
18683
  // packages/agent-runtime/toolCallTransaction.ts
18684
+ function buildCredentialSinkRefusal(toolName, gateId) {
18685
+ return {
18686
+ content: `\u9700\u8981\u7528\u6237\u786E\u8BA4\u624D\u80FD\u628A\u51ED\u636E\u7528\u4E8E ${toolName}\u3002\u53EF\u6539\u8D70\u53D7\u63A7\u901A\u9053\uFF1Anolo secret run --with <name> -- <cmd>\u3002`,
18687
+ metadata: {
18688
+ cancelled: true,
18689
+ actionGateResult: {
18690
+ status: "cancelled",
18691
+ ...gateId ? { gateId } : {}
18692
+ }
18693
+ }
18694
+ };
18695
+ }
18696
+ var credentialGateQueues = /* @__PURE__ */ new WeakMap();
18411
18697
  var LOCAL_TURN_ABORTED_CODE = "LOCAL_TURN_ABORTED";
18412
18698
  function buildAbortedError() {
18413
18699
  const error = new Error("local agent turn aborted by user");
@@ -18656,32 +18942,72 @@ async function executeToolCall(args2) {
18656
18942
  const rawArguments = toolCall.function.arguments;
18657
18943
  let unwrappedArguments = rawArguments;
18658
18944
  if (typeof rawArguments === "string" && rawArguments.includes("$nolo_cred:") && input.adapter.credentialBroker) {
18659
- if (isCommandExecutingTool(toolName)) {
18945
+ const sink = classifyCredentialRefSink(toolName);
18946
+ if (sink === "command") {
18660
18947
  throw new Error(
18661
18948
  `[security] \u62D2\u7EDD\u5728 ${toolName} \u547D\u4EE4\u884C\u4E2D\u76F4\u63A5\u89E3\u5305\u51ED\u8BC1\u5F15\u7528 ($nolo_cred:)\uFF0C\u4EE5\u9632\u5FA1\u63D0\u793A\u8BCD\u6CE8\u5165\u5916\u6CC4\u98CE\u9669\u3002\u8BF7\u4F7F\u7528\u53D7\u63A7\u8BA4\u8BC1\u901A\u9053\u3002`
18662
18949
  );
18663
18950
  }
18664
- unwrappedArguments = await unwrapToolArguments(rawArguments, input.adapter.credentialBroker);
18665
- }
18666
- const executePromise = input.adapter.executeTool({
18667
- id: toolCall.id,
18668
- name: toolName,
18669
- arguments: unwrappedArguments,
18670
- ...userInputText ? { userInput: userInputText } : {},
18671
- ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {},
18672
- ...args2.runToolNames ? { runToolNames: args2.runToolNames } : {},
18673
- ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
18674
- // 定档信号:来源只由 turn 输入推导,不让模型/参数层参与。
18675
- // 三级判据见 plan §10——后台运行优先于子 run(后台派发的子 run 仍是
18676
- // 无人值守的,按 automation 报更保守)。
18677
- origin: input.background ? "automation" : input.runKind === "subtask" ? "agent" : "chat"
18678
- }, {
18679
- ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
18680
- ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {}
18681
- });
18682
- const execStartedAtMs = Date.now();
18683
- toolResult = await runAbortableToolTask(input, executePromise, toolName);
18684
- toolExecMs = Date.now() - execStartedAtMs;
18951
+ if (sink === "confirm") {
18952
+ if (input.onActionGate) {
18953
+ const permissionRequest = buildCredentialSinkPermissionRequest(toolName);
18954
+ const gate = {
18955
+ ...permissionRequest,
18956
+ // [M1] id 带上 toolCall.id,避免同一轮同一工具两次请求 id 碰撞(对齐既有 ask 分支约定)。
18957
+ id: `${permissionRequest.id}-${toolCall.id}`,
18958
+ kind: "confirm",
18959
+ toolName,
18960
+ toolCallId: toolCall.id
18961
+ };
18962
+ const onActionGate = input.onActionGate;
18963
+ const prev = credentialGateQueues.get(input) ?? Promise.resolve();
18964
+ const next = prev.catch(() => void 0).then(
18965
+ () => runAbortableToolTask(
18966
+ input,
18967
+ onActionGate(gate),
18968
+ `${toolName} credential confirmation`
18969
+ )
18970
+ );
18971
+ credentialGateQueues.set(input, next);
18972
+ const replacement = await next.finally(() => {
18973
+ if (credentialGateQueues.get(input) === next) {
18974
+ credentialGateQueues.delete(input);
18975
+ }
18976
+ });
18977
+ if (replacement !== void 0 && isCompletedActionGateResult(replacement?.metadata?.actionGateResult)) {
18978
+ unwrappedArguments = await unwrapToolArguments(rawArguments, input.adapter.credentialBroker);
18979
+ } else {
18980
+ toolResult = buildCredentialSinkRefusal(toolName, gate.id);
18981
+ }
18982
+ } else {
18983
+ toolResult = buildCredentialSinkRefusal(toolName);
18984
+ }
18985
+ }
18986
+ if (sink === "allow") {
18987
+ unwrappedArguments = await unwrapToolArguments(rawArguments, input.adapter.credentialBroker);
18988
+ }
18989
+ }
18990
+ if (!toolResult) {
18991
+ const executePromise = input.adapter.executeTool({
18992
+ id: toolCall.id,
18993
+ name: toolName,
18994
+ arguments: unwrappedArguments,
18995
+ ...userInputText ? { userInput: userInputText } : {},
18996
+ ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {},
18997
+ ...args2.runToolNames ? { runToolNames: args2.runToolNames } : {},
18998
+ ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
18999
+ // 定档信号:来源只由 turn 输入推导,不让模型/参数层参与。
19000
+ // 三级判据见 plan §10——后台运行优先于子 run(后台派发的子 run 仍是
19001
+ // 无人值守的,按 automation 报更保守)。
19002
+ origin: input.background ? "automation" : input.runKind === "subtask" ? "agent" : "chat"
19003
+ }, {
19004
+ ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
19005
+ ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {}
19006
+ });
19007
+ const execStartedAtMs = Date.now();
19008
+ toolResult = await runAbortableToolTask(input, executePromise, toolName);
19009
+ toolExecMs = Date.now() - execStartedAtMs;
19010
+ }
18685
19011
  }
18686
19012
  if (tailDropNotice) {
18687
19013
  toolResult = {
@@ -18696,6 +19022,15 @@ ${toolResult.content}` : toolResult.content,
18696
19022
  toolCallId: toolCall.id,
18697
19023
  metadata: toolResult.metadata
18698
19024
  });
19025
+ if (actionGate && !input.onActionGate && actionGate.kind === "input") {
19026
+ toolResult = {
19027
+ content: "\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u6CA1\u6709\u4EA4\u4E92\u8F93\u5165\u9762\u677F\uFF0C\u65E0\u6CD5\u5F39\u51FA\u51ED\u636E\u586B\u5199\u754C\u9762\uFF0C\u8BE5\u8BF7\u6C42\u5DF2\u88AB\u53D6\u6D88\u3002\u8BF7\u8BA9\u7528\u6237\u5728\u684C\u9762\u7AEF\u6216 Web \u7AEF\u754C\u9762\u63D0\u4F9B\u51ED\u636E\uFF0C\u6216\u76F4\u63A5\u5728\u5BF9\u8BDD\u4E2D\u53D1\u9001\u51ED\u636E\u5185\u5BB9\uFF1B\u51ED\u636E\u4FDD\u5B58\u540E\u7528 nolo secret run --with <NAME> -- <cmd> \u6D88\u8D39\u3002",
19028
+ metadata: {
19029
+ cancelled: true,
19030
+ actionGateResult: { gateId: actionGate.id, status: "cancelled" }
19031
+ }
19032
+ };
19033
+ }
18699
19034
  if (actionGate && input.onActionGate) {
18700
19035
  const replacement = await runAbortableToolTask(input, input.onActionGate(actionGate), `${toolName} action gate`);
18701
19036
  if (replacement) {
@@ -18789,10 +19124,15 @@ function applyPersistedTurnInput(messages, persistedInput, persistedInputReferen
18789
19124
  }
18790
19125
  function createTurnTranscript(args2) {
18791
19126
  let working = args2.initialWorking;
18792
- const raw = args2.initialWorking.slice(
19127
+ let raw = args2.initialWorking.slice(
18793
19128
  args2.prefixCount + args2.historyCount
18794
19129
  );
18795
19130
  const cap = args2.capToolMessage ?? ((msg) => msg);
19131
+ function retract(callback4) {
19132
+ const predicate = callback4;
19133
+ working = working.filter((msg) => !predicate(msg));
19134
+ raw = raw.filter((msg) => !predicate(msg));
19135
+ }
18796
19136
  return {
18797
19137
  working: () => working,
18798
19138
  replaceWorkingHistory: (nextWorkingView) => {
@@ -18811,7 +19151,13 @@ function createTurnTranscript(args2) {
18811
19151
  raw.pop();
18812
19152
  return working.pop();
18813
19153
  },
18814
- persisted: (persistedInput, persistedInputReference) => applyPersistedTurnInput(raw.map(withoutToolImages), persistedInput, persistedInputReference)
19154
+ retract,
19155
+ persisted: (persistedInput, persistedInputReference) => {
19156
+ const firstUser = raw.find(
19157
+ (message) => message.role === "user"
19158
+ );
19159
+ return firstUser?.cliMessageId ? raw.map(withoutToolImages) : applyPersistedTurnInput(raw.map(withoutToolImages), persistedInput, persistedInputReference);
19160
+ }
18815
19161
  };
18816
19162
  }
18817
19163
 
@@ -18863,10 +19209,10 @@ function createTurnUsageLedger(args2) {
18863
19209
  recordProviderCall: ({ usage, model, provider, telemetry }) => {
18864
19210
  turnUsage = mergeTurnUsage(turnUsage, usage);
18865
19211
  lastContextUsage = usage;
18866
- if (usage && Object.keys(usage).length > 0) {
19212
+ if (usage && Object.keys(usage).length > 0 || telemetry?.requestState) {
18867
19213
  providerRecords.push({
18868
- callId: resolveRecordCallId(usage),
18869
- usage,
19214
+ callId: resolveRecordCallId(usage ?? {}),
19215
+ usage: usage ?? {},
18870
19216
  model: model || args2.model || "unknown",
18871
19217
  ...provider || args2.provider ? { provider: provider || args2.provider } : {},
18872
19218
  ...telemetry && Object.keys(telemetry).length > 0 ? { telemetry } : {},
@@ -18897,7 +19243,7 @@ function createTurnUsageLedger(args2) {
18897
19243
  }
18898
19244
 
18899
19245
  // packages/agent-runtime/leafFinalHandoff.ts
18900
- var LEAF_FINAL_HANDOFF_INSTRUCTIONS = `Leaf subtask final: return only the result, blockers/findings, and minimal evidence the parent needs. Do not narrate your process or restate the task. Keep success minimal (a one-line result is enough); on failure include the blocker, severity when relevant, and an evidence reference (file:line, test command, commit, artifact, or run/dialog). If the task explicitly requires a long-form deliverable (document, translation, dataset, code, or other artifact), provide that deliverable in full and keep only the handoff around it concise. During execution, follow the brief as given: report only results incremental to the brief, new evidence, overturned assumptions, and remaining questions; only when new evidence would materially change the goal, risk, irreversibility, or DoD should you surface it as a blocker/finding \u2014 do not silently expand scope or re-litigate the settled direction. Keep success concise, but include evidence for required DoD items.`;
19246
+ var LEAF_FINAL_HANDOFF_INSTRUCTIONS = `Leaf subtask final: return only the result, blockers/findings, and minimal evidence the parent needs. Do not narrate your process or restate the task. Keep success concise without dropping the current delivery scope, unresolved blockers or evidence references; on failure include the blocker, severity when relevant, and an evidence reference (file:line, test command, commit, artifact, or run/dialog). If the task explicitly requires a long-form deliverable (document, translation, dataset, code, or other artifact), provide that deliverable in full and keep only the handoff around it concise. During execution, follow the brief as given: keep progress updates incremental to the brief; the final report must stand alone with the complete current delivery scope, unresolved blockers and evidence references, including on continuation; only when new evidence would materially change the goal, risk, irreversibility, or DoD should you surface it as a blocker/finding \u2014 do not silently expand scope or re-litigate the settled direction. Own investigation, implementation, related checks and failure fixes within the brief\u2019s scope and budget; leave goals and critical decisions to the parent. For required DoD checks, include the worktree, checked version (including uncommitted change scope), command, check scope, pass/fail and original-output reference; explicitly mark checks not run or evidence unavailable. Reuse valid same-version evidence; additional checks are warranted for version changes, missing/conflicting evidence or integration risk. Do not invent version metadata. Process done/exit 0 and assistant claims do not establish passing tests, user acceptance, independent review approval, integration or release; runtime acceptance is observations only and unknown remains unknown. Preserve a requested reviewer JSON/checkVerdict format; do not wrap it in another report. Keep success concise without omitting required evidence.`;
18901
19247
 
18902
19248
  // packages/agent-runtime/contextBlockScope.ts
18903
19249
  var isContextBlockScope = (value) => {
@@ -18913,6 +19259,34 @@ var normalizeContextBlockScopes = (legacyBlocks = void 0, scopes = void 0) => {
18913
19259
  return (Array.isArray(legacyBlocks) ? legacyBlocks : []).filter((block) => typeof block === "string").map((block) => block.trim()).filter((block) => block.length > 0).map((block) => ({ content: block, cacheScope: "turn" }));
18914
19260
  };
18915
19261
 
19262
+ // packages/agent-runtime/providerInputItemLimits.ts
19263
+ var PROVIDER_INPUT_ITEM_LIMITS = [
19264
+ {
19265
+ provider: "opendesign",
19266
+ endpointHost: "open-design.ai",
19267
+ // Upstream HTTP 400: "[code=context_length_exceeded] Input is too long:
19268
+ // conversation history exceeds the limit on input items (1003 > 1000 items)."
19269
+ // type=invalid_request_error, code=context_length_exceeded, param=messages.
19270
+ maxInputItems: 1e3
19271
+ }
19272
+ ];
19273
+ function resolveProviderInputItemLimit(args2) {
19274
+ const byProvider = PROVIDER_INPUT_ITEM_LIMITS.find(
19275
+ (entry) => entry.provider === args2.provider?.toLowerCase()
19276
+ );
19277
+ if (byProvider) return byProvider.maxInputItems;
19278
+ if (!args2.endpoint) return void 0;
19279
+ let host;
19280
+ try {
19281
+ host = new URL(args2.endpoint.includes("://") ? args2.endpoint : `https://${args2.endpoint}`).hostname.toLowerCase();
19282
+ } catch {
19283
+ return void 0;
19284
+ }
19285
+ return PROVIDER_INPUT_ITEM_LIMITS.find(
19286
+ (entry) => host === entry.endpointHost || host.endsWith(`.${entry.endpointHost}`)
19287
+ )?.maxInputItems;
19288
+ }
19289
+
18916
19290
  // packages/agent-runtime/localAutoCompaction.ts
18917
19291
  import { randomUUID } from "node:crypto";
18918
19292
  function toPlanCompressionMessages(history) {
@@ -18932,6 +19306,16 @@ function findSummaryAnchorIndex(bridged, anchorId) {
18932
19306
  const index = Number(legacy[1]);
18933
19307
  return Number.isSafeInteger(index) && index < bridged.length ? index : -1;
18934
19308
  }
19309
+ function logSummarySourceDiagnostics(phase, dialogId, history, anchor) {
19310
+ const sourceHash = hashSummarySourceSlice(history, anchor)?.slice(0, 16);
19311
+ const rows = buildSummarySourceDiagnostics(toPlanCompressionMessages(history), anchor);
19312
+ for (const row of rows) console.log(`[compaction-source] ${JSON.stringify({
19313
+ phase,
19314
+ dialogId,
19315
+ sourceHash,
19316
+ ...row
19317
+ })}`);
19318
+ }
18935
19319
  function hashSummarySourceSlice(history, summarizedBeforeId) {
18936
19320
  if (!summarizedBeforeId) return void 0;
18937
19321
  const bridged = toPlanCompressionMessages(history);
@@ -18991,25 +19375,75 @@ function projectHistoryWithSummary(args2) {
18991
19375
  return [...summaryMsg, ...preservedUser, ...projected];
18992
19376
  }
18993
19377
  var COLD_RESUME_IDLE_MS = 60 * 60 * 1e3;
18994
- async function runSummaryFallback(fallback, content, options) {
19378
+ async function completeRoutedCompactionSummary(args2) {
19379
+ const budget = createSummaryBudget({ mode: "automatic", signal: args2.options.signal, deadlineMs: args2.options.deadlineMs });
18995
19380
  try {
18996
- const text2 = await fallback(content, options);
18997
- if (text2 === null) return { summary: null, error: "no summary" };
18998
- if (typeof text2 !== "string") return { summary: null, error: "non-string output" };
18999
- const trimmed = text2.trim();
19000
- return trimmed.length > 0 ? { summary: trimmed } : { summary: null, error: "empty summary" };
19001
- } catch (error) {
19002
- console.warn("[localLoop] auto-compaction summary fallback failed", {
19003
- attemptId: options.attemptId,
19004
- stage: "fallback"
19381
+ const options = { ...args2.options, signal: budget.signal, deadlineMs: budget.deadlineMs };
19382
+ const eligible = await budget.run(async () => {
19383
+ try {
19384
+ return await args2.fallback.preferPlatform?.(options) === true;
19385
+ } catch (error) {
19386
+ if (budget.signal.aborted || isAbortError(error) || error?.name === "TimeoutError") throw error;
19387
+ return false;
19388
+ }
19389
+ });
19390
+ let currentResult;
19391
+ const result4 = await runSummaryWithContract({
19392
+ budget,
19393
+ eligibility: { userId: "authenticated-account", authenticated: eligible, platformAvailable: eligible, credits: eligible ? 1 : void 0 },
19394
+ platform: {
19395
+ model: PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL,
19396
+ provider: "nolo",
19397
+ attemptId: options.attemptId,
19398
+ run: async () => args2.fallback.complete ? args2.fallback.complete(args2.content, options) : { text: await args2.fallback(args2.content, options) ?? "" }
19399
+ },
19400
+ current: { attemptId: options.attemptId, run: async () => {
19401
+ currentResult = await args2.current();
19402
+ return {
19403
+ text: currentResult.content ?? "",
19404
+ finishReason: currentResult.finish_reason,
19405
+ maxOutputTokens: options.maxOutputTokens,
19406
+ completionTokens: summaryCompletionTokens(currentResult.usage)
19407
+ };
19408
+ } }
19005
19409
  });
19006
- const message = error instanceof Error ? error.message : String(error);
19007
- return { summary: null, error: message };
19410
+ if (result4.kind === "error" || result4.kind === "cancelled") {
19411
+ throw Object.assign(new Error(result4.error.message), result4.error, {
19412
+ type: result4.error.errorType,
19413
+ name: result4.kind === "cancelled" ? "AbortError" : result4.error.category === "timeout" ? "TimeoutError" : "SummaryError"
19414
+ });
19415
+ }
19416
+ if (result4.kind === "truncated") throw {
19417
+ code: "SUMMARY_TRUNCATED",
19418
+ stage: "decode",
19419
+ finishReason: result4.completion?.finishReason,
19420
+ maxOutputTokens: result4.completion?.maxOutputTokens ?? options.maxOutputTokens,
19421
+ completionTokens: result4.completion?.completionTokens,
19422
+ outputChars: result4.completion?.text.length,
19423
+ responseStatus: result4.completion?.responseStatus,
19424
+ incompleteReason: result4.completion?.incompleteReason,
19425
+ model: result4.route === "platform" ? PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL : currentResult?.model,
19426
+ provider: result4.route === "platform" ? "nolo" : currentResult?.provider
19427
+ };
19428
+ return result4.route === "current" && currentResult ? { ...currentResult, summaryCompletion: result4.completion } : {
19429
+ content: result4.kind === "success" ? result4.text : "",
19430
+ model: PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL,
19431
+ provider: "nolo",
19432
+ summaryCompletion: result4.completion
19433
+ };
19434
+ } finally {
19435
+ budget.dispose();
19008
19436
  }
19009
19437
  }
19010
19438
  var COMPACTION_RETRY_BACKOFF_MS = 6e4;
19011
19439
  var COMPACTION_RETRY_BACKOFF_MAX_ENTRIES = 256;
19012
19440
  var compactionRetryBackoff = /* @__PURE__ */ new Map();
19441
+ var COMPACTION_RETRY_DELAYS_MS = [3e3, 8e3];
19442
+ var compactionRetryDelaysOverride;
19443
+ function compactionRetryDelayMs(retryCount) {
19444
+ const table = compactionRetryDelaysOverride ?? COMPACTION_RETRY_DELAYS_MS;
19445
+ return table[Math.min(retryCount, table.length - 1)];
19446
+ }
19013
19447
  function isCompactionBackedOff(dialogId, now) {
19014
19448
  for (const [key, until2] of compactionRetryBackoff) {
19015
19449
  if (until2 <= now) compactionRetryBackoff.delete(key);
@@ -19079,8 +19513,21 @@ async function maybeAutoCompactLocalHistory(args2) {
19079
19513
  reason = "hash-mismatch";
19080
19514
  }
19081
19515
  console.warn(
19082
- `[localLoop] invalidated dialog summary for ${dialogId} (${reason}); discarding and re-compressing`
19516
+ `[localLoop] invalidated dialog summary for ${dialogId} (${reason}); discarding and re-compressing`,
19517
+ // 诊断分项(**仅加日志,不改任何哈希/校验/重锚语义**):区分「历史真被改写」
19518
+ // 与「保存/重算口径不一致」。只记长度、条数、消息 id 与哈希前 8 位;
19519
+ // 消息正文与摘要正文一律不进日志。重算哈希只发生在失效分支内,
19520
+ // 健康路径零额外开销。
19521
+ {
19522
+ reason,
19523
+ historyLength: history.length,
19524
+ storedSourceCount: typeof invalidStored?.sourceCount === "number" ? invalidStored.sourceCount : null,
19525
+ summarizedBeforeId: typeof invalidStored?.summarizedBeforeId === "string" ? invalidStored.summarizedBeforeId : null,
19526
+ recomputedHashPrefix: hashSummarySourceSlice(history, invalidStored?.summarizedBeforeId)?.slice(0, 8) ?? null,
19527
+ storedHashPrefix: typeof invalidStored?.sourceHash === "string" && invalidStored.sourceHash ? invalidStored.sourceHash.slice(0, 8) : null
19528
+ }
19083
19529
  );
19530
+ logSummarySourceDiagnostics("invalidated", dialogId, history, invalidStored?.summarizedBeforeId);
19084
19531
  stored = null;
19085
19532
  }
19086
19533
  const existingSummary = typeof stored?.summary === "string" ? stored.summary : "";
@@ -19088,18 +19535,34 @@ async function maybeAutoCompactLocalHistory(args2) {
19088
19535
  const legacyAnchorIndex = summarizedBeforeId ? findSummaryAnchorIndex(bridged, summarizedBeforeId) : -1;
19089
19536
  const planAnchorId = summarizedBeforeId && /^local-(0|[1-9]\d*)$/.test(summarizedBeforeId) && legacyAnchorIndex >= 0 ? bridged[legacyAnchorIndex].id : summarizedBeforeId;
19090
19537
  const contextWindow = typeof args2.contextWindow === "number" && Number.isFinite(args2.contextWindow) && args2.contextWindow > 0 ? args2.contextWindow : getModelContextWindow(args2.model ?? "");
19091
- const allMsgs = toPlanCompressionMessages(history);
19538
+ const allMsgs = toPlanCompressionMessages(prepareHistoryForNextTurn(history, args2.contextReferenceResolver));
19539
+ const maxInputItems = resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint });
19540
+ const force = args2.force === true || args2.requestOverBudget?.(
19541
+ existingSummary ? projectHistoryWithSummary({ history, summary: existingSummary, summarizedBeforeId }) : history
19542
+ ) === true;
19092
19543
  const plan = planCompression({
19093
19544
  allMsgs,
19094
19545
  summarizedBeforeId: planAnchorId,
19095
19546
  summary: existingSummary,
19096
19547
  contextWindow,
19548
+ // 失败路径补救:预算裁剪即将丢消息时由 localLoop 传入 force,交由 planCompression
19549
+ // 的既有 force 语义产出待压缩切片(仍受最小条数/安全前缀约束)。
19550
+ force,
19551
+ ...force ? { reason: "budget_rescue" } : {},
19552
+ availableHistoryTokens: args2.availableHistoryTokens,
19097
19553
  preserveLatestUserByProjection: true,
19554
+ maxInputItems,
19098
19555
  ...args2.realContextUsagePercent !== void 0 ? { realContextUsagePercent: args2.realContextUsagePercent } : {}
19099
19556
  });
19557
+ const itemDiagnostics = maxInputItems !== void 0 ? {
19558
+ itemCount: plan.diagnostics?.itemCount,
19559
+ maxInputItems,
19560
+ triggeredByItemLimit: plan.diagnostics?.triggeredByItemLimit
19561
+ } : {};
19100
19562
  const projectExisting = () => {
19101
19563
  const diag = plan.diagnostics;
19102
19564
  const diagSnapshot = diag ? {
19565
+ ...itemDiagnostics,
19103
19566
  estimatedTokens: diag.totalUsed,
19104
19567
  historyBudget: diag.historyBudget,
19105
19568
  triggerRatio: diag.triggerRatio,
@@ -19107,7 +19570,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19107
19570
  } : {};
19108
19571
  const skippedDecision = {
19109
19572
  outcome: "skipped",
19110
- skipReason: diag?.emptyReason === "no-pending" ? "no-pending" : diag?.emptyReason === "below-min-compress-count" ? "below-min-compress-count" : "below-trigger",
19573
+ skipReason: diag?.emptyReason === "no-pending" ? "no-pending" : diag?.emptyReason === "below-min-compress-count" ? "below-min-compress-count" : diag?.emptyReason === "no-safe-prefix" ? "no-safe-prefix" : "below-trigger",
19111
19574
  ...diagSnapshot,
19112
19575
  ...diag ? { pendingMsgCount: diag.pendingMsgCount } : {},
19113
19576
  ...diag?.compressCount !== void 0 ? { compressCount: diag.compressCount } : {}
@@ -19121,6 +19584,13 @@ async function maybeAutoCompactLocalHistory(args2) {
19121
19584
  }),
19122
19585
  compressed: true,
19123
19586
  summaryGenerated: false,
19587
+ selectedSummary: {
19588
+ outcome: "loaded",
19589
+ hash: sha256Hex(existingSummary),
19590
+ ...summarizedBeforeId ? { anchorId: summarizedBeforeId } : {},
19591
+ ...stored?.sourceHash ? { sourceHash: stored.sourceHash } : {},
19592
+ ...stored?.sourceCount !== void 0 ? { sourceCount: stored.sourceCount } : {}
19593
+ },
19124
19594
  decision: {
19125
19595
  outcome: "compressed",
19126
19596
  trigger: "existing-summary",
@@ -19141,6 +19611,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19141
19611
  outcome: "skipped",
19142
19612
  skipReason: "retry-backoff",
19143
19613
  ...diag ? {
19614
+ ...itemDiagnostics,
19144
19615
  estimatedTokens: diag.totalUsed,
19145
19616
  historyBudget: diag.historyBudget,
19146
19617
  triggerRatio: diag.triggerRatio,
@@ -19158,14 +19629,22 @@ async function maybeAutoCompactLocalHistory(args2) {
19158
19629
  });
19159
19630
  if (bounded3.status === "blocked") {
19160
19631
  const detail = `bounded compaction blocked: ${bounded3.reason}`;
19161
- console.warn(`[localLoop] ${detail}`);
19632
+ console.warn(
19633
+ `[localLoop] ${detail}`,
19634
+ ...bounded3.diagnostics ? [bounded3.diagnostics] : []
19635
+ );
19162
19636
  return {
19163
19637
  ...projectExisting(),
19164
19638
  decision: { outcome: "skipped", skipReason: "bounded-request-blocked", detail }
19165
19639
  };
19166
19640
  }
19167
19641
  emitPhase({ kind: "compaction-start" });
19168
- const compactionAttemptId = randomUUID();
19642
+ let compactionAttemptId = randomUUID();
19643
+ const maxAttempts = 3;
19644
+ let attempt = 0;
19645
+ let retryCount = 0;
19646
+ let attemptRoute = "current";
19647
+ let attemptTimingLogged = false;
19169
19648
  let compactionT0 = Date.now();
19170
19649
  let compactionInputTokens;
19171
19650
  let compactionPrevSummaryTokens;
@@ -19174,7 +19653,15 @@ async function maybeAutoCompactLocalHistory(args2) {
19174
19653
  let primaryElapsedMs;
19175
19654
  let fallbackElapsedMs;
19176
19655
  let saveElapsedMs;
19656
+ let summaryDeadlineMs = Infinity;
19657
+ let summaryModel = args2.model;
19658
+ let summaryProvider = args2.provider;
19659
+ let summaryDiagnostics = {
19660
+ maxOutputTokens: bounded3.outputTokenBudget
19661
+ };
19177
19662
  const logCompactionTiming = (outcome, fields) => {
19663
+ if (attemptTimingLogged) return;
19664
+ attemptTimingLogged = true;
19178
19665
  if (compactionInputTokens === void 0 && compactionInputSource !== void 0) {
19179
19666
  compactionInputTokens = estimateTokenCount(compactionInputSource);
19180
19667
  }
@@ -19184,10 +19671,20 @@ async function maybeAutoCompactLocalHistory(args2) {
19184
19671
  console.log(
19185
19672
  `[compaction-timing] ${JSON.stringify({
19186
19673
  attemptId: compactionAttemptId,
19187
- model: fields.model ?? args2.model ?? null,
19674
+ attempt,
19675
+ maxAttempts,
19676
+ physicalAttempts: attempt,
19677
+ route: attemptRoute,
19678
+ model: fields.model ?? summaryModel ?? null,
19679
+ provider: summaryProvider ?? null,
19188
19680
  inputTokens: compactionInputTokens ?? null,
19189
19681
  prevSummaryTokens: compactionPrevSummaryTokens ?? null,
19190
- outputChars: fields.outputChars ?? null,
19682
+ outputChars: summaryDiagnostics.outputChars ?? fields.outputChars ?? null,
19683
+ finishReason: summaryDiagnostics.finishReason ?? null,
19684
+ responseStatus: summaryDiagnostics.responseStatus ?? null,
19685
+ incompleteReason: summaryDiagnostics.incompleteReason ?? null,
19686
+ maxOutputTokens: summaryDiagnostics.maxOutputTokens ?? null,
19687
+ completionTokens: summaryDiagnostics.completionTokens ?? null,
19191
19688
  elapsedMs: Date.now() - compactionT0,
19192
19689
  primaryElapsedMs: primaryElapsedMs ?? null,
19193
19690
  fallbackElapsedMs: fallbackElapsedMs ?? null,
@@ -19197,10 +19694,11 @@ async function maybeAutoCompactLocalHistory(args2) {
19197
19694
  );
19198
19695
  };
19199
19696
  try {
19200
- if (args2.abortSignal?.aborted) {
19201
- throw Object.assign(new Error("auto-compaction aborted"), { compactionReason: "aborted" });
19202
- }
19203
- const provider = await args2.resolveProvider();
19697
+ let reportAttemptUsage2 = function(value) {
19698
+ const usage = value?.usage;
19699
+ if (usage && typeof usage === "object") args2.onAttemptUsage?.(usage);
19700
+ };
19701
+ var reportAttemptUsage = reportAttemptUsage2;
19204
19702
  if (args2.abortSignal?.aborted) {
19205
19703
  throw Object.assign(new Error("auto-compaction aborted"), { compactionReason: "aborted" });
19206
19704
  }
@@ -19209,32 +19707,141 @@ async function maybeAutoCompactLocalHistory(args2) {
19209
19707
  compactionInputSource = promptContent;
19210
19708
  compactionPrevSummarySource = existingSummary;
19211
19709
  compactionT0 = Date.now();
19212
- const timeoutMs = typeof args2.timeoutMs === "number" && Number.isFinite(args2.timeoutMs) && args2.timeoutMs > 0 ? args2.timeoutMs : void 0;
19710
+ const timeoutMs = Math.min(6e4, typeof args2.timeoutMs === "number" && Number.isFinite(args2.timeoutMs) && args2.timeoutMs > 0 ? args2.timeoutMs : 6e4);
19711
+ const requestDeadlineMs = Date.now() + timeoutMs;
19712
+ summaryDeadlineMs = requestDeadlineMs;
19213
19713
  const requestController = new AbortController();
19214
19714
  let timeoutHandle;
19215
19715
  let abortListener;
19216
19716
  if (args2.abortSignal?.aborted) requestController.abort(args2.abortSignal.reason);
19217
- const request3 = provider.complete(
19218
- [{ role: "system", content: COMPACTION_SUMMARY_SYSTEM_PROMPT }, { role: "user", content: promptContent }],
19219
- {
19220
- signal: requestController.signal,
19221
- ...timeoutMs ? { timeoutMs } : {},
19222
- // 仅日志用的 attempt id:让 compaction 埋点与 transport 诊断日志 /
19223
- // 服务端 x-request-id 可对上,用于关联请求级证据。不进 prompt/摘要/持久化。
19224
- requestId: compactionAttemptId,
19225
- // Room for factual handoff, exact commands and file operations.
19226
- max_tokens: bounded3.outputTokenBudget,
19227
- reasoning_effort: "low"
19228
- }
19229
- ).then(
19230
- (value) => ({ kind: "done", value }),
19231
- (error) => ({ kind: "provider-error", error })
19232
- );
19233
- const guards = [];
19234
- if (timeoutMs) guards.push(new Promise((resolve6) => {
19235
- timeoutHandle = setTimeout(() => {
19236
- requestController.abort();
19237
- resolve6({ kind: "timeout" });
19717
+ let currentOnly = false;
19718
+ const physicalRequest = async (route, operation) => {
19719
+ if (attempt >= maxAttempts) throw { code: "SUMMARY_ATTEMPT_LIMIT" };
19720
+ if (requestController.signal.aborted) throw requestController.signal.reason;
19721
+ attempt++;
19722
+ attemptRoute = route;
19723
+ attemptTimingLogged = false;
19724
+ compactionAttemptId = randomUUID();
19725
+ compactionT0 = Date.now();
19726
+ primaryElapsedMs = void 0;
19727
+ summaryDiagnostics = { maxOutputTokens: bounded3.outputTokenBudget };
19728
+ try {
19729
+ const value = await operation();
19730
+ reportAttemptUsage2(value);
19731
+ return value;
19732
+ } catch (error) {
19733
+ reportAttemptUsage2(error);
19734
+ const safe = classifySummaryError(error);
19735
+ summaryDiagnostics = {
19736
+ ...summaryDiagnostics,
19737
+ finishReason: safe.finishReason,
19738
+ responseStatus: safe.responseStatus,
19739
+ incompleteReason: safe.incompleteReason,
19740
+ completionTokens: safe.completionTokens,
19741
+ outputChars: safe.outputChars,
19742
+ maxOutputTokens: safe.maxOutputTokens ?? bounded3.outputTokenBudget
19743
+ };
19744
+ primaryElapsedMs = Date.now() - compactionT0;
19745
+ logCompactionTiming(safe.category === "cancelled" ? "aborted" : safe.category === "timeout" ? "timeout" : "provider-error", {});
19746
+ throw error;
19747
+ }
19748
+ };
19749
+ const currentRequest = async () => {
19750
+ currentOnly = true;
19751
+ const provider = await args2.resolveProvider();
19752
+ summaryModel = provider.model ?? args2.model;
19753
+ summaryProvider = args2.provider;
19754
+ if (requestController.signal.aborted) throw requestController.signal.reason ?? new DOMException("Summary cancelled", "AbortError");
19755
+ try {
19756
+ return await physicalRequest("current", () => provider.complete(
19757
+ [{ role: "system", content: COMPACTION_SUMMARY_SYSTEM_PROMPT }, { role: "user", content: promptContent }],
19758
+ {
19759
+ signal: requestController.signal,
19760
+ timeoutMs: Math.max(1, requestDeadlineMs - Date.now()),
19761
+ // 仅日志用的 attempt id:让 compaction 埋点与 transport 诊断日志 /
19762
+ // 服务端 x-request-id 可对上,用于关联请求级证据。不进 prompt/摘要/持久化。
19763
+ requestId: compactionAttemptId,
19764
+ // Room for factual handoff, exact commands and file operations.
19765
+ max_tokens: bounded3.outputTokenBudget,
19766
+ reasoning_effort: "low"
19767
+ }
19768
+ ));
19769
+ } catch (cause) {
19770
+ const safe = classifySummaryError(cause, { model: provider.model, provider: args2.provider ?? void 0, attemptId: compactionAttemptId });
19771
+ throw Object.assign(new Error(safe.message), safe, {
19772
+ type: safe.errorType,
19773
+ name: safe.category === "cancelled" ? "AbortError" : safe.category === "timeout" ? "TimeoutError" : "SummaryError"
19774
+ });
19775
+ }
19776
+ };
19777
+ const fallback = args2.summaryFallback?.preferPlatform ? args2.summaryFallback : void 0;
19778
+ let eligibility;
19779
+ const routedFallback = fallback ? Object.assign(
19780
+ async (content, options) => {
19781
+ summaryModel = PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL;
19782
+ summaryProvider = "nolo";
19783
+ return physicalRequest("platform", () => fallback(content, { ...options, attemptId: compactionAttemptId }));
19784
+ },
19785
+ {
19786
+ preferPlatform: (options) => eligibility ??= fallback.preferPlatform(options),
19787
+ ...fallback.complete ? { complete: async (content, options) => {
19788
+ summaryModel = PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL;
19789
+ summaryProvider = "nolo";
19790
+ return physicalRequest("platform", () => fallback.complete(content, { ...options, attemptId: compactionAttemptId }));
19791
+ } } : {}
19792
+ }
19793
+ ) : void 0;
19794
+ const requestOnce = () => routedFallback && !currentOnly ? completeRoutedCompactionSummary({
19795
+ fallback: routedFallback,
19796
+ content: promptContent,
19797
+ options: {
19798
+ signal: requestController.signal,
19799
+ deadlineMs: requestDeadlineMs,
19800
+ attemptId: compactionAttemptId,
19801
+ maxOutputTokens: bounded3.outputTokenBudget
19802
+ },
19803
+ current: currentRequest
19804
+ }) : currentRequest();
19805
+ const request3 = (async () => {
19806
+ for (; ; ) {
19807
+ try {
19808
+ return await requestOnce();
19809
+ } catch (error) {
19810
+ const safe = classifySummaryError(error);
19811
+ const terminal = isQuotaExhaustedError(safe.status ?? 0, safe.code, safe.errorType) || safe.category === "cancelled" || safe.category === "timeout" || ["PROVIDER_UNAVAILABLE", "SUMMARY_TRUNCATED", "INSUFFICIENT_BALANCE"].includes(safe.code ?? "") || safe.errorType === "insufficient_balance_error";
19812
+ const busy = !terminal && (safe.category === "http" && (safe.status === 503 || safe.status === 429) || /^(capacity|overload(?:ed)?|rate[_-]?limit(?:ed)?)(?:[_-](?:error|exceeded))?$/i.test(safe.errorType ?? "") || ["PLATFORM_LLM_BUSY", "RATE_LIMIT", "CAPACITY", "OVERLOAD", "RESOURCE_EXHAUSTED"].includes(safe.code ?? ""));
19813
+ const delayMs = compactionRetryDelayMs(retryCount);
19814
+ if (!busy || attempt >= maxAttempts || requestController.signal.aborted || requestDeadlineMs - Date.now() < delayMs + 5e3) throw error;
19815
+ primaryElapsedMs = Date.now() - compactionT0;
19816
+ logCompactionTiming("provider-error", {});
19817
+ emitPhase({ kind: "compaction-retry", attempt: attempt + 1, maxAttempts });
19818
+ await new Promise((resolve6, reject) => {
19819
+ const signal = requestController.signal;
19820
+ const cancel = () => {
19821
+ clearTimeout(timer);
19822
+ signal.removeEventListener("abort", cancel);
19823
+ reject(signal.reason);
19824
+ };
19825
+ const timer = setTimeout(() => {
19826
+ signal.removeEventListener("abort", cancel);
19827
+ resolve6();
19828
+ }, delayMs);
19829
+ signal.addEventListener("abort", cancel, { once: true });
19830
+ if (signal.aborted) cancel();
19831
+ });
19832
+ if (requestController.signal.aborted || requestDeadlineMs - Date.now() < 5e3) throw error;
19833
+ retryCount++;
19834
+ }
19835
+ }
19836
+ })().then(
19837
+ (value) => ({ kind: "done", value }),
19838
+ (error) => ({ kind: "provider-error", error })
19839
+ );
19840
+ const guards = [];
19841
+ if (timeoutMs) guards.push(new Promise((resolve6) => {
19842
+ timeoutHandle = setTimeout(() => {
19843
+ requestController.abort(new DOMException("Summary deadline exceeded", "TimeoutError"));
19844
+ resolve6({ kind: "timeout" });
19238
19845
  }, timeoutMs);
19239
19846
  }));
19240
19847
  if (args2.abortSignal) guards.push(new Promise((resolve6) => {
@@ -19250,71 +19857,37 @@ async function maybeAutoCompactLocalHistory(args2) {
19250
19857
  if (timeoutHandle) clearTimeout(timeoutHandle);
19251
19858
  if (abortListener) args2.abortSignal?.removeEventListener("abort", abortListener);
19252
19859
  const result4 = outcome.kind === "done" ? outcome.value : void 0;
19253
- let newSummary = result4?.finish_reason !== "length" && typeof result4?.content === "string" ? result4.content.trim() : "";
19254
- const primaryFailure = outcome.kind === "aborted" || args2.abortSignal?.aborted ? "aborted" : newSummary ? null : outcome.kind === "done" ? "provider-error" : outcome.kind;
19255
- if (primaryFailure === "aborted") {
19256
- throw Object.assign(new Error("auto-compaction aborted"), {
19257
- compactionReason: "aborted"
19258
- });
19259
- }
19260
- const summaryFallback = args2.summaryFallback;
19261
- let fallbackFailureDetail;
19262
- if (primaryFailure && summaryFallback) {
19263
- const fallbackT0 = Date.now();
19264
- const fallbackResult = await runSummaryFallback(
19265
- summaryFallback,
19266
- promptContent,
19267
- {
19268
- signal: args2.abortSignal,
19269
- deadlineMs: Date.now() + 3e4,
19270
- attemptId: compactionAttemptId,
19271
- maxOutputTokens: bounded3.outputTokenBudget
19272
- }
19273
- );
19274
- fallbackElapsedMs = Date.now() - fallbackT0;
19275
- if (args2.abortSignal?.aborted) {
19276
- throw Object.assign(new Error("auto-compaction aborted"), {
19277
- compactionReason: "aborted"
19278
- });
19279
- }
19280
- if (fallbackResult.summary) {
19281
- newSummary = fallbackResult.summary;
19282
- } else {
19283
- fallbackFailureDetail = fallbackResult.error ?? "no summary";
19284
- }
19860
+ if (result4?.model) summaryModel = result4.model;
19861
+ if (result4?.provider) summaryProvider = result4.provider;
19862
+ if (outcome.kind === "aborted") throw Object.assign(new Error("Summary cancelled"), { name: "AbortError", compactionReason: "aborted" });
19863
+ if (outcome.kind === "timeout") throw Object.assign(new Error("Summary deadline exceeded"), { compactionReason: "timeout" });
19864
+ if (outcome.kind === "provider-error") throw outcome.error;
19865
+ const completion = result4?.summaryCompletion;
19866
+ const diagnostic = classifySummaryError({
19867
+ finishReason: completion?.finishReason ?? result4?.finish_reason,
19868
+ responseStatus: completion?.responseStatus,
19869
+ incompleteReason: completion?.incompleteReason,
19870
+ maxOutputTokens: completion?.maxOutputTokens ?? bounded3.outputTokenBudget,
19871
+ completionTokens: completion?.completionTokens ?? summaryCompletionTokens(result4?.usage),
19872
+ outputChars: completion?.text.length ?? result4?.content?.length
19873
+ });
19874
+ summaryDiagnostics = {
19875
+ finishReason: diagnostic.finishReason,
19876
+ responseStatus: diagnostic.responseStatus,
19877
+ incompleteReason: diagnostic.incompleteReason,
19878
+ maxOutputTokens: diagnostic.maxOutputTokens,
19879
+ completionTokens: diagnostic.completionTokens,
19880
+ outputChars: diagnostic.outputChars
19881
+ };
19882
+ if (isTruncatedCompletion({ ...completion, finishReason: completion?.finishReason ?? result4?.finish_reason })) {
19883
+ throw { code: "SUMMARY_TRUNCATED", stage: "decode", ...summaryDiagnostics };
19285
19884
  }
19885
+ const newSummary = result4?.content?.trim() ?? "";
19286
19886
  if (!newSummary) {
19287
- const failureNow = args2.now?.() ?? Date.now();
19288
- recordCompactionFailure(dialogId, failureNow);
19289
- const primaryDetail = outcome.kind === "provider-error" ? outcome.error instanceof Error ? outcome.error.message : String(outcome.error) : outcome.kind === "done" ? "summary model returned empty content" : `auto-compaction timed out after ${timeoutMs ?? primaryElapsedMs}ms`;
19290
- const primaryDiagnostic = `primary failed (${primaryElapsedMs ?? 0}ms): ${primaryDetail}`;
19291
- const fallbackDiagnostic = fallbackElapsedMs !== void 0 ? `; fallback failed (${fallbackElapsedMs}ms): ${fallbackFailureDetail ?? "no summary"}` : "";
19292
- const combinedDetail = `${primaryDiagnostic}${fallbackDiagnostic}`;
19293
- if (outcome.kind === "done") {
19294
- console.warn(
19295
- "[localLoop] auto-compaction produced empty summary; keeping prior projection"
19296
- );
19297
- logCompactionTiming("empty", {});
19298
- const failureReason = "provider-error";
19299
- emitPhase({ kind: "compaction-failed", reason: failureReason });
19300
- const failureMessage = combinedDetail.slice(0, 200);
19301
- return {
19302
- ...projectExisting(),
19303
- failureMessage,
19304
- failureReason,
19305
- decision: {
19306
- outcome: "failed",
19307
- reason: failureReason,
19308
- detail: failureMessage
19309
- }
19310
- };
19311
- }
19312
- const reason = primaryFailure ?? "provider-error";
19313
- throw Object.assign(new Error(combinedDetail), {
19314
- compactionReason: reason,
19315
- primaryElapsedMs,
19316
- fallbackElapsedMs
19317
- });
19887
+ recordCompactionFailure(dialogId, args2.now?.() ?? Date.now());
19888
+ logCompactionTiming("empty", { model: result4?.model });
19889
+ emitPhase({ kind: "compaction-end" });
19890
+ return { ...projectExisting(), failureMessage: "Summary empty", failureReason: "provider-error", decision: { outcome: "failed", reason: "provider-error", detail: "Summary empty", ...itemDiagnostics } };
19318
19891
  }
19319
19892
  const metricsReason = invalidSummary ? "invalid_summary" : "context_budget";
19320
19893
  const metrics = buildCompactionMetricsFromPlan({
@@ -19325,36 +19898,51 @@ async function maybeAutoCompactLocalHistory(args2) {
19325
19898
  msgsToKeep: [...msgsToCompress.slice(bounded3.coveredMessages.length), ...plan.msgsToKeep]
19326
19899
  },
19327
19900
  newSummary,
19328
- summaryUsage: result4?.usage
19901
+ summaryUsage: result4?.usage,
19902
+ summaryInput: {
19903
+ inputTokens: bounded3.inputTokens,
19904
+ capTokens: bounded3.capTokens,
19905
+ expandedMessages: bounded3.expandedMessages,
19906
+ omittedMessages: bounded3.omittedMessages
19907
+ },
19908
+ planCounts: {
19909
+ pendingMessageCount: plan.diagnostics?.pendingMsgCount,
19910
+ plannedCompressCount: plan.diagnostics?.compressCount
19911
+ }
19329
19912
  });
19330
19913
  const projectedHistory = projectHistoryWithSummary({
19331
19914
  history,
19332
19915
  summary: newSummary,
19333
19916
  summarizedBeforeId: bounded3.summarizedBeforeId
19334
19917
  });
19335
- const projectedMessages = toPlanCompressionMessages(projectedHistory);
19918
+ const projectedMessages = toPlanCompressionMessages(prepareHistoryForNextTurn(projectedHistory, args2.contextReferenceResolver));
19336
19919
  const projectedTokens = projectedMessages.reduce((sum2, message) => sum2 + getMessageTokenCount(message), 0);
19337
19920
  const projectedRetained = projectedMessages.slice(1);
19338
19921
  metrics.retainedTokens = projectedRetained.reduce((sum2, message) => sum2 + getMessageTokenCount(message), 0);
19339
19922
  metrics.retainedCount = projectedRetained.length;
19340
- const { effectiveHistoryBudget } = resolveEffectiveCompactionBudgets({
19923
+ const { effectiveRawMessageBudget } = resolveEffectiveCompactionBudgets({
19341
19924
  contextWindow,
19342
19925
  triggerRatio: plan.diagnostics.triggerRatio,
19343
- historyBudget: plan.diagnostics.historyBudget,
19344
- rawMessageBudget: plan.diagnostics.historyBudget,
19345
- summaryTokens: 0
19926
+ historyBudget: contextWindow,
19927
+ rawMessageBudget: contextWindow,
19928
+ summaryTokens: 0,
19929
+ newSummaryTokenReserve: estimateTokenCount(newSummary)
19346
19930
  });
19347
- const withinSafetyBudget = projectedTokens <= effectiveHistoryBudget;
19931
+ const effectiveHistoryBudget = effectiveRawMessageBudget + estimateTokenCount(newSummary);
19932
+ const projectedItemCount = projectedHistory.length + 1;
19933
+ const withinSafetyBudget = projectedTokens <= effectiveHistoryBudget && (maxInputItems === void 0 || projectedItemCount <= Math.floor(maxInputItems * 0.6));
19348
19934
  if (!withinSafetyBudget) {
19349
19935
  console.warn("[localLoop] compaction projection remains above safety budget", {
19350
19936
  projectedTokens,
19351
- effectiveHistoryBudget
19937
+ effectiveHistoryBudget,
19938
+ ...maxInputItems !== void 0 ? { projectedItemCount, maxInputItems } : {}
19352
19939
  });
19353
19940
  }
19354
19941
  const oldProjection = projectExisting();
19355
- const beforeProjectedTokens = toPlanCompressionMessages(oldProjection.history).reduce((sum2, message) => sum2 + getMessageTokenCount(message), 0);
19356
- const historyBudget = plan.diagnostics.historyBudget;
19357
- if (projectedTokens >= beforeProjectedTokens || projectedTokens >= historyBudget) {
19942
+ const beforeProjectedTokens = toPlanCompressionMessages(prepareHistoryForNextTurn(oldProjection.history, args2.contextReferenceResolver)).reduce((sum2, message) => sum2 + getMessageTokenCount(message), 0);
19943
+ const historyBudget = Math.max(0, contextWindow - Math.min(8192, Math.max(1, Math.floor(contextWindow / 4))));
19944
+ const candidateOverBudget = args2.requestOverBudget ? args2.requestOverBudget(projectedHistory) : projectedTokens > historyBudget;
19945
+ if (projectedTokens >= beforeProjectedTokens || candidateOverBudget) {
19358
19946
  const failureMessage = `compaction candidate rejected: ${projectedTokens >= beforeProjectedTokens ? "no token reduction" : "above history budget"} (before=${beforeProjectedTokens}, after=${projectedTokens}, budget=${historyBudget})`;
19359
19947
  console.warn(`[localLoop] ${failureMessage}`);
19360
19948
  recordCompactionFailure(dialogId, args2.now?.() ?? Date.now());
@@ -19364,13 +19952,20 @@ async function maybeAutoCompactLocalHistory(args2) {
19364
19952
  ...oldProjection,
19365
19953
  failureMessage,
19366
19954
  ...result4?.usage ? { usage: result4.usage } : {},
19367
- decision: { outcome: "skipped", skipReason: "unsafe-projection", detail: failureMessage }
19955
+ decision: {
19956
+ outcome: "skipped",
19957
+ skipReason: "unsafe-projection",
19958
+ detail: failureMessage,
19959
+ ...itemDiagnostics,
19960
+ ...maxInputItems !== void 0 ? { projectedItemCount } : {}
19961
+ }
19368
19962
  };
19369
19963
  }
19370
19964
  const sourceMeta = await computeSummarySourceMetadata(
19371
19965
  toPlanCompressionMessages(history),
19372
19966
  bounded3.summarizedBeforeId
19373
19967
  );
19968
+ if (Date.now() >= summaryDeadlineMs) throw Object.assign(new Error("Summary deadline exceeded"), { compactionReason: "timeout" });
19374
19969
  if (args2.abortSignal?.aborted) {
19375
19970
  throw Object.assign(new Error("auto-compaction aborted"), { compactionReason: "aborted" });
19376
19971
  }
@@ -19390,6 +19985,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19390
19985
  )
19391
19986
  });
19392
19987
  saveElapsedMs = Date.now() - saveT0;
19988
+ logSummarySourceDiagnostics("saved", dialogId, history, bounded3.summarizedBeforeId);
19393
19989
  console.log(formatCompactionMetricsLog(metrics));
19394
19990
  logCompactionTiming("success", {
19395
19991
  model: result4?.model ?? args2.model ?? null,
@@ -19400,6 +19996,13 @@ async function maybeAutoCompactLocalHistory(args2) {
19400
19996
  history: projectedHistory,
19401
19997
  compressed: true,
19402
19998
  summaryGenerated: true,
19999
+ selectedSummary: {
20000
+ outcome: "generated",
20001
+ hash: sha256Hex(newSummary),
20002
+ anchorId: bounded3.summarizedBeforeId,
20003
+ ...sourceMeta?.sourceHash ? { sourceHash: sourceMeta.sourceHash } : {},
20004
+ ...sourceMeta?.sourceCount !== void 0 ? { sourceCount: sourceMeta.sourceCount } : {}
20005
+ },
19403
20006
  reason: metricsReason,
19404
20007
  beforeTokens: beforeProjectedTokens,
19405
20008
  afterTokens: projectedTokens,
@@ -19408,7 +20011,9 @@ async function maybeAutoCompactLocalHistory(args2) {
19408
20011
  metrics,
19409
20012
  decision: {
19410
20013
  outcome: "compressed",
19411
- trigger: invalidSummary ? "invalid-summary" : plan.diagnostics?.triggeredByRealUsage ? "real-usage" : "estimate",
20014
+ trigger: invalidSummary ? "invalid-summary" : plan.diagnostics?.triggeredByItemLimit ? "item-limit" : plan.diagnostics?.triggeredByRealUsage ? "real-usage" : "estimate",
20015
+ ...itemDiagnostics,
20016
+ ...maxInputItems !== void 0 ? { projectedItemCount } : {},
19412
20017
  ...plan.diagnostics ? {
19413
20018
  estimatedTokens: plan.diagnostics.totalUsed,
19414
20019
  historyBudget: plan.diagnostics.historyBudget,
@@ -19418,18 +20023,39 @@ async function maybeAutoCompactLocalHistory(args2) {
19418
20023
  }
19419
20024
  };
19420
20025
  } catch (error) {
19421
- console.warn("[localLoop] auto-compaction failed:", error);
19422
- const failureMessage = error instanceof Error && error.message ? error.message.slice(0, 200) : String(error).slice(0, 200);
19423
- const failureReason = error instanceof Error && "compactionReason" in error ? error.compactionReason : "provider-error";
20026
+ const safe = classifySummaryError(error, { model: summaryModel ?? void 0, provider: summaryProvider ?? void 0, attemptId: compactionAttemptId });
20027
+ summaryModel = safe.model ?? summaryModel;
20028
+ summaryProvider = safe.provider ?? summaryProvider;
20029
+ const failureReason = args2.abortSignal?.aborted || safe.category === "cancelled" || error?.compactionReason === "aborted" ? "aborted" : safe.category === "timeout" || error?.compactionReason === "timeout" ? "timeout" : "provider-error";
20030
+ const failureMessage = [safe.message, safe.code, safe.errorType, safe.balanceSource].filter(Boolean).join(" ");
20031
+ if (failureReason !== "aborted") console.warn("[localLoop] auto-compaction failed:", safe);
20032
+ summaryDiagnostics = {
20033
+ ...summaryDiagnostics,
20034
+ ...safe.finishReason === void 0 ? {} : { finishReason: safe.finishReason },
20035
+ ...safe.responseStatus === void 0 ? {} : { responseStatus: safe.responseStatus },
20036
+ ...safe.incompleteReason === void 0 ? {} : { incompleteReason: safe.incompleteReason },
20037
+ ...safe.maxOutputTokens === void 0 ? {} : { maxOutputTokens: safe.maxOutputTokens },
20038
+ ...safe.completionTokens === void 0 ? {} : { completionTokens: safe.completionTokens },
20039
+ ...safe.outputChars === void 0 ? {} : { outputChars: safe.outputChars }
20040
+ };
19424
20041
  logCompactionTiming(failureReason, {});
19425
20042
  const failureNow = args2.now?.() ?? Date.now();
19426
20043
  if (failureReason !== "aborted") recordCompactionFailure(dialogId, failureNow);
19427
- emitPhase({ kind: "compaction-failed", reason: failureReason });
20044
+ if (failureReason === "aborted") emitPhase({ kind: "compaction-end" });
20045
+ else emitPhase({ kind: "compaction-failed", reason: failureReason });
19428
20046
  return {
19429
20047
  ...projectExisting(),
19430
20048
  failureMessage,
19431
20049
  failureReason,
19432
- decision: { outcome: "failed", reason: failureReason, detail: failureMessage }
20050
+ failure: safe,
20051
+ decision: {
20052
+ outcome: "failed",
20053
+ reason: failureReason,
20054
+ detail: failureMessage,
20055
+ ...itemDiagnostics,
20056
+ estimatedTokens: plan.diagnostics?.totalUsed,
20057
+ historyBudget: plan.diagnostics?.historyBudget
20058
+ }
19433
20059
  };
19434
20060
  }
19435
20061
  }
@@ -19440,13 +20066,14 @@ function emitCompactionPhaseEvent(boundary, phase, scope3) {
19440
20066
  emitLoopEvent(boundary, { kind: "turn-phase", phase: "compacting", atMs, compactionScope: scope3 });
19441
20067
  emitLoopEvent(boundary, { kind: "compaction-start", atMs, scope: scope3 });
19442
20068
  } else if (phase.kind === "waiting-provider") emitLoopEvent(boundary, { kind: "turn-phase", phase: "waiting-provider", atMs, compactionScope: scope3 });
20069
+ else if (phase.kind === "compaction-retry") emitLoopEvent(boundary, { kind: "compaction-retry", atMs, scope: scope3, attempt: phase.attempt, maxAttempts: phase.maxAttempts });
19443
20070
  else if (phase.kind === "compaction-end") emitLoopEvent(boundary, { kind: "compaction-end", atMs, scope: scope3 });
19444
20071
  else emitLoopEvent(boundary, { kind: "compaction-failed", atMs, scope: scope3, reason: phase.reason });
19445
20072
  }
19446
20073
  function emitCompactionObservationEvent(boundary, compacted) {
19447
20074
  const decision = compacted.decision;
19448
20075
  if (decision?.outcome === "skipped") {
19449
- const isProtectionGap = decision.skipReason === "bounded-request-blocked" || decision.skipReason === "unsafe-projection" || decision.skipReason === "adapter-missing-summary-methods" || decision.skipReason === "load-summary-failed";
20076
+ const isProtectionGap = decision.skipReason === "bounded-request-blocked" || decision.skipReason === "unsafe-projection" || decision.skipReason === "no-safe-prefix" || decision.skipReason === "adapter-missing-summary-methods" || decision.skipReason === "load-summary-failed";
19450
20077
  const approachingBudget = decision.skipReason === "below-trigger" && typeof decision.estimatedTokens === "number" && typeof decision.historyBudget === "number" && decision.historyBudget > 0 && decision.estimatedTokens >= decision.historyBudget * 0.5;
19451
20078
  if (!isProtectionGap && !approachingBudget) return;
19452
20079
  }
@@ -19454,7 +20081,7 @@ function emitCompactionObservationEvent(boundary, compacted) {
19454
20081
  kind: "compaction",
19455
20082
  atMs: Date.now(),
19456
20083
  ...compacted.reason ? { reason: compacted.reason } : {},
19457
- ...compacted.withinSafetyBudget === false ? { detail: "Estimated projected history remains above the compaction safety budget" } : {},
20084
+ ...compacted.withinSafetyBudget === false ? { detail: "Projected history remains above the token or input-item safety budget" } : {},
19458
20085
  summaryGenerated: compacted.summaryGenerated,
19459
20086
  compressed: compacted.compressed,
19460
20087
  ...compacted.failureMessage ? { failed: true, detail: compacted.failureMessage } : {},
@@ -19464,6 +20091,12 @@ function emitCompactionObservationEvent(boundary, compacted) {
19464
20091
  ...decision && "historyBudget" in decision && decision.historyBudget !== void 0 ? { historyBudget: decision.historyBudget } : {},
19465
20092
  ...decision && "realUsageRatio" in decision && decision.realUsageRatio !== void 0 ? { realUsageRatio: decision.realUsageRatio } : {},
19466
20093
  ...decision && "triggerRatio" in decision && decision.triggerRatio !== void 0 ? { triggerRatio: decision.triggerRatio } : {},
20094
+ ...decision?.maxInputItems !== void 0 ? {
20095
+ itemCount: decision.itemCount,
20096
+ maxInputItems: decision.maxInputItems,
20097
+ triggeredByItemLimit: decision.triggeredByItemLimit,
20098
+ ...decision.projectedItemCount !== void 0 ? { projectedItemCount: decision.projectedItemCount } : {}
20099
+ } : {},
19467
20100
  ...compacted.beforeTokens !== void 0 ? { beforeTokens: compacted.beforeTokens } : {},
19468
20101
  ...compacted.afterTokens !== void 0 ? { afterTokens: compacted.afterTokens } : {},
19469
20102
  ...compacted.savedTokens !== void 0 ? { savedTokens: compacted.savedTokens } : {}
@@ -19482,7 +20115,7 @@ function createTurnCompactionController(args2) {
19482
20115
  }
19483
20116
  };
19484
20117
  const compactionDialogId = args2.continueDialogId ?? ephemeralDialogId;
19485
- const runInitial = async (history) => {
20118
+ const runCompaction = async (history, force) => {
19486
20119
  let realContextUsagePercent;
19487
20120
  if (args2.continueDialogId && typeof args2.adapter.loadLastContextUsage === "function") {
19488
20121
  try {
@@ -19505,15 +20138,21 @@ function createTurnCompactionController(args2) {
19505
20138
  adapter: args2.adapter,
19506
20139
  dialogId: args2.continueDialogId,
19507
20140
  history,
20141
+ contextReferenceResolver: args2.contextReferenceResolver,
19508
20142
  model: args2.model,
20143
+ provider: args2.provider,
20144
+ providerEndpoint: args2.providerEndpoint,
19509
20145
  resolveProvider: args2.resolveProvider,
19510
20146
  contextWindow: args2.contextWindow,
19511
20147
  realContextUsagePercent,
20148
+ force,
19512
20149
  abortSignal: args2.abortSignal,
19513
20150
  timeoutMs: args2.timeoutMs,
19514
20151
  summaryFallback: args2.summaryFallback,
20152
+ onAttemptUsage: args2.onUsage,
19515
20153
  onPhase: (phase) => emitPhase(phase, "initial")
19516
20154
  });
20155
+ args2.onSelectedSummary?.(compacted.selectedSummary ?? { outcome: "absent" });
19517
20156
  emitObservation(compacted);
19518
20157
  return { history: compacted.history, usage: compacted.usage };
19519
20158
  } catch (error) {
@@ -19521,11 +20160,25 @@ function createTurnCompactionController(args2) {
19521
20160
  return { history };
19522
20161
  }
19523
20162
  };
19524
- const maybeCompactInLoop = async () => {
20163
+ const runInitial = async (history) => runCompaction(history, false);
20164
+ const forceCompact = async (history) => {
20165
+ const result4 = await runCompaction(history, true);
20166
+ return { history: result4.history, applied: result4.history !== history, usage: result4.usage };
20167
+ };
20168
+ let lastCompactionOutcome;
20169
+ const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens) => {
20170
+ lastCompactionOutcome = void 0;
19525
20171
  const contextUsage = args2.getContextUsage();
19526
- const inputTokens = contextUsage ? normalizeUsage(contextUsage).input_tokens : 0;
20172
+ let inputTokens = contextUsage ? normalizeUsage(contextUsage).input_tokens : 0;
20173
+ if (initial && args2.continueDialogId && args2.adapter.loadLastContextUsage) {
20174
+ try {
20175
+ inputTokens = (await args2.adapter.loadLastContextUsage(args2.continueDialogId))?.inputTokens ?? 0;
20176
+ } catch (error) {
20177
+ console.warn("[localLoop] loadLastContextUsage failed:", error);
20178
+ }
20179
+ }
19527
20180
  const ratio = inputTokens > 0 ? Math.min(1, inputTokens / args2.contextWindow) : void 0;
19528
- if (ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85) {
20181
+ if (!requestOverBudget && ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85 && resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint }) === void 0) {
19529
20182
  return;
19530
20183
  }
19531
20184
  try {
@@ -19538,18 +20191,22 @@ function createTurnCompactionController(args2) {
19538
20191
  // 锚点与 sourceHash 都必须按持久化形态计算——否则下轮从 store
19539
20192
  // 重载后重算 hash 必不匹配,摘要被判无效、白付一次摘要调用。
19540
20193
  history: args2.getCanonicalCompactionHistory(),
20194
+ requestOverBudget,
20195
+ availableHistoryTokens: availableHistoryTokens?.(),
20196
+ contextReferenceResolver: args2.contextReferenceResolver,
19541
20197
  model: args2.model,
20198
+ provider: args2.provider,
20199
+ providerEndpoint: args2.providerEndpoint,
19542
20200
  resolveProvider: args2.resolveProvider,
19543
20201
  contextWindow: args2.contextWindow,
19544
20202
  ...ratio !== void 0 ? { realContextUsagePercent: ratio } : {},
19545
20203
  abortSignal: args2.abortSignal,
19546
20204
  timeoutMs: args2.timeoutMs,
19547
20205
  summaryFallback: args2.summaryFallback,
19548
- onPhase: (phase) => emitPhase(phase, "in-loop")
20206
+ onAttemptUsage: args2.onUsage,
20207
+ onPhase: (phase) => emitPhase(phase, initial ? "initial" : "in-loop")
19549
20208
  });
19550
- if (compacted.usage) {
19551
- args2.onUsage(compacted.usage);
19552
- }
20209
+ lastCompactionOutcome = { result: compacted };
19553
20210
  if (compacted.compressed) {
19554
20211
  const rebuilt = composeProviderMessages({
19555
20212
  prefix: args2.getWorkingPrefix(),
@@ -19564,16 +20221,65 @@ function createTurnCompactionController(args2) {
19564
20221
  }
19565
20222
  args2.replaceWorkingView(rebuilt.messages);
19566
20223
  }
20224
+ if (compacted.compressed || initial) {
20225
+ args2.onSelectedSummary?.(compacted.selectedSummary ?? { outcome: initial ? "absent" : "unknown" });
20226
+ }
19567
20227
  emitObservation(compacted);
19568
20228
  } catch (error) {
20229
+ lastCompactionOutcome = { ...lastCompactionOutcome, error: classifySummaryError(error) };
19569
20230
  console.warn("[localLoop] in-loop auto-compaction failed:", error);
19570
20231
  }
19571
20232
  };
19572
- return { runInitial, maybeCompactInLoop };
20233
+ return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: () => prepareRequest(), forceCompact, prepareRequest };
19573
20234
  }
19574
20235
 
19575
20236
  // packages/agent-runtime/providerCallTelemetry.ts
19576
20237
  import { createHash as createHash4 } from "node:crypto";
20238
+ var isCount = (v) => Number.isSafeInteger(v) && v >= 0;
20239
+ var isDigest = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
20240
+ var isMessageId = (v) => typeof v === "string" && /^(?:[0-9]{13}-[0-9]{3,6}|[0-9A-HJKMNP-TV-Z]{26}|local-[0-9]{1,12})$/.test(v);
20241
+ var isRecord2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
20242
+ function projectContextProvenance(value) {
20243
+ if (!isRecord2(value) || value.schemaVersion !== 1) return void 0;
20244
+ const transports = ["unknown", "local-cli", "direct-openai-compatible", "codex-oauth", "codex-responses", "owner-oauth-proxy", "server-proxy"];
20245
+ const result4 = { schemaVersion: 1, transport: transports.includes(value.transport) ? value.transport : "unknown" };
20246
+ if (Array.isArray(value.phases)) {
20247
+ result4.phases = [];
20248
+ for (const item of value.phases.slice(0, 8)) {
20249
+ if (!isRecord2(item) || !["history-loaded", "summary-projected", "budget-trim", "final-request"].includes(item.phase)) continue;
20250
+ const phase = { phase: item.phase };
20251
+ if (["local", "remote", "partial", "none", "unknown"].includes(item.source)) phase.source = item.source;
20252
+ for (const key of ["count", "droppedCount"]) if (isCount(item[key])) phase[key] = item[key];
20253
+ for (const key of ["hash", "idsHash"]) if (isDigest(item[key])) phase[key] = item[key];
20254
+ for (const key of ["firstId", "lastId"]) if (isMessageId(item[key])) phase[key] = item[key];
20255
+ result4.phases.push(phase);
20256
+ }
20257
+ }
20258
+ if (isRecord2(value.summary)) {
20259
+ const input = value.summary;
20260
+ const outcomes = ["absent", "loaded", "generated", "invalid", "skipped", "failed", "unknown"];
20261
+ const summary = { outcome: outcomes.includes(input.outcome) ? input.outcome : "unknown" };
20262
+ for (const key of ["summaryId", "hash", "sourceHash"]) if (isDigest(input[key])) summary[key] = input[key];
20263
+ if (isMessageId(input.anchorId)) summary.anchorId = input.anchorId;
20264
+ if (isCount(input.sourceCount)) summary.sourceCount = input.sourceCount;
20265
+ result4.summary = summary;
20266
+ }
20267
+ return result4;
20268
+ }
20269
+ function contextPhase(phase, messages, options = {}) {
20270
+ const digest = (value) => createHash4("sha256").update(JSON.stringify(value) ?? "null").digest("hex");
20271
+ const ids = messages.map((m) => isRecord2(m) && isMessageId(m.cliMessageId) ? m.cliMessageId : null);
20272
+ return {
20273
+ phase,
20274
+ count: messages.length,
20275
+ hash: digest(messages),
20276
+ idsHash: digest(ids),
20277
+ ...ids[0] ? { firstId: ids[0] } : {},
20278
+ ...ids.at(-1) ? { lastId: ids.at(-1) } : {},
20279
+ ...options.source ? { source: options.source } : {},
20280
+ ...isCount(options.droppedCount) ? { droppedCount: options.droppedCount } : {}
20281
+ };
20282
+ }
19577
20283
  var shortHash = (value) => createHash4("sha1").update(value).digest("hex").slice(0, 12);
19578
20284
  var hashMessage = (message) => {
19579
20285
  let text2;
@@ -19613,6 +20319,7 @@ function createDivergeTracker(max4 = DIVERGE_TRACKER_MAX_DIALOGS) {
19613
20319
  var processDivergeTracker = createDivergeTracker();
19614
20320
  function buildRequestTelemetry(args2) {
19615
20321
  try {
20322
+ const provenance = projectContextProvenance(args2.provenance);
19616
20323
  const hashes = args2.messages.map(hashMessage);
19617
20324
  let toolResultChars = 0;
19618
20325
  let toolResultCount = 0;
@@ -19628,6 +20335,7 @@ function buildRequestTelemetry(args2) {
19628
20335
  const diverge = (args2.tracker ?? processDivergeTracker).observe(args2.dialogKey, hashes);
19629
20336
  return {
19630
20337
  ...args2.toolsHash ? { toolsHash: args2.toolsHash } : {},
20338
+ ...provenance ? { provenance } : {},
19631
20339
  msgCount: args2.messages.length,
19632
20340
  contentChars,
19633
20341
  toolResultChars,
@@ -19647,13 +20355,23 @@ function hashToolDefinitions(tools) {
19647
20355
  }
19648
20356
 
19649
20357
  // packages/agent-runtime/localLoop.ts
20358
+ var LocalContextCoverageError = class extends Error {
20359
+ constructor(droppedCount, compactionUsage, diagnostics) {
20360
+ super("Context protection: history cannot fit without losing messages not represented in the sending context. This pending provider request was not sent; canonical history and pending input are retained. Restore summary access/provider availability and retry this same input, or select a larger context window. An invalid summary must be rebuilt before retrying.");
20361
+ this.droppedCount = droppedCount;
20362
+ this.compactionUsage = compactionUsage;
20363
+ this.diagnostics = diagnostics;
20364
+ this.name = "LocalContextCoverageError";
20365
+ }
20366
+ code = "LOCAL_CONTEXT_COVERAGE_REQUIRED";
20367
+ };
19650
20368
  var LOCAL_AGENT_CONFIG_MISSING_CODE = "LOCAL_AGENT_CONFIG_MISSING";
19651
20369
  var LLM_REQUEST_TIMEOUT = "LLM_REQUEST_TIMEOUT";
19652
20370
  var DEFAULT_LLM_REQUEST_TIMEOUT_MS = 10 * 60 * 1e3;
19653
20371
  var DEFAULT_COMPACTION_TIMEOUT_MS = 60 * 1e3;
19654
20372
  var DEFAULT_ROUND_BUDGET_WARNING_THRESHOLD = 25;
19655
20373
  function buildRoundBudgetWarningPrompt(threshold) {
19656
- return `[\u7CFB\u7EDF\u63D0\u793A] \u5F53\u524D\u5355\u6B21\u4EFB\u52A1\u7684\u8FDE\u7EED\u5DE5\u5177\u8C03\u7528\u5DF2\u8FBE ${threshold} \u8F6E\uFF0C\u8BF7\u8FDB\u884C\u8FDB\u5C55\u4E0E\u6210\u672C\u68C0\u67E5\uFF1A\u82E5\u5DF2\u6388\u6743\u76EE\u6807\u672A\u5B8C\u6210\u4E14\u6301\u7EED\u6709\u8FDB\u5C55\uFF0C\u5E94\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u4E0D\u5F97\u4EC5\u56E0\u8F6E\u6570\u4EA4\u63A5\uFF1B\u4EC5\u5728\u76EE\u6807\u5DF2\u5B8C\u6210\u3001\u9047\u5230\u771F\u5B9E\u963B\u585E\u6216\u89E6\u53CA\u786C\u9884\u7B97\u65F6\u624D\u6536\u5C3E\uFF1B\u82E5\u8FDB\u5C55\u505C\u6EDE\uFF0C\u8BF7\u53CA\u65F6\u66F4\u6362\u7B56\u7565\u3002`;
20374
+ return `[\u7CFB\u7EDF\u63D0\u793A] \u5F53\u524D\u5355\u6B21\u4EFB\u52A1\u7684\u8FDE\u7EED\u5DE5\u5177\u8C03\u7528\u5DF2\u8FBE ${threshold} \u8F6E\uFF0C\u8BF7\u8FDB\u884C\u8FDB\u5C55\u4E0E\u6210\u672C\u68C0\u67E5\uFF1A\u82E5\u5DF2\u6388\u6743\u76EE\u6807\u672A\u5B8C\u6210\u4E14\u6301\u7EED\u6709\u8FDB\u5C55\uFF0C\u5E94\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u4E0D\u5F97\u4EC5\u56E0\u8F6E\u6570\u4EA4\u63A5\uFF1B\u4EC5\u5728\u76EE\u6807\u5DF2\u5B8C\u6210\u3001\u9047\u5230\u771F\u5B9E\u963B\u585E\u6216\u7528\u6237\u660E\u786E\u505C\u6B62\u65F6\u624D\u6536\u5C3E\uFF1B\u82E5\u8FDB\u5C55\u505C\u6EDE\uFF0C\u8BF7\u53CA\u65F6\u66F4\u6362\u7B56\u7565\u3002`;
19657
20375
  }
19658
20376
  var ROUND_BUDGET_WARNING_PROMPT = buildRoundBudgetWarningPrompt(
19659
20377
  DEFAULT_ROUND_BUDGET_WARNING_THRESHOLD
@@ -19683,23 +20401,24 @@ var CONCURRENT_READONLY_TOOLS = /* @__PURE__ */ new Set([
19683
20401
  ]);
19684
20402
  function partitionToolCallsIntoBatches(toolCalls) {
19685
20403
  const batches = [];
19686
- let currentReadBatch = [];
19687
- for (let i = 0; i < toolCalls.length; i += 1) {
19688
- const toolCall = toolCalls[i];
19689
- const isReadOnly = CONCURRENT_READONLY_TOOLS.has(toolCall.function.name);
19690
- if (isReadOnly) {
19691
- currentReadBatch.push({ index: i, toolCall });
19692
- } else {
19693
- if (currentReadBatch.length > 0) {
19694
- batches.push({ isConcurrent: true, calls: currentReadBatch });
19695
- currentReadBatch = [];
19696
- }
19697
- batches.push({ isConcurrent: false, calls: [{ index: i, toolCall }] });
20404
+ let currentBatch = [];
20405
+ const flush2 = () => {
20406
+ if (currentBatch.length) batches.push({ isConcurrent: true, calls: currentBatch });
20407
+ currentBatch = [];
20408
+ };
20409
+ for (let index = 0; index < toolCalls.length; index += 1) {
20410
+ const toolCall = toolCalls[index];
20411
+ const contract = resolveToolExecutionContract(toolCall.function.name);
20412
+ const isReadOnly = contract.interaction === "none" && contract.concurrency === "safe";
20413
+ const legacyRead = contract.concurrency === "exclusive" && contract.interaction === "unknown" && CONCURRENT_READONLY_TOOLS.has(toolCall.function.name);
20414
+ if (toolCall.function.name === "startAgentRun" || !isReadOnly && !legacyRead) {
20415
+ flush2();
20416
+ batches.push({ isConcurrent: false, calls: [{ index, toolCall }] });
20417
+ continue;
19698
20418
  }
20419
+ currentBatch.push({ index, toolCall });
19699
20420
  }
19700
- if (currentReadBatch.length > 0) {
19701
- batches.push({ isConcurrent: true, calls: currentReadBatch });
19702
- }
20421
+ flush2();
19703
20422
  return batches;
19704
20423
  }
19705
20424
  function resolveLlmRequestTimeoutMs(input) {
@@ -19708,7 +20427,7 @@ function resolveLlmRequestTimeoutMs(input) {
19708
20427
  }
19709
20428
  function resolveCompactionTimeoutMs(input) {
19710
20429
  const raw = input.compactionTimeoutMs;
19711
- return typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_COMPACTION_TIMEOUT_MS;
20430
+ return typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.min(raw, DEFAULT_COMPACTION_TIMEOUT_MS) : DEFAULT_COMPACTION_TIMEOUT_MS;
19712
20431
  }
19713
20432
  function readHostCompactionSummaryFallback(adapter) {
19714
20433
  const value = adapter.compactionSummaryFallback;
@@ -19876,6 +20595,18 @@ async function loadAdapterDialogHistory(adapter, dialogId, options) {
19876
20595
  }
19877
20596
  return { messages: await adapter.loadDialogHistory(dialogId) };
19878
20597
  }
20598
+ function combineRollbackError(primary, rollbackError) {
20599
+ const primaryError = primary instanceof Error ? primary : new Error(String(primary));
20600
+ const rollbackErr = rollbackError instanceof Error ? rollbackError : new Error(String(rollbackError));
20601
+ const combined = new AggregateError(
20602
+ [primaryError, rollbackErr],
20603
+ `${primaryError.message} (additionally, injection rollback failed: ${rollbackErr.message})`
20604
+ );
20605
+ if (primary && typeof primary === "object") {
20606
+ Object.assign(combined, primary);
20607
+ }
20608
+ return combined;
20609
+ }
19879
20610
  async function runLocalAgentTurn(input) {
19880
20611
  const legacyCallbacks = {
19881
20612
  onLoopEvent: input.onLoopEvent,
@@ -19889,17 +20620,6 @@ async function runLocalAgentTurn(input) {
19889
20620
  observationBoundary.attachCallbacks(legacyCallbacks);
19890
20621
  }
19891
20622
  const loopTiming = createLoopTiming();
19892
- const subtaskBudgetClock = input.subtaskBudgetNow ?? (() => Date.now());
19893
- const subtaskBudgetLimits = {
19894
- maxToolCalls: input.subtaskMaxToolCalls ?? input.subtaskBudgetLimits?.maxToolCalls ?? DEFAULT_SUBTASK_MAX_TOOL_CALLS,
19895
- maxWallClockMs: input.subtaskMaxWallClockMs ?? input.subtaskBudgetLimits?.maxWallClockMs ?? DEFAULT_SUBTASK_MAX_WALL_CLOCK_MS
19896
- };
19897
- const subtaskBudgetTracker = input.runKind === "subtask" ? createSubtaskBudgetTracker({
19898
- limits: subtaskBudgetLimits,
19899
- now: subtaskBudgetClock,
19900
- // 墙钟从 run 开始计(含 provider 初始化与首轮前的准备)。
19901
- startedAtMs: subtaskBudgetClock()
19902
- }) : null;
19903
20623
  try {
19904
20624
  loopTiming.mark("turnStart", 0);
19905
20625
  let agentConfig = await input.adapter.loadAgentConfig(input.agentRef);
@@ -19987,7 +20707,8 @@ async function runLocalAgentTurn(input) {
19987
20707
  if (input.strictContinueHistory && (loaded.source === "none" || loaded.source === "partial")) {
19988
20708
  throw new Error(`Strict continuation history unavailable: ${loaded.source}`);
19989
20709
  }
19990
- history = loaded.messages;
20710
+ const currentIds = new Set(input.userMessages?.map((message) => message.cliMessageId));
20711
+ history = loaded.messages.filter((message) => !currentIds.has(message.cliMessageId));
19991
20712
  dialogHistorySource = loaded.source;
19992
20713
  }
19993
20714
  } catch (error) {
@@ -20073,6 +20794,9 @@ async function runLocalAgentTurn(input) {
20073
20794
  // 平台风控纪律:无条件系统层块,沿用 session 占位约定。
20074
20795
  { content: PLATFORM_RISK_CONTROL_RULE, cacheScope: "session" },
20075
20796
  { content: buildConsultationModeBlock(), cacheScope: "session" },
20797
+ // Git 任务隔离:系统层固定前置,四条装配线同序(请教模式之后、身份信息之前;
20798
+ // skill 配置 disabled 也注入)。
20799
+ { content: WORKTREE_ISOLATION_PRELUDE, cacheScope: "session" },
20076
20800
  { content: identityBlock, cacheScope: "session" },
20077
20801
  ...guidanceScopes,
20078
20802
  // 回复行为准则:local 线(CLI 非交互 / 桌面 / TUI)的唯一注入边界。
@@ -20092,19 +20816,29 @@ async function runLocalAgentTurn(input) {
20092
20816
  let resolvedSummaryProvider;
20093
20817
  const resolveSummaryProviderOnce = async () => {
20094
20818
  if (!resolvedSummaryProvider) {
20095
- resolvedSummaryProvider = await input.adapter.resolveProvider(agentConfig, {
20819
+ const provider = await input.adapter.resolveProvider(agentConfig, {
20820
+ textOnly: true,
20096
20821
  toolNames: [],
20097
20822
  prompt: ""
20098
20823
  });
20824
+ if (provider.textOnly !== true) {
20825
+ throw new Error("auto-compaction requires an isolated text-only provider");
20826
+ }
20827
+ resolvedSummaryProvider = provider;
20099
20828
  }
20100
20829
  return resolvedSummaryProvider;
20101
20830
  };
20102
20831
  const contextWindow = resolveAgentContextWindow(agentConfig);
20103
20832
  const compressionTriggerRatio = resolveCompressionTriggerRatio(contextWindow);
20833
+ let selectedSummary = { outcome: "unknown" };
20834
+ let summaryProjectedPhase = contextPhase("summary-projected", history);
20835
+ const historyLoadedPhase = contextPhase("history-loaded", history, { source: dialogHistorySource ?? "unknown" });
20104
20836
  const compaction = createTurnCompactionController({
20105
20837
  adapter: input.adapter,
20106
20838
  continueDialogId: input.continueDialogId,
20107
20839
  model: agentConfig.model,
20840
+ provider: agentConfig.provider,
20841
+ providerEndpoint: agentConfig.customProviderUrl,
20108
20842
  resolveProvider: resolveSummaryProviderOnce,
20109
20843
  contextWindow,
20110
20844
  compressionTriggerRatio,
@@ -20117,27 +20851,29 @@ async function runLocalAgentTurn(input) {
20117
20851
  summaryFallback: input.compactionSummaryFallback ?? readHostCompactionSummaryFallback(input.adapter),
20118
20852
  boundary: observationBoundary,
20119
20853
  getContextUsage: () => usageLedger.lastContextUsage(),
20120
- getCanonicalCompactionHistory: () => [
20854
+ getCanonicalCompactionHistory: () => orderDialogHistory([
20121
20855
  ...canonicalHistory,
20122
20856
  ...transcript.persisted(
20123
20857
  sanitizedPersistedInput,
20124
20858
  input.persistedInputReference
20125
- )
20126
- ],
20859
+ ).map((message) => {
20860
+ const receipt = message.cliMessageId;
20861
+ return receipt ? { ...message, id: receipt } : message;
20862
+ })
20863
+ ]),
20127
20864
  getWorkingPrefix: () => transcript.working().slice(0, prefixCount),
20128
- replaceWorkingView: (next) => transcript.replaceWorkingHistory(next),
20865
+ onSelectedSummary: (summary) => {
20866
+ selectedSummary = summary;
20867
+ },
20868
+ replaceWorkingView: (next) => {
20869
+ transcript.replaceWorkingHistory(next);
20870
+ summaryProjectedPhase = contextPhase("summary-projected", next);
20871
+ },
20129
20872
  contextReferenceResolver: input.adapter.host === "cli" ? input.contextReferenceResolver : void 0,
20130
20873
  onUsage: (usage) => usageLedger.addCompaction(usage)
20131
20874
  });
20132
- const initialCompaction = await compaction.runInitial(history);
20133
- history = initialCompaction.history;
20134
- const initialCompactionUsage = initialCompaction.usage;
20135
- loopTiming.mark("maybeAutoCompactLocalHistory", 0);
20136
- const trimmedHistory = trimHistoryToContextBudget(history, agentConfig.model, contextWindow);
20137
- if (trimmedHistory.droppedCount > 0) {
20138
- history = trimmedHistory.history;
20139
- }
20140
- loopTiming.mark("trimHistoryToContextBudget", 0);
20875
+ throwIfAborted(input);
20876
+ let budgetTrimPhase = contextPhase("budget-trim", history, { droppedCount: 0 });
20141
20877
  const builtMessages = buildMessages({
20142
20878
  prompt: agentConfig.prompt,
20143
20879
  contextBlockScopes: mergedContextBlockScopes,
@@ -20169,6 +20905,19 @@ async function runLocalAgentTurn(input) {
20169
20905
  ...msg,
20170
20906
  content: truncateToolOutputForContext(msg.content, contextWindow)
20171
20907
  } : msg;
20908
+ if (input.userMessages?.length) {
20909
+ const currentInputStart = builtMessages.prefixCount + history.length;
20910
+ const sanitizedUsers = await Promise.all(input.userMessages.map(async (message) => ({
20911
+ ...message,
20912
+ content: await sanitizeInbound(message.content)
20913
+ })));
20914
+ messages.splice(currentInputStart, messages.length - currentInputStart, ...sanitizedUsers);
20915
+ }
20916
+ if (!input.userMessages?.length && input.adapter.host === "cli") {
20917
+ const userIndex = builtMessages.prefixCount + history.length;
20918
+ const id = dialogTurnUserMessageId(input.runtimeContext?.turnId, 0);
20919
+ if (id && messages[userIndex]?.role === "user") messages[userIndex] = { ...messages[userIndex], id };
20920
+ }
20172
20921
  const acceptToolImages = createToolImageLedger();
20173
20922
  const transcript = createTurnTranscript({
20174
20923
  initialWorking: messages,
@@ -20178,7 +20927,9 @@ async function runLocalAgentTurn(input) {
20178
20927
  });
20179
20928
  const userInputText = extractUserInputText(input.input);
20180
20929
  let toolCallCount = 0;
20930
+ let requestCalibrationRatio = 1;
20181
20931
  let result4 = { content: "" };
20932
+ let stopReason;
20182
20933
  const usageLedger = createTurnUsageLedger({
20183
20934
  model: agentConfig.model,
20184
20935
  provider: agentConfig.provider,
@@ -20187,77 +20938,127 @@ async function runLocalAgentTurn(input) {
20187
20938
  stablePrefixEstimatedTokens: builtMessages.stablePrefixEstimatedTokens
20188
20939
  } : {}
20189
20940
  });
20190
- if (initialCompactionUsage) usageLedger.addCompaction(initialCompactionUsage);
20191
20941
  let loopError;
20942
+ let consumedInjectedMessages = false;
20192
20943
  let round = 0;
20193
- let budgetExhaustion = null;
20194
- const executedToolNameLog = [];
20195
- const markBudgetExhausted = () => {
20196
- if (!subtaskBudgetTracker || budgetExhaustion) return;
20197
- const exhaustion = subtaskBudgetTracker.exhaustion();
20198
- if (!exhaustion) return;
20199
- budgetExhaustion = exhaustion;
20200
- emitLoopEvent(observationBoundary, {
20201
- kind: "budget-exhausted",
20202
- limit: exhaustion.limit,
20203
- atMs: exhaustion.atMs,
20204
- maxToolCalls: exhaustion.limits.maxToolCalls,
20205
- maxWallClockMs: exhaustion.limits.maxWallClockMs,
20206
- toolCallsExecuted: exhaustion.toolCallsExecuted,
20207
- elapsedMs: exhaustion.elapsedMs,
20208
- round
20209
- });
20210
- };
20211
20944
  let emptyAssistantRepairPending = false;
20212
20945
  let emptyAssistantRepairUsed = false;
20213
20946
  let reasoningEmptyRepairCount = 0;
20214
20947
  let skipFinalAppend = false;
20215
20948
  let partialContent = "";
20216
20949
  const progressGuard = createLocalLoopProgressGuard(input.progressGuardConfig);
20217
- const budgetAdmissionGate = () => {
20218
- if (!subtaskBudgetTracker) return true;
20219
- if (!subtaskBudgetTracker.isExhausted()) return true;
20220
- markBudgetExhausted();
20221
- return false;
20950
+ let pendingInjectionCommits = [];
20951
+ let inFlightTransactions = [];
20952
+ let rollbackInjectionCommits = async () => {
20222
20953
  };
20223
20954
  try {
20224
20955
  const provider = await resolveProviderOnce();
20225
- const applyPendingInjections = () => {
20956
+ const applyPendingInjections = async () => {
20226
20957
  if (!input.drainInjections) return false;
20227
- let pending = [];
20228
- try {
20229
- pending = input.drainInjections() ?? [];
20230
- } catch (error) {
20231
- console.warn("[localLoop] drainInjections failed:", error);
20232
- return false;
20233
- }
20958
+ const pending = await input.drainInjections() ?? [];
20234
20959
  let injected = false;
20235
- for (const text2 of pending) {
20236
- if (typeof text2 !== "string" || !text2.trim()) continue;
20237
- const safeText = scrubSecrets(text2).cleaned;
20238
- transcript.push({ role: "user", content: safeText });
20960
+ for (const entry of pending) {
20961
+ if (typeof entry === "string") {
20962
+ if (!entry.trim()) continue;
20963
+ transcript.push({ role: "user", content: scrubSecrets(entry).cleaned });
20964
+ } else if (entry && typeof entry === "object" && "messages" in entry) {
20965
+ for (const message of entry.messages) {
20966
+ const content = typeof message.content === "string" ? scrubSecrets(message.content).cleaned : Array.isArray(message.content) ? message.content.map((part) => part?.type === "text" && typeof part.text === "string" ? { ...part, text: scrubSecrets(part.text).cleaned } : part) : message.content;
20967
+ transcript.push({
20968
+ role: "user",
20969
+ content,
20970
+ ...message.cliMessageId ? { cliMessageId: message.cliMessageId } : {},
20971
+ ...Number.isFinite(message.cliHistoryOrder) ? { cliHistoryOrder: message.cliHistoryOrder } : {}
20972
+ });
20973
+ }
20974
+ pendingInjectionCommits.push({ commit: entry.commit, rollback: entry.rollback, messages: entry.messages });
20975
+ } else if (entry && typeof entry === "object" && "content" in entry) {
20976
+ const content = typeof entry.content === "string" ? scrubSecrets(entry.content).cleaned : Array.isArray(entry.content) ? entry.content.map((part) => part?.type === "text" && typeof part.text === "string" ? { ...part, text: scrubSecrets(part.text).cleaned } : part) : entry.content;
20977
+ transcript.push({
20978
+ role: "user",
20979
+ content,
20980
+ ...entry.cliMessageId ? { cliMessageId: entry.cliMessageId } : {}
20981
+ });
20982
+ } else {
20983
+ continue;
20984
+ }
20985
+ consumedInjectedMessages = true;
20239
20986
  injected = true;
20240
20987
  }
20241
20988
  return injected;
20242
20989
  };
20990
+ rollbackInjectionCommits = async (transactions) => {
20991
+ const errors = [];
20992
+ for (const transaction of transactions.slice().reverse()) {
20993
+ try {
20994
+ await transaction.rollback();
20995
+ } catch (rollbackError) {
20996
+ errors.push(rollbackError);
20997
+ }
20998
+ const ids = new Set(
20999
+ transaction.messages.map((message) => message.cliMessageId).filter((id) => Boolean(id))
21000
+ );
21001
+ if (ids.size > 0) {
21002
+ transcript.retract((msg) => {
21003
+ const id = msg.cliMessageId;
21004
+ return typeof id === "string" && ids.has(id);
21005
+ });
21006
+ }
21007
+ }
21008
+ if (errors.length > 0) {
21009
+ throw new Error(
21010
+ `injection rollback failed: ${errors.map((error) => error instanceof Error ? error.message : String(error)).join("; ")}`
21011
+ );
21012
+ }
21013
+ };
20243
21014
  const newDialogTelemetryKey = `new:${crypto.randomUUID()}`;
20244
21015
  let roundBudgetWarningInjected = false;
20245
- let subtaskToolBudgetWarningInjected = false;
20246
21016
  const roundWarningThreshold = input.roundBudgetWarningThreshold ?? DEFAULT_ROUND_BUDGET_WARNING_THRESHOLD;
20247
21017
  while (true) {
20248
21018
  partialContent = "";
20249
21019
  throwIfAborted(input);
20250
21020
  loopTiming.mark("roundStart", round);
20251
- applyPendingInjections();
21021
+ await applyPendingInjections();
20252
21022
  if (roundWarningThreshold > 0 && round >= roundWarningThreshold && !roundBudgetWarningInjected) {
20253
21023
  const prompt = buildRoundBudgetWarningPrompt(roundWarningThreshold);
20254
21024
  transcript.push({ role: "user", content: prompt });
20255
21025
  roundBudgetWarningInjected = true;
20256
21026
  }
20257
- if (subtaskBudgetTracker && !subtaskToolBudgetWarningInjected && subtaskBudgetTracker.toolCallsExecuted > 0 && subtaskBudgetTracker.remainingToolCalls() > 0 && subtaskBudgetTracker.remainingToolCalls() <= Math.max(1, Math.ceil(subtaskBudgetTracker.limits.maxToolCalls * 0.1))) {
20258
- transcript.push({ role: "user", content: `\u5B50\u4EFB\u52A1\u5DE5\u5177\u9884\u7B97\u5373\u5C06\u7528\u5C3D\uFF08\u5269\u4F59 ${subtaskBudgetTracker.remainingToolCalls()} \u6B21\uFF09\u3002\u8BF7\u4F18\u5148\u6536\u5C3E\u5E76\u7ED9\u51FA\u53EF\u8BFB\u7684\u9636\u6BB5\u7ED3\u679C\u3002` });
20259
- subtaskToolBudgetWarningInjected = true;
20260
- }
21027
+ const projectRequest = (source) => {
21028
+ const prepared = prepareMessagesForProviderCall(source);
21029
+ const base = filterImagePartsFromMessages(prepared.messages, supportsImages);
21030
+ return emptyAssistantRepairPending ? [...base, { role: "user", content: EMPTY_ASSISTANT_REPAIR_PROMPT }] : base;
21031
+ };
21032
+ const admissionProvider = await resolveProviderOnce();
21033
+ throwIfAborted(input);
21034
+ const requestOverBudget = (messages2) => !evaluateLocalRequestBudget({
21035
+ messages: messages2,
21036
+ contextWindow,
21037
+ descriptor: admissionProvider.requestBudget,
21038
+ calibrationRatio: requestCalibrationRatio
21039
+ }).fitsEstimate;
21040
+ const availableHistoryTokens = () => {
21041
+ const decision = evaluateLocalRequestBudget({
21042
+ messages: [],
21043
+ contextWindow,
21044
+ descriptor: admissionProvider.requestBudget,
21045
+ calibrationRatio: requestCalibrationRatio
21046
+ });
21047
+ const prefixTokens = estimateLocalRequestInput(projectRequest(transcript.working().slice(0, prefixCount)));
21048
+ return Math.max(0, Math.floor(decision.availableInputTokens / requestCalibrationRatio) - prefixTokens - (admissionProvider.requestBudget?.toolSchemaTokens ?? 0));
21049
+ };
21050
+ const historyTokensBeforeCompaction = Math.ceil(estimateLocalRequestInput(
21051
+ projectRequest(transcript.working()).slice(prefixCount)
21052
+ ) * requestCalibrationRatio);
21053
+ await compaction.prepareRequest((source) => {
21054
+ const projected = composeProviderMessages({
21055
+ prefix: transcript.working().slice(0, prefixCount),
21056
+ history: source,
21057
+ contextReferenceResolver: input.adapter.host === "cli" ? input.contextReferenceResolver : void 0
21058
+ });
21059
+ return requestOverBudget(projectRequest(projected.messages));
21060
+ }, round === 0, availableHistoryTokens);
21061
+ throwIfAborted(input);
20261
21062
  const preparedMessages = prepareMessagesForProviderCall(transcript.working());
20262
21063
  if (!supportsImages && hasImageInRuntimeMessages(preparedMessages.messages) && !imageDowngradeEmitted) {
20263
21064
  emitLoopEvent(observationBoundary, {
@@ -20267,11 +21068,27 @@ async function runLocalAgentTurn(input) {
20267
21068
  });
20268
21069
  imageDowngradeEmitted = true;
20269
21070
  }
20270
- const baseRequestMessages = filterImagePartsFromMessages(
20271
- preparedMessages.messages,
20272
- supportsImages
20273
- );
20274
- const requestMessages = emptyAssistantRepairPending ? [...baseRequestMessages, { role: "user", content: EMPTY_ASSISTANT_REPAIR_PROMPT }] : baseRequestMessages;
21071
+ const requestMessages = projectRequest(transcript.working());
21072
+ if (requestOverBudget(requestMessages)) {
21073
+ const budget = evaluateLocalRequestBudget({
21074
+ messages: requestMessages,
21075
+ contextWindow,
21076
+ descriptor: admissionProvider.requestBudget,
21077
+ calibrationRatio: requestCalibrationRatio
21078
+ });
21079
+ const largestMessageTokens = requestMessages.reduce((largest, message) => Math.max(
21080
+ largest,
21081
+ Math.ceil(estimateLocalRequestInput([message]) * requestCalibrationRatio)
21082
+ ), 0);
21083
+ throw new LocalContextCoverageError(0, void 0, classifyContextRefusal({
21084
+ outcome: compaction.getLastCompactionOutcome(),
21085
+ historyTokens: historyTokensBeforeCompaction,
21086
+ budget: budget.availableInputTokens,
21087
+ droppedCount: 0,
21088
+ largestMessageTokens
21089
+ }));
21090
+ }
21091
+ budgetTrimPhase = contextPhase("budget-trim", requestMessages, { droppedCount: 0 });
20275
21092
  const contextMetrics = {
20276
21093
  ...preparedMessages.metrics,
20277
21094
  messageCount: requestMessages.length,
@@ -20299,63 +21116,109 @@ async function runLocalAgentTurn(input) {
20299
21116
  // 无 dialogId 的新对话用本 turn 唯一键,避免不同新对话共用一个槽误报漂移。
20300
21117
  dialogKey: input.continueDialogId || newDialogTelemetryKey,
20301
21118
  messages: requestMessages,
21119
+ provenance: {
21120
+ schemaVersion: 1,
21121
+ transport: provider.transport ?? "unknown",
21122
+ phases: [historyLoadedPhase, summaryProjectedPhase, budgetTrimPhase, contextPhase("final-request", requestMessages)],
21123
+ summary: selectedSummary
21124
+ },
20302
21125
  toolsHash: safeToolNamesHash(agentTools)
20303
21126
  });
20304
- if (!budgetAdmissionGate()) {
20305
- break;
20306
- }
20307
21127
  resetToolImageDelivery(requestMessages.flatMap(toolImages));
20308
- result4 = await runCompleteWithTimeout({
20309
- provider,
20310
- messages: requestMessages,
20311
- options: {
21128
+ if (pendingInjectionCommits.length > 0) {
21129
+ inFlightTransactions = pendingInjectionCommits.splice(0);
21130
+ try {
21131
+ for (const transaction of inFlightTransactions) await transaction.commit();
21132
+ if (input.abortSignal?.aborted) throw buildAbortedError();
21133
+ } catch (error) {
21134
+ const toRollback = inFlightTransactions;
21135
+ inFlightTransactions = [];
21136
+ try {
21137
+ await rollbackInjectionCommits(toRollback);
21138
+ } catch (rbErr) {
21139
+ throw combineRollbackError(error, rbErr);
21140
+ }
21141
+ throw error;
21142
+ }
21143
+ }
21144
+ let providerInvoked = false;
21145
+ try {
21146
+ result4 = await runCompleteWithTimeout({
21147
+ provider: { complete: (messages2, options) => {
21148
+ providerInvoked = true;
21149
+ inFlightTransactions = [];
21150
+ return provider.complete(messages2, options);
21151
+ } },
21152
+ messages: requestMessages,
21153
+ options: {
21154
+ timeoutMs: resolveLlmRequestTimeoutMs(input),
21155
+ // 用户取消信号穿进 provider options:providerStreamRetry 据此在
21156
+ // 取消后跳过重试,provider 分支(如 antigravity/openai-compatible)
21157
+ // 也可把 fetch 绑定到同一信号,实现真正的传输层取消。
21158
+ ...input.abortSignal ? { signal: input.abortSignal } : {},
21159
+ // 计费归因:续聊轮次带上 dialogId,platform proxy 才能把 token 记录
21160
+ // 归到具体对话而不是 chat-proxy 兜底桶。新对话首轮 id 尚未分配。
21161
+ ...input.continueDialogId ? { dialogId: input.continueDialogId } : {},
21162
+ ...shouldStreamDeltas ? { onTextDelta: (chunk) => {
21163
+ llmStreamActivity += 1;
21164
+ partialContent += chunk;
21165
+ observationBoundary.emit({
21166
+ kind: "text-delta",
21167
+ chunk,
21168
+ round,
21169
+ atMs: Date.now()
21170
+ });
21171
+ } } : {},
21172
+ ...shouldStreamReasoning ? { onReasoningDelta: (chunk) => {
21173
+ llmStreamActivity += 1;
21174
+ observationBoundary.emit({
21175
+ kind: "reasoning-delta",
21176
+ chunk,
21177
+ round,
21178
+ atMs: Date.now()
21179
+ });
21180
+ } } : {},
21181
+ ...shouldPassToolEvents ? { onToolEvent: (event) => {
21182
+ llmStreamActivity += 1;
21183
+ observationBoundary.emit({
21184
+ kind: "tool-event",
21185
+ event,
21186
+ round,
21187
+ atMs: Date.now()
21188
+ });
21189
+ } } : {},
21190
+ ...shouldPassToolEvents ? { toolEventRound: round } : {}
21191
+ },
20312
21192
  timeoutMs: resolveLlmRequestTimeoutMs(input),
20313
- // 用户取消信号穿进 provider options:providerStreamRetry 据此在
20314
- // 取消后跳过重试,provider 分支(如 antigravity/openai-compatible)
20315
- // 也可把 fetch 绑定到同一信号,实现真正的传输层取消。
20316
- ...input.abortSignal ? { signal: input.abortSignal } : {},
20317
- // 计费归因:续聊轮次带上 dialogId,platform proxy 才能把 token 记录
20318
- // 归到具体对话而不是 chat-proxy 兜底桶。新对话首轮 id 尚未分配。
20319
- ...input.continueDialogId ? { dialogId: input.continueDialogId } : {},
20320
- ...shouldStreamDeltas ? { onTextDelta: (chunk) => {
20321
- llmStreamActivity += 1;
20322
- partialContent += chunk;
20323
- observationBoundary.emit({
20324
- kind: "text-delta",
20325
- chunk,
20326
- round,
20327
- atMs: Date.now()
20328
- });
20329
- } } : {},
20330
- ...shouldStreamReasoning ? { onReasoningDelta: (chunk) => {
20331
- llmStreamActivity += 1;
20332
- observationBoundary.emit({
20333
- kind: "reasoning-delta",
20334
- chunk,
20335
- round,
20336
- atMs: Date.now()
20337
- });
20338
- } } : {},
20339
- ...shouldPassToolEvents ? { onToolEvent: (event) => {
20340
- llmStreamActivity += 1;
20341
- observationBoundary.emit({
20342
- kind: "tool-event",
20343
- event,
20344
- round,
20345
- atMs: Date.now()
20346
- });
20347
- } } : {},
20348
- ...shouldPassToolEvents ? { toolEventRound: round } : {}
20349
- },
20350
- timeoutMs: resolveLlmRequestTimeoutMs(input),
20351
- activityVersion: () => llmStreamActivity,
20352
- round,
20353
- input,
20354
- boundary: observationBoundary,
20355
- context: contextMetrics,
20356
- providerName: agentConfig.provider,
20357
- model: provider.model
20358
- });
21193
+ activityVersion: () => llmStreamActivity,
21194
+ round,
21195
+ input,
21196
+ boundary: observationBoundary,
21197
+ context: contextMetrics,
21198
+ providerName: agentConfig.provider,
21199
+ model: provider.model
21200
+ });
21201
+ } catch (error) {
21202
+ if (!providerInvoked && inFlightTransactions.length > 0) {
21203
+ const toRollback = inFlightTransactions;
21204
+ inFlightTransactions = [];
21205
+ try {
21206
+ await rollbackInjectionCommits(toRollback);
21207
+ } catch (rbErr) {
21208
+ error = combineRollbackError(error, rbErr);
21209
+ }
21210
+ }
21211
+ if (providerInvoked) usageLedger.recordProviderCall({
21212
+ model: agentConfig.model,
21213
+ telemetry: {
21214
+ ...requestTelemetry,
21215
+ round,
21216
+ endTs: Date.now(),
21217
+ requestState: input.abortSignal?.aborted ? "cancelled" : "failed"
21218
+ }
21219
+ });
21220
+ throw error;
21221
+ }
20359
21222
  acceptToolImages.discard(requestMessages.flatMap(toolImages).filter((image) => toolImageDelivery(image) === "impossible"));
20360
21223
  acceptToolImages.commit(
20361
21224
  requestMessages.flatMap(toolImages).filter((image) => toolImageDelivery(image) === "delivered"),
@@ -20365,13 +21228,25 @@ async function runLocalAgentTurn(input) {
20365
21228
  const pending = toolImages(message).filter((image) => supportsImages && !toolImageDelivery(image));
20366
21229
  return pending.length ? { ...message, [TOOL_IMAGES]: pending } : stripToolImages(message);
20367
21230
  }));
21231
+ const actualInput = normalizeUsage(result4.usage).input_tokens;
21232
+ const estimatedInput = estimateLocalRequestInput(
21233
+ requestMessages,
21234
+ admissionProvider.requestBudget?.toolSchemaTokens ?? 0
21235
+ );
21236
+ requestCalibrationRatio = updateLocalRequestCalibration(requestCalibrationRatio, actualInput, estimatedInput);
20368
21237
  loopTiming.mark("llmCall", round);
20369
21238
  usageLedger.recordProviderCall({
20370
21239
  usage: result4.usage,
20371
21240
  model: result4.model,
20372
21241
  provider: result4.provider,
20373
- telemetry: finalizeCallTelemetry(requestTelemetry, result4, round, callStartedAt)
21242
+ telemetry: { ...finalizeCallTelemetry(requestTelemetry, result4, round, callStartedAt), requestState: "completed" }
20374
21243
  });
21244
+ if (!result4.content && result4.output?.some((block) => block.type === "text") && !result4.output.some((block) => block.type === "toolCall")) {
21245
+ result4 = {
21246
+ ...result4,
21247
+ content: result4.output.filter((block) => block.type === "text").map((block) => block.text).join("")
21248
+ };
21249
+ }
20375
21250
  const assistantGuardVerdict = progressGuard.observeAssistantResponse(result4);
20376
21251
  if (assistantGuardVerdict.action === "stall") {
20377
21252
  emitLoopEvent(observationBoundary, {
@@ -20389,11 +21264,11 @@ async function runLocalAgentTurn(input) {
20389
21264
  };
20390
21265
  break;
20391
21266
  }
20392
- if (result4.runtimeProviderFailure) {
21267
+ if (result4.error || result4.runtimeProviderFailure) {
20393
21268
  result4 = {
20394
21269
  ...result4,
20395
21270
  error: true,
20396
- errorMessage: result4.runtimeProviderFailure.message
21271
+ errorMessage: result4.runtimeProviderFailure?.message ?? result4.errorMessage
20397
21272
  };
20398
21273
  break;
20399
21274
  }
@@ -20456,13 +21331,14 @@ ${reasoningTailLog}
20456
21331
  ...result4.reasoning_content ? { reasoning_content: result4.reasoning_content } : {}
20457
21332
  };
20458
21333
  transcript.push(assistantMessage);
20459
- if (applyPendingInjections()) {
21334
+ if (await applyPendingInjections()) {
20460
21335
  loopTiming.mark("roundEnd", round);
20461
21336
  round += 1;
20462
21337
  continue;
20463
21338
  }
20464
21339
  transcript.popLast();
20465
21340
  }
21341
+ stopReason = "done";
20466
21342
  break;
20467
21343
  }
20468
21344
  const outputBlocks = result4.output ?? [];
@@ -20481,9 +21357,11 @@ ${reasoningTailLog}
20481
21357
  }
20482
21358
  }
20483
21359
  if (hasInlineExecutedTools) {
20484
- for (const blockMsg of blocksToOpenAiMessages(outputBlocks)) {
21360
+ for (const blockMsg of blocksToOpenAiMessages(outputBlocks, input.adapter.workspaceRoot)) {
20485
21361
  transcript.pushTool(blockMsg);
20486
21362
  }
21363
+ const inlineResults = outputBlocks.flatMap((block) => block.type === "toolCall" && block.result ? [block.result] : []);
21364
+ stopReason = inlineResults.some(isToolExecutionFailure) ? "error" : inlineResults.some(({ metadata }) => metadata?.uiAskChoice === true && metadata.resolved !== true) ? "pending" : "done";
20487
21365
  skipFinalAppend = true;
20488
21366
  break;
20489
21367
  }
@@ -20500,15 +21378,10 @@ ${reasoningTailLog}
20500
21378
  const executedToolResults = [];
20501
21379
  loopTiming.mark("toolLoopStart", round);
20502
21380
  const slotResults = new Array(toolCalls.length);
20503
- const runSingleTool = async ({ index, toolCall }) => {
20504
- throwIfAborted(input);
20505
- if (!budgetAdmissionGate()) {
20506
- skippedToolCalls.push(toolCall);
20507
- return;
20508
- }
20509
- subtaskBudgetTracker?.recordToolCallExecuted();
21381
+ const runSingleTool = async ({ index, toolCall }, executionInput = input, isClosed = () => false) => {
21382
+ throwIfAborted(executionInput);
20510
21383
  const { toolResult, toolExecMs } = await executeToolCall({
20511
- input,
21384
+ input: executionInput,
20512
21385
  toolCall,
20513
21386
  round,
20514
21387
  boundary: observationBoundary,
@@ -20521,12 +21394,12 @@ ${reasoningTailLog}
20521
21394
  ...result4.finish_reason ? { finishReason: result4.finish_reason } : {}
20522
21395
  }
20523
21396
  });
21397
+ if (isClosed()) return;
20524
21398
  slotResults[index] = {
20525
21399
  toolName: toolCall.function.name,
20526
21400
  toolResult,
20527
21401
  toolExecMs
20528
21402
  };
20529
- executedToolNameLog.push(toolCall.function.name);
20530
21403
  };
20531
21404
  const commitSlot = (i) => {
20532
21405
  const toolCall = toolCalls[i];
@@ -20545,7 +21418,8 @@ ${reasoningTailLog}
20545
21418
  content: formatToolMessageContent({
20546
21419
  toolName,
20547
21420
  content: toolResult.content,
20548
- metadata: observedMetadata
21421
+ metadata: observedMetadata,
21422
+ workspaceRoot: input.adapter.workspaceRoot
20549
21423
  }),
20550
21424
  tool_call_id: toolCall.id,
20551
21425
  toolName,
@@ -20557,14 +21431,36 @@ ${reasoningTailLog}
20557
21431
  } } : {}
20558
21432
  });
20559
21433
  };
20560
- const skippedToolCalls = [];
20561
21434
  const batches = partitionToolCallsIntoBatches(toolCalls);
20562
21435
  for (const batch of batches) {
20563
21436
  throwIfAborted(input);
20564
21437
  let batchError;
20565
21438
  try {
20566
21439
  if (batch.isConcurrent && batch.calls.length > 1) {
20567
- await Promise.all(batch.calls.map(runSingleTool));
21440
+ const controller = new AbortController();
21441
+ const batchInput = {
21442
+ ...input,
21443
+ abortSignal: input.abortSignal ? AbortSignal.any([input.abortSignal, controller.signal]) : controller.signal
21444
+ };
21445
+ let closed = false;
21446
+ let failed = false;
21447
+ let firstError;
21448
+ const tasks = batch.calls.map((call) => runAbortableToolTask(
21449
+ batchInput,
21450
+ runSingleTool(call, batchInput, () => closed),
21451
+ call.toolCall.function.name
21452
+ ).catch((error) => {
21453
+ if (!failed) {
21454
+ failed = true;
21455
+ firstError = error;
21456
+ closed = true;
21457
+ controller.abort();
21458
+ }
21459
+ throw error;
21460
+ }));
21461
+ await Promise.allSettled(tasks);
21462
+ closed = true;
21463
+ if (failed) throw firstError;
20568
21464
  } else {
20569
21465
  for (const call of batch.calls) {
20570
21466
  await runSingleTool(call);
@@ -20581,15 +21477,20 @@ ${reasoningTailLog}
20581
21477
  }
20582
21478
  if (batchError) throw batchError;
20583
21479
  }
20584
- for (const skipped of skippedToolCalls) {
20585
- transcript.pushTool({
20586
- role: "tool",
20587
- content: "[\u5B50\u4EFB\u52A1\u9884\u7B97\u4E0A\u9650\u5DF2\u89E6\u53D1] \u8BE5\u5DE5\u5177\u8C03\u7528\u672A\u6267\u884C\uFF1A\u5DF2\u8FBE\u5B50\u4EFB\u52A1\u9884\u7B97\u4E0A\u9650\uFF0C\u672C\u8F6E\u4E0D\u518D\u53D1\u8D77\u65B0\u7684\u5DE5\u5177\u8C03\u7528\u3002",
20588
- tool_call_id: skipped.id,
20589
- toolName: skipped.function.name
20590
- });
21480
+ const handoff = executedToolResults.map(({ content }) => {
21481
+ try {
21482
+ return typeof content === "string" ? JSON.parse(content) : null;
21483
+ } catch {
21484
+ return null;
21485
+ }
21486
+ }).find((value) => value?.handoff && typeof value.content === "string" && value.content.trim());
21487
+ if (handoff) {
21488
+ result4 = { ...result4, content: handoff.content };
21489
+ stopReason = "handoff";
21490
+ break;
20591
21491
  }
20592
- if (budgetExhaustion) {
21492
+ if (executedToolResults.some(({ metadata }) => metadata?.uiAskChoice === true && metadata.resolved !== true)) {
21493
+ stopReason = "pending";
20593
21494
  break;
20594
21495
  }
20595
21496
  const toolExecutionGuardVerdict = progressGuard.observeToolExecution(
@@ -20612,117 +21513,28 @@ ${reasoningTailLog}
20612
21513
  };
20613
21514
  break;
20614
21515
  }
20615
- await compaction.maybeCompactInLoop();
20616
- if (!budgetAdmissionGate()) {
20617
- break;
20618
- }
20619
21516
  loopTiming.mark("roundEnd", round);
20620
21517
  round += 1;
20621
21518
  }
20622
21519
  } catch (error) {
20623
- loopError = error;
20624
- }
20625
- const finalBudgetExhaustion = budgetExhaustion;
20626
- let budgetWrapupFailure;
20627
- let budgetWrapupSucceeded = false;
20628
- if (!loopError && finalBudgetExhaustion && subtaskBudgetTracker && finalBudgetExhaustion.limit === "max-tool-calls" && !input.abortSignal?.aborted && subtaskBudgetTracker.elapsedMs() < subtaskBudgetTracker.limits.maxWallClockMs) {
20629
- const remainingMs = subtaskBudgetTracker.limits.maxWallClockMs - subtaskBudgetTracker.elapsedMs();
20630
- const timeoutMs = Math.min(3e4, remainingMs);
20631
- const controller = new AbortController();
20632
- let rejectCancelled = () => {
20633
- };
20634
- const cancelled = new Promise((_, reject) => {
20635
- rejectCancelled = reject;
20636
- });
20637
- const onAbort = () => {
20638
- controller.abort();
20639
- rejectCancelled(buildAbortedError());
20640
- };
20641
- input.abortSignal?.addEventListener("abort", onAbort, { once: true });
20642
- if (input.abortSignal?.aborted) onAbort();
20643
- let timer;
20644
- let wrapRequestStarted = false;
20645
- let wrapUsageCaptured = false;
20646
- let wrapOutcomeReceived = false;
21520
+ const toRollback = [...pendingInjectionCommits.splice(0), ...inFlightTransactions];
21521
+ inFlightTransactions = [];
21522
+ let rollbackErr;
20647
21523
  try {
20648
- const deadline = new Promise((_, reject) => {
20649
- timer = setTimeout(() => {
20650
- controller.abort();
20651
- reject(new Error("budget wrap-up timed out"));
20652
- }, timeoutMs);
20653
- });
20654
- const work = async () => {
20655
- const wrapProvider = await input.adapter.resolveProvider(agentConfig, { toolNames: [], prompt: "", textOnly: true });
20656
- if (!wrapProvider.textOnly) throw new Error(`host ${input.adapter.host} does not support isolated text-only provider`);
20657
- if (controller.signal.aborted || input.abortSignal?.aborted || subtaskBudgetTracker.elapsedMs() >= subtaskBudgetTracker.limits.maxWallClockMs) throw new Error("budget wrap-up cancelled or deadline reached");
20658
- const wrapMessages = [
20659
- ...filterImagePartsFromMessages(prepareMessagesForProviderCall(transcript.working()).messages, supportsImages),
20660
- { role: "user", content: "\u5DE5\u5177\u9884\u7B97\u5DF2\u8017\u5C3D\u3002\u4E0D\u8981\u8C03\u7528\u5DE5\u5177\uFF1B\u4EC5\u57FA\u4E8E\u5DF2\u5B8C\u6210\u5185\u5BB9\uFF0C\u7B80\u8FF0\u7ED3\u679C\u3001\u8BC1\u636E\u4E0E\u672A\u5B8C\u6210\u4E8B\u9879\u3002" }
20661
- ];
20662
- const startedAt = Date.now();
20663
- const telemetry2 = buildRequestTelemetry({ dialogKey: input.continueDialogId || `budget:${crypto.randomUUID()}`, messages: wrapMessages, toolsHash: safeToolNamesHash([]) });
20664
- wrapRequestStarted = true;
20665
- const summary2 = await runCompleteWithTimeout({
20666
- provider: wrapProvider,
20667
- messages: wrapMessages,
20668
- options: { max_tokens: 1024, noRetries: true, timeoutMs, signal: controller.signal, ...input.continueDialogId ? { dialogId: input.continueDialogId } : {} },
20669
- timeoutMs,
20670
- round,
20671
- input,
20672
- boundary: observationBoundary,
20673
- providerName: agentConfig.provider,
20674
- model: wrapProvider.model
20675
- });
20676
- return { summary: summary2, telemetry: finalizeCallTelemetry(telemetry2, summary2, round, startedAt) };
20677
- };
20678
- const { summary, telemetry } = await Promise.race([work(), deadline, cancelled]);
20679
- wrapOutcomeReceived = true;
20680
- usageLedger.recordProviderCall({ usage: summary.usage, model: summary.model, provider: summary.provider, telemetry });
20681
- wrapUsageCaptured = Boolean(summary.usage);
20682
- if (summary.tool_calls?.length || summary.output?.some((block) => block.type === "toolCall")) throw new Error("text-only provider returned a tool call");
20683
- if (summary.error || typeof summary.content !== "string" || !summary.content.trim()) throw new Error("text-only provider returned no usable summary");
20684
- if (input.abortSignal?.aborted) throw buildAbortedError();
20685
- result4 = { ...result4, content: summary.content.trim().slice(0, 12e3) };
20686
- budgetWrapupSucceeded = true;
20687
- } catch (error) {
20688
- if (input.abortSignal?.aborted) {
20689
- const aborted = buildAbortedError();
20690
- if (wrapRequestStarted && !wrapUsageCaptured) {
20691
- aborted.message += "\uFF08\u65E0\u5DE5\u5177\u603B\u7ED3\u8BF7\u6C42\u53EF\u80FD\u5DF2\u8BA1\u8D39\uFF0C\u672A\u8FD4\u56DE\u7684\u7528\u91CF\u672A\u77E5\uFF09";
20692
- aborted.usageUnavailable = true;
20693
- }
20694
- loopError = aborted;
20695
- } else {
20696
- const detail = error instanceof Error ? error.message : "unknown error";
20697
- budgetWrapupFailure = scrubSecrets(detail).cleaned.slice(0, 300);
20698
- if (wrapRequestStarted && !wrapOutcomeReceived) budgetWrapupFailure += "\uFF1B\u8BF7\u6C42\u53EF\u80FD\u5DF2\u8BA1\u8D39\uFF0C\u672A\u8FD4\u56DE\u7684\u7528\u91CF\u672A\u77E5";
20699
- }
20700
- } finally {
20701
- if (timer) clearTimeout(timer);
20702
- controller.abort();
20703
- input.abortSignal?.removeEventListener("abort", onAbort);
21524
+ await rollbackInjectionCommits(toRollback);
21525
+ } catch (rbErr) {
21526
+ rollbackErr = rbErr;
20704
21527
  }
21528
+ loopError = rollbackErr ? combineRollbackError(error, rollbackErr) : error;
20705
21529
  }
20706
21530
  if (!loopError && input.abortSignal?.aborted) loopError = buildAbortedError();
20707
- if (budgetExhaustion) {
20708
- if (!budgetWrapupSucceeded && !budgetWrapupFailure) {
20709
- budgetWrapupFailure = input.abortSignal?.aborted ? "\u7528\u6237\u5DF2\u53D6\u6D88" : "\u5899\u949F\u9884\u7B97\u5DF2\u8017\u5C3D\uFF0C\u672A\u53D1\u8D77\u603B\u7ED3\u8BF7\u6C42";
20710
- }
20711
- const previousContent = typeof result4?.content === "string" ? result4.content.trim() : "";
20712
- result4 = {
20713
- ...result4,
20714
- content: [
20715
- previousContent,
20716
- ...budgetWrapupFailure ? [`\u65E0\u5DE5\u5177\u603B\u7ED3\u672A\u5B8C\u6210\uFF08${budgetWrapupFailure}\uFF09\uFF1B\u4EE5\u4E0B\u662F\u4FDD\u7559\u7684\u5DF2\u6709\u5185\u5BB9\u548C\u9884\u7B97\u72B6\u6001\u3002`] : [],
20717
- buildSubtaskBudgetExhaustedContent({
20718
- exhaustion: budgetExhaustion,
20719
- roundsCompleted: round,
20720
- recentToolNames: executedToolNameLog
20721
- })
20722
- ].filter((part) => part.length > 0).join("\n\n")
20723
- };
20724
- }
20725
21531
  if (loopError) {
21532
+ if (loopError instanceof LocalContextCoverageError && round === 0 && !consumedInjectedMessages) {
21533
+ if (input.continueDialogId) attachDialogIdToError(loopError, input.continueDialogId);
21534
+ attachUsageRecordsToError(loopError, usageLedger.records());
21535
+ await loopTiming.flush();
21536
+ throw loopError;
21537
+ }
20726
21538
  const turnMessages2 = transcript.persisted(
20727
21539
  sanitizedPersistedInput,
20728
21540
  input.persistedInputReference
@@ -20748,6 +21560,10 @@ ${reasoningTailLog}
20748
21560
  throw loopError;
20749
21561
  }
20750
21562
  result4 = result4;
21563
+ result4 = {
21564
+ ...result4,
21565
+ stopReason: input.abortSignal?.aborted ? "aborted" : result4.error || result4.runtimeProviderFailure || result4.emptyAssistantFallbackReason ? "error" : stopReason
21566
+ };
20751
21567
  if (!skipFinalAppend) {
20752
21568
  const truncatedReasoningTailLog = resolveTruncatedReasoningTailLog(
20753
21569
  result4.emptyAssistantFallbackReason,
@@ -20834,6 +21650,231 @@ function buildResponsesRequestBody(body, model, options) {
20834
21650
  };
20835
21651
  }
20836
21652
 
21653
+ // packages/agent-runtime/responsesProtocolLeakSanitizer.ts
21654
+ var LEAKED_PROTOCOL_NOTICE = "\n\n[\u63D0\u793A\uFF1A\u5DF2\u62E6\u622A\u6A21\u578B\u751F\u6210\u7684\u672A\u6267\u884C\u5DE5\u5177\u534F\u8BAE\u7247\u6BB5]";
21655
+ var INLINE_MARKER_REGEXES = [
21656
+ /\u3011\u3010\u3002\s*assistant\s+to\s*=\s*functions\./i,
21657
+ /\u3011\u3010\u3002\s*functions\./i,
21658
+ /<\|(?:im_start|start_header_id)\|>\s*assistant\s+to\s*=\s*functions\./i,
21659
+ /<\|(?:im_start|start_header_id)\|>\s*functions\./i
21660
+ ];
21661
+ var INLINE_MARKER_PREFIXES = [
21662
+ "\u3011\u3010\u3002assistant to=functions.",
21663
+ "\u3011\u3010\u3002functions.",
21664
+ "<|im_start|>assistant to=functions.",
21665
+ "<|im_start|>functions.",
21666
+ "<|start_header_id|>assistant to=functions.",
21667
+ "<|start_header_id|>functions."
21668
+ ];
21669
+ var TAB_D_PREFIX = " Dfunctions.".toLowerCase();
21670
+ function findLeakedMarker(text2, wasAtLineStart) {
21671
+ let earliestIndex = -1;
21672
+ let earliestLength = 0;
21673
+ for (const regex of INLINE_MARKER_REGEXES) {
21674
+ const match7 = regex.exec(text2);
21675
+ if (match7 && match7.index !== void 0) {
21676
+ if (earliestIndex === -1 || match7.index < earliestIndex) {
21677
+ earliestIndex = match7.index;
21678
+ earliestLength = match7[0].length;
21679
+ }
21680
+ }
21681
+ }
21682
+ const lineMarkerRegex = /(?:^|[\r\n])[ \t]*\tDfunctions\./gi;
21683
+ let m;
21684
+ while ((m = lineMarkerRegex.exec(text2)) !== null) {
21685
+ const isNewline = m[0].startsWith("\n") || m[0].startsWith("\r");
21686
+ const actualIndex = m.index + (isNewline ? 1 : 0);
21687
+ if (actualIndex === 0 && !wasAtLineStart) {
21688
+ continue;
21689
+ }
21690
+ if (earliestIndex === -1 || actualIndex < earliestIndex) {
21691
+ earliestIndex = actualIndex;
21692
+ earliestLength = m[0].length - (isNewline ? 1 : 0);
21693
+ }
21694
+ break;
21695
+ }
21696
+ return earliestIndex >= 0 ? { index: earliestIndex, length: earliestLength } : null;
21697
+ }
21698
+ function calculateHoldLength(buffer3, wasAtLineStart) {
21699
+ let hold = 0;
21700
+ const lower = buffer3.toLowerCase();
21701
+ for (const prefix of INLINE_MARKER_PREFIXES) {
21702
+ const pLower = prefix.toLowerCase();
21703
+ const limit = Math.min(lower.length, pLower.length);
21704
+ for (let len = limit; len > 0; len--) {
21705
+ if (pLower.startsWith(lower.slice(-len))) {
21706
+ if (len > hold) hold = len;
21707
+ break;
21708
+ }
21709
+ }
21710
+ }
21711
+ const trailingLineMatch = /(?:^|[\r\n])[ \t]*$/.exec(buffer3);
21712
+ if (trailingLineMatch) {
21713
+ const isNewline = trailingLineMatch[0].startsWith("\n") || trailingLineMatch[0].startsWith("\r");
21714
+ const len = trailingLineMatch[0].length - (isNewline ? 1 : 0);
21715
+ if (len > 0 && (isNewline || wasAtLineStart)) {
21716
+ if (len > hold) hold = len;
21717
+ }
21718
+ }
21719
+ const trailingTabMatch = /(?:^|[\r\n])[ \t]*(\t[a-zA-Z0-9_\.]*)$/i.exec(lower);
21720
+ if (trailingTabMatch) {
21721
+ const candidate = trailingTabMatch[1];
21722
+ if (TAB_D_PREFIX.startsWith(candidate)) {
21723
+ const isNewline = trailingTabMatch[0].startsWith("\n") || trailingTabMatch[0].startsWith("\r");
21724
+ const len = trailingTabMatch[0].length - (isNewline ? 1 : 0);
21725
+ if (isNewline || wasAtLineStart) {
21726
+ if (len > hold) hold = len;
21727
+ }
21728
+ }
21729
+ }
21730
+ const trailingFenceMatch = /(?:^|[\r\n])[ ]{0,3}(?:`{1,2}|~{1,2})$/.exec(buffer3);
21731
+ if (trailingFenceMatch) {
21732
+ const isNewline = trailingFenceMatch[0].startsWith("\n") || trailingFenceMatch[0].startsWith("\r");
21733
+ const len = trailingFenceMatch[0].length - (isNewline ? 1 : 0);
21734
+ if (isNewline || wasAtLineStart) {
21735
+ if (len > hold) hold = len;
21736
+ }
21737
+ }
21738
+ return hold;
21739
+ }
21740
+ function createResponsesProtocolLeakSanitizer(onTextDelta) {
21741
+ let safeContent = "";
21742
+ let buffer3 = "";
21743
+ let inCodeFence = false;
21744
+ let fenceChar = "";
21745
+ let fenceLength = 0;
21746
+ let intercepted = false;
21747
+ let wasAtLineStart = true;
21748
+ const emit = (text2) => {
21749
+ safeContent += text2;
21750
+ onTextDelta?.(text2);
21751
+ if (text2.length > 0) {
21752
+ const last = text2[text2.length - 1];
21753
+ wasAtLineStart = last === "\n" || last === "\r";
21754
+ }
21755
+ };
21756
+ const processBuffer = (isFinal) => {
21757
+ if (intercepted) return;
21758
+ while (buffer3.length > 0) {
21759
+ if (!inCodeFence) {
21760
+ let fenceIndex = -1;
21761
+ let fenceMarkerStr = "";
21762
+ let lineStartOffset = 0;
21763
+ const fenceRegex = /(?:^|[\r\n])[ ]{0,3}(`{3,}|~{3,})[^\r\n]*(?:\r?\n|$)/g;
21764
+ let m;
21765
+ while ((m = fenceRegex.exec(buffer3)) !== null) {
21766
+ const isNewlinePreceded = m[0].startsWith("\n") || m[0].startsWith("\r");
21767
+ const actualStart = m.index + (isNewlinePreceded ? 1 : 0);
21768
+ if (actualStart === 0 && !wasAtLineStart) {
21769
+ continue;
21770
+ }
21771
+ fenceIndex = actualStart;
21772
+ fenceMarkerStr = m[1];
21773
+ lineStartOffset = m[0].length - (isNewlinePreceded ? 1 : 0);
21774
+ break;
21775
+ }
21776
+ const markerMatch = findLeakedMarker(buffer3, wasAtLineStart);
21777
+ const markerIndex = markerMatch ? markerMatch.index : -1;
21778
+ if (markerIndex >= 0 && (fenceIndex === -1 || markerIndex < fenceIndex)) {
21779
+ const normalPart = buffer3.slice(0, markerIndex);
21780
+ emit(normalPart);
21781
+ emit(LEAKED_PROTOCOL_NOTICE);
21782
+ intercepted = true;
21783
+ buffer3 = "";
21784
+ return;
21785
+ }
21786
+ if (fenceIndex >= 0) {
21787
+ if (!isFinal && !buffer3.slice(fenceIndex).includes("\n") && !buffer3.slice(fenceIndex).includes("\r")) {
21788
+ const beforeFence2 = buffer3.slice(0, fenceIndex);
21789
+ emit(beforeFence2);
21790
+ buffer3 = buffer3.slice(fenceIndex);
21791
+ return;
21792
+ }
21793
+ const beforeFence = buffer3.slice(0, fenceIndex);
21794
+ emit(beforeFence);
21795
+ inCodeFence = true;
21796
+ fenceChar = fenceMarkerStr[0];
21797
+ fenceLength = fenceMarkerStr.length;
21798
+ emit(buffer3.slice(fenceIndex, fenceIndex + lineStartOffset));
21799
+ buffer3 = buffer3.slice(fenceIndex + lineStartOffset);
21800
+ continue;
21801
+ }
21802
+ if (isFinal) {
21803
+ emit(buffer3);
21804
+ buffer3 = "";
21805
+ return;
21806
+ }
21807
+ const hold = calculateHoldLength(buffer3, wasAtLineStart);
21808
+ if (hold === 0) {
21809
+ emit(buffer3);
21810
+ buffer3 = "";
21811
+ } else if (hold < buffer3.length) {
21812
+ emit(buffer3.slice(0, buffer3.length - hold));
21813
+ buffer3 = buffer3.slice(buffer3.length - hold);
21814
+ }
21815
+ return;
21816
+ } else {
21817
+ const closeRegex = new RegExp(`(?:^|[\\r\\n])[ ]{0,3}${fenceChar}{${fenceLength},}[ ]*(?:\\r?\\n|$)`, "g");
21818
+ const closeMatch = closeRegex.exec(buffer3);
21819
+ if (closeMatch) {
21820
+ const isNewlinePreceded = closeMatch[0].startsWith("\n") || closeMatch[0].startsWith("\r");
21821
+ const actualStart = closeMatch.index + (isNewlinePreceded ? 1 : 0);
21822
+ if (actualStart === 0 && !wasAtLineStart) {
21823
+ emit(buffer3.slice(0, closeMatch.index + 1));
21824
+ buffer3 = buffer3.slice(closeMatch.index + 1);
21825
+ continue;
21826
+ }
21827
+ const closeEnd = closeMatch.index + closeMatch[0].length;
21828
+ emit(buffer3.slice(0, closeEnd));
21829
+ buffer3 = buffer3.slice(closeEnd);
21830
+ inCodeFence = false;
21831
+ fenceChar = "";
21832
+ fenceLength = 0;
21833
+ continue;
21834
+ }
21835
+ if (isFinal) {
21836
+ emit(buffer3);
21837
+ buffer3 = "";
21838
+ return;
21839
+ }
21840
+ const trailingCloseMatch = new RegExp(`(?:^|[\\r\\n])[ ]{0,3}${fenceChar}{1,${fenceLength}}$`).exec(buffer3);
21841
+ const hold = trailingCloseMatch ? trailingCloseMatch[0].length : 0;
21842
+ if (hold === 0) {
21843
+ emit(buffer3);
21844
+ buffer3 = "";
21845
+ } else if (hold < buffer3.length) {
21846
+ emit(buffer3.slice(0, buffer3.length - hold));
21847
+ buffer3 = buffer3.slice(buffer3.length - hold);
21848
+ }
21849
+ return;
21850
+ }
21851
+ }
21852
+ };
21853
+ return {
21854
+ push(chunk) {
21855
+ if (intercepted) return;
21856
+ if (chunk.length === 0) {
21857
+ emit("");
21858
+ return;
21859
+ }
21860
+ buffer3 += chunk;
21861
+ processBuffer(false);
21862
+ },
21863
+ finalize() {
21864
+ processBuffer(true);
21865
+ return {
21866
+ content: safeContent,
21867
+ intercepted
21868
+ };
21869
+ }
21870
+ };
21871
+ }
21872
+ function sanitizeResponsesProtocolLeakText(text2) {
21873
+ const sanitizer = createResponsesProtocolLeakSanitizer();
21874
+ sanitizer.push(text2);
21875
+ return sanitizer.finalize();
21876
+ }
21877
+
20837
21878
  // packages/agent-runtime/responsesSseStream.ts
20838
21879
  function toResponsesStreamFailure(raw, fallbackPrefix = "Responses") {
20839
21880
  if (!raw || typeof raw !== "object") return void 0;
@@ -20870,6 +21911,8 @@ function hasNumericTokenCount(u) {
20870
21911
  function createResponsesStreamCollector(callbacks) {
20871
21912
  let content = "";
20872
21913
  let reasoning = "";
21914
+ const textSanitizer = createResponsesProtocolLeakSanitizer(callbacks?.onTextDelta);
21915
+ let sawNonEmptyOutputTextDelta = false;
20873
21916
  const toolCallsAcc = createResponsesToolAccumulator();
20874
21917
  let usage;
20875
21918
  let failure;
@@ -20921,8 +21964,8 @@ function createResponsesStreamCollector(callbacks) {
20921
21964
  return;
20922
21965
  }
20923
21966
  if (type === "response.output_text.delta" && typeof ev.delta === "string") {
20924
- content += ev.delta;
20925
- callbacks?.onTextDelta?.(ev.delta);
21967
+ if (ev.delta.length > 0) sawNonEmptyOutputTextDelta = true;
21968
+ textSanitizer.push(ev.delta);
20926
21969
  return;
20927
21970
  }
20928
21971
  if ((type === "response.reasoning_text.delta" || type === "response.reasoning.delta") && typeof ev.delta === "string") {
@@ -20932,11 +21975,11 @@ function createResponsesStreamCollector(callbacks) {
20932
21975
  }
20933
21976
  if (type === "response.output_item.added" || type === "response.output_item.done") {
20934
21977
  const item = ev.item;
20935
- if (item?.type === "message" && !content) {
21978
+ if (item?.type === "message" && !sawNonEmptyOutputTextDelta) {
20936
21979
  const itemText = extractOutputTextFromItem(item);
20937
21980
  if (itemText) {
20938
- content = itemText;
20939
- callbacks?.onTextDelta?.(itemText);
21981
+ sawNonEmptyOutputTextDelta = true;
21982
+ textSanitizer.push(itemText);
20940
21983
  }
20941
21984
  }
20942
21985
  applyResponsesToolEvent(toolCallsAcc, ev);
@@ -21035,8 +22078,16 @@ function createResponsesStreamCollector(callbacks) {
21035
22078
  if (authoritativeCompletedTools && failure) {
21036
22079
  finalToolCalls = [];
21037
22080
  }
22081
+ const sanitized = textSanitizer.finalize();
22082
+ content = sanitized.content;
22083
+ let intercepted = sanitized.intercepted;
21038
22084
  if (!content && completedResponse) {
21039
- content = extractTextFromResponseOutput(completedResponse);
22085
+ const extracted = extractTextFromResponseOutput(completedResponse);
22086
+ if (extracted) {
22087
+ const sanitizedExtracted = sanitizeResponsesProtocolLeakText(extracted);
22088
+ content = sanitizedExtracted.content;
22089
+ if (sanitizedExtracted.intercepted) intercepted = true;
22090
+ }
21040
22091
  }
21041
22092
  if (!reasoning && completedResponse) {
21042
22093
  reasoning = extractReasoningFromResponseOutput(completedResponse);
@@ -21051,6 +22102,7 @@ function createResponsesStreamCollector(callbacks) {
21051
22102
  ...streamComplete ? { finish_reason: finalToolCalls.length > 0 ? "tool_calls" : "stop" } : {},
21052
22103
  ...streamComplete ? { stream_complete: true } : {},
21053
22104
  ...streamTruncated ? { stream_truncated: true } : {},
22105
+ ...intercepted ? { leaked_protocol_intercepted: true } : {},
21054
22106
  ...completedResponse ? { completed_response: completedResponse } : {},
21055
22107
  ...completedResponse && typeof completedResponse.id === "string" ? { response_id: completedResponse.id } : {},
21056
22108
  ...failure ? { failure } : {}
@@ -21432,6 +22484,7 @@ async function executeOpenAiCompatibleChatCompletion(args2) {
21432
22484
  ...streamed2.usage ? { usage: streamed2.usage } : {},
21433
22485
  ...streamed2.stream_complete ? { stream_complete: true } : {},
21434
22486
  ...streamed2.finish_reason ? { finish_reason: streamed2.finish_reason } : {},
22487
+ ...streamed2.leaked_protocol_intercepted ? { leaked_protocol_intercepted: true } : {},
21435
22488
  trace: args2.messages
21436
22489
  });
21437
22490
  }
@@ -21479,6 +22532,16 @@ async function executeOpenAiCompatibleChatCompletion(args2) {
21479
22532
  throw error;
21480
22533
  }
21481
22534
  }
22535
+ function describeOpenAiCompatibleRequestBudget(args2) {
22536
+ const request3 = buildOpenAiCompatibleChatCompletionRequest({ ...args2, messages: [] });
22537
+ const body = JSON.parse(request3.init.body);
22538
+ const cap = body.max_completion_tokens ?? body.max_output_tokens ?? body.max_tokens;
22539
+ return {
22540
+ toolSchemaTokens: estimateTokenCount(JSON.stringify(body.tools ?? [])),
22541
+ // Explicit wire allowance is conservatively reserved. Omitted provider defaults are unknown.
22542
+ output: typeof cap === "number" && Number.isFinite(cap) && cap > 0 ? { semantics: "shared-window", finalWireCapTokens: cap } : { semantics: "unknown", fallbackReserveTokens: 8192 }
22543
+ };
22544
+ }
21482
22545
 
21483
22546
  // packages/agent-runtime/openAiCompatibleProviderConfig.ts
21484
22547
  async function resolveOpenAiCompatibleProviderConfig(args2) {
@@ -22235,6 +23298,7 @@ function dialogMessageRecordToAgentRuntimeMessage(record2) {
22235
23298
  return {
22236
23299
  ...typeof record2.id === "string" ? { id: record2.id } : {},
22237
23300
  role: record2.role,
23301
+ ...Number.isFinite(record2.metadata?.cliHistoryOrder) ? { cliHistoryOrder: record2.metadata.cliHistoryOrder } : {},
22238
23302
  content: record2.content ?? "",
22239
23303
  ...record2.contextReference !== void 0 ? { context_reference: record2.contextReference } : {},
22240
23304
  ...typeof record2.reasoning_content === "string" ? { reasoning_content: record2.reasoning_content } : {},
@@ -22622,7 +23686,8 @@ function createHybridRecordStore(deps) {
22622
23686
  const normalizedLocalRecord = normalizeHybridRecord(dbKey, localRecord);
22623
23687
  if (normalizedLocalRecord && options?.remote !== true) return normalizedLocalRecord;
22624
23688
  if (options?.remote === false) return null;
22625
- const fallbackDeadlineMs = requestTimeoutMs > 0 ? Date.now() + requestTimeoutMs : null;
23689
+ const effectiveTimeoutMs = typeof options?.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : requestTimeoutMs;
23690
+ const fallbackDeadlineMs = effectiveTimeoutMs > 0 ? Date.now() + effectiveTimeoutMs : null;
22626
23691
  for (const server of resolveHybridServers(
22627
23692
  deps.defaultServer,
22628
23693
  options?.preferredServerOrigin,
@@ -22673,10 +23738,271 @@ function createHybridRecordStore(deps) {
22673
23738
  var DEFAULT_SANDBOX_TMPFS_SIZE_BYTES = 128 * 1024 * 1024;
22674
23739
  var BWRAP_PROBE_TTL_MS = 5 * 6e4;
22675
23740
 
23741
+ // node_modules/async-mutex/index.mjs
23742
+ var E_TIMEOUT = new Error("timeout while waiting for mutex to become available");
23743
+ var E_ALREADY_LOCKED = new Error("mutex already locked");
23744
+ var E_CANCELED = new Error("request for lock canceled");
23745
+ var __awaiter$2 = function(thisArg, _arguments, P, generator) {
23746
+ function adopt(value) {
23747
+ return value instanceof P ? value : new P(function(resolve6) {
23748
+ resolve6(value);
23749
+ });
23750
+ }
23751
+ return new (P || (P = Promise))(function(resolve6, reject) {
23752
+ function fulfilled(value) {
23753
+ try {
23754
+ step(generator.next(value));
23755
+ } catch (e) {
23756
+ reject(e);
23757
+ }
23758
+ }
23759
+ function rejected(value) {
23760
+ try {
23761
+ step(generator["throw"](value));
23762
+ } catch (e) {
23763
+ reject(e);
23764
+ }
23765
+ }
23766
+ function step(result4) {
23767
+ result4.done ? resolve6(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23768
+ }
23769
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23770
+ });
23771
+ };
23772
+ var Semaphore = class {
23773
+ constructor(_value, _cancelError = E_CANCELED) {
23774
+ this._value = _value;
23775
+ this._cancelError = _cancelError;
23776
+ this._queue = [];
23777
+ this._weightedWaiters = [];
23778
+ }
23779
+ acquire(weight = 1, priority = 0) {
23780
+ if (weight <= 0)
23781
+ throw new Error(`invalid weight ${weight}: must be positive`);
23782
+ return new Promise((resolve6, reject) => {
23783
+ const task = { resolve: resolve6, reject, weight, priority };
23784
+ const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
23785
+ if (i === -1 && weight <= this._value) {
23786
+ this._dispatchItem(task);
23787
+ } else {
23788
+ this._queue.splice(i + 1, 0, task);
23789
+ }
23790
+ });
23791
+ }
23792
+ runExclusive(callback_1) {
23793
+ return __awaiter$2(this, arguments, void 0, function* (callback4, weight = 1, priority = 0) {
23794
+ const [value, release3] = yield this.acquire(weight, priority);
23795
+ try {
23796
+ return yield callback4(value);
23797
+ } finally {
23798
+ release3();
23799
+ }
23800
+ });
23801
+ }
23802
+ waitForUnlock(weight = 1, priority = 0) {
23803
+ if (weight <= 0)
23804
+ throw new Error(`invalid weight ${weight}: must be positive`);
23805
+ if (this._couldLockImmediately(weight, priority)) {
23806
+ return Promise.resolve();
23807
+ } else {
23808
+ return new Promise((resolve6) => {
23809
+ if (!this._weightedWaiters[weight - 1])
23810
+ this._weightedWaiters[weight - 1] = [];
23811
+ insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve6, priority });
23812
+ });
23813
+ }
23814
+ }
23815
+ isLocked() {
23816
+ return this._value <= 0;
23817
+ }
23818
+ getValue() {
23819
+ return this._value;
23820
+ }
23821
+ setValue(value) {
23822
+ this._value = value;
23823
+ this._dispatchQueue();
23824
+ }
23825
+ release(weight = 1) {
23826
+ if (weight <= 0)
23827
+ throw new Error(`invalid weight ${weight}: must be positive`);
23828
+ this._value += weight;
23829
+ this._dispatchQueue();
23830
+ }
23831
+ cancel() {
23832
+ this._queue.forEach((entry) => entry.reject(this._cancelError));
23833
+ this._queue = [];
23834
+ }
23835
+ _dispatchQueue() {
23836
+ this._drainUnlockWaiters();
23837
+ while (this._queue.length > 0 && this._queue[0].weight <= this._value) {
23838
+ this._dispatchItem(this._queue.shift());
23839
+ this._drainUnlockWaiters();
23840
+ }
23841
+ }
23842
+ _dispatchItem(item) {
23843
+ const previousValue = this._value;
23844
+ this._value -= item.weight;
23845
+ item.resolve([previousValue, this._newReleaser(item.weight)]);
23846
+ }
23847
+ _newReleaser(weight) {
23848
+ let called = false;
23849
+ return () => {
23850
+ if (called)
23851
+ return;
23852
+ called = true;
23853
+ this.release(weight);
23854
+ };
23855
+ }
23856
+ _drainUnlockWaiters() {
23857
+ if (this._queue.length === 0) {
23858
+ for (let weight = this._value; weight > 0; weight--) {
23859
+ const waiters = this._weightedWaiters[weight - 1];
23860
+ if (!waiters)
23861
+ continue;
23862
+ waiters.forEach((waiter) => waiter.resolve());
23863
+ this._weightedWaiters[weight - 1] = [];
23864
+ }
23865
+ } else {
23866
+ const queuedPriority = this._queue[0].priority;
23867
+ for (let weight = this._value; weight > 0; weight--) {
23868
+ const waiters = this._weightedWaiters[weight - 1];
23869
+ if (!waiters)
23870
+ continue;
23871
+ const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);
23872
+ (i === -1 ? waiters : waiters.splice(0, i)).forEach((waiter) => waiter.resolve());
23873
+ }
23874
+ }
23875
+ }
23876
+ _couldLockImmediately(weight, priority) {
23877
+ return (this._queue.length === 0 || this._queue[0].priority < priority) && weight <= this._value;
23878
+ }
23879
+ };
23880
+ function insertSorted(a, v) {
23881
+ const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);
23882
+ a.splice(i + 1, 0, v);
23883
+ }
23884
+ function findIndexFromEnd(a, predicate) {
23885
+ for (let i = a.length - 1; i >= 0; i--) {
23886
+ if (predicate(a[i])) {
23887
+ return i;
23888
+ }
23889
+ }
23890
+ return -1;
23891
+ }
23892
+ var __awaiter$1 = function(thisArg, _arguments, P, generator) {
23893
+ function adopt(value) {
23894
+ return value instanceof P ? value : new P(function(resolve6) {
23895
+ resolve6(value);
23896
+ });
23897
+ }
23898
+ return new (P || (P = Promise))(function(resolve6, reject) {
23899
+ function fulfilled(value) {
23900
+ try {
23901
+ step(generator.next(value));
23902
+ } catch (e) {
23903
+ reject(e);
23904
+ }
23905
+ }
23906
+ function rejected(value) {
23907
+ try {
23908
+ step(generator["throw"](value));
23909
+ } catch (e) {
23910
+ reject(e);
23911
+ }
23912
+ }
23913
+ function step(result4) {
23914
+ result4.done ? resolve6(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23915
+ }
23916
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23917
+ });
23918
+ };
23919
+ var Mutex = class {
23920
+ constructor(cancelError) {
23921
+ this._semaphore = new Semaphore(1, cancelError);
23922
+ }
23923
+ acquire() {
23924
+ return __awaiter$1(this, arguments, void 0, function* (priority = 0) {
23925
+ const [, releaser] = yield this._semaphore.acquire(1, priority);
23926
+ return releaser;
23927
+ });
23928
+ }
23929
+ runExclusive(callback4, priority = 0) {
23930
+ return this._semaphore.runExclusive(() => callback4(), 1, priority);
23931
+ }
23932
+ isLocked() {
23933
+ return this._semaphore.isLocked();
23934
+ }
23935
+ waitForUnlock(priority = 0) {
23936
+ return this._semaphore.waitForUnlock(1, priority);
23937
+ }
23938
+ release() {
23939
+ if (this._semaphore.isLocked())
23940
+ this._semaphore.release();
23941
+ }
23942
+ cancel() {
23943
+ return this._semaphore.cancel();
23944
+ }
23945
+ };
23946
+
23947
+ // packages/database-engine/dialogOwner.ts
23948
+ var dialogOwnerKey = (dialogId) => `dialogown-${dialogId}`;
23949
+ var locks = /* @__PURE__ */ new Map();
23950
+ async function registerDialogOwner(args2) {
23951
+ const emit = (event) => {
23952
+ try {
23953
+ (args2.log ?? ((event2) => console.warn(event2)))(event);
23954
+ } catch {
23955
+ }
23956
+ };
23957
+ const key = dialogOwnerKey(args2.dialogId);
23958
+ let mutex = locks.get(key);
23959
+ if (!mutex) {
23960
+ mutex = new Mutex();
23961
+ locks.set(key, mutex);
23962
+ }
23963
+ try {
23964
+ await mutex.runExclusive(async () => {
23965
+ let existing;
23966
+ try {
23967
+ existing = await args2.store.get(key);
23968
+ } catch (error) {
23969
+ if (!isLevelNotFoundError(error)) throw error;
23970
+ existing = null;
23971
+ }
23972
+ if (existing != null) {
23973
+ if (existing.ownerId !== args2.ownerId) emit({
23974
+ event: "dialog_owner_conflict",
23975
+ dialogId: args2.dialogId,
23976
+ existingOwnerId: existing.ownerId,
23977
+ attemptedOwnerId: args2.ownerId,
23978
+ source: args2.source
23979
+ });
23980
+ return;
23981
+ }
23982
+ await args2.store.put(key, {
23983
+ dialogId: args2.dialogId,
23984
+ ownerId: args2.ownerId,
23985
+ ...args2.spaceId !== void 0 ? { spaceId: args2.spaceId } : {},
23986
+ source: args2.source,
23987
+ registeredAt: (args2.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))()
23988
+ });
23989
+ });
23990
+ } catch (error) {
23991
+ emit({
23992
+ event: "dialog_owner_registration_failed",
23993
+ dialogId: args2.dialogId,
23994
+ source: args2.source,
23995
+ error: error instanceof Error ? error.message : String(error)
23996
+ });
23997
+ } finally {
23998
+ if (!mutex.isLocked() && locks.get(key) === mutex) locks.delete(key);
23999
+ }
24000
+ }
24001
+
22676
24002
  // packages/cli/client/localDialogRecords.ts
22677
24003
  var localDialogMessageRecordToRuntimeMessage = dialogMessageRecordToAgentRuntimeMessage;
22678
24004
  function buildLocalDialogWritePlan(args2) {
22679
- return buildAgentRuntimeDialogWritePlan({
24005
+ const plan = buildAgentRuntimeDialogWritePlan({
22680
24006
  input: args2.input,
22681
24007
  userId: args2.userId,
22682
24008
  now: args2.now,
@@ -22688,6 +24014,157 @@ function buildLocalDialogWritePlan(args2) {
22688
24014
  },
22689
24015
  ...args2.titleOverride ? { titleOverride: args2.titleOverride } : {}
22690
24016
  });
24017
+ const turnId = args2.input.runtimeContext?.turnId;
24018
+ const captureUserMessageIds = [];
24019
+ if (typeof turnId === "string" && /^turn-[0-9A-HJKMNP-TV-Z]{26}$/.test(turnId)) {
24020
+ const messages = args2.input.messages.filter((message) => message.role !== "system");
24021
+ for (const [index, message] of messages.entries()) {
24022
+ if (message.role !== "user" || message.cliMessageId) continue;
24023
+ const op = plan.ops[index + 1];
24024
+ const id = dialogTurnUserMessageId(turnId, index);
24025
+ const key = `dialog-${plan.dialogId}-msg-${id}`;
24026
+ op.key = key;
24027
+ op.value = { ...op.value, id, dbKey: key };
24028
+ captureUserMessageIds.push(id);
24029
+ }
24030
+ }
24031
+ return { ...plan, captureUserMessageIds };
24032
+ }
24033
+ async function saveCliPendingUserMessages(args2) {
24034
+ const dialogKey = `dialog-${args2.userId}-${args2.dialogId}`;
24035
+ const existing = await args2.store.read(dialogKey, { remote: false });
24036
+ const now = (/* @__PURE__ */ new Date()).toISOString();
24037
+ const ops = [];
24038
+ if (!existing) ops.push({ type: "put", key: dialogKey, value: {
24039
+ id: args2.dialogId,
24040
+ dbKey: dialogKey,
24041
+ type: "dialog",
24042
+ userId: args2.userId,
24043
+ primaryAgentKey: args2.agentKey,
24044
+ cybots: [args2.agentKey],
24045
+ createdAt: now,
24046
+ updatedAt: now
24047
+ } });
24048
+ for (const request3 of args2.requests) {
24049
+ if (!request3.messageId) throw new Error("Pending user message requires a stable messageId");
24050
+ const key = `dialog-${args2.dialogId}-msg-${request3.messageId}`;
24051
+ if (await args2.store.read(key, { remote: false })) continue;
24052
+ ops.push({ type: "put", key, value: {
24053
+ id: request3.messageId,
24054
+ dbKey: key,
24055
+ type: "message",
24056
+ dialogId: args2.dialogId,
24057
+ userId: args2.userId,
24058
+ role: "user",
24059
+ content: request3.text,
24060
+ createdAt: now,
24061
+ metadata: {
24062
+ queueState: "pending",
24063
+ source: request3.source ?? "tui",
24064
+ imagePaths: request3.imagePaths,
24065
+ mediaPaths: request3.mediaPaths
24066
+ }
24067
+ } });
24068
+ }
24069
+ await registerDialogOwner({
24070
+ store: { get: (key) => args2.store.read(key, { remote: false }), put: (key, value) => args2.store.batch([{ type: "put", key, value }]) },
24071
+ dialogId: args2.dialogId,
24072
+ ownerId: args2.userId,
24073
+ source: "cli-pending-user"
24074
+ });
24075
+ if (ops.length) await args2.store.batch(ops);
24076
+ }
24077
+ async function readCliPendingUserMessages(store, dialogId) {
24078
+ const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-M3F76NIP.js");
24079
+ const rows = await readDialogMessageRecords({ store, dialogId });
24080
+ const uncertain = rows.filter(({ record: record2 }) => record2.metadata?.cliBatchPhase === "requested" && !record2.metadata?.cliBatchResolution);
24081
+ const recovery = uncertain.length ? {
24082
+ status: "unknown",
24083
+ messageIds: uncertain.map((row) => row.messageId),
24084
+ // Attribute each unknown batch to its own members via the tail receipt.
24085
+ // `acceptedUserMessageIds` is written by `markCliUserBatchPhase`; older
24086
+ // records carry the same field from the legacy admission path. Records with
24087
+ // neither fall back to every accepted row (never attribute a completed
24088
+ // batch's members to an unknown one when the receipt is available).
24089
+ batches: uncertain.map((row) => {
24090
+ const receiptIds = row.record.metadata?.acceptedUserMessageIds;
24091
+ const memberIds = Array.isArray(receiptIds) && receiptIds.length ? receiptIds : rows.filter((message) => message.record.metadata?.queueState === "accepted").map((message) => message.messageId);
24092
+ const memberSet = new Set(memberIds);
24093
+ return { batchId: row.messageId, messages: rows.filter((message) => memberSet.has(message.messageId)).map((message) => ({ messageId: message.messageId, text: String(message.record.content ?? "") })) };
24094
+ }),
24095
+ message: `Batch provider outcome unknown for ${uncertain.map((row) => row.messageId).join(", ")}; pending history retained; resubmission paused to avoid duplicate billing`
24096
+ } : { status: "ready", messageIds: [] };
24097
+ const pending = rows.filter(({ record: record2 }) => record2.role === "user" && record2.metadata?.queueState === "pending").map(({ record: record2, messageId }) => ({
24098
+ messageId,
24099
+ source: record2.metadata?.source,
24100
+ text: String(record2.content ?? ""),
24101
+ event: { kind: "user", text: String(record2.content ?? "") },
24102
+ imagePaths: record2.metadata?.imagePaths,
24103
+ mediaPaths: record2.metadata?.mediaPaths
24104
+ }));
24105
+ return { pending, recovery };
24106
+ }
24107
+ async function markCliUserBatchPhase(store, dialogId, messageId, phase, messageIds, preparedMessages) {
24108
+ const key = `dialog-${dialogId}-msg-${messageId}`;
24109
+ const record2 = await store.read(key, { remote: false });
24110
+ if (!record2) throw new Error("Missing durable batch receipt");
24111
+ const current = record2.metadata?.cliBatchPhase;
24112
+ if (phase === "requested" && (current === "requested" || current === "completed")) {
24113
+ throw new Error(`Batch ${messageId} already requested; resubmission blocked`);
24114
+ }
24115
+ const ops = [];
24116
+ for (const id of messageIds) {
24117
+ const messageKey = `dialog-${dialogId}-msg-${id}`;
24118
+ const message = await store.read(messageKey, { remote: false });
24119
+ if (!message) throw new Error(`Missing batch user message ${id}`);
24120
+ const prepared = preparedMessages?.find((item) => item.cliMessageId === id);
24121
+ ops.push({ type: "put", key: messageKey, value: {
24122
+ ...message,
24123
+ ...prepared ? { content: prepared.content } : {},
24124
+ metadata: {
24125
+ ...message.metadata,
24126
+ queueState: "accepted",
24127
+ cliBatchId: messageId,
24128
+ ...Number.isFinite(prepared?.cliHistoryOrder) ? { cliHistoryOrder: prepared.cliHistoryOrder } : {},
24129
+ ...id === messageId ? { cliBatchPhase: phase, acceptedUserMessageIds: [...messageIds] } : {}
24130
+ }
24131
+ } });
24132
+ }
24133
+ await store.batch(ops);
24134
+ }
24135
+ async function rollbackCliUserBatchPhase(store, dialogId, batchId, messageIds) {
24136
+ const ops = [];
24137
+ for (const id of messageIds) {
24138
+ const key = `dialog-${dialogId}-msg-${id}`;
24139
+ const record2 = await store.read(key, { remote: false });
24140
+ if (!record2) continue;
24141
+ const metadata = { ...record2.metadata };
24142
+ delete metadata.cliBatchPhase;
24143
+ delete metadata.cliBatchId;
24144
+ delete metadata.acceptedUserMessageIds;
24145
+ metadata.queueState = "pending";
24146
+ ops.push({ type: "put", key, value: { ...record2, metadata } });
24147
+ }
24148
+ if (ops.length) await store.batch(ops);
24149
+ }
24150
+ async function buildCliBatchCompletionOp(store, dialogId, batchId) {
24151
+ const key = `dialog-${dialogId}-msg-${batchId}`;
24152
+ const record2 = await store.read(key, { remote: false });
24153
+ if (!record2) throw new Error(`Missing batch user message ${batchId}`);
24154
+ return { type: "put", key, value: {
24155
+ ...record2,
24156
+ metadata: { ...record2.metadata, cliBatchPhase: "completed" }
24157
+ } };
24158
+ }
24159
+ async function resolveCliUnknownBatchWithoutResend(store, dialogId, batchId) {
24160
+ const key = `dialog-${dialogId}-msg-${batchId}`;
24161
+ const record2 = await store.read(key, { remote: false });
24162
+ if (!record2 || record2.metadata?.cliBatchPhase !== "requested") throw new Error(`Unknown requested batch not found: ${batchId}`);
24163
+ if (record2.metadata.cliBatchResolution) return;
24164
+ await store.batch([{ type: "put", key, value: { ...record2, metadata: {
24165
+ ...record2.metadata,
24166
+ cliBatchResolution: { decision: "continue-without-resend", decidedBy: "user", decidedAt: (/* @__PURE__ */ new Date()).toISOString() }
24167
+ } } }]);
22691
24168
  }
22692
24169
 
22693
24170
  // packages/agent-runtime/noloWorkspaceTools.node.ts
@@ -22705,7 +24182,7 @@ async function runNoloWorkspaceCliTool(call, args2) {
22705
24182
  cmd,
22706
24183
  stdout: "pipe",
22707
24184
  stderr: "pipe",
22708
- env: args2.env
24185
+ env: call.name === "listAgents" ? { ...process.env, ...args2.env, NOLO_PLANNING_CALLER: JSON.stringify(args2.planningCaller ?? {}) } : args2.env
22709
24186
  });
22710
24187
  const [stdout, stderr, exitCode] = await Promise.all([
22711
24188
  readNoloProcessStream(proc.stdout),
@@ -22804,7 +24281,7 @@ function buildLoadSkillExecutor(args2) {
22804
24281
  const parsed = parseNoloWorkspaceToolArguments(call.arguments);
22805
24282
  const referenceKeys = ["source", "slug", "projectBinding", "relativePath", "dbKey", "id", "skillId"];
22806
24283
  if (referenceKeys.some((key) => Object.hasOwn(parsed, key))) {
22807
- return loadPreciseSkill(args2.cwd, parsed);
24284
+ return loadPreciseSkill(args2.cwd, parsed, args2.agentSkillSource, args2.resolveAgentSkillSource);
22808
24285
  }
22809
24286
  const name = noloStringArg(parsed.name ?? parsed.skillName ?? parsed.skill);
22810
24287
  if (!name) {
@@ -22813,12 +24290,14 @@ function buildLoadSkillExecutor(args2) {
22813
24290
  metadata: { loadSkill: true, resolved: false }
22814
24291
  };
22815
24292
  }
22816
- const { resolveSkillByName } = await import("./skillDiscovery-XKHROSH2.js");
24293
+ const { resolveSkillByName } = await import("./skillDiscovery-I37M5KJC.js");
22817
24294
  const resolved = resolveSkillByName(args2.cwd, name);
22818
24295
  if (!resolved) {
22819
- const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-2QETTQPM.js");
24296
+ const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-BAE2LDXF.js");
22820
24297
  const builtin = resolveBuiltinSkillByName(name);
22821
24298
  if (builtin) {
24299
+ const denied = await rejectDisabledBuiltin(args2.agentSkillSource, builtin.slug, name, args2.resolveAgentSkillSource);
24300
+ if (denied) return denied;
22822
24301
  return {
22823
24302
  content: `Skill "${name}" loaded inline. Follow its instructions.
22824
24303
 
@@ -22858,7 +24337,25 @@ ${body}`,
22858
24337
  }
22859
24338
  };
22860
24339
  }
22861
- async function loadPreciseSkill(cwd, parsed) {
24340
+ async function rejectDisabledBuiltin(source, slug, requestedName, resolveSource) {
24341
+ if (resolveSource) {
24342
+ try {
24343
+ source = await resolveSource();
24344
+ } catch {
24345
+ source = null;
24346
+ }
24347
+ if (!source) return {
24348
+ content: `Skill "${requestedName}" cannot be loaded: current agent policy is unavailable.`,
24349
+ metadata: { loadSkill: true, resolved: false, builtin: true, policyUnavailable: true, slug, name: requestedName, requestedName }
24350
+ };
24351
+ }
24352
+ if (!isAgentSkillDisabled(source, slug)) return null;
24353
+ return {
24354
+ content: `Skill "${requestedName}" \u5DF2\u88AB\u7981\u7528\uFF1A\u8BE5\u80FD\u529B\u5728\u6B64 agent \u4E0A\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u52A0\u8F7D\u3002`,
24355
+ metadata: { loadSkill: true, resolved: false, builtin: true, disabled: true, slug, name: requestedName, requestedName }
24356
+ };
24357
+ }
24358
+ async function loadPreciseSkill(cwd, parsed, agentSkillSource, resolveAgentSkillSource) {
22862
24359
  const source = parsed.source;
22863
24360
  const has2 = (key) => Object.hasOwn(parsed, key);
22864
24361
  const reject = (reason) => ({
@@ -22875,9 +24372,11 @@ async function loadPreciseSkill(cwd, parsed) {
22875
24372
  if (!nonEmpty(parsed.slug) || has2("projectBinding") || has2("relativePath")) {
22876
24373
  return reject("builtin requires only an exact slug.");
22877
24374
  }
22878
- const { listBuiltinSkills } = await import("./builtinSkillRegistry-2QETTQPM.js");
24375
+ const { listBuiltinSkills } = await import("./builtinSkillRegistry-BAE2LDXF.js");
22879
24376
  const builtin = listBuiltinSkills().find((entry) => entry.slug === parsed.slug);
22880
24377
  if (!builtin) return reject("builtin slug not found.");
24378
+ const denied = await rejectDisabledBuiltin(agentSkillSource, builtin.slug, builtin.slug, resolveAgentSkillSource);
24379
+ if (denied) return { ...denied, metadata: { ...denied.metadata, source } };
22881
24380
  return {
22882
24381
  content: `Skill "${builtin.slug}" loaded inline. Follow its instructions.
22883
24382
 
@@ -22899,7 +24398,7 @@ ${builtin.content}`,
22899
24398
  }
22900
24399
  try {
22901
24400
  const { realpathSync, statSync, readFileSync } = await import("node:fs");
22902
- const { resolve: resolve6, relative: relative6, isAbsolute: isAbsolute5, basename: basename3, sep: sep3 } = await import("node:path");
24401
+ const { resolve: resolve6, relative: relative6, isAbsolute: isAbsolute5, basename: basename4, sep: sep3 } = await import("node:path");
22903
24402
  const inside = (root, target) => {
22904
24403
  const rel = relative6(root, target);
22905
24404
  return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute5(rel);
@@ -22908,7 +24407,7 @@ ${builtin.content}`,
22908
24407
  if (!isAbsolute5(parsed.projectBinding) || realpathSync(parsed.projectBinding) !== realCwd) {
22909
24408
  return reject("projectBinding does not match the authorized cwd.");
22910
24409
  }
22911
- if (isAbsolute5(parsed.relativePath) || basename3(parsed.relativePath) !== "SKILL.md") {
24410
+ if (isAbsolute5(parsed.relativePath) || basename4(parsed.relativePath) !== "SKILL.md") {
22912
24411
  return reject("relativePath must reference a project SKILL.md.");
22913
24412
  }
22914
24413
  const skillsRoot = resolve6(realCwd, ".agents", "skills");
@@ -22916,7 +24415,7 @@ ${builtin.content}`,
22916
24415
  if (!inside(skillsRoot, candidate)) return reject("path is outside cwd/.agents/skills/.");
22917
24416
  const realRoot = realpathSync(skillsRoot);
22918
24417
  const realPath = realpathSync(candidate);
22919
- if (realRoot !== skillsRoot || !inside(realRoot, realPath) || basename3(realPath) !== "SKILL.md") {
24418
+ if (realRoot !== skillsRoot || !inside(realRoot, realPath) || basename4(realPath) !== "SKILL.md") {
22920
24419
  return reject("skill path escapes cwd/.agents/skills/ or is not SKILL.md.");
22921
24420
  }
22922
24421
  if (!statSync(realPath).isFile()) return reject("SKILL.md is not a file.");
@@ -22939,7 +24438,7 @@ ${body}`,
22939
24438
  }
22940
24439
  }
22941
24440
  async function formatUnknownSkillMessage(cwd, requestedName) {
22942
- const { discoverSkills } = await import("./skillDiscovery-XKHROSH2.js");
24441
+ const { discoverSkills } = await import("./skillDiscovery-I37M5KJC.js");
22943
24442
  let available = [];
22944
24443
  try {
22945
24444
  available = discoverSkills(cwd).map((s) => s.name);
@@ -23582,6 +25081,7 @@ export {
23582
25081
  createStrictHostCredentialBroker,
23583
25082
  readCommandActionGatePayload,
23584
25083
  readActionGate,
25084
+ orderDialogHistory,
23585
25085
  Option_exports,
23586
25086
  Duration_exports,
23587
25087
  Exit_exports,
@@ -23604,12 +25104,15 @@ export {
23604
25104
  createLocalWorkspaceToolExecutors,
23605
25105
  buildToolParametersIndex,
23606
25106
  getAgentRuntimeToolParametersIndex,
25107
+ registerLocalShellLifecycle,
25108
+ getLocalShellLifecycle,
23607
25109
  normalizeLocalToolName,
23608
25110
  isCommandExecutingTool,
23609
25111
  resolveLocalToolPolicy,
23610
25112
  runExecShellGates,
23611
25113
  executeLocalToolWithPolicy,
23612
25114
  LOCAL_TURN_ABORTED_CODE,
25115
+ projectContextProvenance,
23613
25116
  hashToolDefinitions,
23614
25117
  LOCAL_AGENT_CONFIG_MISSING_CODE,
23615
25118
  runLocalAgentTurn,
@@ -23621,6 +25124,7 @@ export {
23621
25124
  parseOpenAiCompatibleChatCompletionResponse,
23622
25125
  readOpenAiCompatibleSseCompletion,
23623
25126
  executeOpenAiCompatibleChatCompletion,
25127
+ describeOpenAiCompatibleRequestBudget,
23624
25128
  resolveOpenAiCompatibleProviderConfig,
23625
25129
  dialogMessageRecordToAgentRuntimeMessage,
23626
25130
  buildAgentRuntimeDialogWritePlan,
@@ -23628,8 +25132,15 @@ export {
23628
25132
  parseSyncServersEnv,
23629
25133
  DEFAULT_HYBRID_READ_TIMEOUT_MS,
23630
25134
  createHybridRecordStore,
25135
+ registerDialogOwner,
23631
25136
  localDialogMessageRecordToRuntimeMessage,
23632
25137
  buildLocalDialogWritePlan,
25138
+ saveCliPendingUserMessages,
25139
+ readCliPendingUserMessages,
25140
+ markCliUserBatchPhase,
25141
+ rollbackCliUserBatchPhase,
25142
+ buildCliBatchCompletionOp,
25143
+ resolveCliUnknownBatchWithoutResend,
23633
25144
  buildNoloWorkspaceCliToolExecutors,
23634
25145
  buildLoadSkillExecutor,
23635
25146
  isStableSessionIdentityEnabled,