nolo-cli 0.228.0-alpha.1 → 0.228.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 (238) hide show
  1. package/README.md +3 -5
  2. package/{_executeModel-WZKT6XEU.js → _executeModel-GIFVXKDT.js} +89 -82
  3. package/{accountResolver-QETKNC7T.js → accountResolver-NGICIMEE.js} +1 -1
  4. package/{action-GDZDXPMB.js → action-WZTKEF5H.js} +9 -6
  5. package/{addContentAction-7RO4AMRI.js → addContentAction-MLI6GOBV.js} +14 -13
  6. package/{addDialogAgentAction-EVYBGTXB.js → addDialogAgentAction-ARGQM22H.js} +17 -16
  7. package/{agentDeleteCommand-PZWRHNXY.js → agentDeleteCommand-UF7XVELS.js} +120 -111
  8. package/{agentEmailCommands-QTKMEICX.js → agentEmailCommands-SFHRPQYC.js} +120 -107
  9. package/agentListCommands-IXKBP3W5.js +644 -0
  10. package/{agentMachineCommands-7QGICJLM.js → agentMachineCommands-7NX6PWQ6.js} +56 -48
  11. package/{agentProviderCommands-STI3DQ6A.js → agentProviderCommands-C5T7C5KZ.js} +2 -2
  12. package/{agentPullCommand-KHV4EELF.js → agentPullCommand-4EQZYHU4.js} +1 -1
  13. package/agentRecordCommands-IUNX6XD6.js +188 -0
  14. package/{agentRunCommand-OFQLOF5Y.js → agentRunCommand-LCR4XADM.js} +127 -111
  15. package/{agentRunControl-MBG4U6SL.js → agentRunControl-RN2P6AOD.js} +11 -9
  16. package/{agentRuntimeLocal-TU4LA353.js → agentRuntimeLocal-LVXPQ7QA.js} +57 -43
  17. package/{agentSlice-L4SBGWTB.js → agentSlice-ZGMOH6TE.js} +15 -14
  18. package/{appDeleteCommands-JWP3XPUA.js → appDeleteCommands-BESCJOQM.js} +56 -48
  19. package/{appDeployCommands-6E4TQCWI.js → appDeployCommands-LPTR6IOX.js} +56 -48
  20. package/{appDeployStatusCommands-ALU4SADG.js → appDeployStatusCommands-BZ7KZ5RD.js} +56 -48
  21. package/{appGetCommands-JEY4L6L4.js → appGetCommands-EDWGJV4S.js} +56 -48
  22. package/{appListCommands-PCAVHU7M.js → appListCommands-OPRWYPM6.js} +56 -48
  23. package/{authCommand-CGRIIOOV.js → authCommand-3C3RN4OU.js} +25 -19
  24. package/{authCommands-55OGQGCR.js → authCommands-ZMVEDCQD.js} +12 -6
  25. package/{builtinSkillRegistry-BAE2LDXF.js → builtinSkillRegistry-VRCMQ77Q.js} +7 -7
  26. package/{chromeCommands-G5UDKVSV.js → chromeCommands-O4IIKTBD.js} +384 -7
  27. package/{chromeOpsCommands-WAA45NCS.js → chromeOpsCommands-NZITLHWO.js} +3 -3
  28. package/{chunk-AUAJTAFM.js → chunk-2BKNICGK.js} +4 -4
  29. package/{chunk-QYB23WUH.js → chunk-2FK2KZSL.js} +1 -1
  30. package/chunk-2SXN7LAY.js +15 -0
  31. package/{chunk-H6L2NFHY.js → chunk-3DJJ4CFG.js} +11 -11
  32. package/{chunk-TSPMLCWI.js → chunk-4IQN6FWY.js} +5 -5
  33. package/{chunk-GUXZK7SE.js → chunk-4OXPN3WC.js} +17 -6
  34. package/chunk-4ZCTKB27.js +31 -0
  35. package/chunk-53W5BXLN.js +340 -0
  36. package/{chunk-3P54D2E4.js → chunk-5HUO7SEX.js} +9 -107
  37. package/chunk-6ASGEP5D.js +21 -0
  38. package/{chunk-DDC6P6EH.js → chunk-6CXQ3YNJ.js} +68 -40
  39. package/{chunk-G7IUT2V3.js → chunk-6MTVACLN.js} +365 -64
  40. package/{chunk-ZOHO6MOF.js → chunk-6RSNVJGO.js} +2 -99
  41. package/{chunk-XSW4EXQV.js → chunk-6TVYUQRM.js} +55 -18
  42. package/{chunk-PDCV7P5W.js → chunk-6XIE5ZGI.js} +1 -1
  43. package/{chunk-7Z6EW7AH.js → chunk-6XVPMGXK.js} +97 -11
  44. package/{chunk-ALAES342.js → chunk-73PZD7JZ.js} +9 -5
  45. package/{chunk-2MCB7CD7.js → chunk-7UVVLYKC.js} +9 -9
  46. package/{chunk-S6FDXXZV.js → chunk-ADOOL3PG.js} +2 -2
  47. package/{chunk-OWKNSIXL.js → chunk-AEZBAFC6.js} +334 -77
  48. package/{chunk-PWTNI4N7.js → chunk-ANUP75N2.js} +22 -0
  49. package/{chunk-RG2DGNL6.js → chunk-ARFCL53U.js} +5 -5
  50. package/{chunk-SRCCSTIM.js → chunk-AS6L5KSD.js} +4 -4
  51. package/{chunk-GPOV42YM.js → chunk-BAH3BAUZ.js} +8 -8
  52. package/{chunk-N5Z2V73W.js → chunk-BFKJ2RS3.js} +1 -1
  53. package/{chunk-F6Z6ZCUV.js → chunk-BVEDT6DM.js} +3 -3
  54. package/chunk-C5A54QS7.js +108 -0
  55. package/{chunk-CD3RU7XL.js → chunk-CD2DK5JA.js} +120 -14
  56. package/{chunk-BP5ZJ6B4.js → chunk-CD64YXRB.js} +1 -1
  57. package/{chunk-VP3BINY7.js → chunk-CIGCTSBF.js} +31 -1
  58. package/{chunk-D6YNCNM6.js → chunk-CIUZXD5D.js} +12 -12
  59. package/{chunk-EVGU5P4U.js → chunk-CO6E7YK6.js} +1 -1
  60. package/{chunk-VMJVAJ6W.js → chunk-CTIEJRTP.js} +28 -4
  61. package/{chunk-7JGMNKKG.js → chunk-CTWCZKNS.js} +29 -8
  62. package/{chunk-YFLVRVYK.js → chunk-D25ONVOH.js} +1 -1
  63. package/{chunk-LKA64WH4.js → chunk-DMPZMYH4.js} +37 -1
  64. package/{chunk-262R3XNN.js → chunk-E5RYFR7E.js} +334 -103
  65. package/{chunk-OQHIVPG4.js → chunk-E6A5NHDH.js} +4 -1
  66. package/{chunk-HSSBDZLD.js → chunk-EDT65EUE.js} +6 -6
  67. package/{chunk-IAAIUH64.js → chunk-EQZQUQ33.js} +7 -7
  68. package/{chunk-HBRDSQ3M.js → chunk-ESN4WNWU.js} +3 -2
  69. package/{chunk-2YGBI2XB.js → chunk-FE7G6DSP.js} +11 -1
  70. package/{chunk-547ENH5T.js → chunk-FFFKAOJN.js} +4 -4
  71. package/{chunk-5ZUOVCKT.js → chunk-FGHEF6WI.js} +3 -1
  72. package/{chunk-IXG6YXQM.js → chunk-FTWAOKFU.js} +795 -361
  73. package/chunk-GAHJLSDO.js +107 -0
  74. package/{chunk-2X7WFDT6.js → chunk-GX6DITLQ.js} +1 -1
  75. package/{chunk-GYS5FUYR.js → chunk-HCCQEMTK.js} +28 -28
  76. package/{chunk-CMMI3DAT.js → chunk-HZDK56EK.js} +33 -26
  77. package/{chunk-UE2EVEYS.js → chunk-IIOSZAJX.js} +4 -4
  78. package/chunk-IIRJ4P4I.js +24 -0
  79. package/{chunk-QCB42576.js → chunk-IJZC2KIJ.js} +1 -1
  80. package/{chunk-RYOLWYBK.js → chunk-ITBX27W6.js} +97 -21
  81. package/{chunk-VSYTM22R.js → chunk-J2VIGDJN.js} +6 -6
  82. package/{chunk-QBZCGP34.js → chunk-JEWMQR6J.js} +1 -1
  83. package/{chunk-6QHKRARD.js → chunk-JFRJEPFI.js} +29 -5
  84. package/{chunk-S6K5F3KP.js → chunk-JP2BH4NC.js} +1 -1
  85. package/{chunk-MDZWUD3R.js → chunk-JU7VN4LF.js} +38 -29
  86. package/{chunk-RTHFJZ6M.js → chunk-K26XPZRB.js} +2 -2
  87. package/{chunk-ZYKJBRZ3.js → chunk-K7VIXYTZ.js} +1 -3
  88. package/chunk-KK3FCYZM.js +647 -0
  89. package/chunk-KLAMJNKQ.js +33394 -0
  90. package/{chunk-4JVNURX4.js → chunk-KQHEGELM.js} +68 -16
  91. package/chunk-KXOPLLFP.js +190 -0
  92. package/{chunk-GOCSSER3.js → chunk-KZ5OD2MO.js} +4 -4
  93. package/{chunk-ILHQ2AXT.js → chunk-KZAT2M2V.js} +14 -8
  94. package/chunk-LHCGKAFO.js +739 -0
  95. package/{chunk-XJPLSAPJ.js → chunk-LMGFVH65.js} +107 -104
  96. package/{chunk-QRGDJA4B.js → chunk-LTVEOOZL.js} +19 -6
  97. package/{chunk-L32W3PRP.js → chunk-MAA42MMV.js} +233 -17
  98. package/{chunk-ATEKLSLR.js → chunk-MTM4LRVG.js} +14 -9
  99. package/chunk-MVOZ22RZ.js +26 -0
  100. package/{chunk-2NPD3FTX.js → chunk-MYYNZG2M.js} +139 -39
  101. package/{chunk-DBUR22G5.js → chunk-MZVCFV3T.js} +19 -15
  102. package/{chunk-K67C2JUC.js → chunk-N74XL3NI.js} +9 -9
  103. package/{chunk-VS276URX.js → chunk-NEG5LYK5.js} +1 -1
  104. package/{chunk-RBPUNSG5.js → chunk-OAZP4TSA.js} +18 -108
  105. package/{chunk-SMJEXX2S.js → chunk-ODBYGVO2.js} +232 -10
  106. package/{chunk-M4SFKP5L.js → chunk-OHUYN3YU.js} +3 -3
  107. package/{chunk-HYLRQDEE.js → chunk-OLGFIQN2.js} +6 -6
  108. package/{chunk-M3JEW6N6.js → chunk-OYUMJMC5.js} +15 -0
  109. package/chunk-P27E22MA.js +203 -0
  110. package/{chunk-BIWI5M4E.js → chunk-PBPXXMWZ.js} +1 -1
  111. package/{chunk-OBSEKCVK.js → chunk-PQ63BDV3.js} +210 -51
  112. package/{chunk-4I2MXV5Q.js → chunk-PVFYPUIM.js} +2 -0
  113. package/{chunk-OG6MQOQG.js → chunk-QMNVV3YM.js} +10 -37
  114. package/{chunk-GACR7H6T.js → chunk-R5NRFXGD.js} +5 -5
  115. package/{chunk-5FUN7EG4.js → chunk-RD3QLZQV.js} +83 -47
  116. package/{chunk-4WVJLODK.js → chunk-RHBD22LV.js} +9 -4
  117. package/{chunk-EXJK7TQO.js → chunk-RMWDKLBE.js} +1520 -562
  118. package/{chunk-TGNIKIHR.js → chunk-RR3MB26M.js} +2 -2
  119. package/{chunk-OOJNQK6V.js → chunk-S25VJYXV.js} +8 -2
  120. package/{chunk-STJ6LSQE.js → chunk-SCMYAGQE.js} +1135 -712
  121. package/{chunk-YKY4OVOX.js → chunk-SPU3L3OR.js} +17 -170
  122. package/chunk-SR4FE5VD.js +9 -0
  123. package/{chunk-DUUDXSLX.js → chunk-SX6AWTNK.js} +28 -4
  124. package/{chunk-ZH3KXFHS.js → chunk-TMRJGSK2.js} +1 -1
  125. package/{chunk-S2NTVGA2.js → chunk-U35UUM5K.js} +2 -1
  126. package/{chunk-PPJYZRSQ.js → chunk-U5LOKQ2R.js} +30 -14
  127. package/{chunk-UAIHKQIA.js → chunk-U6RD332P.js} +18 -2
  128. package/{chunk-3U44JB3O.js → chunk-UF6J7NXV.js} +1 -1
  129. package/{chunk-Q3IVPFVO.js → chunk-UHW6SCVK.js} +1 -1
  130. package/chunk-UOUMPHS5.js +103 -0
  131. package/{chunk-HHFGE2WF.js → chunk-UPOW5HTG.js} +5 -5
  132. package/{chunk-DEA37IUY.js → chunk-V4IYI3SB.js} +2 -2
  133. package/{chunk-UWAIJOF2.js → chunk-VKCPKCSS.js} +66 -92
  134. package/{chunk-HGDKT2D6.js → chunk-VTHWBTRE.js} +177 -1
  135. package/{chunk-OBIC6EG7.js → chunk-VUHKG4KS.js} +3 -3
  136. package/{chunk-EEOOBRA7.js → chunk-W3HSD32M.js} +13 -6
  137. package/{chunk-P2ZLUIW2.js → chunk-W6T4FNZP.js} +351 -26
  138. package/chunk-WDWZPASX.js +29 -0
  139. package/chunk-WFGNWWJI.js +326 -0
  140. package/{chunk-R6Z5S5GA.js → chunk-WQDTSK5U.js} +51 -14
  141. package/{chunk-OYU2MA5S.js → chunk-X22AUZKL.js} +152 -167
  142. package/{chunk-4ZGPHFLE.js → chunk-X3OZ655T.js} +2 -2
  143. package/{chunk-NHY322ZU.js → chunk-XCA4WHX5.js} +588 -64
  144. package/{chunk-TI2EPRHE.js → chunk-XJSEST7D.js} +3 -3
  145. package/{chunk-JUSHVFNF.js → chunk-XNTZD4AE.js} +1230 -1356
  146. package/chunk-XSRSAU3O.js +133 -0
  147. package/{chunk-CYWNWA77.js → chunk-Y4NPF2UN.js} +6 -3
  148. package/{chunk-FJSNBZXR.js → chunk-YDRRGVT5.js} +1 -1
  149. package/{chunk-R3NEQZ53.js → chunk-YFW4H6DL.js} +405 -338
  150. package/{chunk-BNMPUQW6.js → chunk-YGDYYFRX.js} +20 -24
  151. package/{chunk-4N6G2CKP.js → chunk-YHNUDTU4.js} +49 -3
  152. package/chunk-YJPK35HB.js +175 -0
  153. package/{chunk-6OVNSQHN.js → chunk-YLAHYLDQ.js} +5 -0
  154. package/{chunk-AGYPUBFW.js → chunk-Z7KE4K3H.js} +195 -123
  155. package/{chunk-DGYCDA6W.js → chunk-ZM5AZTQG.js} +20 -13
  156. package/{chunk-CBUZ6DKA.js → chunk-ZQ6K57FJ.js} +1 -1
  157. package/{cliAgentConfigHelpers-BTRHMPW2.js → cliAgentConfigHelpers-37ZNEY5Y.js} +9 -9
  158. package/{cliAuthorityBrokerClient-XHH7MH2P.js → cliAuthorityBrokerClient-SFPC3WVK.js} +1 -1
  159. package/{cliLocalAgentRecordReader-M3F76NIP.js → cliLocalAgentRecordReader-MCQVRWBR.js} +59 -47
  160. package/{commandRegistry-ZLWHQVAI.js → commandRegistry-NTH5IAN5.js} +104 -92
  161. package/{contentThunks-4ZX2TO7C.js → contentThunks-SPXTX5U2.js} +38 -36
  162. package/{cooldownCommands-YB5H5BBK.js → cooldownCommands-TIFCHCUN.js} +1 -1
  163. package/{createAgentAutomationAction-L4CYUZJG.js → createAgentAutomationAction-KUQKCOXB.js} +38 -36
  164. package/{createDialogAction-QTU2R2Q3.js → createDialogAction-HJN5U3XS.js} +39 -37
  165. package/{createPageAction-F3GJTHW2.js → createPageAction-ZAHRDOAU.js} +43 -41
  166. package/{db-M7FU2GNK.js → db-CMUTP3W5.js} +2 -2
  167. package/{dbSlice-XRUZOGSU.js → dbSlice-656PMWR2.js} +13 -12
  168. package/{deleteFile-6URDHYRB.js → deleteFile-ZCQESEEQ.js} +10 -7
  169. package/{dialogCommands-NRLCOPJR.js → dialogCommands-KZTZLWPZ.js} +61 -54
  170. package/dialogMessageRecord-OAV77LT7.js +7 -0
  171. package/{dialogNotifyCommand-SHGPCU22.js → dialogNotifyCommand-PST75COP.js} +11 -11
  172. package/{dialogSlice-P2S4LXQD.js → dialogSlice-BXIERQHO.js} +39 -37
  173. package/{dialogUsageCommand-W2WCSGKF.js → dialogUsageCommand-6RW2FY6K.js} +5 -5
  174. package/{docCreateCommands-YJRDA3RX.js → docCreateCommands-26HJ5NAY.js} +55 -47
  175. package/{docDeleteCommands-A5QIHZNF.js → docDeleteCommands-UAOHH5XK.js} +57 -49
  176. package/{docReadCommands-CF2LTMYH.js → docReadCommands-4ADG7YE6.js} +55 -47
  177. package/{docStore-6O7NYL6A.js → docStore-FZ75HWP2.js} +15 -14
  178. package/{docUpdateCommands-QRKV4ZXE.js → docUpdateCommands-OGFJZENF.js} +55 -47
  179. package/fetchMessages-TQEUZD7H.js +1 -1
  180. package/{getPricing-LF5C4XSI.js → getPricing-FCHYVRJU.js} +4 -4
  181. package/{handleSendMessageAction-7IHLR37A.js → handleSendMessageAction-KP6GGBFY.js} +84 -79
  182. package/{hostCredentialCreate-VNCQUAFT.js → hostCredentialCreate-23TX56G7.js} +119 -105
  183. package/index.js +8 -8
  184. package/{lib-OT5OTXRU.js → lib-62SWPXNF.js} +3 -7
  185. package/{localDialogRead-CCOCVGAP.js → localDialogRead-CIOTQM5T.js} +1 -1
  186. package/{localRuntimeAdapter-FOWVNMIK.js → localRuntimeAdapter-MTUWOYPN.js} +126 -111
  187. package/{localRuntimeAuthority-IBJAT62G.js → localRuntimeAuthority-TYHQCTZN.js} +5 -3
  188. package/{localRuntimeDb-N7KHDXS2.js → localRuntimeDb-BO7IVWAZ.js} +1 -1
  189. package/{machineCommands-ZGC3J4JB.js → machineCommands-4WJUJQHW.js} +260 -323
  190. package/{machineWsRunDispatch-KK5U4M3G.js → machineWsRunDispatch-V3U4JM67.js} +115 -102
  191. package/markdownToSlate-KIYM7B3P.js +8 -0
  192. package/mcpLocalAuthorizeCommand-TI656UWC.js +106 -0
  193. package/{memberThunks-7Y3OYSJQ.js → memberThunks-JFYC4Z5L.js} +20 -15
  194. package/{models-H5NNZRLH.js → models-EP7VG6N2.js} +2 -2
  195. package/{overlay-BBQZXGYI.js → overlay-JA3SPVUS.js} +5 -3
  196. package/package.json +1 -1
  197. package/{projectArchive-7ZDYBXAX.js → projectArchive-NU2Z5HOR.js} +45 -43
  198. package/{providerPresetApply-WHAMP2D5.js → providerPresetApply-4H7YP5D7.js} +6 -6
  199. package/{providerRegistry-ZI2KORJ7.js → providerRegistry-F3UPOTIY.js} +6 -6
  200. package/{read-TYMBGEXO.js → read-BRZHXUJ6.js} +9 -8
  201. package/{readDocTool-SKQVHBLO.js → readDocTool-N7RVFQEE.js} +1 -1
  202. package/{readlineWorkspace-YHT4SX2C.js → readlineWorkspace-T56MRMS5.js} +6426 -3669
  203. package/rememberExplicit-CPAPONSI.js +15 -0
  204. package/{removeDialogAgentAction-F5QE2O2B.js → removeDialogAgentAction-J7XU7OUX.js} +19 -18
  205. package/{runAgentClientLoop-H4ED5V3K.js → runAgentClientLoop-O2GRCGRZ.js} +97 -75
  206. package/{runtimeDoctorCommands-RRKPBGVO.js → runtimeDoctorCommands-RDRJXMXC.js} +8 -8
  207. package/{secretCommands-KZWBZIYS.js → secretCommands-2FEMRUFM.js} +3 -3
  208. package/{setDialogExtraReferencesAction-72L27ERM.js → setDialogExtraReferencesAction-Q4V2ZZW2.js} +16 -15
  209. package/{setPrimaryDialogAgentAction-GJJDUSGJ.js → setPrimaryDialogAgentAction-742H5S6T.js} +19 -18
  210. package/{settingThunks-ZRGWVGZD.js → settingThunks-T4FXSV6M.js} +185 -66
  211. package/{skillDiscovery-I37M5KJC.js → skillDiscovery-MDDKPTW3.js} +4 -3
  212. package/{spaceCommands-MEH3HJBC.js → spaceCommands-W5TAVFDT.js} +59 -51
  213. package/{streamAgentChatTurn-ZXPOXU33.js → streamAgentChatTurn-OWDJMU5E.js} +238 -178
  214. package/{switchDialogAgentAction-IIJBPND3.js → switchDialogAgentAction-HLDLHRRA.js} +17 -16
  215. package/{tableCommands-FTAOCBTX.js → tableCommands-44GC4N6J.js} +8 -5
  216. package/{toolApiClient-OGQEBQVX.js → toolApiClient-N5PYW2R3.js} +8 -6
  217. package/{tools-2MRWA2PP.js → tools-O7SGGVA3.js} +67 -62
  218. package/{tuiRestart-2IL37YIB.js → tuiRestart-EOGC2BYY.js} +10 -10
  219. package/{tuiSummaryLlmCaller-W2QN4VAC.js → tuiSummaryLlmCaller-TM5BU73J.js} +16 -15
  220. package/{updateCommands-CPATDG6J.js → updateCommands-FBYA5WVG.js} +3 -3
  221. package/{updateDialogTitleAction-RZ3KZSGQ.js → updateDialogTitleAction-EXSZGTLL.js} +40 -38
  222. package/{usageCommand-2BF74MKF.js → usageCommand-L4OFWXEU.js} +2 -2
  223. package/{usageRebuildCommand-UHB55BQM.js → usageRebuildCommand-7JR33UHS.js} +3 -3
  224. package/webapi-QVV65DQF.js +2487 -0
  225. package/{windowsSelfUpdate-ZFD6J5HF.js → windowsSelfUpdate-M4V77OUB.js} +2 -2
  226. package/workContext-Y3ADAPZU.js +14 -0
  227. package/workContextAccess-VU5I4LKZ.js +11 -0
  228. package/workContextWriteNotice-YCSSMHN4.js +7 -0
  229. package/{workloadLifecycle-HFJIN5IZ.js → workloadLifecycle-ZCSQCHG3.js} +2 -2
  230. package/agentListCommands-GUGMORTK.js +0 -1005
  231. package/agentRecordCommands-SLLADS5C.js +0 -175
  232. package/chunk-2WZXXAQD.js +0 -57
  233. package/chunk-5ZMIIR23.js +0 -265
  234. package/chunk-62HXNQVV.js +0 -134
  235. package/chunk-TUSTONB3.js +0 -81
  236. package/chunk-ZXF6D3I6.js +0 -359
  237. package/{chunk-W6RFEDN4.js → chunk-AETZ7AD6.js} +3 -3
  238. /package/{chunk-FJ23FZXF.js → chunk-VIYVRPMJ.js} +0 -0
@@ -1,11 +1,13 @@
1
1
  import {
2
+ AGENT_PROMPT_IN_MESSAGES,
2
3
  DEVIN_CONNECT_URL,
3
4
  parseSseDataLineJson,
4
5
  parseSseDataLineObject
5
- } from "./chunk-2NPD3FTX.js";
6
+ } from "./chunk-MYYNZG2M.js";
6
7
  import {
8
+ ALWAYS_EXCLUDED_GLOBS,
7
9
  EXECUTION_BACKEND_KINDS
8
- } from "./chunk-PWTNI4N7.js";
10
+ } from "./chunk-ANUP75N2.js";
9
11
  import {
10
12
  formatImageSummary,
11
13
  readLocalImage
@@ -18,7 +20,7 @@ import {
18
20
  flushChatCompletionStream,
19
21
  providerHttpFailure,
20
22
  throwIfChatCompletionStreamFailed
21
- } from "./chunk-HSSBDZLD.js";
23
+ } from "./chunk-EDT65EUE.js";
22
24
  import {
23
25
  readSseFrames
24
26
  } from "./chunk-HNUWUO75.js";
@@ -30,19 +32,7 @@ import {
30
32
  evaluateRequestBudget,
31
33
  hasImageInRuntimeMessages,
32
34
  stripImagePartsFromMessages
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";
35
+ } from "./chunk-4OXPN3WC.js";
46
36
  import {
47
37
  applyShapingCounts,
48
38
  attachProjectionFacts,
@@ -53,7 +43,7 @@ import {
53
43
  projectUserPartForModel,
54
44
  resolveOutboundDiagnosticSink,
55
45
  writeThinkingFacts
56
- } from "./chunk-QYB23WUH.js";
46
+ } from "./chunk-2FK2KZSL.js";
57
47
  import {
58
48
  createThinkParserState,
59
49
  createToolCallAccumulator,
@@ -62,16 +52,9 @@ import {
62
52
  finalizeAccumulatedToolCalls
63
53
  } from "./chunk-56GBUMO5.js";
64
54
  import {
65
- CREDENTIAL_HYGIENE_RULE,
66
- DELETE_SAFETY_RED_LINE,
67
- DISPATCH_BACKEND_POLICY,
68
- DISPATCH_CANDIDATE_POLICY,
69
- PARALLEL_DISPATCH_DEFAULT_RULE,
70
- PLATFORM_RISK_CONTROL_RULE,
71
55
  TOOL_GUIDED_SECTION_ORDER,
72
- VERIFY_BEFORE_CONCLUDING_RULE,
73
- buildConsultationModeBlock,
74
56
  buildIdentityBlock,
57
+ buildPlatformStaticScopedBlocks,
75
58
  buildRuntimeGuidanceBlocks,
76
59
  detectDispatchIntent,
77
60
  detectDispatchIntentFromMessages,
@@ -79,7 +62,22 @@ import {
79
62
  hashStablePrefixContent,
80
63
  resolveResponseGuidelines,
81
64
  resolveToolGuidedSections
82
- } from "./chunk-AGYPUBFW.js";
65
+ } from "./chunk-Z7KE4K3H.js";
66
+ import {
67
+ BRIDGE_STREAM_MAX_CHARS,
68
+ CLI_NOLO_WORKSPACE_TOOL_NAMES,
69
+ DEFAULT_READ_DIALOG_MAX_RESPONSE_CHARS,
70
+ NOLO_WORKSPACE_TOOL_NAMES,
71
+ buildDialogReadEnvelope,
72
+ buildNoloWorkspaceCommandArgs,
73
+ buildNoloWorkspaceOpenAiTools,
74
+ createStreamingDialogReadProjector,
75
+ noloPositiveIntegerString,
76
+ noloStringArg,
77
+ parseNoloWorkspaceToolArguments,
78
+ readTextStreamUpToChars,
79
+ resolveNoloDialogInput
80
+ } from "./chunk-ITBX27W6.js";
83
81
  import {
84
82
  classifyUnparsableToolArgs,
85
83
  collectStablePromptPrefix,
@@ -103,7 +101,7 @@ import {
103
101
  toOpenAiCompatibleMessages,
104
102
  toResponsesTools,
105
103
  transferDowngradedToolTurnOrigin
106
- } from "./chunk-EEOOBRA7.js";
104
+ } from "./chunk-W3HSD32M.js";
107
105
  import {
108
106
  TOOL_HAD_IMAGES,
109
107
  TOOL_IMAGES,
@@ -118,29 +116,33 @@ import {
118
116
  withoutToolImages
119
117
  } from "./chunk-X4O7FJF5.js";
120
118
  import {
121
- BRIDGE_STREAM_MAX_CHARS,
122
- CLI_NOLO_WORKSPACE_TOOL_NAMES,
123
- DEFAULT_READ_DIALOG_MAX_RESPONSE_CHARS,
124
- NOLO_WORKSPACE_TOOL_NAMES,
125
- buildDialogReadEnvelope,
126
- buildNoloWorkspaceCommandArgs,
127
- buildNoloWorkspaceOpenAiTools,
128
- createStreamingDialogReadProjector,
129
- noloPositiveIntegerString,
130
- noloStringArg,
131
- parseNoloWorkspaceToolArguments,
132
- readTextStreamUpToChars,
133
- resolveNoloDialogInput
134
- } from "./chunk-RYOLWYBK.js";
119
+ resolveToolExecutionContract
120
+ } from "./chunk-DMPZMYH4.js";
135
121
  import {
136
- applyToolSurfaceConstraints
137
- } from "./chunk-VS276URX.js";
122
+ resolveAgentImageInputSupport,
123
+ resolveToolImagePolicy
124
+ } from "./chunk-SX6AWTNK.js";
138
125
  import {
126
+ isContextOverflowText,
139
127
  isQuotaExhaustedError
140
128
  } from "./chunk-TLE77UJ5.js";
129
+ import {
130
+ PROJECT_INSTRUCTION_MAX_BYTES,
131
+ PROJECT_INSTRUCTION_MAX_CHARS,
132
+ SECRET_PATTERNS,
133
+ clipToolText,
134
+ hasPotentialSecrets,
135
+ isCompleteInstructionOutput,
136
+ resolveHistoricalToolContentCap,
137
+ resolveToolOutputProfile,
138
+ sanitizeToolOutputContent,
139
+ sanitizeToolOutputText,
140
+ scrubObjectSecrets,
141
+ scrubSecrets
142
+ } from "./chunk-WFGNWWJI.js";
141
143
  import {
142
144
  isAgentSkillDisabled
143
- } from "./chunk-FJSNBZXR.js";
145
+ } from "./chunk-YDRRGVT5.js";
144
146
  import {
145
147
  buildDialogFallbackTitleFromUserInput
146
148
  } from "./chunk-2MBTWINN.js";
@@ -152,16 +154,18 @@ import {
152
154
  resolveEmptyAssistantFallbackMessage,
153
155
  resolveEmptyAssistantOutcome,
154
156
  resolveTruncatedReasoningTailLog
155
- } from "./chunk-QRGDJA4B.js";
157
+ } from "./chunk-LTVEOOZL.js";
156
158
  import {
157
159
  COMPACTION_SUMMARY_SCHEMA_VERSION,
158
160
  COMPACTION_SUMMARY_SYSTEM_PROMPT,
159
- buildBoundedCompactionRequest,
160
161
  buildCompactionMetricsFromPlan,
162
+ buildHistoricalCompactionRequest,
161
163
  buildSummarySourceDiagnostics,
164
+ buildSummarySourceSegments,
162
165
  classifySummaryError,
163
166
  computeSummarySourceMetadata,
164
167
  createSummaryBudget,
168
+ diffSummarySourceSegments,
165
169
  formatCompactionMetricsLog,
166
170
  getMessageTokenCount,
167
171
  getModelContextWindow,
@@ -173,10 +177,9 @@ import {
173
177
  resolveCompressionTriggerRatio,
174
178
  resolveEffectiveCompactionBudgets,
175
179
  runSummaryWithContract,
176
- sha256Hex,
177
180
  summaryCompletionTokens,
178
181
  truncateToolOutputForContext
179
- } from "./chunk-L32W3PRP.js";
182
+ } from "./chunk-MAA42MMV.js";
180
183
  import {
181
184
  createProviderCallTimingTracker,
182
185
  finalizeProviderCallTiming,
@@ -184,21 +187,15 @@ import {
184
187
  observeMeaningfulProviderResponse,
185
188
  withProviderCallTimingFields
186
189
  } from "./chunk-H57T64RA.js";
190
+ import {
191
+ sha256Hex
192
+ } from "./chunk-SR4FE5VD.js";
187
193
  import {
188
194
  clipCompactText
189
195
  } from "./chunk-5MMAK75Q.js";
190
196
  import {
191
197
  asRecordOrEmpty
192
198
  } from "./chunk-KX6YBIHG.js";
193
- import {
194
- assertCredentialRef
195
- } from "./chunk-OQHIVPG4.js";
196
- import {
197
- isAbortError
198
- } from "./chunk-7DPNBQSV.js";
199
- import {
200
- isLevelNotFoundError
201
- } from "./chunk-OW765XBU.js";
202
199
  import {
203
200
  TOOL_OUTPUT_SPILL_BYTES,
204
201
  TOOL_OUTPUT_SPILL_LINES,
@@ -225,25 +222,51 @@ import {
225
222
  spillLargeToolOutput,
226
223
  spillToolOutput,
227
224
  toProcessTaskView,
228
- truncateToolOutput
229
- } from "./chunk-VMJVAJ6W.js";
225
+ truncateToolOutput,
226
+ workspaceChildEnv
227
+ } from "./chunk-CTIEJRTP.js";
230
228
  import {
231
229
  estimateTokenCount
232
230
  } from "./chunk-PSCNXBYA.js";
231
+ import {
232
+ isLevelNotFoundError
233
+ } from "./chunk-OW765XBU.js";
234
+ import {
235
+ isAbortError
236
+ } from "./chunk-7DPNBQSV.js";
237
+ import {
238
+ buildAgentsMdLayer,
239
+ buildAgentsMdLayerHeader,
240
+ buildDialogSummaryLayer,
241
+ hasMemoryTools
242
+ } from "./chunk-5HUO7SEX.js";
243
+ import {
244
+ MEMORY_USE_GUIDANCE,
245
+ buildUserResponseLanguageContext
246
+ } from "./chunk-YGDYYFRX.js";
233
247
  import {
234
248
  resolveNoloStateDir
235
249
  } from "./chunk-6UBGXX2W.js";
236
250
  import {
237
- WORKTREE_ISOLATION_PRELUDE
238
- } from "./chunk-G7IUT2V3.js";
251
+ isTombstoneRecord
252
+ } from "./chunk-BV3FLP2L.js";
239
253
  import {
240
- canonicalizeToolName,
241
- canonicalizeToolNames
242
- } from "./chunk-6OVNSQHN.js";
254
+ dialogMessageRecordToAgentRuntimeMessage
255
+ } from "./chunk-4ZCTKB27.js";
243
256
  import {
244
257
  dialogMessageKey,
245
258
  dialogMessageRange
246
259
  } from "./chunk-OJKUU3LP.js";
260
+ import {
261
+ resolveLocalUserId
262
+ } from "./chunk-UPOW5HTG.js";
263
+ import {
264
+ applyToolSurfaceConstraints
265
+ } from "./chunk-NEG5LYK5.js";
266
+ import {
267
+ canonicalizeToolName,
268
+ canonicalizeToolNames
269
+ } from "./chunk-YLAHYLDQ.js";
247
270
  import {
248
271
  asTrimmedNonEmptyStringArray
249
272
  } from "./chunk-I42VC5KR.js";
@@ -251,18 +274,12 @@ import {
251
274
  asOptionalPositiveFiniteNumber
252
275
  } from "./chunk-U6VC4MU4.js";
253
276
  import {
254
- buildDialogSummaryLayer
255
- } from "./chunk-3P54D2E4.js";
256
- import {
257
- buildUserResponseLanguageContext
258
- } from "./chunk-BNMPUQW6.js";
277
+ toErrorMessage
278
+ } from "./chunk-HNMXYYJR.js";
259
279
  import {
260
280
  buildProviderAuthHeaders,
261
281
  buildProviderExecutionPlan
262
- } from "./chunk-RTHFJZ6M.js";
263
- import {
264
- toErrorMessage
265
- } from "./chunk-HNMXYYJR.js";
282
+ } from "./chunk-K26XPZRB.js";
266
283
  import {
267
284
  asTrimmedString
268
285
  } from "./chunk-3EUW3WEO.js";
@@ -277,7 +294,7 @@ import {
277
294
  } from "./chunk-CF7PE763.js";
278
295
  import {
279
296
  PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL
280
- } from "./chunk-OBSEKCVK.js";
297
+ } from "./chunk-PQ63BDV3.js";
281
298
  import {
282
299
  asTrimmedLowercaseString
283
300
  } from "./chunk-QSJ3HFEF.js";
@@ -5582,8 +5599,8 @@ var runPromiseExitWith = (context3) => {
5582
5599
  const runFork3 = runForkWith(context3);
5583
5600
  return (effect, options) => {
5584
5601
  const fiber3 = runFork3(effect, options);
5585
- return new Promise((resolve6) => {
5586
- fiber3.addObserver((exit3) => resolve6(exit3));
5602
+ return new Promise((resolve7) => {
5603
+ fiber3.addObserver((exit3) => resolve7(exit3));
5587
5604
  });
5588
5605
  };
5589
5606
  };
@@ -12806,8 +12823,8 @@ var toReadableStreamWith = /* @__PURE__ */ dual((args2) => isStream(args2[0]), (
12806
12823
  }
12807
12824
  },
12808
12825
  pull() {
12809
- return new Promise((resolve6) => {
12810
- currentResolve = resolve6;
12826
+ return new Promise((resolve7) => {
12827
+ currentResolve = resolve7;
12811
12828
  latch.openUnsafe();
12812
12829
  });
12813
12830
  },
@@ -13341,255 +13358,6 @@ function sanitizeToolCallPairing(messages) {
13341
13358
  return output;
13342
13359
  }
13343
13360
 
13344
- // packages/agent-runtime/secretScrubber.ts
13345
- var SECRET_PATTERNS = [
13346
- // 1. PEM 私钥块(高危硬拦截)
13347
- {
13348
- kind: "PRIVATE_KEY",
13349
- placeholder: "[REDACTED:PRIVATE_KEY]",
13350
- regex: /-----BEGIN (?:[A-Z0-9 ]+)?PRIVATE KEY-----[\s\S]+?-----END (?:[A-Z0-9 ]+)?PRIVATE KEY-----/g
13351
- },
13352
- // 2. Anthropic API Key (sk-ant-...)
13353
- {
13354
- kind: "ANTHROPIC_KEY",
13355
- placeholder: "[REDACTED:ANTHROPIC_KEY]",
13356
- regex: /\bsk-ant-[a-zA-Z0-9_\-]{20,}\b/g
13357
- },
13358
- // 3. OpenAI / DeepSeek / 通用 API Key (sk-...)
13359
- {
13360
- kind: "API_KEY",
13361
- placeholder: "[REDACTED:API_KEY]",
13362
- regex: /\bsk-[a-zA-Z0-9_\-]{24,}\b/g
13363
- },
13364
- // 3b. BigModel / 智谱(GLM)API Key:32 位 hex + "." + 16 位字母数字
13365
- // (2026-11 实证:这类 key 没有任何可辨识前缀,此前漏在清洗与入路隔离之外,
13366
- // 用户贴进对话后明文直接进了 prompt / 历史 / 工具日志。)
13367
- {
13368
- kind: "BIGMODEL_KEY",
13369
- placeholder: "[REDACTED:BIGMODEL_KEY]",
13370
- regex: /\b[0-9a-fA-F]{32}\.[A-Za-z0-9]{16}\b/g
13371
- },
13372
- // 4. GitHub 访问令牌 (ghp_..., gho_..., github_pat_...)
13373
- {
13374
- kind: "GITHUB_TOKEN",
13375
- placeholder: "[REDACTED:GITHUB_TOKEN]",
13376
- regex: /\b(?:gh[pousr]_[a-zA-Z0-9]{30,}|github_pat_[a-zA-Z0-9_]{40,})\b/g
13377
- },
13378
- // 5. Bearer Token (JWT / Authorization Bearer)
13379
- {
13380
- kind: "BEARER_TOKEN",
13381
- placeholder: "Bearer [REDACTED:BEARER_TOKEN]",
13382
- regex: /\bBearer\s+[a-zA-Z0-9_\-\.]{25,}\b/gi
13383
- },
13384
- // 6. 常见环境变量或配置中的密码赋值 (PASSWORD=..., PASSWD=...)
13385
- {
13386
- kind: "PASSWORD",
13387
- placeholder: "$1=[REDACTED:PASSWORD]",
13388
- regex: /\b((?:DB_|DATABASE_|ADMIN_|ROOT_|MYSQL_|POSTGRES_)?(?:PASSWORD|PASSWD|SECRET_KEY))\s*=\s*['"]?([^\s'"]{4,})['"]?/gi
13389
- }
13390
- ];
13391
- var QUICK_PROBE_SUBSTRINGS = [
13392
- "sk-",
13393
- "ghp_",
13394
- "gho_",
13395
- "ghu_",
13396
- "ghs_",
13397
- "ghr_",
13398
- "github_pat_",
13399
- "PRIVATE KEY",
13400
- "Bearer ",
13401
- "bearer ",
13402
- "PASSWORD",
13403
- "password",
13404
- "PASSWD",
13405
- "SECRET_KEY"
13406
- ];
13407
- var UNPREFIXED_PROBE_REGEX = /\b[0-9a-fA-F]{32}\.[A-Za-z0-9]{16}\b/;
13408
- function hasPotentialSecrets(text2) {
13409
- if (typeof text2 !== "string" || text2.length === 0) return false;
13410
- if (QUICK_PROBE_SUBSTRINGS.some((probe) => text2.includes(probe))) return true;
13411
- return UNPREFIXED_PROBE_REGEX.test(text2);
13412
- }
13413
- function scrubSecrets(text2) {
13414
- if (typeof text2 !== "string" || text2.length === 0) {
13415
- return { cleaned: text2, redactedCount: 0, matchedKinds: [] };
13416
- }
13417
- if (!hasPotentialSecrets(text2)) {
13418
- return { cleaned: text2, redactedCount: 0, matchedKinds: [] };
13419
- }
13420
- let cleaned = text2;
13421
- let redactedCount = 0;
13422
- const matchedKinds = [];
13423
- for (const pattern of SECRET_PATTERNS) {
13424
- pattern.regex.lastIndex = 0;
13425
- const matches = cleaned.match(pattern.regex);
13426
- if (matches && matches.length > 0) {
13427
- redactedCount += matches.length;
13428
- if (!matchedKinds.includes(pattern.kind)) {
13429
- matchedKinds.push(pattern.kind);
13430
- }
13431
- cleaned = cleaned.replace(pattern.regex, pattern.placeholder);
13432
- }
13433
- }
13434
- return { cleaned, redactedCount, matchedKinds };
13435
- }
13436
- function scrubObjectSecrets(val) {
13437
- if (val === null || val === void 0) return val;
13438
- if (typeof val === "string") {
13439
- return scrubSecrets(val).cleaned;
13440
- }
13441
- if (Array.isArray(val)) {
13442
- return val.map((item) => scrubObjectSecrets(item));
13443
- }
13444
- if (typeof val === "object") {
13445
- if (val instanceof Date || val instanceof RegExp) return val;
13446
- const result4 = {};
13447
- for (const [k, v] of Object.entries(val)) {
13448
- result4[k] = scrubObjectSecrets(v);
13449
- }
13450
- return result4;
13451
- }
13452
- return val;
13453
- }
13454
-
13455
- // packages/agent-runtime/toolOutputSanitizer.ts
13456
- var SANITIZE_REPLACEMENT_CHAR = "\uFFFD";
13457
- var MAX_CONTROL_SEQUENCE_CHARS = 256;
13458
- var ESC = 27;
13459
- var BEL = 7;
13460
- var LINE_FEED = 10;
13461
- var TAB = 9;
13462
- var DEL = 127;
13463
- var C1_DCS = 144;
13464
- var C1_SOS = 152;
13465
- var C1_CSI = 155;
13466
- var C1_ST = 156;
13467
- var C1_OSC = 157;
13468
- var C1_PM = 158;
13469
- var C1_APC = 159;
13470
- var HIGH_SURROGATE_MIN = 55296;
13471
- var HIGH_SURROGATE_MAX = 56319;
13472
- var LOW_SURROGATE_MIN = 56320;
13473
- var LOW_SURROGATE_MAX = 57343;
13474
- var NEEDS_SANITIZE_RE = new RegExp("[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f]|\\p{Cs}", "u");
13475
- function isC1Introducer(code) {
13476
- return code === C1_CSI || code === C1_OSC || code === C1_DCS || code === C1_SOS || code === C1_PM || code === C1_APC;
13477
- }
13478
- var UNTERMINATED_SEQUENCE = -1;
13479
- function skipCsiBody(text2, start, limit) {
13480
- let i = start;
13481
- while (i < limit) {
13482
- const code = text2.charCodeAt(i);
13483
- if (code >= 64 && code <= 126) return i + 1;
13484
- if (code >= 32 && code <= 63) {
13485
- i += 1;
13486
- continue;
13487
- }
13488
- return i;
13489
- }
13490
- return UNTERMINATED_SEQUENCE;
13491
- }
13492
- function skipControlStringBody(text2, start, limit) {
13493
- const length = text2.length;
13494
- let i = start;
13495
- while (i < limit) {
13496
- const code = text2.charCodeAt(i);
13497
- if (code === BEL || code === C1_ST) return i + 1;
13498
- if (code === ESC && i + 1 < length && text2.charCodeAt(i + 1) === 92) {
13499
- return Math.min(i + 2, limit);
13500
- }
13501
- i += 1;
13502
- }
13503
- return UNTERMINATED_SEQUENCE;
13504
- }
13505
- function skipEscapeSequence(text2, escIndex) {
13506
- const length = text2.length;
13507
- const limit = Math.min(length, escIndex + MAX_CONTROL_SEQUENCE_CHARS);
13508
- const leadIndex = escIndex + 1;
13509
- if (leadIndex >= length) return leadIndex;
13510
- const lead = text2.charCodeAt(leadIndex);
13511
- if (lead === 91) {
13512
- const csiEnd = skipCsiBody(text2, leadIndex + 1, limit);
13513
- return csiEnd === UNTERMINATED_SEQUENCE ? escIndex + 1 : csiEnd;
13514
- }
13515
- if (lead === 93 || lead === 80 || lead === 88 || lead === 94 || lead === 95) {
13516
- const stringEnd = skipControlStringBody(text2, leadIndex + 1, limit);
13517
- return stringEnd === UNTERMINATED_SEQUENCE ? escIndex + 1 : stringEnd;
13518
- }
13519
- let j = leadIndex;
13520
- while (j < limit && text2.charCodeAt(j) >= 32 && text2.charCodeAt(j) <= 47) {
13521
- j += 1;
13522
- }
13523
- if (j < limit) {
13524
- const final = text2.charCodeAt(j);
13525
- if (final >= 48 && final <= 126) return j + 1;
13526
- }
13527
- return escIndex + 1;
13528
- }
13529
- function skipC1Sequence(text2, index) {
13530
- const limit = Math.min(text2.length, index + MAX_CONTROL_SEQUENCE_CHARS);
13531
- const code = text2.charCodeAt(index);
13532
- const bodyEnd = code === C1_CSI ? skipCsiBody(text2, index + 1, limit) : skipControlStringBody(text2, index + 1, limit);
13533
- return bodyEnd === UNTERMINATED_SEQUENCE ? index + 1 : bodyEnd;
13534
- }
13535
- function sanitizeToolOutputText(text2) {
13536
- if (typeof text2 !== "string" || text2.length === 0) return text2;
13537
- if (!NEEDS_SANITIZE_RE.test(text2)) return text2;
13538
- const out = [];
13539
- const length = text2.length;
13540
- let plainStart = 0;
13541
- let i = 0;
13542
- const dropRange = (end3) => {
13543
- if (plainStart < i) out.push(text2.slice(plainStart, i));
13544
- i = end3;
13545
- plainStart = end3;
13546
- };
13547
- while (i < length) {
13548
- const code = text2.charCodeAt(i);
13549
- if (code === LINE_FEED || code === TAB) {
13550
- i += 1;
13551
- continue;
13552
- }
13553
- if (code === ESC) {
13554
- dropRange(skipEscapeSequence(text2, i));
13555
- continue;
13556
- }
13557
- if (isC1Introducer(code)) {
13558
- dropRange(skipC1Sequence(text2, i));
13559
- continue;
13560
- }
13561
- if (code < 32 || code === DEL || code >= 128 && code <= 159) {
13562
- dropRange(i + 1);
13563
- continue;
13564
- }
13565
- if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {
13566
- const low = text2.charCodeAt(i + 1);
13567
- if (low >= LOW_SURROGATE_MIN && low <= LOW_SURROGATE_MAX) {
13568
- i += 2;
13569
- continue;
13570
- }
13571
- if (plainStart < i) out.push(text2.slice(plainStart, i));
13572
- out.push(SANITIZE_REPLACEMENT_CHAR);
13573
- i += 1;
13574
- plainStart = i;
13575
- continue;
13576
- }
13577
- if (code >= LOW_SURROGATE_MIN && code <= LOW_SURROGATE_MAX) {
13578
- if (plainStart < i) out.push(text2.slice(plainStart, i));
13579
- out.push(SANITIZE_REPLACEMENT_CHAR);
13580
- i += 1;
13581
- plainStart = i;
13582
- continue;
13583
- }
13584
- i += 1;
13585
- }
13586
- if (plainStart < length) out.push(text2.slice(plainStart));
13587
- return out.join("");
13588
- }
13589
- function sanitizeToolOutputContent(content) {
13590
- return typeof content === "string" ? sanitizeToolOutputText(content) : content;
13591
- }
13592
-
13593
13361
  // packages/agent-runtime/providerMessageProjection.ts
13594
13362
  var TOOL_DURATION_METADATA_KEY = "toolExecMs";
13595
13363
  var OBSERVATION_ONLY_METADATA_KEYS = /* @__PURE__ */ new Set([
@@ -13736,6 +13504,7 @@ function projectToolContentForProvider(args2) {
13736
13504
  const content = typeof rawContent === "string" ? sanitizeToolOutputText(rawContent) : rawContent;
13737
13505
  if (typeof content !== "string") return content;
13738
13506
  if (isSpilledToolOutput(content)) return content;
13507
+ if (isCompleteInstructionOutput(args2.toolName, args2.metadata, content)) return content;
13739
13508
  const metadataText = compactToolMetadata(args2.metadata);
13740
13509
  const embeddedMetadataIndex = metadataText ? content.indexOf("\n\n[tool metadata]\n") : -1;
13741
13510
  const contentForProjection = embeddedMetadataIndex >= 0 ? content.slice(0, embeddedMetadataIndex) : content;
@@ -13934,7 +13703,8 @@ ${args2.input}` : [
13934
13703
  const prefix2 = stableContent ? [{
13935
13704
  role: "system",
13936
13705
  content: stableContent,
13937
- stable_prefix_chars: stableContent.length
13706
+ stable_prefix_chars: stableContent.length,
13707
+ ...args2.prompt?.trim() ? { [AGENT_PROMPT_IN_MESSAGES]: true } : {}
13938
13708
  }] : [];
13939
13709
  const composed2 = composeProviderMessages({
13940
13710
  prefix: prefix2,
@@ -13957,7 +13727,11 @@ ${args2.input}` : [
13957
13727
  }
13958
13728
  const blocks = (args2.contextBlocks ?? []).map((block) => block.trim()).filter(Boolean);
13959
13729
  const systemContent = [args2.prompt?.trim(), ...blocks].filter(Boolean).join("\n\n");
13960
- const prefix = systemContent ? [{ role: "system", content: systemContent }] : [];
13730
+ const prefix = systemContent ? [{
13731
+ role: "system",
13732
+ content: systemContent,
13733
+ ...args2.prompt?.trim() ? { [AGENT_PROMPT_IN_MESSAGES]: true } : {}
13734
+ }] : [];
13961
13735
  const composed = composeProviderMessages({
13962
13736
  prefix,
13963
13737
  history: args2.history,
@@ -14127,7 +13901,7 @@ function buildToolResultsSignature(toolExecutions) {
14127
13901
  function resolveProgressGuardConfig(options, env = typeof process !== "undefined" ? process.env : {}) {
14128
13902
  const envDisabled = env.NOLO_LOOP_PROGRESS_GUARD_DISABLED === "true" || env.NOLO_LOOP_PROGRESS_GUARD_DISABLED === "1";
14129
13903
  const disabled = options?.disabled ?? envDisabled ?? false;
14130
- const parsePositiveInt = (val, fallback) => {
13904
+ const parsePositiveInt = (val, fallback2) => {
14131
13905
  if (typeof val === "number" && Number.isFinite(val) && val >= 1) {
14132
13906
  return Math.floor(val);
14133
13907
  }
@@ -14137,7 +13911,7 @@ function resolveProgressGuardConfig(options, env = typeof process !== "undefined
14137
13911
  return parsed;
14138
13912
  }
14139
13913
  }
14140
- return fallback;
13914
+ return fallback2;
14141
13915
  };
14142
13916
  const maxConsecutiveIdenticalRounds = parsePositiveInt(
14143
13917
  options?.maxConsecutiveIdenticalRounds ?? env.NOLO_LOOP_MAX_IDENTICAL_ROUNDS,
@@ -14895,9 +14669,9 @@ function normalizeExecShellInput(input) {
14895
14669
  const record2 = input;
14896
14670
  let rawCommand = resolveShellCommandArg(record2);
14897
14671
  if (typeof rawCommand !== "string" || !rawCommand.trim()) {
14898
- const fallback = record2.command ?? record2.cmd;
14899
- if (typeof fallback === "string" && fallback.trim()) {
14900
- rawCommand = fallback;
14672
+ const fallback2 = record2.command ?? record2.cmd;
14673
+ if (typeof fallback2 === "string" && fallback2.trim()) {
14674
+ rawCommand = fallback2;
14901
14675
  }
14902
14676
  }
14903
14677
  const command = typeof rawCommand === "string" ? rawCommand.trim() : "";
@@ -15070,22 +14844,275 @@ async function invokeCapability(capabilityOrName, input, ctx = {}) {
15070
14844
  import { existsSync as existsSync2 } from "node:fs";
15071
14845
  import { createHash as createHash3 } from "node:crypto";
15072
14846
 
14847
+ // packages/agent-runtime/agentsMd.ts
14848
+ import { readFileSync, realpathSync, statSync } from "node:fs";
14849
+ import { isAbsolute, relative, resolve, sep } from "node:path";
14850
+ var AGENTS_MD_MAX_BYTES = 16 * 1024;
14851
+ var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
14852
+ var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
14853
+ function truncateAgentsMdContent(content, maxBytes = AGENTS_MD_MAX_BYTES) {
14854
+ const buf = Buffer.from(content, "utf8");
14855
+ if (buf.byteLength <= maxBytes) {
14856
+ return content;
14857
+ }
14858
+ let boundary = Math.min(maxBytes, buf.byteLength);
14859
+ while (boundary > 0 && boundary < buf.byteLength && (buf[boundary] & 192) === 128) {
14860
+ boundary--;
14861
+ }
14862
+ const boundarySlice = buf.subarray(0, boundary).toString("utf8");
14863
+ const slice = buf.subarray(0, maxBytes);
14864
+ const lastNewline = slice.lastIndexOf(10);
14865
+ if (lastNewline > 0) {
14866
+ const lineCandidate = slice.subarray(0, lastNewline).toString("utf8");
14867
+ const lineBytes = Buffer.byteLength(lineCandidate, "utf8");
14868
+ const boundaryBytes = Buffer.byteLength(boundarySlice, "utf8");
14869
+ if (lineCandidate.trim().length > 0 && lineBytes * 2 >= boundaryBytes) {
14870
+ return lineCandidate.replace(/\r$/, "");
14871
+ }
14872
+ }
14873
+ return boundarySlice.replace(/\r$/, "");
14874
+ }
14875
+ var AGENTS_MD_SUMMARY_MAX_BYTES = 3072;
14876
+ var AGENTS_MD_SUMMARY_ITEM_MAX_CHARS = 120;
14877
+ var AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS = [
14878
+ "review",
14879
+ "\u8BC4\u5BA1",
14880
+ "commit",
14881
+ "\u63D0\u4EA4",
14882
+ "worktree",
14883
+ "\u6D4B\u8BD5",
14884
+ "typecheck",
14885
+ "\u7C7B\u578B\u68C0\u67E5",
14886
+ "push",
14887
+ "\u53D1\u5E03",
14888
+ "\u6587\u6863\u843D\u4F4D",
14889
+ "\u5220\u9664",
14890
+ "\u6D3E\u53D1"
14891
+ ];
14892
+ var AGENTS_MD_SUMMARY_POINTER_INSTRUCTION = "\u7528 readFile \u8BFB\u5168\u6587\uFF1A%REL%\uFF08cwd\uFF09/ %PATH%\n\u4EC5\u7D22\u5F15\uFF08\u672A\u6CE8\u5165\u5168\u6587\uFF09\uFF1A\u63D0\u4EA4/\u8BC4\u5BA1\u95E8\u7981\u3001worktree \u9694\u79BB\u3001\u6D4B\u8BD5/typecheck\u3001\u6587\u6863\u843D\u4F4D\u3001\u5220\u9664\u3001push/\u53D1\u5E03\u524D\uFF0C**\u5FC5\u987B\u5148 readFile \u8BFB\u5168\u6587\u518D\u6267\u884C**\u3002\n\u8DEF\u5F84\uFF1A%REL% \u76F8\u5BF9 cwd\uFF1Bmachine:<id>/\u6C99\u76D2\u6267\u884C\u9762 cwd \u7531\u5176\u51B3\u5B9A\uFF0C\u8BFB\u4E0D\u5230\u8BA9\u5BBF\u4E3B\u6CE8\u5165\u6216\u7528\u7EDD\u5BF9\u8DEF\u5F84\u3002";
14893
+ var AGENTS_MD_SUMMARY_DELETE_REFERENCE = "- \u5220\u9664/\u4E0D\u53EF\u9006\u64CD\u4F5C\uFF1A\u9075\u5B88\u7CFB\u7EDF\u63D0\u793A\u7684\u5220\u9664\u7EA2\u7EBF\uFF08\u5148\u5448\u73B0\u5B8C\u6574\u5F85\u5220\u6E05\u5355\u5E76\u83B7\u7528\u6237\u660E\u786E\u786E\u8BA4\uFF0C\u7981\u6B62\u5148\u5220\u540E\u62A5\u3001\u7981\u6B62\u6A21\u7CCA\u5B9A\u4F4D\uFF09\uFF0C\u4ED3\u5E93\u82E5\u6709\u9644\u52A0\u5220\u9664\u89C4\u5219\u89C1\u5B8C\u6574\u6587\u4EF6\u3002";
14894
+ var clipToChars = (text2, maxChars) => text2.length <= maxChars ? text2 : `${text2.slice(0, maxChars).trimEnd()}\u2026`;
14895
+ var parseAgentsMdItem = (body) => {
14896
+ const bold = /^\*\*(.+?)\*\*/.exec(body);
14897
+ if (bold) {
14898
+ return {
14899
+ label: bold[1].trim().replace(/[::]$/, ""),
14900
+ rest: body.slice(bold[0].length).replace(/^[::\s]+/, "")
14901
+ };
14902
+ }
14903
+ const firstClause = body.split(/[::]/)[0];
14904
+ return {
14905
+ label: clipToChars(firstClause.trim(), 40),
14906
+ rest: body.slice(firstClause.length).replace(/^[::\s]+/, "")
14907
+ };
14908
+ };
14909
+ var AGENTS_MD_COMMAND_TOKEN_PREFIX = /^(bunx?|npx|node|npm|pnpm|yarn|git|gh|tsc|deno)\b\s/;
14910
+ var extractAgentsMdCommandTokens = (body) => {
14911
+ const tokens = [];
14912
+ const seen = /* @__PURE__ */ new Set();
14913
+ for (const match7 of body.matchAll(/`([^`\n]+)`/g)) {
14914
+ const raw = match7[1];
14915
+ if (!AGENTS_MD_COMMAND_TOKEN_PREFIX.test(raw)) continue;
14916
+ if (seen.has(raw)) continue;
14917
+ seen.add(raw);
14918
+ tokens.push(raw);
14919
+ }
14920
+ return tokens;
14921
+ };
14922
+ var buildAgentsMdItemGist = (firstSentence, bulletBody) => {
14923
+ const max4 = AGENTS_MD_SUMMARY_ITEM_MAX_CHARS;
14924
+ const clipped = clipToChars(firstSentence, max4);
14925
+ const missing = extractAgentsMdCommandTokens(bulletBody).filter(
14926
+ (token) => !clipped.includes(token)
14927
+ );
14928
+ if (missing.length === 0) return clipped;
14929
+ let tail = "";
14930
+ for (const token of missing) {
14931
+ const candidate = tail ? `${tail} \`${token}\`` : `\`${token}\``;
14932
+ if (candidate.length > max4) continue;
14933
+ tail = candidate;
14934
+ }
14935
+ if (!tail) return clipped;
14936
+ const room = max4 - tail.length - 2;
14937
+ const head3 = room > 0 ? clipToChars(firstSentence, room) : "";
14938
+ return head3 ? `${head3} ${tail}` : tail;
14939
+ };
14940
+ var priorityOf = (label) => {
14941
+ const lowered = label.toLowerCase();
14942
+ for (let i = 0; i < AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS.length; i += 1) {
14943
+ if (lowered.includes(AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS[i].toLowerCase())) {
14944
+ return i;
14945
+ }
14946
+ }
14947
+ return -1;
14948
+ };
14949
+ var collectAgentsMdSummaryItems = (content) => {
14950
+ const items = [];
14951
+ const seen = /* @__PURE__ */ new Set();
14952
+ let section = null;
14953
+ for (const rawLine of content.split(/\r?\n/)) {
14954
+ const line = rawLine.trim();
14955
+ if (!line) continue;
14956
+ const heading = /^#{2,3}\s+(.+)$/.exec(line);
14957
+ if (heading) {
14958
+ section = heading[1].trim();
14959
+ continue;
14960
+ }
14961
+ if (line.startsWith("#") || line.startsWith("<") || line.startsWith("<!--")) {
14962
+ continue;
14963
+ }
14964
+ const bullet = /^[-*]\s+(.+)$/.exec(line);
14965
+ if (!bullet) continue;
14966
+ const { label, rest } = parseAgentsMdItem(bullet[1]);
14967
+ if (!label || seen.has(label)) continue;
14968
+ seen.add(label);
14969
+ const firstSentence = rest.split("\u3002")[0].trim();
14970
+ items.push({
14971
+ section,
14972
+ label,
14973
+ gist: buildAgentsMdItemGist(firstSentence, bullet[1]),
14974
+ priority: priorityOf(label)
14975
+ });
14976
+ }
14977
+ return items;
14978
+ };
14979
+ function buildAgentsMdSummaryBody(content, filePath, options = {}) {
14980
+ const budgetBytes = options.budgetBytes ?? AGENTS_MD_SUMMARY_MAX_BYTES;
14981
+ const items = collectAgentsMdSummaryItems(content);
14982
+ if (items.length === 0) return null;
14983
+ const relativePath = options.fileName ?? "AGENTS.md";
14984
+ const pointer = AGENTS_MD_SUMMARY_POINTER_INSTRUCTION.replaceAll(
14985
+ "%REL%",
14986
+ relativePath
14987
+ ).replaceAll("%PATH%", filePath);
14988
+ const head3 = `${pointer}
14989
+ ${AGENTS_MD_SUMMARY_DELETE_REFERENCE}
14990
+ `;
14991
+ if (Buffer.byteLength(head3, "utf8") > budgetBytes) return null;
14992
+ const candidates = [
14993
+ ...items.filter((item) => item.priority >= 0).sort((a, b) => a.priority - b.priority),
14994
+ ...items.filter((item) => item.priority < 0)
14995
+ ];
14996
+ const noteBlock = `
14997
+ \u2026\uFF08\u7D22\u5F15\u5DF2\u622A\u65AD\uFF0C\u5176\u4F59\u951A\u70B9\u89C1\u5B8C\u6574\u6587\u4EF6\uFF09`;
14998
+ const noteBytes = Buffer.byteLength(noteBlock, "utf8");
14999
+ let used = Buffer.byteLength(head3, "utf8");
15000
+ const admitted = [];
15001
+ const seenSections = /* @__PURE__ */ new Set();
15002
+ let truncated = false;
15003
+ for (const item of candidates) {
15004
+ const line = item.gist ? `- ${item.label}\uFF1A${item.gist}` : `- ${item.label}`;
15005
+ const headingCost = item.section && !seenSections.has(item.section) ? Buffer.byteLength(`
15006
+ ## ${item.section}`, "utf8") : 0;
15007
+ const cost = headingCost + Buffer.byteLength(`
15008
+ ${line}`, "utf8");
15009
+ if (used + cost + noteBytes > budgetBytes) {
15010
+ truncated = true;
15011
+ continue;
15012
+ }
15013
+ used += cost;
15014
+ if (item.section) seenSections.add(item.section);
15015
+ admitted.push(item);
15016
+ }
15017
+ const groupOrder = [];
15018
+ for (const item of admitted) {
15019
+ if (!groupOrder.includes(item.section)) groupOrder.push(item.section);
15020
+ }
15021
+ const frozen = [];
15022
+ for (const section of groupOrder) {
15023
+ for (const item of admitted) {
15024
+ if (item.section !== section) continue;
15025
+ frozen.push({
15026
+ section,
15027
+ line: item.gist ? `- ${item.label}\uFF1A${item.gist}` : `- ${item.label}`
15028
+ });
15029
+ }
15030
+ }
15031
+ if (admitted.length === 0) return null;
15032
+ return `${head3}${renderSummarySections(frozen)}${truncated ? noteBlock : ""}`;
15033
+ }
15034
+ var renderSummarySections = (entries) => {
15035
+ let rendered = "";
15036
+ let currentSection = null;
15037
+ for (const entry of entries) {
15038
+ if (entry.section && entry.section !== currentSection) {
15039
+ rendered += `
15040
+ ## ${entry.section}`;
15041
+ currentSection = entry.section;
15042
+ }
15043
+ rendered += `
15044
+ ${entry.line}`;
15045
+ }
15046
+ return rendered;
15047
+ };
15048
+ function readAgentsMdLayerFromDisk(cwd) {
15049
+ if (!cwd) return null;
15050
+ let root;
15051
+ try {
15052
+ root = realpathSync(cwd);
15053
+ } catch {
15054
+ return null;
15055
+ }
15056
+ for (const name of AGENTS_MD_CANDIDATES) {
15057
+ const filePath = resolve(cwd, name);
15058
+ try {
15059
+ const target = realpathSync(resolve(root, name));
15060
+ const targetRelative = relative(root, target);
15061
+ if (targetRelative === ".." || targetRelative.startsWith(`..${sep}`) || isAbsolute(targetRelative)) continue;
15062
+ if (!statSync(target).isFile()) continue;
15063
+ const raw = readFileSync(target, "utf8");
15064
+ const content = raw.trim();
15065
+ if (!content) continue;
15066
+ const totalBytes = Buffer.byteLength(raw, "utf8");
15067
+ const trimmedBytes = Buffer.byteLength(content, "utf8");
15068
+ const headerBytes = Buffer.byteLength(buildAgentsMdLayerHeader(name), "utf8");
15069
+ if (headerBytes + trimmedBytes <= AGENTS_MD_MAX_BYTES) {
15070
+ return buildAgentsMdLayer(content, name);
15071
+ }
15072
+ const summaryBody = buildAgentsMdSummaryBody(content, filePath, {
15073
+ // 正文预算 = 摘要上限 − 块头部:buildAgentsMdLayer 会再拼一次头部,
15074
+ // 因此「头部 + 正文」才等于最终注入字节,不得超过摘要上限。
15075
+ budgetBytes: AGENTS_MD_SUMMARY_MAX_BYTES - headerBytes,
15076
+ fileName: name
15077
+ });
15078
+ if (summaryBody) return buildAgentsMdLayer(summaryBody, name);
15079
+ const buildMarker = (omitted2, withPath) => {
15080
+ const pathPart = withPath ? `\u5B8C\u6574\u6587\u4EF6\uFF1A${filePath}` : `\u5B8C\u6574\u6587\u4EF6\uFF1A\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u7684 ${name}`;
15081
+ return `<!-- AGENTS.md truncated: \u539F\u6587\u4EF6 ${totalBytes} \u5B57\u8282\uFF0C\u6CE8\u5165\u9884\u7B97 ${AGENTS_MD_MAX_BYTES} \u5B57\u8282\uFF0C\u5DF2\u7701\u7565 ${omitted2} \u5B57\u8282\uFF08\u4E0A\u6587\u53EF\u80FD\u7F3A\u5C11\u6587\u4EF6\u672B\u5C3E\u7684 commit/review \u95E8\u7981\u7EC6\u5219\uFF0C\u63D0\u4EA4/\u8BC4\u5BA1\u524D\u8BF7\u8BFB\u5B8C\u6574\u6587\u4EF6\uFF09\u3002${pathPart} -->`;
15082
+ };
15083
+ const bodyBudget = AGENTS_MD_MAX_BYTES - AGENTS_MD_MARKER_RESERVE_BYTES - 2 - headerBytes;
15084
+ const body = truncateAgentsMdContent(content, bodyBudget);
15085
+ const bodyBytes = Buffer.byteLength(body, "utf8");
15086
+ const omitted = Math.max(0, totalBytes - bodyBytes);
15087
+ let marker = buildMarker(omitted, true);
15088
+ if (Buffer.byteLength(marker, "utf8") > AGENTS_MD_MARKER_RESERVE_BYTES) {
15089
+ marker = buildMarker(omitted, false);
15090
+ }
15091
+ return buildAgentsMdLayer(`${body}
15092
+
15093
+ ${marker}`, name);
15094
+ } catch {
15095
+ }
15096
+ }
15097
+ return null;
15098
+ }
15099
+
15073
15100
  // packages/agent-runtime/visualRenderer.node.ts
15074
15101
  import { createRequire } from "node:module";
15075
15102
  import { existsSync } from "node:fs";
15076
15103
  import { realpath, stat, readFile } from "node:fs/promises";
15077
- import { isAbsolute, relative, win32 } from "node:path";
15104
+ import { isAbsolute as isAbsolute2, relative as relative2, win32 } from "node:path";
15078
15105
  import { fileURLToPath, pathToFileURL } from "node:url";
15079
15106
  import { lookup as lookup2 } from "node:dns/promises";
15080
15107
  import { isIP } from "node:net";
15081
15108
  function isVisualPathOutside(rel) {
15082
- return rel === ".." || /^\.\.[\\/]/.test(rel) || isAbsolute(rel) || win32.isAbsolute(rel);
15109
+ return rel === ".." || /^\.\.[\\/]/.test(rel) || isAbsolute2(rel) || win32.isAbsolute(rel);
15083
15110
  }
15084
15111
  async function validateVisualUrl(input, workspaceRoot) {
15085
15112
  const url = new URL(input);
15086
15113
  if (url.protocol === "file:") {
15087
15114
  const [root, path] = await Promise.all([realpath(workspaceRoot), realpath(fileURLToPath(url))]);
15088
- const rel = relative(root, path);
15115
+ const rel = relative2(root, path);
15089
15116
  if (isVisualPathOutside(rel)) throw new Error("Renderer file URL is outside workspaceRoot.");
15090
15117
  if (!(await stat(path)).isFile()) throw new Error("Renderer file URL must point to a file, not a directory.");
15091
15118
  return pathToFileURL(path);
@@ -15125,7 +15152,7 @@ var VisualRenderSemaphore = class {
15125
15152
  active = 0;
15126
15153
  queue = [];
15127
15154
  async run(task) {
15128
- if (this.active >= this.limit) await new Promise((resolve6) => this.queue.push(resolve6));
15155
+ if (this.active >= this.limit) await new Promise((resolve7) => this.queue.push(resolve7));
15129
15156
  else this.active++;
15130
15157
  try {
15131
15158
  return await task();
@@ -15159,10 +15186,10 @@ async function renderVisualPage(args2) {
15159
15186
  if (typeof args2.persistScreenshot !== "function") {
15160
15187
  throw new Error("renderVisualPage: persistScreenshot is required (expected a function that stores the PNG bytes)");
15161
15188
  }
15162
- if (!isAbsolute(args2.workspaceRoot)) {
15189
+ if (!isAbsolute2(args2.workspaceRoot)) {
15163
15190
  throw new Error("renderVisualPage: workspaceRoot must be an absolute path");
15164
15191
  }
15165
- if (!isAbsolute(args2.screenshotPath) || !relative(args2.workspaceRoot, args2.screenshotPath) || isVisualPathOutside(relative(args2.workspaceRoot, args2.screenshotPath))) {
15192
+ if (!isAbsolute2(args2.screenshotPath) || !relative2(args2.workspaceRoot, args2.screenshotPath) || isVisualPathOutside(relative2(args2.workspaceRoot, args2.screenshotPath))) {
15166
15193
  throw new Error("renderVisualPage: screenshotPath must be a file path inside workspaceRoot");
15167
15194
  }
15168
15195
  if (args2.timeoutMs !== void 0 && (typeof args2.timeoutMs !== "number" || !Number.isFinite(args2.timeoutMs) || args2.timeoutMs <= 0)) {
@@ -15319,7 +15346,7 @@ finally:
15319
15346
  pass
15320
15347
  bus.signal_unsubscribe(subscription)
15321
15348
  `;
15322
- var capturePortalScreenshot = (signal) => new Promise((resolve6, reject) => {
15349
+ var capturePortalScreenshot = (signal) => new Promise((resolve7, reject) => {
15323
15350
  const child = spawn("/usr/bin/python3", ["-c", PORTAL_SCRIPT], { stdio: ["ignore", "pipe", "pipe"] });
15324
15351
  let stdout = "";
15325
15352
  let stderr = "";
@@ -15340,7 +15367,7 @@ var capturePortalScreenshot = (signal) => new Promise((resolve6, reject) => {
15340
15367
  if (signal.aborted) return reject(new Error("portal capture timeout"));
15341
15368
  if (code !== 0) return reject(new Error(stderr.trim() || `portal helper exited ${code}`));
15342
15369
  try {
15343
- resolve6(JSON.parse(stdout));
15370
+ resolve7(JSON.parse(stdout));
15344
15371
  } catch {
15345
15372
  reject(new Error("invalid portal response"));
15346
15373
  }
@@ -15352,7 +15379,7 @@ function createHostWindowCapture(options = {}) {
15352
15379
  let active = 0;
15353
15380
  const waiters = [];
15354
15381
  function acquire(signal) {
15355
- return new Promise((resolve6, reject) => {
15382
+ return new Promise((resolve7, reject) => {
15356
15383
  const abort = () => {
15357
15384
  const index = waiters.indexOf(start);
15358
15385
  if (index >= 0) waiters.splice(index, 1);
@@ -15361,7 +15388,7 @@ function createHostWindowCapture(options = {}) {
15361
15388
  const start = () => {
15362
15389
  signal.removeEventListener("abort", abort);
15363
15390
  active++;
15364
- resolve6();
15391
+ resolve7();
15365
15392
  };
15366
15393
  if (signal.aborted) return abort();
15367
15394
  if (active < concurrency) start();
@@ -15390,7 +15417,17 @@ function createHostWindowCapture(options = {}) {
15390
15417
  return {
15391
15418
  ...image,
15392
15419
  content: `${formatImageSummary({ kind: "screenshot", ...image.imageSummary })}
15393
- \u6765\u6E90\uFF1A\u5BBF\u4E3B portal \u5168\u5C4F/\u4EA4\u4E92\u9009\u62E9\u7ED3\u679C\uFF1Bportal \u672A\u63D0\u4F9B\u5E94\u7528/\u7A97\u53E3\u8EAB\u4EFD\uFF0C\u65E0\u6CD5\u786E\u8BA4\u7A97\u53E3\u540D\u3002`
15420
+ \u6765\u6E90\uFF1A\u5BBF\u4E3B portal \u5168\u5C4F/\u4EA4\u4E92\u9009\u62E9\u7ED3\u679C\uFF1Bportal \u672A\u63D0\u4F9B\u5E94\u7528/\u7A97\u53E3\u8EAB\u4EFD\uFF0C\u65E0\u6CD5\u786E\u8BA4\u7A97\u53E3\u540D\u3002`,
15421
+ metadata: {
15422
+ path: image.imageSummary.path,
15423
+ imageArtifacts: [{
15424
+ path: image.imageSummary.path,
15425
+ kind: "screenshot",
15426
+ width: image.imageSummary.width,
15427
+ height: image.imageSummary.height,
15428
+ bytes: image.imageSummary.bytes
15429
+ }]
15430
+ }
15394
15431
  };
15395
15432
  } finally {
15396
15433
  active--;
@@ -15419,7 +15456,7 @@ var captureHostWindow = createHostWindowCapture();
15419
15456
  // packages/agent-runtime/localWorkspaceTools.ts
15420
15457
  import { lstat as lstat2, readdir as readdir2, readFile as readFile4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
15421
15458
  import { homedir } from "node:os";
15422
- import { dirname as dirname2, relative as relative4, resolve as resolve4, sep as sep2 } from "node:path";
15459
+ import { dirname as dirname2, relative as relative5, resolve as resolve5, sep as sep3 } from "node:path";
15423
15460
  import { spawn as spawnChildProcess2 } from "node:child_process";
15424
15461
 
15425
15462
  // packages/agent-runtime/runResultReadProjection.ts
@@ -15502,12 +15539,12 @@ function isLineRangeCovered(request3, covered) {
15502
15539
 
15503
15540
  // packages/agent-runtime/fileTextSearch.ts
15504
15541
  import { readdir, readFile as readFile3, stat as stat3 } from "node:fs/promises";
15505
- import { basename as basename2, relative as relative2, resolve as resolve2 } from "node:path";
15542
+ import { basename as basename2, relative as relative3, resolve as resolve3 } from "node:path";
15506
15543
  import { spawn as spawnChildProcess } from "node:child_process";
15507
15544
 
15508
15545
  // packages/agent-runtime/gitignore.ts
15509
15546
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
15510
- import { resolve } from "node:path";
15547
+ import { resolve as resolve2 } from "node:path";
15511
15548
  function isIgnorableFsError(err) {
15512
15549
  if (err && typeof err === "object" && "code" in err) {
15513
15550
  const code = err.code;
@@ -15518,7 +15555,7 @@ function isIgnorableFsError(err) {
15518
15555
  async function readRootGitignorePatterns(workspaceRoot) {
15519
15556
  let content;
15520
15557
  try {
15521
- content = await readFile2(resolve(workspaceRoot, ".gitignore"), "utf8");
15558
+ content = await readFile2(resolve2(workspaceRoot, ".gitignore"), "utf8");
15522
15559
  } catch (err) {
15523
15560
  if (isIgnorableFsError(err)) return [];
15524
15561
  throw err;
@@ -15532,7 +15569,7 @@ async function readRootGitignorePatterns(workspaceRoot) {
15532
15569
  }
15533
15570
  async function hasRootGitignore(workspaceRoot) {
15534
15571
  try {
15535
- await stat2(resolve(workspaceRoot, ".gitignore"));
15572
+ await stat2(resolve2(workspaceRoot, ".gitignore"));
15536
15573
  return true;
15537
15574
  } catch (err) {
15538
15575
  if (isIgnorableFsError(err)) return false;
@@ -15542,8 +15579,10 @@ async function hasRootGitignore(workspaceRoot) {
15542
15579
 
15543
15580
  // packages/agent-runtime/fileTextSearch.ts
15544
15581
  var normalizePath = (value) => value.replaceAll("\\", "/");
15545
- var pathFor = (root, file, absolute = false) => absolute ? normalizePath(file) : normalizePath(relative2(root, file) || basename2(file));
15582
+ var pathFor = (root, file, absolute = false) => absolute ? normalizePath(file) : normalizePath(relative3(root, file) || basename2(file));
15546
15583
  var COMMAND_LIMIT_HEADROOM = 1;
15584
+ var MAX_SEARCH_FILE_BYTES = 8 * 1024 * 1024;
15585
+ var MAX_SEARCH_LINE_CHARS = 2e3;
15547
15586
  async function runCommand(binary, args2, cwd, maxResults) {
15548
15587
  const recordLimit = maxResults === void 0 ? 0 : Math.max(0, maxResults) + COMMAND_LIMIT_HEADROOM;
15549
15588
  return await new Promise((done4) => {
@@ -15551,7 +15590,12 @@ async function runCommand(binary, args2, cwd, maxResults) {
15551
15590
  try {
15552
15591
  const child = spawnChildProcess(binary, args2, { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
15553
15592
  child.stdout.on("data", (chunk) => {
15554
- stdout += chunk.toString();
15593
+ const room = MAX_SEARCH_FILE_BYTES - stdout.length;
15594
+ stdout += chunk.toString().slice(0, Math.max(0, room));
15595
+ if (stdout.length >= MAX_SEARCH_FILE_BYTES && !stopped) {
15596
+ stopped = true;
15597
+ child.kill();
15598
+ }
15555
15599
  recordCount = parseMatches(cwd, stdout).length;
15556
15600
  if (recordLimit > 0 && recordCount >= recordLimit && !stopped) {
15557
15601
  stopped = true;
@@ -15581,14 +15625,14 @@ function isGrepExpressibleExclude(pattern) {
15581
15625
  }
15582
15626
  function commandArgs(o, binary, target) {
15583
15627
  const args2 = binary === "rg" ? ["--line-number", "--no-heading", "--color", "never", "--null"] : ["-RIn", "--binary-files=without-match", "--null"];
15584
- if (binary === "rg") args2.push("--no-require-git");
15628
+ if (binary === "rg") args2.push("--no-require-git", "--max-columns", String(MAX_SEARCH_LINE_CHARS), "--max-columns-preview");
15585
15629
  if (o.regex !== true) args2.push(binary === "rg" ? "--fixed-strings" : "-F");
15586
15630
  else if (binary === "grep") args2.push("-E");
15587
15631
  if (o.caseSensitive === false) args2.push("-i");
15588
15632
  if (binary === "rg") {
15589
15633
  if (o.includeIgnored) args2.push("--no-ignore");
15590
15634
  for (const x of o.exclude ?? []) args2.push("--glob", `!${x}`);
15591
- if (o.include) args2.push("--glob", o.include);
15635
+ if (o.include) args2.push("--type-add", `noloSearch:${o.include}`, "--type", "noloSearch");
15592
15636
  } else {
15593
15637
  for (const x of o.exclude ?? []) {
15594
15638
  const clean = extractGrepExcludeDir(x);
@@ -15603,29 +15647,37 @@ function parseMatches(root, output) {
15603
15647
  const records = [];
15604
15648
  const pattern = /(?:^|\n)([^\0\n]+)\0(\d+):(.*?)(?=\n[^\0\n]+\0|$)/gs;
15605
15649
  for (const match7 of output.matchAll(pattern)) {
15606
- records.push({ file: resolve2(root, match7[1] ?? ""), line: Number(match7[2]), text: (match7[3] ?? "").replace(/\n$/, "") });
15650
+ records.push({ file: resolve3(root, match7[1] ?? ""), line: Number(match7[2]), text: (match7[3] ?? "").replace(/\n$/, "") });
15607
15651
  }
15608
15652
  return records;
15609
15653
  }
15610
15654
  async function decorate(root, raw, context3, absolute = false) {
15611
- const cache = /* @__PURE__ */ new Map(), out = [];
15655
+ const out = [];
15612
15656
  for (const x of raw) {
15613
- let lines = cache.get(x.file);
15614
- if (!lines) {
15657
+ let lines = [];
15658
+ if (context3 > 0) {
15615
15659
  try {
15616
- lines = (await readFile3(x.file, "utf8")).split(/\r\n|\r|\n/);
15660
+ if ((await stat3(x.file)).size <= MAX_SEARCH_FILE_BYTES) {
15661
+ lines = (await readFile3(x.file, "utf8")).split(/\r\n|\r|\n/);
15662
+ }
15617
15663
  } catch {
15618
- continue;
15619
15664
  }
15620
- cache.set(x.file, lines);
15621
15665
  }
15622
15666
  const i = x.line - 1;
15623
- out.push({ path: pathFor(root, x.file, absolute), line: x.line, text: lines[i] ?? x.text, before: lines.slice(Math.max(0, i - context3), i), after: lines.slice(i + 1, i + context3 + 1) });
15667
+ out.push({
15668
+ path: pathFor(root, x.file, absolute),
15669
+ line: x.line,
15670
+ text: (lines[i] ?? x.text).slice(0, MAX_SEARCH_LINE_CHARS),
15671
+ before: lines.slice(Math.max(0, i - context3), i).map((line) => line.slice(0, MAX_SEARCH_LINE_CHARS)),
15672
+ after: lines.slice(i + 1, i + context3 + 1).map((line) => line.slice(0, MAX_SEARCH_LINE_CHARS))
15673
+ });
15624
15674
  }
15625
15675
  return out;
15626
15676
  }
15627
15677
  function globMatch(pattern, value) {
15628
15678
  const p = normalizePath(pattern).replace(/^!/, "");
15679
+ const brace = /\{([^{}]+)\}/.exec(p);
15680
+ if (brace) return brace[1].split(",").some((part) => globMatch(p.slice(0, brace.index) + part + p.slice(brace.index + brace[0].length), value));
15629
15681
  let source = "";
15630
15682
  for (let i = 0; i < p.length; i++) {
15631
15683
  const c = p[i];
@@ -15661,7 +15713,7 @@ async function jsSearch(o, targetPath) {
15661
15713
  } else {
15662
15714
  const walk = async (dir) => {
15663
15715
  for (const e of await readdir(dir, { withFileTypes: true })) {
15664
- const f = resolve2(dir, e.name), rel = pathFor(o.root, f);
15716
+ const f = resolve3(dir, e.name), rel = pathFor(o.root, f);
15665
15717
  if (e.isDirectory()) {
15666
15718
  if (!excludes.some((p) => globMatch(p, rel))) await walk(f);
15667
15719
  } else if (e.isFile() && !excludes.some((p) => globMatch(p, rel)) && !isIgnored(rel) && (!o.include || globMatch(o.include, rel))) {
@@ -15675,6 +15727,8 @@ async function jsSearch(o, targetPath) {
15675
15727
  const needle = o.caseSensitive === false ? o.query.toLowerCase() : o.query;
15676
15728
  const out = [], context3 = o.contextLines ?? 0;
15677
15729
  for (const file of files) {
15730
+ const info = await stat3(file).catch(() => null);
15731
+ if (!info || info.size > MAX_SEARCH_FILE_BYTES) continue;
15678
15732
  const text2 = await readText(file);
15679
15733
  if (!text2 || text2.includes("\0")) continue;
15680
15734
  const lines = text2.split(/\r\n|\r|\n/);
@@ -15683,7 +15737,7 @@ async function jsSearch(o, targetPath) {
15683
15737
  const hit = matcher ? matcher.test(line) : o.caseSensitive === false ? line.toLowerCase().includes(needle) : line.includes(needle);
15684
15738
  if (!hit) continue;
15685
15739
  if (out.length >= max4) return { matches: out, totalMatches: max4, truncated: true, engine: "js" };
15686
- out.push({ path: pathFor(o.root, file, o.absolutePaths === true), line: i + 1, text: line, before: lines.slice(Math.max(0, i - context3), i), after: lines.slice(i + 1, i + context3 + 1) });
15740
+ out.push({ path: pathFor(o.root, file, o.absolutePaths === true), line: i + 1, text: line.slice(0, MAX_SEARCH_LINE_CHARS), before: lines.slice(Math.max(0, i - context3), i).map((line2) => line2.slice(0, MAX_SEARCH_LINE_CHARS)), after: lines.slice(i + 1, i + context3 + 1).map((line2) => line2.slice(0, MAX_SEARCH_LINE_CHARS)) });
15687
15741
  }
15688
15742
  }
15689
15743
  return { matches: out, totalMatches: out.length, truncated: false, engine: "js" };
@@ -15710,12 +15764,13 @@ var COMMAND_ENGINES = [
15710
15764
  { engine: "grep", binaryOption: "resolveGrepBinary", binaryName: "grep", argsKey: "grep" }
15711
15765
  ];
15712
15766
  async function searchFileTextMatches(o) {
15713
- const targetPath = resolve2(o.root, o.target || ".");
15767
+ const targetPath = resolve3(o.root, o.target || ".");
15714
15768
  const targetStat = await stat3(targetPath).catch(() => null);
15715
15769
  if (!targetStat) return { matches: [], totalMatches: 0, truncated: false, engine: "js" };
15716
15770
  if (targetStat.isFile()) return jsSearch(o, targetPath);
15717
15771
  const run2 = o.runCommand ?? runCommand, max4 = o.maxResults;
15718
15772
  for (const entry of COMMAND_ENGINES) {
15773
+ if (entry.engine === "ripgrep" && o.include && /[/\\]/.test(o.include)) continue;
15719
15774
  if (entry.engine === "grep" && !await canGrepFulfillOptions(o)) continue;
15720
15775
  const injectedResolver = o[entry.binaryOption];
15721
15776
  const binary = injectedResolver ? injectedResolver() : resolveExecutableOnPath(entry.binaryName);
@@ -15763,6 +15818,7 @@ var TASK_WAIT_DEFAULT_TIMEOUT_MS = 5 * 6e4;
15763
15818
  var TASK_WAIT_MAX_TIMEOUT_MS = 5 * 6e4;
15764
15819
  var TASK_WAIT_POLL_INTERVAL_MS = 250;
15765
15820
  var TASK_STOP_GRACE_MS = 2e3;
15821
+ var TASK_STOP_POLL_INTERVAL_MS = 40;
15766
15822
  function resolveCleanupReport(evidence, previousStatus) {
15767
15823
  const diagnostic = evidence.diagnostic ? { diagnostic: evidence.diagnostic } : {};
15768
15824
  if (evidence.confirmedStopped) {
@@ -15779,7 +15835,7 @@ function resolveCleanupReport(evidence, previousStatus) {
15779
15835
  }
15780
15836
  var TERMINAL_EVENT_TYPES = /* @__PURE__ */ new Set(["exited", "killed"]);
15781
15837
  function defaultSleep(ms) {
15782
- return new Promise((resolve6) => setTimeout(resolve6, ms));
15838
+ return new Promise((resolve7) => setTimeout(resolve7, ms));
15783
15839
  }
15784
15840
  function defaultSignalSender(pid, signal) {
15785
15841
  process.kill(pid, signal);
@@ -15984,8 +16040,17 @@ async function runTaskStop(args2) {
15984
16040
  )
15985
16041
  };
15986
16042
  }
15987
- if (graceMs > 0) await sleep3(graceMs);
15988
- if (!isProcessGroupAlive(record2.pgid, kill)) {
16043
+ let alive = isProcessGroupAlive(record2.pgid, kill);
16044
+ if (alive && graceMs > 0) {
16045
+ let remaining = graceMs;
16046
+ while (remaining > 0 && alive) {
16047
+ const step = Math.min(TASK_STOP_POLL_INTERVAL_MS, remaining);
16048
+ await sleep3(step);
16049
+ remaining -= step;
16050
+ alive = isProcessGroupAlive(record2.pgid, kill);
16051
+ }
16052
+ }
16053
+ if (!alive) {
15989
16054
  return {
15990
16055
  outcome: "stopped",
15991
16056
  taskId,
@@ -16030,6 +16095,7 @@ var WORKSPACE_TOOL_NAMES = [
16030
16095
  "writeFile",
16031
16096
  "editFile",
16032
16097
  "globFiles",
16098
+ "searchFiles",
16033
16099
  "captureVisualState",
16034
16100
  "execShell",
16035
16101
  "launchProcess",
@@ -16054,7 +16120,7 @@ function buildWorkspacePathProperty() {
16054
16120
  };
16055
16121
  }
16056
16122
  function buildReadWorkspaceDescription() {
16057
- return "Read a UTF-8 text file inside the workspace. Absolute paths and ~/ are also accepted (runtime spill files can be read directly). Use lines for focused range reads after search to save tokens. A range already delivered earlier for an unchanged file answers with a short notice instead of resending (force:true refetches).";
16123
+ return "Read a UTF-8 text file inside the workspace. For multiple files, call readFile concurrently in the same turn. Absolute paths and ~/ are also accepted (runtime spill files can be read directly). Use lines for focused range reads after search to save tokens. A range already delivered earlier for an unchanged file answers with a short notice instead of resending (force:true refetches).";
16058
16124
  }
16059
16125
  function buildReadWorkspaceParameters() {
16060
16126
  const path = buildWorkspacePathProperty();
@@ -16379,6 +16445,31 @@ function buildWorkspaceToolDefinition(toolName) {
16379
16445
  if (toolName === "editFile") {
16380
16446
  return buildReplaceWorkspaceTextTool();
16381
16447
  }
16448
+ if (toolName === "searchFiles") {
16449
+ return {
16450
+ type: "function",
16451
+ function: {
16452
+ name: "searchFiles",
16453
+ description: "Search UTF-8 text files in the workspace by literal string or regex (works across code, docs, notes, and data files on Windows/macOS/Linux; respects .gitignore by default and stops early at maxResults). Prefer searchFiles over shell grep/rg/Select-String.",
16454
+ parameters: {
16455
+ type: "object",
16456
+ properties: {
16457
+ query: { type: "string", minLength: 1, description: "Search text. Also accepts pattern when query is omitted (grep/rg alias compatibility)." },
16458
+ path: buildWorkspacePathProperty(),
16459
+ regex: { type: "boolean", description: "Default false: search for a literal string. Set true for regex." },
16460
+ caseSensitive: { type: "boolean", description: "Default true." },
16461
+ include: { type: "string", description: "File glob filter, e.g. *.{ts,md}." },
16462
+ exclude: { type: "array", items: { type: "string" } },
16463
+ contextLines: { type: "integer", minimum: 0, maximum: 5 },
16464
+ maxResults: { type: "integer", minimum: 1, maximum: 1e3, description: "Default 100; stop early after this many matches." },
16465
+ includeIgnored: { type: "boolean", description: "Default false: respect .gitignore." }
16466
+ },
16467
+ required: ["query"],
16468
+ additionalProperties: false
16469
+ }
16470
+ }
16471
+ };
16472
+ }
16382
16473
  if (toolName === "globFiles") {
16383
16474
  return buildGlobWorkspaceFilesTool();
16384
16475
  }
@@ -16400,10 +16491,10 @@ function filterDeclaredWorkspaceToolNames(args2) {
16400
16491
  // packages/agent-runtime/workspacePathGuard.ts
16401
16492
  import { constants as fsConstants } from "node:fs";
16402
16493
  import { lstat, mkdir, open, readlink, realpath as realpath2 } from "node:fs/promises";
16403
- import { basename as basename3, dirname, isAbsolute as isAbsolute2, join as join2, relative as relative3, resolve as resolve3, sep } from "node:path";
16494
+ import { basename as basename3, dirname, isAbsolute as isAbsolute3, join as join2, relative as relative4, resolve as resolve4, sep as sep2 } from "node:path";
16404
16495
  function isPathInsideRoot(root, targetPath) {
16405
- const rel = relative3(resolve3(root), resolve3(targetPath));
16406
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute2(rel);
16496
+ const rel = relative4(resolve4(root), resolve4(targetPath));
16497
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute3(rel);
16407
16498
  }
16408
16499
  function isNotFoundError(error) {
16409
16500
  const code = error?.code;
@@ -16411,7 +16502,7 @@ function isNotFoundError(error) {
16411
16502
  }
16412
16503
  async function realpathAllowMissing(targetPath) {
16413
16504
  const tail = [];
16414
- let current = resolve3(targetPath);
16505
+ let current = resolve4(targetPath);
16415
16506
  for (; ; ) {
16416
16507
  try {
16417
16508
  const real = await realpath2(current);
@@ -16430,8 +16521,8 @@ async function realpathAllowMissing(targetPath) {
16430
16521
  }
16431
16522
  async function resolveWorkspaceSafePath(args2) {
16432
16523
  const requested = args2.requestedPath ?? args2.targetPath;
16433
- const lexicalRoot = resolve3(args2.workspaceRoot);
16434
- const targetPath = resolve3(args2.targetPath);
16524
+ const lexicalRoot = resolve4(args2.workspaceRoot);
16525
+ const targetPath = resolve4(args2.targetPath);
16435
16526
  const lexicalInside = args2.lexicalInside ?? isPathInsideRoot(lexicalRoot, targetPath);
16436
16527
  const [physicalRoot, resolved] = await Promise.all([
16437
16528
  realpath2(lexicalRoot).catch(() => null),
@@ -16490,7 +16581,7 @@ async function resolveOpenedFilePath(handle) {
16490
16581
  for (const root of FD_LINK_ROOTS) {
16491
16582
  try {
16492
16583
  const linked = await readlink(`${root}/${handle.fd}`);
16493
- if (isAbsolute2(linked)) return linked.replace(/ \(deleted\)$/, "");
16584
+ if (isAbsolute3(linked)) return linked.replace(/ \(deleted\)$/, "");
16494
16585
  } catch {
16495
16586
  }
16496
16587
  }
@@ -16587,7 +16678,7 @@ async function openPinnedDirectory(dirPath, guard) {
16587
16678
  }
16588
16679
  async function createMissingDirectoryChain(guard) {
16589
16680
  const missing = [];
16590
- let existing = resolve3(guard.path);
16681
+ let existing = resolve4(guard.path);
16591
16682
  for (; ; ) {
16592
16683
  try {
16593
16684
  await lstat(existing);
@@ -16707,25 +16798,6 @@ async function readRootGitignorePatterns2(workspaceRoot) {
16707
16798
  return readRootGitignorePatterns(workspaceRoot);
16708
16799
  }
16709
16800
  var DEFAULT_LOCAL_API_ORIGIN = "http://127.0.0.1:38123";
16710
- var ALWAYS_EXCLUDED_GLOBS = [
16711
- ".git/**",
16712
- ".nolo/**",
16713
- "node_modules/**",
16714
- "*.tsbuildinfo",
16715
- "dist/**",
16716
- "build/**",
16717
- "out/**",
16718
- "coverage/**",
16719
- ".next/**",
16720
- ".turbo/**",
16721
- "public/assets/**",
16722
- "*.min.js",
16723
- "*.min.css",
16724
- "*.map",
16725
- "*.lock",
16726
- "bun.lockb",
16727
- "*.ldb"
16728
- ];
16729
16801
  function readTrimmedString(value) {
16730
16802
  return asOptionalTrimmedString(value);
16731
16803
  }
@@ -16799,12 +16871,12 @@ function parseWorkspaceToolArguments(raw) {
16799
16871
  }
16800
16872
  }
16801
16873
  function normalizeWorkspaceRelativePath(args2) {
16802
- const relativePath = relative4(args2.workspaceRoot, args2.targetPath);
16874
+ const relativePath = relative5(args2.workspaceRoot, args2.targetPath);
16803
16875
  return relativePath || ".";
16804
16876
  }
16805
16877
  function isPathInsideWorkspace(args2) {
16806
- const relativePath = relative4(args2.workspaceRoot, args2.targetPath);
16807
- return relativePath === "" || !relativePath.startsWith("..") && !relativePath.includes(`..${sep2}`);
16878
+ const relativePath = relative5(args2.workspaceRoot, args2.targetPath);
16879
+ return relativePath === "" || !relativePath.startsWith("..") && !relativePath.includes(`..${sep3}`);
16808
16880
  }
16809
16881
  var PATH_FIELD_ALIASES = ["path", "file_path", "filePath", "filename", "file", "target_file", "targetFile", "file_to_read", "fileToRead", "target_path", "read_path", "path_to_read", "pathToRead"];
16810
16882
  var OLD_TEXT_FIELD_ALIASES = ["oldText", "old_string", "oldString", "search", "search_string", "find", "match"];
@@ -17086,14 +17158,14 @@ async function resolveRuntimeOwnedSpillPath(targetPath) {
17086
17158
  }
17087
17159
  function expandHomePath(requestedPath) {
17088
17160
  if (requestedPath === "~") return homedir();
17089
- if (requestedPath.startsWith("~/")) return resolve4(homedir(), requestedPath.slice(2));
17161
+ if (requestedPath.startsWith("~/")) return resolve5(homedir(), requestedPath.slice(2));
17090
17162
  return requestedPath;
17091
17163
  }
17092
17164
  function resolveRequestedWorkspacePath(workspaceRoot, requestedPath) {
17093
- return resolve4(resolve4(workspaceRoot), expandHomePath(requestedPath));
17165
+ return resolve5(resolve5(workspaceRoot), expandHomePath(requestedPath));
17094
17166
  }
17095
17167
  async function resolveLocalWorkspaceToolApproval(args2) {
17096
- const workspaceRoot = resolve4(args2.workspaceRoot);
17168
+ const workspaceRoot = resolve5(args2.workspaceRoot);
17097
17169
  const targetPath = resolveRequestedWorkspacePath(workspaceRoot, args2.requestedPath);
17098
17170
  const insideWorkspace = isPathInsideWorkspace({ workspaceRoot, targetPath });
17099
17171
  const guard = await resolveWorkspaceSafePath({
@@ -17190,6 +17262,53 @@ var READ_FILE_LEDGER_MAX_RECORDS = 64;
17190
17262
  var READ_FILE_LEDGER_MAX_KEYS = 256;
17191
17263
  async function readFileTool(args2) {
17192
17264
  const parsed = parseWorkspaceToolArguments(args2.call.arguments);
17265
+ if (parsed.files !== void 0 && !args2.batchItem) {
17266
+ if (!Array.isArray(parsed.files) || parsed.files.length < 1 || parsed.files.length > 8 || pickFirstAlias(parsed, PATH_FIELD_ALIASES) !== void 0) {
17267
+ return { content: "[readFile] Supply either path or files (1\u20138 items), not both.", metadata: { status: "invalid-arguments" } };
17268
+ }
17269
+ if (parsed.files.some((file) => !file || typeof file !== "object" || typeof file.path !== "string" || !file.path || file.path.length > 512 || file.lines !== void 0 && typeof file.lines !== "string")) {
17270
+ return { content: "[readFile] Each batch item requires a path (maximum 512 characters) and optional string lines.", metadata: { status: "invalid-arguments" } };
17271
+ }
17272
+ const items = parsed.files.map((item) => ({ path: item.path, status: "not-delivered" }));
17273
+ const budget = resolveHistoricalToolContentCap("readFile", 0);
17274
+ const batchStartLedger = args2.readLedger ? new Map([...args2.readLedger].map(([key, entry2]) => [key, { ...entry2, records: [...entry2.records] }])) : void 0;
17275
+ for (let i = 0; i < parsed.files.length; i++) {
17276
+ const file = parsed.files[i];
17277
+ if (!file || typeof file !== "object" || typeof file.path !== "string" || !file.path || file.lines !== void 0 && typeof file.lines !== "string") {
17278
+ items[i] = { ...items[i], status: "invalid-arguments" };
17279
+ continue;
17280
+ }
17281
+ const trialLedger = args2.readLedger ? new Map([...args2.readLedger].map(([key, entry2]) => [key, { ...entry2, records: [...entry2.records] }])) : void 0;
17282
+ try {
17283
+ const result4 = await readFileTool({ ...args2, batchItem: true, readLedger: trialLedger, call: { ...args2.call, arguments: JSON.stringify(file) } });
17284
+ const metadata2 = result4.metadata ?? {};
17285
+ const candidate = { path: file.path, status: metadata2.deduped ? "already-delivered" : metadata2.status === "invalid-arguments" ? "invalid-arguments" : metadata2.truncatedByCharLimit || metadata2.partialLine ? "partial" : "complete", content: result4.content, ...metadata2 };
17286
+ const previous = items[i];
17287
+ items[i] = candidate;
17288
+ const formatted = formatToolMessageContent({ toolName: "readFile", content: JSON.stringify(items), metadata: { batch: true, items: items.map(({ path, status, startLine, endLine }) => ({ path, status, startLine, endLine })) } });
17289
+ if (formatted.length > budget) {
17290
+ items[i] = previous;
17291
+ continue;
17292
+ }
17293
+ if (args2.readLedger && trialLedger) {
17294
+ args2.readLedger.clear();
17295
+ for (const [key, value] of trialLedger) args2.readLedger.set(key, value);
17296
+ }
17297
+ } catch {
17298
+ items[i] = { path: file.path, status: "error" };
17299
+ }
17300
+ }
17301
+ const batchContent = JSON.stringify(items);
17302
+ const batchMetadata = { batch: true, items: items.map(({ path, status, startLine, endLine }) => ({ path, status, startLine, endLine })) };
17303
+ if (formatToolMessageContent({ toolName: "readFile", content: batchContent, metadata: batchMetadata }).length > budget) {
17304
+ if (args2.readLedger && batchStartLedger) {
17305
+ args2.readLedger.clear();
17306
+ for (const [key, value] of batchStartLedger) args2.readLedger.set(key, value);
17307
+ }
17308
+ return { content: "[readFile] Batch request exceeds the shared delivery budget; no content delivered. Use fewer or shorter paths.", metadata: { status: "batch-limit-exceeded" } };
17309
+ }
17310
+ return { content: batchContent, metadata: batchMetadata };
17311
+ }
17193
17312
  const requestedPath = requireWorkspaceToolPath(parsed);
17194
17313
  const parsedSlice = readFileSliceArgs(parsed);
17195
17314
  if (parsedSlice.error) {
@@ -17216,13 +17335,24 @@ async function readFileTool(args2) {
17216
17335
  ...sliceArgs
17217
17336
  });
17218
17337
  const relativePath = normalizeWorkspaceRelativePath({
17219
- workspaceRoot: resolve4(args2.workspaceRoot),
17338
+ workspaceRoot: resolve5(args2.workspaceRoot),
17220
17339
  targetPath: absolutePath
17221
17340
  });
17222
- const cap = resolveHistoricalToolContentCap("readFile", 0);
17341
+ const instructionPath = AGENTS_MD_CANDIDATES.some((name) => absolutePath === resolve5(args2.workspaceRoot, name));
17342
+ const instructionLimit = PROJECT_INSTRUCTION_MAX_BYTES;
17343
+ const instructionOversized = Buffer.byteLength(content) > instructionLimit || countLines(content) > TOOL_OUTPUT_SPILL_LINES;
17344
+ const instruction = !args2.batchItem && instructionPath && !instructionOversized;
17345
+ if (!args2.batchItem && instructionPath && instructionOversized && Object.keys(sliceArgs).length === 0) {
17346
+ return {
17347
+ content: `[readFile] Project instruction exceeds the delivery limit (${instructionLimit} bytes or ${TOOL_OUTPUT_SPILL_LINES} lines); no content delivered. Continue with lines="1-" to inspect the first bounded range.`,
17348
+ metadata: { path: relativePath, status: "instruction-limit-exceeded", truncated: true, totalBytes: Buffer.byteLength(originalContent) }
17349
+ };
17350
+ }
17351
+ const cap = instruction ? PROJECT_INSTRUCTION_MAX_CHARS : resolveHistoricalToolContentCap("readFile", 0);
17223
17352
  const selectedLines = splitTextLines(sliced.content);
17224
17353
  const makeMetadata = (body, endLine, windowed2, partialLine) => ({
17225
17354
  path: relativePath,
17355
+ ...instruction ? { projectInstruction: true } : {},
17226
17356
  bytes: Buffer.byteLength(body),
17227
17357
  totalBytes: Buffer.byteLength(originalContent),
17228
17358
  ...projection.projected ? {
@@ -17234,6 +17364,7 @@ async function readFileTool(args2) {
17234
17364
  ...partialLine ? { partialLine: true } : { endLine },
17235
17365
  totalLines: sliced.totalLines,
17236
17366
  truncated: sliced.truncated || windowed2,
17367
+ ...scrubSecrets(sanitizeToolOutputText(body)).cleaned !== body ? { contentSanitized: true } : {},
17237
17368
  ...windowed2 ? { truncatedByByteLimit: true, truncatedByCharLimit: true } : {},
17238
17369
  ...sliceArgs.maxLines ? { maxLines: sliceArgs.maxLines } : {},
17239
17370
  ...sliceArgs.tailLines ? { tailLines: sliceArgs.tailLines } : {},
@@ -17286,7 +17417,7 @@ async function readFileTool(args2) {
17286
17417
  ledger?.delete(relativePath);
17287
17418
  }
17288
17419
  if (!force && entry && ledger && !oversizedLine) {
17289
- const retainedCap = resolveHistoricalToolContentCap("readFile", 0);
17420
+ const retainedCap = instructionPath && !instructionOversized ? PROJECT_INSTRUCTION_MAX_CHARS : resolveHistoricalToolContentCap("readFile", 0);
17290
17421
  const retained = filterRetainedLedgerRecords(entry.records, retainedCap);
17291
17422
  if (retained.length > 0 && isLineRangeCovered(deliveredRange, retained)) {
17292
17423
  ledger.delete(relativePath);
@@ -17345,7 +17476,7 @@ async function writeFileTool(args2) {
17345
17476
  await ensureGuardedParentDirectory({ workspaceRoot: args2.workspaceRoot, fileApproval: approval });
17346
17477
  await writeGuardApprovedFile(approval, content);
17347
17478
  const relativePath = normalizeWorkspaceRelativePath({
17348
- workspaceRoot: resolve4(args2.workspaceRoot),
17479
+ workspaceRoot: resolve5(args2.workspaceRoot),
17349
17480
  targetPath: absolutePath
17350
17481
  });
17351
17482
  const activity = extractActivity(parsed);
@@ -17468,7 +17599,7 @@ ${hint}` : "")
17468
17599
  }
17469
17600
  await writeGuardApprovedFile(approval, nextContent);
17470
17601
  const relativePath = normalizeWorkspaceRelativePath({
17471
- workspaceRoot: resolve4(args2.workspaceRoot),
17602
+ workspaceRoot: resolve5(args2.workspaceRoot),
17472
17603
  targetPath: absolutePath
17473
17604
  });
17474
17605
  const activity = extractActivity(parsed);
@@ -17508,9 +17639,9 @@ async function listWorkspaceEntries(args2) {
17508
17639
  const names = (await readdir2(dirPath)).sort((left, right) => left.localeCompare(right));
17509
17640
  for (const name of names) {
17510
17641
  if (truncated) break;
17511
- const absolutePath = resolve4(dirPath, name);
17642
+ const absolutePath = resolve5(dirPath, name);
17512
17643
  const info = await stat4(absolutePath);
17513
- const relativePath = relative4(args2.dirPath, absolutePath) || ".";
17644
+ const relativePath = relative5(args2.dirPath, absolutePath) || ".";
17514
17645
  const isDirectory = info.isDirectory();
17515
17646
  entries.push(isDirectory ? `${relativePath}/` : relativePath);
17516
17647
  if (args2.maxResults && entries.length >= args2.maxResults) {
@@ -17537,28 +17668,30 @@ async function internalSearchWorkspace(args2) {
17537
17668
  allowRuntimeOwnedSpill: true,
17538
17669
  ...args2.confirmExternalFileAccess ? { confirmExternalFileAccess: args2.confirmExternalFileAccess } : {}
17539
17670
  });
17540
- const workspaceRoot = resolve4(args2.workspaceRoot);
17671
+ const workspaceRoot = resolve5(args2.workspaceRoot);
17541
17672
  const inside = isPathInsideWorkspace({ workspaceRoot, targetPath: searchPath });
17542
17673
  const result4 = await searchFileTextMatches({
17543
17674
  root: inside ? workspaceRoot : searchPath,
17544
17675
  target: inside ? normalizeWorkspaceRelativePath({ workspaceRoot, targetPath: searchPath }) : ".",
17545
17676
  query: args2.query,
17546
- regex: true,
17677
+ regex: args2.regex ?? true,
17547
17678
  caseSensitive: args2.caseSensitive !== false,
17548
17679
  contextLines: args2.contextLines,
17549
17680
  maxResults: args2.maxResults ?? 200,
17550
- includeIgnored: args2.workspaceRoot.includes(".worktrees") || !inside,
17681
+ includeIgnored: args2.includeIgnored ?? (args2.workspaceRoot.includes(".worktrees") || !inside),
17551
17682
  absolutePaths: !inside,
17552
- exclude: inside ? [...ALWAYS_EXCLUDED_GLOBS] : []
17683
+ exclude: [...inside ? ALWAYS_EXCLUDED_GLOBS : [], ...args2.exclude ?? []],
17684
+ include: args2.include,
17685
+ resolveRipgrepBinary: args2.resolveRipgrepBinary,
17686
+ resolveGrepBinary: args2.resolveGrepBinary
17553
17687
  });
17554
17688
  const outputLines = result4.matches.flatMap((match7) => [
17555
17689
  ...match7.before.map((line, index) => `${match7.path}:${Math.max(1, match7.line - match7.before.length + index)}-${line}`),
17556
17690
  `${match7.path}:${match7.line}:${match7.text}`,
17557
17691
  ...match7.after.map((line, index) => `${match7.path}:${match7.line + index + 1}-${line}`)
17558
17692
  ]);
17559
- const rawContent = outputLines.join("\n");
17693
+ const rawContent = scrubSecrets(outputLines.join("\n")).cleaned;
17560
17694
  const content = truncateToolOutput(rawContent, SEARCH_OUTPUT_CHAR_LIMIT);
17561
- const matchLines = result4.matches.map((match7) => `${match7.path}:${match7.line}:${match7.text}`);
17562
17695
  return {
17563
17696
  content,
17564
17697
  metadata: {
@@ -17567,6 +17700,7 @@ async function internalSearchWorkspace(args2) {
17567
17700
  searchedPath: inside ? normalizeWorkspaceRelativePath({ workspaceRoot, targetPath: searchPath }) : ".",
17568
17701
  count: outputLines.length,
17569
17702
  matchCount: result4.totalMatches,
17703
+ totalMatches: result4.totalMatches,
17570
17704
  matchedFiles: Array.from(new Set(result4.matches.map((match7) => match7.path))),
17571
17705
  truncated: result4.truncated || content.length !== rawContent.length,
17572
17706
  limitedByMaxResults: result4.truncated,
@@ -17617,7 +17751,7 @@ async function globFilesTool(args2) {
17617
17751
  ...args2.confirmExternalFileAccess ? { confirmExternalFileAccess: args2.confirmExternalFileAccess } : {}
17618
17752
  });
17619
17753
  const relativeSearchPath = normalizeWorkspaceRelativePath({
17620
- workspaceRoot: resolve4(args2.workspaceRoot),
17754
+ workspaceRoot: resolve5(args2.workspaceRoot),
17621
17755
  targetPath: searchPath
17622
17756
  });
17623
17757
  const pathPrefix = relativeSearchPath === "." ? "" : `${relativeSearchPath.replace(/\/+$/, "")}/`;
@@ -17812,7 +17946,14 @@ async function captureVisualStateTool(args2) {
17812
17946
  script: null,
17813
17947
  args: [],
17814
17948
  compatibilityVersion: 2,
17815
- compatibilityNote: "Platform rendering replaces workspace scripts; script/args/stdoutTail no longer describe a subprocess. Existing page metrics and path fields are retained."
17949
+ compatibilityNote: "Platform rendering replaces workspace scripts; script/args/stdoutTail no longer describe a subprocess. Existing page metrics and path fields are retained.",
17950
+ imageArtifacts: [{
17951
+ path: screenshotPath,
17952
+ kind: "screenshot",
17953
+ width: image.imageSummary.width,
17954
+ height: image.imageSummary.height,
17955
+ bytes: image.imageSummary.bytes
17956
+ }]
17816
17957
  }
17817
17958
  };
17818
17959
  } catch (error) {
@@ -17914,7 +18055,8 @@ async function launchProcessTool(args2) {
17914
18055
  ];
17915
18056
  const detached = process.platform !== "win32";
17916
18057
  const proc = spawnChildProcess2(cmdArgs[0] ?? "", cmdArgs.slice(1), {
17917
- cwd: resolve4(args2.workspaceRoot),
18058
+ cwd: resolve5(args2.workspaceRoot),
18059
+ env: workspaceChildEnv(),
17918
18060
  stdio: ["ignore", "pipe", "pipe"],
17919
18061
  detached,
17920
18062
  windowsHide: true
@@ -18183,6 +18325,36 @@ function createLocalWorkspaceToolExecutors(args2) {
18183
18325
  workspaceRoot: args2.workspaceRoot,
18184
18326
  ...fileAccess
18185
18327
  }),
18328
+ searchFiles: async (call) => {
18329
+ const parsed = parseWorkspaceToolArguments(call.arguments);
18330
+ const query = parsed.query === void 0 ? parsed.pattern : parsed.query;
18331
+ if (typeof query !== "string" || !query.length) throw new Error("searchFiles requires a non-empty query.");
18332
+ for (const key of ["regex", "caseSensitive", "includeIgnored"]) {
18333
+ if (parsed[key] !== void 0 && typeof parsed[key] !== "boolean") throw new Error(`${key} must be a boolean.`);
18334
+ }
18335
+ for (const key of ["path", "include"]) {
18336
+ if (parsed[key] !== void 0 && typeof parsed[key] !== "string") throw new Error(`${key} must be a string.`);
18337
+ }
18338
+ if (parsed.exclude !== void 0 && (!Array.isArray(parsed.exclude) || !parsed.exclude.every((item) => typeof item === "string"))) throw new Error("exclude must be an array of strings.");
18339
+ for (const [key, min4, max4] of [["contextLines", 0, 5], ["maxResults", 1, 1e3]]) {
18340
+ if (parsed[key] !== void 0 && (!Number.isInteger(parsed[key]) || Number(parsed[key]) < min4 || Number(parsed[key]) > max4)) throw new Error(`${key} must be an integer from ${min4} to ${max4}.`);
18341
+ }
18342
+ return internalSearchWorkspace({
18343
+ workspaceRoot: args2.workspaceRoot,
18344
+ query,
18345
+ path: parsed.path,
18346
+ regex: parsed.regex === true,
18347
+ caseSensitive: parsed.caseSensitive !== false,
18348
+ include: parsed.include,
18349
+ exclude: parsed.exclude ?? [],
18350
+ contextLines: parsed.contextLines,
18351
+ maxResults: parsed.maxResults ?? 100,
18352
+ includeIgnored: parsed.includeIgnored === true,
18353
+ confirmExternalFileAccess: args2.confirmExternalFileAccess,
18354
+ resolveRipgrepBinary: args2.resolveRipgrepBinary,
18355
+ resolveGrepBinary: args2.resolveGrepBinary
18356
+ });
18357
+ },
18186
18358
  globFiles: (call) => globFilesTool({
18187
18359
  call,
18188
18360
  workspaceRoot: args2.workspaceRoot,
@@ -18230,20 +18402,33 @@ function createLocalWorkspaceToolExecutors(args2) {
18230
18402
  });
18231
18403
  return await readLocalImage(absolutePath);
18232
18404
  } catch (error) {
18233
- throw new Error(`read_image: failed to read ${JSON.stringify(path)}: ${error instanceof Error ? error.message : String(error)}`);
18405
+ const inner = (error instanceof Error ? error.message : String(error)).replace(/^read_image:\s*/i, "");
18406
+ throw new Error(`read_image: failed to read ${JSON.stringify(path)}: ${inner}`);
18234
18407
  }
18235
18408
  }));
18236
18409
  return {
18237
18410
  content: results2.map((result4) => result4.content).join("\n"),
18238
- images: results2.flatMap((result4) => result4.images ?? [])
18239
- };
18411
+ images: results2.flatMap((result4) => result4.images ?? []),
18412
+ metadata: {
18413
+ paths: imagePaths,
18414
+ count: imagePaths.length,
18415
+ ...imagePaths.length === 1 ? { path: imagePaths[0] } : {},
18416
+ imageArtifacts: results2.map((result4) => ({
18417
+ path: result4.imageSummary.path,
18418
+ kind: "image",
18419
+ width: result4.imageSummary.width,
18420
+ height: result4.imageSummary.height,
18421
+ bytes: result4.imageSummary.bytes
18422
+ }))
18423
+ }
18424
+ };
18240
18425
  },
18241
- readFile: (call) => readFileTool({
18426
+ readFile: Object.assign((call) => readFileTool({
18242
18427
  call,
18243
18428
  workspaceRoot: args2.workspaceRoot,
18244
18429
  ...readFileLedger ? { readLedger: readFileLedger } : {},
18245
18430
  ...fileAccess
18246
- }),
18431
+ }), { resetReadLedger: () => readFileLedger?.clear() }),
18247
18432
  writeFile: (call) => writeFileTool({
18248
18433
  call,
18249
18434
  workspaceRoot: args2.workspaceRoot,
@@ -18403,6 +18588,9 @@ function validateToolArguments(args2) {
18403
18588
  }
18404
18589
  record2 = parsed;
18405
18590
  }
18591
+ if (toolName === "searchFiles" && record2.query === void 0 && typeof record2.pattern === "string" && record2.pattern.length) {
18592
+ record2 = { ...record2, query: record2.pattern };
18593
+ }
18406
18594
  for (const field of requiredFields) {
18407
18595
  if (record2[field] !== void 0) continue;
18408
18596
  if (isAliasSatisfied(record2, field)) continue;
@@ -18487,6 +18675,7 @@ var DEFAULT_LOCAL_TOOLS = /* @__PURE__ */ new Set([
18487
18675
  "writeFile",
18488
18676
  "editFile",
18489
18677
  "globFiles",
18678
+ "searchFiles",
18490
18679
  "execShell",
18491
18680
  "launchProcess",
18492
18681
  "listProcesses",
@@ -18743,6 +18932,78 @@ function emitLoopEvent(boundary, event, bridge) {
18743
18932
  function clip(value, max4 = 240) {
18744
18933
  return clipCompactText(value, max4);
18745
18934
  }
18935
+ var IMAGE_ARTIFACT_TOOL_NAMES = /* @__PURE__ */ new Set([
18936
+ "read_image",
18937
+ "captureVisualState",
18938
+ "browser_screenshot",
18939
+ "captureHostWindow"
18940
+ ]);
18941
+ function sanitizeArtifactPath(raw) {
18942
+ if (typeof raw !== "string") return void 0;
18943
+ const trimmed = raw.trim();
18944
+ if (!trimmed || /[\u0000-\u001f\u007f]/.test(trimmed)) return void 0;
18945
+ if (/^(?:https?|data|javascript):/i.test(trimmed)) return void 0;
18946
+ return trimmed;
18947
+ }
18948
+ function normalizeStructuredImageArtifact(raw, defaultKind) {
18949
+ if (!raw || typeof raw !== "object") return void 0;
18950
+ const item = raw;
18951
+ const path = sanitizeArtifactPath(item.path);
18952
+ if (!path) return void 0;
18953
+ const kind = item.kind === "image" || item.kind === "screenshot" ? item.kind : defaultKind;
18954
+ return {
18955
+ path,
18956
+ kind,
18957
+ ...typeof item.width === "number" && Number.isFinite(item.width) && item.width > 0 ? { width: item.width } : {},
18958
+ ...typeof item.height === "number" && Number.isFinite(item.height) && item.height > 0 ? { height: item.height } : {},
18959
+ ...typeof item.bytes === "number" && Number.isFinite(item.bytes) && item.bytes > 0 ? { bytes: item.bytes } : {}
18960
+ };
18961
+ }
18962
+ function extractToolImageArtifacts(toolName, toolResult) {
18963
+ if (!IMAGE_ARTIFACT_TOOL_NAMES.has(toolName)) return void 0;
18964
+ const metadata = toolResult.metadata;
18965
+ if (!metadata || typeof metadata !== "object") return void 0;
18966
+ if (metadata.ok === false || metadata.imageDelivered === false || metadata.cancelled === true || metadata.failed === true) {
18967
+ return void 0;
18968
+ }
18969
+ const defaultKind = toolName === "read_image" ? "image" : "screenshot";
18970
+ const byPath = /* @__PURE__ */ new Map();
18971
+ const add2 = (candidate) => {
18972
+ const path = sanitizeArtifactPath(candidate.path);
18973
+ if (!path) return;
18974
+ const kind = candidate.kind ?? defaultKind;
18975
+ const existing = byPath.get(path);
18976
+ if (!existing) {
18977
+ byPath.set(path, {
18978
+ path,
18979
+ kind,
18980
+ ...candidate.width !== void 0 ? { width: candidate.width } : {},
18981
+ ...candidate.height !== void 0 ? { height: candidate.height } : {},
18982
+ ...candidate.bytes !== void 0 ? { bytes: candidate.bytes } : {}
18983
+ });
18984
+ return;
18985
+ }
18986
+ if (existing.width === void 0 && candidate.width !== void 0) existing.width = candidate.width;
18987
+ if (existing.height === void 0 && candidate.height !== void 0) existing.height = candidate.height;
18988
+ if (existing.bytes === void 0 && candidate.bytes !== void 0) existing.bytes = candidate.bytes;
18989
+ };
18990
+ if (Array.isArray(metadata.imageArtifacts)) {
18991
+ for (const entry of metadata.imageArtifacts) {
18992
+ const normalized = normalizeStructuredImageArtifact(entry, defaultKind);
18993
+ if (normalized) add2(normalized);
18994
+ }
18995
+ return byPath.size > 0 ? Array.from(byPath.values()) : void 0;
18996
+ }
18997
+ if (Array.isArray(metadata.paths)) {
18998
+ for (const item of metadata.paths) {
18999
+ if (typeof item === "string") add2({ path: item });
19000
+ }
19001
+ }
19002
+ if (typeof metadata.screenshotPath === "string") add2({ path: metadata.screenshotPath });
19003
+ if (typeof metadata.savedTo === "string") add2({ path: metadata.savedTo });
19004
+ if (typeof metadata.path === "string") add2({ path: metadata.path });
19005
+ return byPath.size > 0 ? Array.from(byPath.values()) : void 0;
19006
+ }
18746
19007
  function projectSafeToolObservationMetadata(metadata) {
18747
19008
  if (!metadata || typeof metadata !== "object") return void 0;
18748
19009
  const safe = {};
@@ -18988,12 +19249,18 @@ async function executeToolCall(args2) {
18988
19249
  }
18989
19250
  }
18990
19251
  if (!toolResult) {
19252
+ let runtimeContext = input.runtimeContext;
19253
+ if (args2.getDirectWorkSource && !runtimeContext?.userMessageId && toolName === "rememberMemory" && parseNoloWorkspaceToolArguments(unwrappedArguments).mode === "work") {
19254
+ const id = await args2.getDirectWorkSource();
19255
+ throwIfAborted(input);
19256
+ if (id) runtimeContext = { ...runtimeContext, userMessageId: id };
19257
+ }
18991
19258
  const executePromise = input.adapter.executeTool({
18992
19259
  id: toolCall.id,
18993
19260
  name: toolName,
18994
19261
  arguments: unwrappedArguments,
18995
19262
  ...userInputText ? { userInput: userInputText } : {},
18996
- ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {},
19263
+ ...runtimeContext ? { runtimeContext } : {},
18997
19264
  ...args2.runToolNames ? { runToolNames: args2.runToolNames } : {},
18998
19265
  ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
18999
19266
  // 定档信号:来源只由 turn 输入推导,不让模型/参数层参与。
@@ -19002,7 +19269,7 @@ async function executeToolCall(args2) {
19002
19269
  origin: input.background ? "automation" : input.runKind === "subtask" ? "agent" : "chat"
19003
19270
  }, {
19004
19271
  ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
19005
- ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {}
19272
+ ...runtimeContext ? { runtimeContext } : {}
19006
19273
  });
19007
19274
  const execStartedAtMs = Date.now();
19008
19275
  toolResult = await runAbortableToolTask(input, executePromise, toolName);
@@ -19041,6 +19308,7 @@ ${toolResult.content}` : toolResult.content,
19041
19308
  const finishedAt = Date.now();
19042
19309
  const summary = summarizeToolResult(toolResult.content, toolResult.metadata);
19043
19310
  const safeMetadata = projectSafeToolObservationMetadata(toolResult.metadata);
19311
+ const imageArtifacts = extractToolImageArtifacts(toolName, toolResult);
19044
19312
  loopTiming.mark("toolExecute", round);
19045
19313
  emitLoopEvent(
19046
19314
  boundary,
@@ -19063,7 +19331,8 @@ ${toolResult.content}` : toolResult.content,
19063
19331
  elapsedMs: Math.max(0, finishedAt - startedAt),
19064
19332
  ...summary ? { summary } : {},
19065
19333
  ...typeof toolResult.content === "string" ? { content: toolResult.content } : {},
19066
- metadata: toolResult.metadata
19334
+ metadata: toolResult.metadata,
19335
+ ...imageArtifacts ? { imageArtifacts } : {}
19067
19336
  }
19068
19337
  );
19069
19338
  } catch (error) {
@@ -19242,6 +19511,137 @@ function createTurnUsageLedger(args2) {
19242
19511
  };
19243
19512
  }
19244
19513
 
19514
+ // packages/agent-runtime/agentRunIsolation.ts
19515
+ var ORCHESTRATION_TOOL_NAMES = /* @__PURE__ */ new Set([
19516
+ "startAgentRun",
19517
+ "controlAgentRun",
19518
+ "listAgents",
19519
+ "readAgent",
19520
+ "runStreamingAgent"
19521
+ ]);
19522
+ var INTERACTION_REQUIRED_TOOL_NAMES = /* @__PURE__ */ new Set([
19523
+ "ask_user",
19524
+ // 凭据请求:需要宿主交互面板(Block 1a);desktop 无通道时同 ask_user 剥离。
19525
+ "secret-request"
19526
+ ]);
19527
+ var SELF_MUTATION_TOOL_NAMES = /* @__PURE__ */ new Set([
19528
+ "updateSelf",
19529
+ "updateAgent"
19530
+ ]);
19531
+ var SUBTASK_REMOVED_TOOL_NAMES = /* @__PURE__ */ new Set([
19532
+ ...ORCHESTRATION_TOOL_NAMES,
19533
+ ...INTERACTION_REQUIRED_TOOL_NAMES,
19534
+ ...SELF_MUTATION_TOOL_NAMES
19535
+ ]);
19536
+ function isSubtaskRun(env) {
19537
+ if (!env) return false;
19538
+ const value = env.NOLO_AGENT_RUN_CHILD;
19539
+ return typeof value === "string" && value.length > 0 && value !== "0";
19540
+ }
19541
+ var RUN_WAKE_CHANNEL_ENV = "NOLO_RUN_WAKE";
19542
+ function hasRunWakeChannel(env) {
19543
+ if (!env) return false;
19544
+ const value = env[RUN_WAKE_CHANNEL_ENV];
19545
+ return typeof value === "string" && value.length > 0 && value !== "0";
19546
+ }
19547
+ function filterToolNamesForRunKind(toolNames, isSubtask) {
19548
+ if (!isSubtask) return [...toolNames];
19549
+ return toolNames.filter((name) => !SUBTASK_REMOVED_TOOL_NAMES.has(name));
19550
+ }
19551
+
19552
+ // packages/agent-runtime/subtaskBudget.ts
19553
+ var DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_1_TOOL_CALLS = 40;
19554
+ var DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_2_TOOL_CALLS = 80;
19555
+ var SUBTASK_SOFT_BUDGET_MILESTONE_1_PREFIX = "[\u7CFB\u7EDF\u63D0\u793A \xB7 \u5B50\u4EFB\u52A1\u8F6F\u9884\u7B97\u63D0\u9192]";
19556
+ var SUBTASK_SOFT_BUDGET_MILESTONE_2_PREFIX = "[\u7CFB\u7EDF\u63D0\u793A \xB7 \u5B50\u4EFB\u52A1\u5F3A\u6536\u655B\u63D0\u9192]";
19557
+ function buildSubtaskSoftBudgetMilestone1Prompt(toolCallCount) {
19558
+ return `${SUBTASK_SOFT_BUDGET_MILESTONE_1_PREFIX} \u5F53\u524D\u5B50\u4EFB\u52A1\u5DF2\u7D2F\u8BA1\u6267\u884C ${toolCallCount} \u6B21\u5DE5\u5177\u8C03\u7528\uFF0C\u8BF7\u505A\u4E00\u6B21\u6536\u655B\u81EA\u68C0\uFF1A\u82E5\u6838\u5FC3\u76EE\u6807\u4E0E\u5FC5\u9700\u9A8C\u8BC1\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u5C3D\u5FEB\u6574\u7406\u7ED3\u679C\u5E76\u6536\u655B\u4EA4\u4ED8\uFF1B\u82E5\u540C\u4E00\u62A5\u9519\u5DF2\u8FDE\u7EED\u91CD\u8BD5\u4E14\u65E0\u65B0\u8BC1\u636E\uFF0C\u8BF7\u505C\u6B62\u76F2\u8BD5\u5E76\u5728\u7ED3\u679C\u4E2D\u5982\u5B9E\u62A5\u544A\u6839\u56E0\u4E0E\u963B\u788D\uFF1B\u82E5\u786E\u7CFB\u6B63\u5E38\u7684\u591A\u6587\u4EF6\u4FEE\u6539\u6216\u9A8C\u8BC1\u5DE5\u4F5C\uFF0C\u53EF\u7EE7\u7EED\u7A33\u6B65\u5B8C\u6210\u3002`;
19559
+ }
19560
+ function buildSubtaskSoftBudgetMilestone2Prompt(toolCallCount) {
19561
+ return `${SUBTASK_SOFT_BUDGET_MILESTONE_2_PREFIX} \u5F53\u524D\u5B50\u4EFB\u52A1\u5DF2\u7D2F\u8BA1\u6267\u884C ${toolCallCount} \u6B21\u5DE5\u5177\u8C03\u7528\u3002\u5EFA\u8BAE\u5728\u5B8C\u6210\u5F53\u524D\u624B\u5934\u6700\u540E\u4E00\u6B65\u5FC5\u8981\u9A8C\u8BC1\u540E\uFF0C\u7ACB\u5373\u6574\u7406\u5DF2\u6709\u6210\u679C\u3001\u672A\u5B8C\u6210\u9879\u4E0E\u5EFA\u8BAE\u7684\u4E0B\u4E00\u6B65\u76F4\u63A5\u4EA4\u4ED8\u7236\u5BF9\u8BDD\uFF0C\u907F\u514D\u5355\u6B21\u5B50\u4EFB\u52A1\u8FC7\u5EA6\u6D88\u8017\u914D\u989D\u4E0E\u4E0A\u4E0B\u6587\u3002`;
19562
+ }
19563
+ function resolveSoftBudgetEnv(explicitEnv) {
19564
+ if (explicitEnv !== void 0) return explicitEnv;
19565
+ if (typeof process !== "undefined" && process.env) return process.env;
19566
+ return void 0;
19567
+ }
19568
+ function isEnvSoftBudgetDisabled(env) {
19569
+ const raw = env?.NOLO_SUBTASK_SOFT_BUDGET?.trim().toLowerCase();
19570
+ return raw === "0" || raw === "false";
19571
+ }
19572
+ function hasParentDialogEnvSignal(env) {
19573
+ const raw = env?.NOLO_PARENT_DIALOG_ID;
19574
+ return typeof raw === "string" && raw.trim().length > 0;
19575
+ }
19576
+ function normalizeThreshold(value) {
19577
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
19578
+ return void 0;
19579
+ }
19580
+ return Math.floor(value);
19581
+ }
19582
+ function createSubtaskSoftBudgetAdvisor(options) {
19583
+ const env = resolveSoftBudgetEnv(options?.env);
19584
+ const envDisabled = isEnvSoftBudgetDisabled(env);
19585
+ const configDisabled = options?.softBudget === false || typeof options?.softBudget === "object" && options.softBudget !== null && options.softBudget.enabled === false;
19586
+ const configEnabled = options?.softBudget === true || typeof options?.softBudget === "object" && options.softBudget !== null && options.softBudget.enabled !== false;
19587
+ const hasSubtaskContext = options?.isSubtask === true || options?.runKind === "subtask" || hasParentDialogEnvSignal(env) || isSubtaskRun(env);
19588
+ const enabled = !envDisabled && !configDisabled && (configEnabled || hasSubtaskContext);
19589
+ const rawConfig = typeof options?.softBudget === "object" && options.softBudget !== null ? options.softBudget : void 0;
19590
+ const milestone1ToolCalls = normalizeThreshold(rawConfig?.milestone1ToolCalls) ?? DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_1_TOOL_CALLS;
19591
+ const explicitMilestone2 = normalizeThreshold(rawConfig?.milestone2ToolCalls);
19592
+ const milestone2ToolCalls = explicitMilestone2 !== void 0 ? Math.max(milestone1ToolCalls + 1, explicitMilestone2) : Math.max(
19593
+ DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_2_TOOL_CALLS,
19594
+ milestone1ToolCalls * 2
19595
+ );
19596
+ let milestone1Triggered = false;
19597
+ let milestone2Triggered = false;
19598
+ let lastObservedToolCallCount = 0;
19599
+ function observeToolCalls(toolCallCount) {
19600
+ const normalized = typeof toolCallCount === "number" && Number.isFinite(toolCallCount) && toolCallCount > 0 ? Math.floor(toolCallCount) : 0;
19601
+ if (normalized > lastObservedToolCallCount) {
19602
+ lastObservedToolCallCount = normalized;
19603
+ }
19604
+ if (!enabled) return null;
19605
+ if (!milestone2Triggered && normalized >= milestone2ToolCalls) {
19606
+ milestone1Triggered = true;
19607
+ milestone2Triggered = true;
19608
+ return {
19609
+ milestone: 2,
19610
+ threshold: milestone2ToolCalls,
19611
+ toolCallCount: normalized,
19612
+ message: buildSubtaskSoftBudgetMilestone2Prompt(normalized)
19613
+ };
19614
+ }
19615
+ if (!milestone1Triggered && normalized >= milestone1ToolCalls) {
19616
+ milestone1Triggered = true;
19617
+ return {
19618
+ milestone: 1,
19619
+ threshold: milestone1ToolCalls,
19620
+ toolCallCount: normalized,
19621
+ message: buildSubtaskSoftBudgetMilestone1Prompt(normalized)
19622
+ };
19623
+ }
19624
+ return null;
19625
+ }
19626
+ function getState2() {
19627
+ return {
19628
+ enabled,
19629
+ milestone1ToolCalls,
19630
+ milestone2ToolCalls,
19631
+ milestone1Triggered,
19632
+ milestone2Triggered,
19633
+ lastObservedToolCallCount
19634
+ };
19635
+ }
19636
+ return {
19637
+ enabled,
19638
+ milestone1ToolCalls,
19639
+ milestone2ToolCalls,
19640
+ observeToolCalls,
19641
+ getState: getState2
19642
+ };
19643
+ }
19644
+
19245
19645
  // packages/agent-runtime/leafFinalHandoff.ts
19246
19646
  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.`;
19247
19647
 
@@ -19306,8 +19706,17 @@ function findSummaryAnchorIndex(bridged, anchorId) {
19306
19706
  const index = Number(legacy[1]);
19307
19707
  return Number.isSafeInteger(index) && index < bridged.length ? index : -1;
19308
19708
  }
19309
- function logSummarySourceDiagnostics(phase, dialogId, history, anchor) {
19709
+ function logSummarySourceDiagnostics(phase, dialogId, history, anchor, segmentDiff) {
19310
19710
  const sourceHash = hashSummarySourceSlice(history, anchor)?.slice(0, 16);
19711
+ if (phase === "invalidated" && segmentDiff) {
19712
+ console.log(`[compaction-source] ${JSON.stringify({
19713
+ phase,
19714
+ dialogId,
19715
+ sourceHash,
19716
+ kind: "segment-diff",
19717
+ ...segmentDiff
19718
+ })}`);
19719
+ }
19311
19720
  const rows = buildSummarySourceDiagnostics(toPlanCompressionMessages(history), anchor);
19312
19721
  for (const row of rows) console.log(`[compaction-source] ${JSON.stringify({
19313
19722
  phase,
@@ -19505,13 +19914,15 @@ async function maybeAutoCompactLocalHistory(args2) {
19505
19914
  let reason;
19506
19915
  if (invalidStored?.schemaVersion !== void 0 && invalidStored.schemaVersion !== COMPACTION_SUMMARY_SCHEMA_VERSION) {
19507
19916
  reason = "schema-version-mismatch";
19508
- } else if (typeof invalidStored?.summarizedBeforeId !== "string" || !bridged.some((m) => m.id === invalidStored.summarizedBeforeId)) {
19917
+ } else if (typeof invalidStored?.summarizedBeforeId !== "string" || findSummaryAnchorIndex(bridged, invalidStored.summarizedBeforeId) === -1) {
19509
19918
  reason = "anchor-not-found";
19510
19919
  } else if (typeof invalidStored?.sourceCount === "number" && history.length < invalidStored.sourceCount) {
19511
19920
  reason = "history-trimmed";
19512
19921
  } else {
19513
19922
  reason = "hash-mismatch";
19514
19923
  }
19924
+ const currentSegments = buildSummarySourceSegments(bridged, invalidStored?.summarizedBeforeId);
19925
+ const segmentDiff = reason === "hash-mismatch" ? diffSummarySourceSegments(invalidStored?.sourceSegments, currentSegments) : void 0;
19515
19926
  console.warn(
19516
19927
  `[localLoop] invalidated dialog summary for ${dialogId} (${reason}); discarding and re-compressing`,
19517
19928
  // 诊断分项(**仅加日志,不改任何哈希/校验/重锚语义**):区分「历史真被改写」
@@ -19524,10 +19935,17 @@ async function maybeAutoCompactLocalHistory(args2) {
19524
19935
  storedSourceCount: typeof invalidStored?.sourceCount === "number" ? invalidStored.sourceCount : null,
19525
19936
  summarizedBeforeId: typeof invalidStored?.summarizedBeforeId === "string" ? invalidStored.summarizedBeforeId : null,
19526
19937
  recomputedHashPrefix: hashSummarySourceSlice(history, invalidStored?.summarizedBeforeId)?.slice(0, 8) ?? null,
19527
- storedHashPrefix: typeof invalidStored?.sourceHash === "string" && invalidStored.sourceHash ? invalidStored.sourceHash.slice(0, 8) : null
19938
+ storedHashPrefix: typeof invalidStored?.sourceHash === "string" && invalidStored.sourceHash ? invalidStored.sourceHash.slice(0, 8) : null,
19939
+ ...segmentDiff ? { segmentDiff } : {}
19528
19940
  }
19529
19941
  );
19530
- logSummarySourceDiagnostics("invalidated", dialogId, history, invalidStored?.summarizedBeforeId);
19942
+ logSummarySourceDiagnostics(
19943
+ "invalidated",
19944
+ dialogId,
19945
+ history,
19946
+ invalidStored?.summarizedBeforeId,
19947
+ segmentDiff
19948
+ );
19531
19949
  stored = null;
19532
19950
  }
19533
19951
  const existingSummary = typeof stored?.summary === "string" ? stored.summary : "";
@@ -19537,7 +19955,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19537
19955
  const contextWindow = typeof args2.contextWindow === "number" && Number.isFinite(args2.contextWindow) && args2.contextWindow > 0 ? args2.contextWindow : getModelContextWindow(args2.model ?? "");
19538
19956
  const allMsgs = toPlanCompressionMessages(prepareHistoryForNextTurn(history, args2.contextReferenceResolver));
19539
19957
  const maxInputItems = resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint });
19540
- const force = args2.force === true || args2.requestOverBudget?.(
19958
+ const force = args2.force === true || invalidSummary || args2.requestOverBudget?.(
19541
19959
  existingSummary ? projectHistoryWithSummary({ history, summary: existingSummary, summarizedBeforeId }) : history
19542
19960
  ) === true;
19543
19961
  const plan = planCompression({
@@ -19621,7 +20039,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19621
20039
  };
19622
20040
  }
19623
20041
  const msgsToCompress = plan.msgsToCompress;
19624
- const bounded3 = buildBoundedCompactionRequest({
20042
+ const bounded3 = buildHistoricalCompactionRequest({
19625
20043
  msgsToCompress,
19626
20044
  previousSummary: existingSummary,
19627
20045
  contextWindow,
@@ -19774,20 +20192,20 @@ async function maybeAutoCompactLocalHistory(args2) {
19774
20192
  });
19775
20193
  }
19776
20194
  };
19777
- const fallback = args2.summaryFallback?.preferPlatform ? args2.summaryFallback : void 0;
20195
+ const fallback2 = args2.summaryFallback?.preferPlatform ? args2.summaryFallback : void 0;
19778
20196
  let eligibility;
19779
- const routedFallback = fallback ? Object.assign(
20197
+ const routedFallback = fallback2 ? Object.assign(
19780
20198
  async (content, options) => {
19781
20199
  summaryModel = PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL;
19782
20200
  summaryProvider = "nolo";
19783
- return physicalRequest("platform", () => fallback(content, { ...options, attemptId: compactionAttemptId }));
20201
+ return physicalRequest("platform", () => fallback2(content, { ...options, attemptId: compactionAttemptId }));
19784
20202
  },
19785
20203
  {
19786
- preferPlatform: (options) => eligibility ??= fallback.preferPlatform(options),
19787
- ...fallback.complete ? { complete: async (content, options) => {
20204
+ preferPlatform: (options) => eligibility ??= fallback2.preferPlatform(options),
20205
+ ...fallback2.complete ? { complete: async (content, options) => {
19788
20206
  summaryModel = PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL;
19789
20207
  summaryProvider = "nolo";
19790
- return physicalRequest("platform", () => fallback.complete(content, { ...options, attemptId: compactionAttemptId }));
20208
+ return physicalRequest("platform", () => fallback2.complete(content, { ...options, attemptId: compactionAttemptId }));
19791
20209
  } } : {}
19792
20210
  }
19793
20211
  ) : void 0;
@@ -19815,7 +20233,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19815
20233
  primaryElapsedMs = Date.now() - compactionT0;
19816
20234
  logCompactionTiming("provider-error", {});
19817
20235
  emitPhase({ kind: "compaction-retry", attempt: attempt + 1, maxAttempts });
19818
- await new Promise((resolve6, reject) => {
20236
+ await new Promise((resolve7, reject) => {
19819
20237
  const signal = requestController.signal;
19820
20238
  const cancel = () => {
19821
20239
  clearTimeout(timer);
@@ -19824,7 +20242,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19824
20242
  };
19825
20243
  const timer = setTimeout(() => {
19826
20244
  signal.removeEventListener("abort", cancel);
19827
- resolve6();
20245
+ resolve7();
19828
20246
  }, delayMs);
19829
20247
  signal.addEventListener("abort", cancel, { once: true });
19830
20248
  if (signal.aborted) cancel();
@@ -19838,16 +20256,16 @@ async function maybeAutoCompactLocalHistory(args2) {
19838
20256
  (error) => ({ kind: "provider-error", error })
19839
20257
  );
19840
20258
  const guards = [];
19841
- if (timeoutMs) guards.push(new Promise((resolve6) => {
20259
+ if (timeoutMs) guards.push(new Promise((resolve7) => {
19842
20260
  timeoutHandle = setTimeout(() => {
19843
20261
  requestController.abort(new DOMException("Summary deadline exceeded", "TimeoutError"));
19844
- resolve6({ kind: "timeout" });
20262
+ resolve7({ kind: "timeout" });
19845
20263
  }, timeoutMs);
19846
20264
  }));
19847
- if (args2.abortSignal) guards.push(new Promise((resolve6) => {
20265
+ if (args2.abortSignal) guards.push(new Promise((resolve7) => {
19848
20266
  abortListener = () => {
19849
20267
  requestController.abort(args2.abortSignal?.reason);
19850
- resolve6({ kind: "aborted" });
20268
+ resolve7({ kind: "aborted" });
19851
20269
  };
19852
20270
  args2.abortSignal?.addEventListener("abort", abortListener, { once: true });
19853
20271
  if (args2.abortSignal?.aborted) abortListener();
@@ -19961,8 +20379,13 @@ async function maybeAutoCompactLocalHistory(args2) {
19961
20379
  }
19962
20380
  };
19963
20381
  }
20382
+ const bridgedHistory = toPlanCompressionMessages(history);
19964
20383
  const sourceMeta = await computeSummarySourceMetadata(
19965
- toPlanCompressionMessages(history),
20384
+ bridgedHistory,
20385
+ bounded3.summarizedBeforeId
20386
+ );
20387
+ const sourceSegments = buildSummarySourceSegments(
20388
+ bridgedHistory,
19966
20389
  bounded3.summarizedBeforeId
19967
20390
  );
19968
20391
  if (Date.now() >= summaryDeadlineMs) throw Object.assign(new Error("Summary deadline exceeded"), { compactionReason: "timeout" });
@@ -19970,7 +20393,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19970
20393
  throw Object.assign(new Error("auto-compaction aborted"), { compactionReason: "aborted" });
19971
20394
  }
19972
20395
  const saveT0 = Date.now();
19973
- await adapter.saveDialogSummary({
20396
+ const summarySavePayload = {
19974
20397
  dialogId,
19975
20398
  summary: newSummary,
19976
20399
  summarizedBeforeId: bounded3.summarizedBeforeId,
@@ -19978,12 +20401,14 @@ async function maybeAutoCompactLocalHistory(args2) {
19978
20401
  sourceHash: sourceMeta?.sourceHash,
19979
20402
  sourceCount: sourceMeta?.sourceCount ?? 0,
19980
20403
  schemaVersion: COMPACTION_SUMMARY_SCHEMA_VERSION,
20404
+ ...sourceSegments.length > 0 ? { sourceSegments } : {},
19981
20405
  referenceKeys: Array.from(
19982
20406
  new Set(
19983
20407
  history.slice(0, sourceMeta?.sourceCount ?? 0).flatMap((message) => extractReferenceKeysFromMessage(message))
19984
20408
  )
19985
20409
  )
19986
- });
20410
+ };
20411
+ await adapter.saveDialogSummary(summarySavePayload);
19987
20412
  saveElapsedMs = Date.now() - saveT0;
19988
20413
  logSummarySourceDiagnostics("saved", dialogId, history, bounded3.summarizedBeforeId);
19989
20414
  console.log(formatCompactionMetricsLog(metrics));
@@ -20166,7 +20591,7 @@ function createTurnCompactionController(args2) {
20166
20591
  return { history: result4.history, applied: result4.history !== history, usage: result4.usage };
20167
20592
  };
20168
20593
  let lastCompactionOutcome;
20169
- const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens) => {
20594
+ const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens, force = false) => {
20170
20595
  lastCompactionOutcome = void 0;
20171
20596
  const contextUsage = args2.getContextUsage();
20172
20597
  let inputTokens = contextUsage ? normalizeUsage(contextUsage).input_tokens : 0;
@@ -20178,8 +20603,8 @@ function createTurnCompactionController(args2) {
20178
20603
  }
20179
20604
  }
20180
20605
  const ratio = inputTokens > 0 ? Math.min(1, inputTokens / args2.contextWindow) : void 0;
20181
- if (!requestOverBudget && ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85 && resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint }) === void 0) {
20182
- return;
20606
+ if (!force && !requestOverBudget && ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85 && resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint }) === void 0) {
20607
+ return false;
20183
20608
  }
20184
20609
  try {
20185
20610
  const compacted = await maybeAutoCompactLocalHistory({
@@ -20199,6 +20624,7 @@ function createTurnCompactionController(args2) {
20199
20624
  providerEndpoint: args2.providerEndpoint,
20200
20625
  resolveProvider: args2.resolveProvider,
20201
20626
  contextWindow: args2.contextWindow,
20627
+ ...force ? { force: true } : {},
20202
20628
  ...ratio !== void 0 ? { realContextUsagePercent: ratio } : {},
20203
20629
  abortSignal: args2.abortSignal,
20204
20630
  timeoutMs: args2.timeoutMs,
@@ -20225,12 +20651,16 @@ function createTurnCompactionController(args2) {
20225
20651
  args2.onSelectedSummary?.(compacted.selectedSummary ?? { outcome: initial ? "absent" : "unknown" });
20226
20652
  }
20227
20653
  emitObservation(compacted);
20654
+ return Boolean(compacted.compressed && compacted.summaryGenerated);
20228
20655
  } catch (error) {
20229
20656
  lastCompactionOutcome = { ...lastCompactionOutcome, error: classifySummaryError(error) };
20230
20657
  console.warn("[localLoop] in-loop auto-compaction failed:", error);
20658
+ return false;
20231
20659
  }
20232
20660
  };
20233
- return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: () => prepareRequest(), forceCompact, prepareRequest };
20661
+ return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: async () => {
20662
+ await prepareRequest();
20663
+ }, forceCompact, prepareRequest };
20234
20664
  }
20235
20665
 
20236
20666
  // packages/agent-runtime/providerCallTelemetry.ts
@@ -20608,6 +21038,7 @@ function combineRollbackError(primary, rollbackError) {
20608
21038
  return combined;
20609
21039
  }
20610
21040
  async function runLocalAgentTurn(input) {
21041
+ input = { ...input, runtimeContext: input.runtimeContext ? { ...input.runtimeContext } : void 0 };
20611
21042
  const legacyCallbacks = {
20612
21043
  onLoopEvent: input.onLoopEvent,
20613
21044
  onToolEvent: input.onToolEvent,
@@ -20750,8 +21181,16 @@ async function runLocalAgentTurn(input) {
20750
21181
  // 防止 session-scope 的 agentCollaboration 段逐轮翻转击穿前缀缓存。
20751
21182
  dispatchIntent: detectDispatchIntentFromMessages(history) || detectDispatchIntent(
20752
21183
  typeof input.input === "string" ? input.input : void 0
20753
- )
21184
+ ),
21185
+ runKind: input.runKind
20754
21186
  });
21187
+ const callerScopes = normalizeContextBlockScopes(
21188
+ input.contextBlocks,
21189
+ input.contextBlockScopes
21190
+ );
21191
+ const callerHasMemoryGuidance = callerScopes.some(
21192
+ (scope3) => scope3.content.includes(MEMORY_USE_GUIDANCE)
21193
+ );
20755
21194
  const guidanceScopes = [
20756
21195
  ...input.userLanguage?.trim() ? [buildUserResponseLanguageContext({ language: input.userLanguage })] : [],
20757
21196
  guidanceBlocks.startupProtocol,
@@ -20760,12 +21199,14 @@ async function runLocalAgentTurn(input) {
20760
21199
  // 注入顺序遵循 TOOL_GUIDED_SECTION_ORDER(与 buildSystemPrompt 的显式
20761
21200
  // layer 列表同源),禁止用 Object.values 自行定序。
20762
21201
  ...TOOL_GUIDED_SECTION_ORDER.map((id) => toolGuidedSections[id] ?? ""),
21202
+ // 记忆使用指引(session-scope,进稳定前缀):判定真值是 turnContext 的
21203
+ // `hasMemoryTools`(有效工具面),与 web/server 的 buildSystemPrompt 同一条
21204
+ // 规则。放在这里而不是各宿主:CLI/TUI/desktop 都经 runLocalAgentTurn 进入本
21205
+ // 函数,一处即可覆盖三端,并补齐「空库 + 有记忆工具」这一档——此前本地宿主
21206
+ // 只按记忆 overlay 是否为空门控,空库时模型永远不知道该怎么用记忆工具。
21207
+ ...hasMemoryTools(agentTools) && !callerHasMemoryGuidance ? [MEMORY_USE_GUIDANCE] : [],
20763
21208
  ...input.runKind === "subtask" ? [LEAF_FINAL_HANDOFF_INSTRUCTIONS] : []
20764
21209
  ].map((content) => content.trim()).filter((content) => content.length > 0).map((content) => ({ content, cacheScope: "session" }));
20765
- const callerScopes = normalizeContextBlockScopes(
20766
- input.contextBlocks,
20767
- input.contextBlockScopes
20768
- );
20769
21210
  const responseGuidelines = resolveResponseGuidelines(
20770
21211
  input.responseViewport ?? "unknown"
20771
21212
  );
@@ -20779,24 +21220,8 @@ async function runLocalAgentTurn(input) {
20779
21220
  ] : []
20780
21221
  ];
20781
21222
  const mergedContextBlockScopes = [
20782
- // 删除安全红线:系统层最高优先级约束,位于所有块之前(含身份信息块),
20783
- // owner 要求常驻「根本提示词」的最顶部(2026-09-26 批量误删事故)。
20784
- { content: DELETE_SAFETY_RED_LINE, cacheScope: "session" },
20785
- // 凭据纪律:与红线同为系统层固定块,紧随其后(四条装配线同源)。
20786
- { content: CREDENTIAL_HYGIENE_RULE, cacheScope: "session" },
20787
- // 并行是默认:系统层固定块,紧随红线(localLoop 无 static 作用域,用 session 占位,
20788
- // 「最顶」由数组首位保证——与红线同一约定)。
20789
- { content: VERIFY_BEFORE_CONCLUDING_RULE, cacheScope: "session" },
20790
- { content: PARALLEL_DISPATCH_DEFAULT_RULE, cacheScope: "session" },
20791
- // 派发落点:并行派发纪律的下一层(派到哪个执行后端),沿用 session 占位约定。
20792
- { content: DISPATCH_BACKEND_POLICY, cacheScope: "session" },
20793
- { content: DISPATCH_CANDIDATE_POLICY, cacheScope: "session" },
20794
- // 平台风控纪律:无条件系统层块,沿用 session 占位约定。
20795
- { content: PLATFORM_RISK_CONTROL_RULE, cacheScope: "session" },
20796
- { content: buildConsultationModeBlock(), cacheScope: "session" },
20797
- // Git 任务隔离:系统层固定前置,四条装配线同序(请教模式之后、身份信息之前;
20798
- // skill 配置 disabled 也注入)。
20799
- { content: WORKTREE_ISOLATION_PRELUDE, cacheScope: "session" },
21223
+ // 顶部固定平台层(唯一真源见 platformStaticPromptLayers.ts;localLoop 无 static 作用域,session 占位)。
21224
+ ...buildPlatformStaticScopedBlocks(),
20800
21225
  { content: identityBlock, cacheScope: "session" },
20801
21226
  ...guidanceScopes,
20802
21227
  // 回复行为准则:local 线(CLI 非交互 / 桌面 / TUI)的唯一注入边界。
@@ -20867,6 +21292,7 @@ async function runLocalAgentTurn(input) {
20867
21292
  },
20868
21293
  replaceWorkingView: (next) => {
20869
21294
  transcript.replaceWorkingHistory(next);
21295
+ input.adapter.onWorkingHistoryReplaced?.();
20870
21296
  summaryProjectedPhase = contextPhase("summary-projected", next);
20871
21297
  },
20872
21298
  contextReferenceResolver: input.adapter.host === "cli" ? input.contextReferenceResolver : void 0,
@@ -20925,6 +21351,24 @@ async function runLocalAgentTurn(input) {
20925
21351
  historyCount: history.length,
20926
21352
  capToolMessage
20927
21353
  });
21354
+ let prepareDirectWorkMemorySource = !input.userMessages?.length ? input.prepareDirectWorkMemorySource : void 0;
21355
+ const directUserMessage = prepareDirectWorkMemorySource ? transcript.persisted(sanitizedPersistedInput, input.persistedInputReference)[0] : void 0;
21356
+ let directWorkSource;
21357
+ const getDirectWorkSource = async () => {
21358
+ const prepare = prepareDirectWorkMemorySource;
21359
+ if (!prepare || directUserMessage?.role !== "user") return void 0;
21360
+ const attempt = directWorkSource ??= (async () => {
21361
+ try {
21362
+ const id2 = await prepare(directUserMessage);
21363
+ return id2 && id2 === directUserMessage.id ? id2 : void 0;
21364
+ } catch {
21365
+ return void 0;
21366
+ }
21367
+ })();
21368
+ const id = await attempt;
21369
+ if (!id && directWorkSource === attempt) directWorkSource = void 0;
21370
+ return id;
21371
+ };
20928
21372
  const userInputText = extractUserInputText(input.input);
20929
21373
  let toolCallCount = 0;
20930
21374
  let requestCalibrationRatio = 1;
@@ -20947,6 +21391,12 @@ async function runLocalAgentTurn(input) {
20947
21391
  let skipFinalAppend = false;
20948
21392
  let partialContent = "";
20949
21393
  const progressGuard = createLocalLoopProgressGuard(input.progressGuardConfig);
21394
+ const softBudgetAdvisor = createSubtaskSoftBudgetAdvisor({
21395
+ softBudget: input.softBudget,
21396
+ isSubtask: input.isSubtask,
21397
+ runKind: input.runKind,
21398
+ ...input.softBudgetEnv ? { env: input.softBudgetEnv } : {}
21399
+ });
20950
21400
  let pendingInjectionCommits = [];
20951
21401
  let inFlightTransactions = [];
20952
21402
  let rollbackInjectionCommits = async () => {
@@ -21068,7 +21518,7 @@ async function runLocalAgentTurn(input) {
21068
21518
  });
21069
21519
  imageDowngradeEmitted = true;
21070
21520
  }
21071
- const requestMessages = projectRequest(transcript.working());
21521
+ let requestMessages = projectRequest(transcript.working());
21072
21522
  if (requestOverBudget(requestMessages)) {
21073
21523
  const budget = evaluateLocalRequestBudget({
21074
21524
  messages: requestMessages,
@@ -21089,7 +21539,7 @@ async function runLocalAgentTurn(input) {
21089
21539
  }));
21090
21540
  }
21091
21541
  budgetTrimPhase = contextPhase("budget-trim", requestMessages, { droppedCount: 0 });
21092
- const contextMetrics = {
21542
+ let contextMetrics = {
21093
21543
  ...preparedMessages.metrics,
21094
21544
  messageCount: requestMessages.length,
21095
21545
  contentChars: requestMessages.reduce(
@@ -21111,8 +21561,8 @@ async function runLocalAgentTurn(input) {
21111
21561
  input.onToolEvent || input.onObservationEvent || input.observationBoundary
21112
21562
  );
21113
21563
  let llmStreamActivity = 0;
21114
- const callStartedAt = Date.now();
21115
- const requestTelemetry = buildRequestTelemetry({
21564
+ let callStartedAt = Date.now();
21565
+ let requestTelemetry = buildRequestTelemetry({
21116
21566
  // 无 dialogId 的新对话用本 turn 唯一键,避免不同新对话共用一个槽误报漂移。
21117
21567
  dialogKey: input.continueDialogId || newDialogTelemetryKey,
21118
21568
  messages: requestMessages,
@@ -21129,6 +21579,17 @@ async function runLocalAgentTurn(input) {
21129
21579
  inFlightTransactions = pendingInjectionCommits.splice(0);
21130
21580
  try {
21131
21581
  for (const transaction of inFlightTransactions) await transaction.commit();
21582
+ input.runtimeContext = { ...input.runtimeContext };
21583
+ delete input.runtimeContext.userMessageId;
21584
+ prepareDirectWorkMemorySource = void 0;
21585
+ const admittedMessages = inFlightTransactions.flatMap((transaction) => transaction.messages);
21586
+ if (admittedMessages.length === 1 && admittedMessages[0]?.cliMessageId) {
21587
+ try {
21588
+ const id = await input.resolveInjectedUserMessageId?.(admittedMessages);
21589
+ if (id === admittedMessages[0].cliMessageId) input.runtimeContext.userMessageId = id;
21590
+ } catch {
21591
+ }
21592
+ }
21132
21593
  if (input.abortSignal?.aborted) throw buildAbortedError();
21133
21594
  } catch (error) {
21134
21595
  const toRollback = inFlightTransactions;
@@ -21141,83 +21602,148 @@ async function runLocalAgentTurn(input) {
21141
21602
  throw error;
21142
21603
  }
21143
21604
  }
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
- } },
21605
+ const tryOverflowRescueCompaction = async () => {
21606
+ const beforeTokens = estimateLocalRequestInput(requestMessages);
21607
+ const compacted = await compaction.prepareRequest((source) => {
21608
+ const projected = composeProviderMessages({
21609
+ prefix: transcript.working().slice(0, prefixCount),
21610
+ history: source,
21611
+ contextReferenceResolver: input.adapter.host === "cli" ? input.contextReferenceResolver : void 0
21612
+ });
21613
+ return requestOverBudget(projectRequest(projected.messages));
21614
+ }, false, availableHistoryTokens, true);
21615
+ if (!compacted) return false;
21616
+ const nextPrepared = prepareMessagesForProviderCall(transcript.working());
21617
+ const nextRequestMessages = projectRequest(transcript.working());
21618
+ const afterTokens = estimateLocalRequestInput(nextRequestMessages);
21619
+ if (afterTokens >= beforeTokens || requestOverBudget(nextRequestMessages)) return false;
21620
+ requestMessages = nextRequestMessages;
21621
+ contextMetrics = {
21622
+ ...nextPrepared.metrics,
21623
+ messageCount: requestMessages.length,
21624
+ contentChars: requestMessages.reduce(
21625
+ (total, message) => total + contentCharCount(message.content),
21626
+ 0
21627
+ ),
21628
+ stableContextChars: builtMessages.stableContextChars,
21629
+ dynamicContextChars: builtMessages.dynamicContextChars
21630
+ };
21631
+ callStartedAt = Date.now();
21632
+ requestTelemetry = buildRequestTelemetry({
21633
+ dialogKey: input.continueDialogId || newDialogTelemetryKey,
21152
21634
  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 } : {}
21635
+ provenance: {
21636
+ schemaVersion: 1,
21637
+ transport: provider.transport ?? "unknown",
21638
+ phases: [historyLoadedPhase, summaryProjectedPhase, budgetTrimPhase, contextPhase("final-request", requestMessages)],
21639
+ summary: selectedSummary
21191
21640
  },
21192
- timeoutMs: resolveLlmRequestTimeoutMs(input),
21193
- activityVersion: () => llmStreamActivity,
21194
- round,
21195
- input,
21196
- boundary: observationBoundary,
21197
- context: contextMetrics,
21198
- providerName: agentConfig.provider,
21199
- model: provider.model
21641
+ toolsHash: safeToolNamesHash(agentTools)
21200
21642
  });
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);
21643
+ resetToolImageDelivery(requestMessages.flatMap(toolImages));
21644
+ return true;
21645
+ };
21646
+ let overflowRescueAttempted = false;
21647
+ while (true) {
21648
+ llmStreamActivity = 0;
21649
+ partialContent = "";
21650
+ let providerInvoked = false;
21651
+ try {
21652
+ result4 = await runCompleteWithTimeout({
21653
+ provider: { complete: (messages2, options) => {
21654
+ providerInvoked = true;
21655
+ inFlightTransactions = [];
21656
+ return provider.complete(messages2, options);
21657
+ } },
21658
+ messages: requestMessages,
21659
+ options: {
21660
+ timeoutMs: resolveLlmRequestTimeoutMs(input),
21661
+ // 用户取消信号穿进 provider options:providerStreamRetry 据此在
21662
+ // 取消后跳过重试,provider 分支(如 antigravity/openai-compatible)
21663
+ // 也可把 fetch 绑定到同一信号,实现真正的传输层取消。
21664
+ ...input.abortSignal ? { signal: input.abortSignal } : {},
21665
+ // 计费归因:续聊轮次带上 dialogId,platform proxy 才能把 token 记录
21666
+ // 归到具体对话而不是 chat-proxy 兜底桶。新对话首轮 id 尚未分配。
21667
+ ...input.continueDialogId ? { dialogId: input.continueDialogId } : {},
21668
+ ...shouldStreamDeltas ? { onTextDelta: (chunk) => {
21669
+ llmStreamActivity += 1;
21670
+ partialContent += chunk;
21671
+ observationBoundary.emit({
21672
+ kind: "text-delta",
21673
+ chunk,
21674
+ round,
21675
+ atMs: Date.now()
21676
+ });
21677
+ } } : {},
21678
+ ...shouldStreamReasoning ? { onReasoningDelta: (chunk) => {
21679
+ llmStreamActivity += 1;
21680
+ observationBoundary.emit({
21681
+ kind: "reasoning-delta",
21682
+ chunk,
21683
+ round,
21684
+ atMs: Date.now()
21685
+ });
21686
+ } } : {},
21687
+ ...shouldPassToolEvents ? { onToolEvent: (event) => {
21688
+ llmStreamActivity += 1;
21689
+ observationBoundary.emit({
21690
+ kind: "tool-event",
21691
+ event,
21692
+ round,
21693
+ atMs: Date.now()
21694
+ });
21695
+ } } : {},
21696
+ ...shouldPassToolEvents ? { toolEventRound: round } : {}
21697
+ },
21698
+ timeoutMs: resolveLlmRequestTimeoutMs(input),
21699
+ activityVersion: () => llmStreamActivity,
21700
+ round,
21701
+ input,
21702
+ boundary: observationBoundary,
21703
+ context: contextMetrics,
21704
+ providerName: agentConfig.provider,
21705
+ model: provider.model
21706
+ });
21707
+ } catch (error) {
21708
+ if (!providerInvoked && inFlightTransactions.length > 0) {
21709
+ const toRollback = inFlightTransactions;
21710
+ inFlightTransactions = [];
21711
+ try {
21712
+ await rollbackInjectionCommits(toRollback);
21713
+ } catch (rbErr) {
21714
+ error = combineRollbackError(error, rbErr);
21715
+ }
21716
+ }
21717
+ if (providerInvoked) usageLedger.recordProviderCall({
21718
+ model: agentConfig.model,
21719
+ telemetry: {
21720
+ ...requestTelemetry,
21721
+ round,
21722
+ endTs: Date.now(),
21723
+ requestState: input.abortSignal?.aborted ? "cancelled" : "failed"
21724
+ }
21725
+ });
21726
+ if (providerInvoked && !overflowRescueAttempted && llmStreamActivity === 0 && !input.abortSignal?.aborted && isContextOverflowText(toErrorMessage(error))) {
21727
+ overflowRescueAttempted = true;
21728
+ if (await tryOverflowRescueCompaction()) {
21729
+ continue;
21730
+ }
21209
21731
  }
21732
+ throw error;
21210
21733
  }
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"
21734
+ if ((result4.error || result4.runtimeProviderFailure) && !overflowRescueAttempted && llmStreamActivity === 0 && !input.abortSignal?.aborted && isContextOverflowText(result4.runtimeProviderFailure?.message ?? result4.errorMessage ?? "")) {
21735
+ overflowRescueAttempted = true;
21736
+ usageLedger.recordProviderCall({
21737
+ usage: result4.usage,
21738
+ model: result4.model ?? agentConfig.model,
21739
+ provider: result4.provider,
21740
+ telemetry: { ...finalizeCallTelemetry(requestTelemetry, result4, round, callStartedAt), requestState: "failed" }
21741
+ });
21742
+ if (await tryOverflowRescueCompaction()) {
21743
+ continue;
21218
21744
  }
21219
- });
21220
- throw error;
21745
+ }
21746
+ break;
21221
21747
  }
21222
21748
  acceptToolImages.discard(requestMessages.flatMap(toolImages).filter((image) => toolImageDelivery(image) === "impossible"));
21223
21749
  acceptToolImages.commit(
@@ -21383,6 +21909,7 @@ ${reasoningTailLog}
21383
21909
  const { toolResult, toolExecMs } = await executeToolCall({
21384
21910
  input: executionInput,
21385
21911
  toolCall,
21912
+ ...prepareDirectWorkMemorySource ? { getDirectWorkSource } : {},
21386
21913
  round,
21387
21914
  boundary: observationBoundary,
21388
21915
  loopTiming,
@@ -21513,6 +22040,15 @@ ${reasoningTailLog}
21513
22040
  };
21514
22041
  break;
21515
22042
  }
22043
+ if (!input.abortSignal?.aborted) {
22044
+ const softBudgetAdvisory = softBudgetAdvisor.observeToolCalls(toolCallCount);
22045
+ if (softBudgetAdvisory) {
22046
+ transcript.push({
22047
+ role: "user",
22048
+ content: softBudgetAdvisory.message
22049
+ });
22050
+ }
22051
+ }
21516
22052
  loopTiming.mark("roundEnd", round);
21517
22053
  round += 1;
21518
22054
  }
@@ -22568,757 +23104,6 @@ async function resolveOpenAiCompatibleProviderConfig(args2) {
22568
23104
  };
22569
23105
  }
22570
23106
 
22571
- // packages/agent-runtime/macOsKeychainCredentialBroker.ts
22572
- import { spawn as spawn2 } from "node:child_process";
22573
- var MACOS_KEYCHAIN_SERVICE_PREFIX = "nolo.credentials.keys";
22574
- var MACOS_KEYCHAIN_ACCOUNT = "api-key";
22575
- var SECURITY_ITEM_NOT_FOUND_EXIT = 44;
22576
- var DEFAULT_SECURITY_BIN = "/usr/bin/security";
22577
- function safeCredentialRef(ref) {
22578
- try {
22579
- return assertCredentialRef(ref);
22580
- } catch {
22581
- throw new Error("invalid_ref");
22582
- }
22583
- }
22584
- function credentialRefToMacOsKeychainService(ref, servicePrefix = MACOS_KEYCHAIN_SERVICE_PREFIX) {
22585
- const safe = safeCredentialRef(ref);
22586
- const hex = Buffer.from(safe, "utf8").toString("hex");
22587
- if (!hex) {
22588
- throw new Error("invalid_ref");
22589
- }
22590
- return `${servicePrefix}.${hex}`;
22591
- }
22592
- function rethrowBrokerError(op, _error) {
22593
- throw new Error(`credential_broker_${op}_failed`);
22594
- }
22595
- function createDefaultSecurityRunner(securityBin = DEFAULT_SECURITY_BIN) {
22596
- return function defaultSecurityRunner(input) {
22597
- return new Promise((resolve6) => {
22598
- let settled = false;
22599
- const finish = (result4) => {
22600
- if (settled) return;
22601
- settled = true;
22602
- resolve6(result4);
22603
- };
22604
- let child;
22605
- try {
22606
- child = spawn2(securityBin, input.args, {
22607
- stdio: ["pipe", "pipe", "pipe"]
22608
- });
22609
- } catch {
22610
- finish({ exitCode: -1, stdout: "", stderr: "" });
22611
- return;
22612
- }
22613
- let stdout = "";
22614
- let stderr = "";
22615
- child.stdout?.setEncoding("utf8");
22616
- child.stderr?.setEncoding("utf8");
22617
- child.stdout?.on("data", (chunk) => {
22618
- stdout += chunk;
22619
- });
22620
- child.stderr?.on("data", (chunk) => {
22621
- stderr += chunk;
22622
- });
22623
- child.on("error", () => {
22624
- finish({ exitCode: -1, stdout: "", stderr: "" });
22625
- });
22626
- child.on("close", (code) => {
22627
- finish({
22628
- exitCode: typeof code === "number" ? code : -1,
22629
- stdout,
22630
- stderr
22631
- });
22632
- });
22633
- if (input.stdin !== void 0) {
22634
- child.stdin?.write(input.stdin);
22635
- }
22636
- child.stdin?.end();
22637
- });
22638
- };
22639
- }
22640
- function createMacOsKeychainCredentialBroker(options = {}) {
22641
- const runner = options.runner ?? createDefaultSecurityRunner(options.securityBin);
22642
- const servicePrefix = options.servicePrefix ?? MACOS_KEYCHAIN_SERVICE_PREFIX;
22643
- const account = options.account ?? MACOS_KEYCHAIN_ACCOUNT;
22644
- const serviceFor = (ref) => credentialRefToMacOsKeychainService(ref, servicePrefix);
22645
- return {
22646
- async get(ref) {
22647
- const safeRef = safeCredentialRef(ref);
22648
- const service4 = serviceFor(safeRef);
22649
- let result4;
22650
- try {
22651
- result4 = await runner({
22652
- args: [
22653
- "find-generic-password",
22654
- "-a",
22655
- account,
22656
- "-s",
22657
- service4,
22658
- "-w"
22659
- ]
22660
- });
22661
- } catch (error) {
22662
- rethrowBrokerError("get", error);
22663
- }
22664
- if (result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22665
- return null;
22666
- }
22667
- if (result4.exitCode !== 0) {
22668
- rethrowBrokerError("get");
22669
- }
22670
- const secret = result4.stdout.replace(/\n$/, "");
22671
- return secret.length > 0 ? secret : null;
22672
- },
22673
- async put(ref, secret) {
22674
- const safeRef = safeCredentialRef(ref);
22675
- const value = asTrimmedString(secret);
22676
- if (!value) {
22677
- throw new Error("Cannot store an empty credential secret.");
22678
- }
22679
- const service4 = serviceFor(safeRef);
22680
- const stdin = `${value}
22681
- ${value}
22682
- `;
22683
- let result4;
22684
- try {
22685
- result4 = await runner({
22686
- args: [
22687
- "add-generic-password",
22688
- "-a",
22689
- account,
22690
- "-s",
22691
- service4,
22692
- "-U",
22693
- "-w"
22694
- ],
22695
- stdin
22696
- });
22697
- } catch (error) {
22698
- rethrowBrokerError("put", error);
22699
- }
22700
- if (result4.exitCode !== 0) {
22701
- rethrowBrokerError("put");
22702
- }
22703
- },
22704
- async delete(ref) {
22705
- const safeRef = safeCredentialRef(ref);
22706
- const service4 = serviceFor(safeRef);
22707
- let result4;
22708
- try {
22709
- result4 = await runner({
22710
- args: [
22711
- "delete-generic-password",
22712
- "-a",
22713
- account,
22714
- "-s",
22715
- service4
22716
- ]
22717
- });
22718
- } catch (error) {
22719
- rethrowBrokerError("delete", error);
22720
- }
22721
- if (result4.exitCode === 0 || result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22722
- return;
22723
- }
22724
- rethrowBrokerError("delete");
22725
- },
22726
- async has(ref) {
22727
- const safeRef = safeCredentialRef(ref);
22728
- const service4 = serviceFor(safeRef);
22729
- let result4;
22730
- try {
22731
- result4 = await runner({
22732
- args: [
22733
- "find-generic-password",
22734
- "-a",
22735
- account,
22736
- "-s",
22737
- service4
22738
- ]
22739
- });
22740
- } catch (error) {
22741
- rethrowBrokerError("has", error);
22742
- }
22743
- if (result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22744
- return false;
22745
- }
22746
- if (result4.exitCode !== 0) {
22747
- rethrowBrokerError("has");
22748
- }
22749
- return true;
22750
- }
22751
- };
22752
- }
22753
-
22754
- // packages/agent-runtime/windowsCredentialManagerBroker.ts
22755
- import { spawn as spawn3 } from "node:child_process";
22756
- var WINDOWS_CREDENTIAL_TARGET_PREFIX = "nolo.credentials.keys";
22757
- var WIN_ERROR_NOT_FOUND = 1168;
22758
- var WINDOWS_CREDENTIAL_MANAGER_SCRIPT = `
22759
- $ErrorActionPreference = 'Stop'
22760
- try {
22761
- $raw = [Console]::In.ReadToEnd()
22762
- if ([string]::IsNullOrWhiteSpace($raw)) { exit 1 }
22763
- $req = $raw | ConvertFrom-Json
22764
- $op = [string]$req.op
22765
- $target = [string]$req.target
22766
- if ([string]::IsNullOrWhiteSpace($op) -or [string]::IsNullOrWhiteSpace($target)) { exit 1 }
22767
-
22768
- Add-Type @"
22769
- using System;
22770
- using System.Runtime.InteropServices;
22771
- using System.Text;
22772
-
22773
- public class NoloCredNative {
22774
- public const int CRED_TYPE_GENERIC = 1;
22775
- public const int CRED_PERSIST_LOCAL_MACHINE = 2;
22776
- public const int ERROR_NOT_FOUND = 1168;
22777
-
22778
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
22779
- public struct CREDENTIAL {
22780
- public int Flags;
22781
- public int Type;
22782
- public string TargetName;
22783
- public string Comment;
22784
- public long LastWritten;
22785
- public int CredentialBlobSize;
22786
- public IntPtr CredentialBlob;
22787
- public int Persist;
22788
- public int AttributeCount;
22789
- public IntPtr Attributes;
22790
- public string TargetAlias;
22791
- public string UserName;
22792
- }
22793
-
22794
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22795
- public static extern bool CredWriteW(ref CREDENTIAL userCredential, uint flags);
22796
-
22797
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22798
- public static extern bool CredReadW(string target, int type, int reservedFlag, out IntPtr credentialPtr);
22799
-
22800
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22801
- public static extern bool CredDeleteW(string target, int type, int flags);
22802
-
22803
- [DllImport("advapi32.dll", SetLastError = true)]
22804
- public static extern void CredFree(IntPtr buffer);
22805
- }
22806
- "@
22807
-
22808
- if ($op -eq 'get') {
22809
- $ptr = [IntPtr]::Zero
22810
- $ok = [NoloCredNative]::CredReadW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0, [ref]$ptr)
22811
- if (-not $ok) {
22812
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22813
- }
22814
- try {
22815
- $cred = [Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [type][NoloCredNative+CREDENTIAL])
22816
- if ($cred.CredentialBlobSize -le 0 -or $cred.CredentialBlob -eq [IntPtr]::Zero) {
22817
- $payload = @{ secret = '' } | ConvertTo-Json -Compress
22818
- [Console]::Out.Write($payload)
22819
- exit 0
22820
- }
22821
- $bytes = New-Object byte[] $cred.CredentialBlobSize
22822
- [Runtime.InteropServices.Marshal]::Copy($cred.CredentialBlob, $bytes, 0, $cred.CredentialBlobSize)
22823
- $secret = [Text.Encoding]::UTF8.GetString($bytes)
22824
- $payload = @{ secret = $secret } | ConvertTo-Json -Compress
22825
- [Console]::Out.Write($payload)
22826
- exit 0
22827
- } finally {
22828
- [NoloCredNative]::CredFree($ptr)
22829
- }
22830
- }
22831
-
22832
- if ($op -eq 'has') {
22833
- $ptr = [IntPtr]::Zero
22834
- $ok = [NoloCredNative]::CredReadW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0, [ref]$ptr)
22835
- if (-not $ok) {
22836
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22837
- }
22838
- [NoloCredNative]::CredFree($ptr)
22839
- exit 0
22840
- }
22841
-
22842
- if ($op -eq 'put') {
22843
- $secret = [string]$req.secret
22844
- if ([string]::IsNullOrEmpty($secret)) { exit 1 }
22845
- $blob = [Text.Encoding]::UTF8.GetBytes($secret)
22846
- $cred = New-Object NoloCredNative+CREDENTIAL
22847
- $cred.Type = [NoloCredNative]::CRED_TYPE_GENERIC
22848
- $cred.TargetName = $target
22849
- $cred.UserName = 'api-key'
22850
- $cred.Persist = [NoloCredNative]::CRED_PERSIST_LOCAL_MACHINE
22851
- $cred.CredentialBlobSize = $blob.Length
22852
- $cred.CredentialBlob = [Runtime.InteropServices.Marshal]::AllocHGlobal($blob.Length)
22853
- try {
22854
- if ($blob.Length -gt 0) {
22855
- [Runtime.InteropServices.Marshal]::Copy($blob, 0, $cred.CredentialBlob, $blob.Length)
22856
- }
22857
- $ok = [NoloCredNative]::CredWriteW([ref]$cred, 0)
22858
- if (-not $ok) {
22859
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22860
- }
22861
- exit 0
22862
- } finally {
22863
- [Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
22864
- }
22865
- }
22866
-
22867
- if ($op -eq 'delete') {
22868
- $ok = [NoloCredNative]::CredDeleteW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0)
22869
- if (-not $ok) {
22870
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22871
- }
22872
- exit 0
22873
- }
22874
-
22875
- exit 1
22876
- } catch {
22877
- exit 1
22878
- }
22879
- `.trim();
22880
- function safeCredentialRef2(ref) {
22881
- try {
22882
- return assertCredentialRef(ref);
22883
- } catch {
22884
- throw new Error("invalid_ref");
22885
- }
22886
- }
22887
- function credentialRefToWindowsCredentialTarget(ref, targetPrefix = WINDOWS_CREDENTIAL_TARGET_PREFIX) {
22888
- const safe = safeCredentialRef2(ref);
22889
- const hex = Buffer.from(safe, "utf8").toString("hex");
22890
- if (!hex) {
22891
- throw new Error("invalid_ref");
22892
- }
22893
- return `${targetPrefix}.${hex}`;
22894
- }
22895
- function rethrowBrokerError2(op, _error) {
22896
- throw new Error(`credential_broker_${op}_failed`);
22897
- }
22898
- function buildWindowsCredentialPowerShellArgs(script = WINDOWS_CREDENTIAL_MANAGER_SCRIPT) {
22899
- const encoded = Buffer.from(script, "utf16le").toString("base64");
22900
- return [
22901
- "-NoProfile",
22902
- "-NonInteractive",
22903
- "-ExecutionPolicy",
22904
- "Bypass",
22905
- "-EncodedCommand",
22906
- encoded
22907
- ];
22908
- }
22909
- function requestStdin(payload) {
22910
- return JSON.stringify(payload);
22911
- }
22912
- function parseGetSecretFromStdout(stdout) {
22913
- const trimmed = asTrimmedString(stdout);
22914
- if (!trimmed) {
22915
- rethrowBrokerError2("get");
22916
- }
22917
- let parsed;
22918
- try {
22919
- parsed = JSON.parse(trimmed);
22920
- } catch {
22921
- rethrowBrokerError2("get");
22922
- }
22923
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || typeof parsed.secret !== "string") {
22924
- rethrowBrokerError2("get");
22925
- }
22926
- return parsed.secret;
22927
- }
22928
- function spawnShell(bin, args2, stdin) {
22929
- return new Promise((resolve6) => {
22930
- let settled = false;
22931
- const finish = (result4) => {
22932
- if (settled) return;
22933
- settled = true;
22934
- resolve6(result4);
22935
- };
22936
- let child;
22937
- try {
22938
- child = spawn3(bin, args2, {
22939
- stdio: ["pipe", "pipe", "pipe"],
22940
- windowsHide: true
22941
- });
22942
- } catch {
22943
- finish({ exitCode: -1, stdout: "", stderr: "" });
22944
- return;
22945
- }
22946
- let stdout = "";
22947
- let stderr = "";
22948
- child.stdout?.setEncoding("utf8");
22949
- child.stderr?.setEncoding("utf8");
22950
- child.stdout?.on("data", (chunk) => {
22951
- stdout += chunk;
22952
- });
22953
- child.stderr?.on("data", (chunk) => {
22954
- stderr += chunk;
22955
- });
22956
- child.on("error", () => {
22957
- finish({ exitCode: -1, stdout: "", stderr: "" });
22958
- });
22959
- child.on("close", (code) => {
22960
- finish({
22961
- exitCode: typeof code === "number" ? code : -1,
22962
- stdout,
22963
- stderr
22964
- });
22965
- });
22966
- if (stdin !== void 0) {
22967
- child.stdin?.write(stdin);
22968
- }
22969
- child.stdin?.end();
22970
- });
22971
- }
22972
- function createDefaultWindowsCredentialRunner(shellBin) {
22973
- let resolvedBin = shellBin ?? null;
22974
- return async function defaultWindowsCredentialRunner(input) {
22975
- if (resolvedBin) {
22976
- return spawnShell(resolvedBin, input.args, input.stdin);
22977
- }
22978
- const first = await spawnShell("powershell.exe", input.args, input.stdin);
22979
- if (first.exitCode !== -1) {
22980
- resolvedBin = "powershell.exe";
22981
- return first;
22982
- }
22983
- const second = await spawnShell("pwsh", input.args, input.stdin);
22984
- if (second.exitCode !== -1) {
22985
- resolvedBin = "pwsh";
22986
- }
22987
- return second;
22988
- };
22989
- }
22990
- function createWindowsCredentialManagerBroker(options = {}) {
22991
- const runner = options.runner ?? createDefaultWindowsCredentialRunner(options.shellBin);
22992
- const targetPrefix = options.targetPrefix ?? WINDOWS_CREDENTIAL_TARGET_PREFIX;
22993
- const targetFor = (ref) => credentialRefToWindowsCredentialTarget(ref, targetPrefix);
22994
- const staticArgs = buildWindowsCredentialPowerShellArgs();
22995
- return {
22996
- async get(ref) {
22997
- const safeRef = safeCredentialRef2(ref);
22998
- const target = targetFor(safeRef);
22999
- let result4;
23000
- try {
23001
- result4 = await runner({
23002
- args: staticArgs,
23003
- stdin: requestStdin({ op: "get", target })
23004
- });
23005
- } catch (error) {
23006
- rethrowBrokerError2("get", error);
23007
- }
23008
- if (result4.exitCode === WIN_ERROR_NOT_FOUND) {
23009
- return null;
23010
- }
23011
- if (result4.exitCode !== 0) {
23012
- rethrowBrokerError2("get");
23013
- }
23014
- const secret = parseGetSecretFromStdout(result4.stdout);
23015
- return secret.length > 0 ? secret : null;
23016
- },
23017
- async put(ref, secret) {
23018
- const safeRef = safeCredentialRef2(ref);
23019
- const value = asTrimmedString(secret);
23020
- if (!value) {
23021
- throw new Error("Cannot store an empty credential secret.");
23022
- }
23023
- const target = targetFor(safeRef);
23024
- let result4;
23025
- try {
23026
- result4 = await runner({
23027
- args: staticArgs,
23028
- stdin: requestStdin({ op: "put", target, secret: value })
23029
- });
23030
- } catch (error) {
23031
- rethrowBrokerError2("put", error);
23032
- }
23033
- if (result4.exitCode !== 0) {
23034
- rethrowBrokerError2("put");
23035
- }
23036
- },
23037
- async delete(ref) {
23038
- const safeRef = safeCredentialRef2(ref);
23039
- const target = targetFor(safeRef);
23040
- let result4;
23041
- try {
23042
- result4 = await runner({
23043
- args: staticArgs,
23044
- stdin: requestStdin({ op: "delete", target })
23045
- });
23046
- } catch (error) {
23047
- rethrowBrokerError2("delete", error);
23048
- }
23049
- if (result4.exitCode === 0 || result4.exitCode === WIN_ERROR_NOT_FOUND) {
23050
- return;
23051
- }
23052
- rethrowBrokerError2("delete");
23053
- },
23054
- async has(ref) {
23055
- const safeRef = safeCredentialRef2(ref);
23056
- const target = targetFor(safeRef);
23057
- let result4;
23058
- try {
23059
- result4 = await runner({
23060
- args: staticArgs,
23061
- stdin: requestStdin({ op: "has", target })
23062
- });
23063
- } catch (error) {
23064
- rethrowBrokerError2("has", error);
23065
- }
23066
- if (result4.exitCode === WIN_ERROR_NOT_FOUND) {
23067
- return false;
23068
- }
23069
- if (result4.exitCode !== 0) {
23070
- rethrowBrokerError2("has");
23071
- }
23072
- return true;
23073
- }
23074
- };
23075
- }
23076
-
23077
- // packages/agent-runtime/linuxSecretServiceCredentialBroker.ts
23078
- import { spawn as spawn4 } from "node:child_process";
23079
- var LINUX_SECRET_SERVICE_ATTRIBUTE = "nolo-credential";
23080
- var SECRET_TOOL_NO_MATCH_EXIT = 1;
23081
- var DEFAULT_SECRET_TOOL_BIN = "secret-tool";
23082
- function safeCredentialRef3(ref) {
23083
- try {
23084
- return assertCredentialRef(ref);
23085
- } catch {
23086
- throw new Error("invalid_ref");
23087
- }
23088
- }
23089
- function brokerFailure(op) {
23090
- throw new Error(`credential_broker_${op}_failed`);
23091
- }
23092
- function createDefaultSecretToolRunner(secretToolBin = DEFAULT_SECRET_TOOL_BIN) {
23093
- return (input) => new Promise((resolve6) => {
23094
- let stdout = "";
23095
- let stderr = "";
23096
- let settled = false;
23097
- const finish = (result4) => {
23098
- if (settled) return;
23099
- settled = true;
23100
- resolve6(result4);
23101
- };
23102
- let child;
23103
- try {
23104
- child = spawn4(secretToolBin, input.args, {
23105
- stdio: ["pipe", "pipe", "pipe"]
23106
- });
23107
- } catch {
23108
- finish({ exitCode: -1, stdout: "", stderr: "" });
23109
- return;
23110
- }
23111
- child.stdout?.on("data", (chunk) => {
23112
- stdout += chunk;
23113
- });
23114
- child.stderr?.on("data", (chunk) => {
23115
- stderr += chunk;
23116
- });
23117
- child.on("error", () => {
23118
- finish({ exitCode: -1, stdout: "", stderr: "" });
23119
- });
23120
- child.on("close", (code) => {
23121
- finish({
23122
- exitCode: typeof code === "number" ? code : -1,
23123
- stdout,
23124
- stderr
23125
- });
23126
- });
23127
- if (input.stdin !== void 0) {
23128
- child.stdin?.write(input.stdin);
23129
- }
23130
- child.stdin?.end();
23131
- });
23132
- }
23133
- function createLinuxSecretServiceCredentialBroker(options = {}) {
23134
- const runner = options.runner ?? createDefaultSecretToolRunner(options.secretToolBin);
23135
- const attribute = options.attribute ?? LINUX_SECRET_SERVICE_ATTRIBUTE;
23136
- const attrArgs = (ref) => [attribute, ref];
23137
- const lookup3 = async (ref) => {
23138
- try {
23139
- return await runner({ args: ["lookup", ...attrArgs(ref)] });
23140
- } catch {
23141
- brokerFailure("get");
23142
- }
23143
- };
23144
- return {
23145
- async get(ref) {
23146
- const safeRef = safeCredentialRef3(ref);
23147
- const result4 = await lookup3(safeRef);
23148
- if (result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) return null;
23149
- if (result4.exitCode !== 0) brokerFailure("get");
23150
- const secret = result4.stdout.replace(/\n$/, "");
23151
- return secret.length > 0 ? secret : null;
23152
- },
23153
- async put(ref, secret) {
23154
- const safeRef = safeCredentialRef3(ref);
23155
- const value = asTrimmedString(secret);
23156
- if (!value) {
23157
- throw new Error("Cannot store an empty credential secret.");
23158
- }
23159
- const args2 = [
23160
- "store",
23161
- `--label=nolo-credential:${safeRef}`,
23162
- ...attrArgs(safeRef)
23163
- ];
23164
- if (value.includes("\n") || args2.some((arg) => arg.includes(value))) {
23165
- brokerFailure("put");
23166
- }
23167
- let result4;
23168
- try {
23169
- result4 = await runner({ args: args2, stdin: value });
23170
- } catch {
23171
- brokerFailure("put");
23172
- }
23173
- if (result4.exitCode !== 0) brokerFailure("put");
23174
- },
23175
- async delete(ref) {
23176
- const safeRef = safeCredentialRef3(ref);
23177
- let result4;
23178
- try {
23179
- result4 = await runner({ args: ["clear", ...attrArgs(safeRef)] });
23180
- } catch {
23181
- brokerFailure("delete");
23182
- }
23183
- if (result4.exitCode === 0 || result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) {
23184
- return;
23185
- }
23186
- brokerFailure("delete");
23187
- },
23188
- async has(ref) {
23189
- const safeRef = safeCredentialRef3(ref);
23190
- const result4 = await lookup3(safeRef);
23191
- if (result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) return false;
23192
- if (result4.exitCode !== 0) brokerFailure("has");
23193
- return true;
23194
- }
23195
- };
23196
- }
23197
-
23198
- // packages/agent-runtime/desktopHostCredentialBroker.ts
23199
- function createClosedCredentialBroker(code = "credential_store_unavailable") {
23200
- const fail9 = () => {
23201
- throw new Error(code);
23202
- };
23203
- return {
23204
- get: fail9,
23205
- put: fail9,
23206
- delete: fail9,
23207
- has: () => false
23208
- };
23209
- }
23210
- function createHostCredentialBrokerChain(args2) {
23211
- const { strict, session, legacy, notifySessionFallback, notifyLegacyHit } = args2;
23212
- const legacyNoticed = /* @__PURE__ */ new Set();
23213
- let sessionNotified = false;
23214
- const noticeSession = () => {
23215
- if (sessionNotified || !notifySessionFallback) return;
23216
- sessionNotified = true;
23217
- try {
23218
- notifySessionFallback();
23219
- } catch {
23220
- }
23221
- };
23222
- return {
23223
- async get(ref) {
23224
- try {
23225
- const strictValue = await strict.get(ref);
23226
- if (strictValue !== null && strictValue !== void 0) return strictValue;
23227
- } catch {
23228
- }
23229
- const sessionValue = await session.get(ref);
23230
- if (sessionValue !== null && sessionValue !== void 0) return sessionValue;
23231
- if (!legacy) return null;
23232
- const legacyValue = await legacy.get(ref);
23233
- if (legacyValue !== null && legacyValue !== void 0) {
23234
- if (notifyLegacyHit && !legacyNoticed.has(ref)) {
23235
- legacyNoticed.add(ref);
23236
- try {
23237
- notifyLegacyHit(ref);
23238
- } catch {
23239
- }
23240
- }
23241
- return legacyValue;
23242
- }
23243
- return null;
23244
- },
23245
- async put(ref, secret) {
23246
- try {
23247
- await strict.put(ref, secret);
23248
- if (await strict.has(ref)) return;
23249
- } catch {
23250
- }
23251
- await session.put(ref, secret);
23252
- noticeSession();
23253
- },
23254
- async delete(ref) {
23255
- try {
23256
- await strict.delete(ref);
23257
- } catch {
23258
- }
23259
- try {
23260
- await session.delete(ref);
23261
- } catch {
23262
- }
23263
- if (legacy) await legacy.delete(ref);
23264
- },
23265
- async has(ref) {
23266
- try {
23267
- if (await strict.has(ref)) return true;
23268
- } catch {
23269
- }
23270
- if (await session.has(ref)) return true;
23271
- return legacy ? await legacy.has(ref) : false;
23272
- }
23273
- };
23274
- }
23275
- function createStrictHostCredentialBroker(options = {}) {
23276
- const platform = options.platform ?? process.platform;
23277
- const env = options.env ?? process.env;
23278
- const override = String(env.NOLO_DESKTOP_CREDENTIAL_STORE ?? "").trim().toLowerCase();
23279
- if (override === "file") {
23280
- return createClosedCredentialBroker("credential_store_file_not_allowed");
23281
- }
23282
- if (platform === "darwin" || override === "keychain") {
23283
- return options.keychainBroker ?? (options.createKeychainBroker ?? (() => createMacOsKeychainCredentialBroker()))();
23284
- }
23285
- if (platform === "win32" || override === "credman") {
23286
- return options.windowsCredentialBroker ?? (options.createWindowsCredentialBroker ?? (() => createWindowsCredentialManagerBroker()))();
23287
- }
23288
- if (platform === "linux" || override === "secret-service") {
23289
- return options.linuxSecretServiceBroker ?? (options.createLinuxSecretServiceBroker ?? (() => createLinuxSecretServiceCredentialBroker()))();
23290
- }
23291
- return createClosedCredentialBroker("credential_store_unsupported");
23292
- }
23293
-
23294
- // packages/agent-runtime/dialogMessageRecord.ts
23295
- function dialogMessageRecordToAgentRuntimeMessage(record2) {
23296
- if (!record2 || typeof record2 !== "object") return null;
23297
- if (record2.role !== "user" && record2.role !== "assistant" && record2.role !== "tool") return null;
23298
- return {
23299
- ...typeof record2.id === "string" ? { id: record2.id } : {},
23300
- role: record2.role,
23301
- ...Number.isFinite(record2.metadata?.cliHistoryOrder) ? { cliHistoryOrder: record2.metadata.cliHistoryOrder } : {},
23302
- content: record2.content ?? "",
23303
- ...record2.contextReference !== void 0 ? { context_reference: record2.contextReference } : {},
23304
- ...typeof record2.reasoning_content === "string" ? { reasoning_content: record2.reasoning_content } : {},
23305
- ...typeof record2.toolCallId === "string" ? { tool_call_id: record2.toolCallId } : {},
23306
- ...Array.isArray(record2.tool_calls) ? { tool_calls: record2.tool_calls } : {},
23307
- ...record2.toolPayload !== void 0 ? { toolPayload: record2.toolPayload } : {},
23308
- ...typeof record2.toolName === "string" ? { toolName: record2.toolName } : {},
23309
- // 写侧(dialogWritePlan)把 tool_result_metadata 以 `metadata` 字段落库;
23310
- // 回读必须还原,否则跨 turn 投影丢失 metadata 后缀,同一 tool 消息的字节
23311
- // 在 turn 边界漂移 → provider 前缀缓存断裂(stable projection 契约,
23312
- // 见 docs/plans/2026-09-05-tool-output-cache-stability.md)。
23313
- ...record2.metadata && typeof record2.metadata === "object" ? { tool_result_metadata: record2.metadata } : {},
23314
- ...(() => {
23315
- const raw = record2.createdAt;
23316
- const ms = typeof raw === "number" ? raw : typeof raw === "string" ? Date.parse(raw) : NaN;
23317
- return Number.isFinite(ms) ? { createdAt: ms } : {};
23318
- })()
23319
- };
23320
- }
23321
-
23322
23107
  // packages/agent-runtime/dialogWritePlan.ts
23323
23108
  function extractLastUserText(messages) {
23324
23109
  const lastUser = [...messages].reverse().find((message) => message.role === "user");
@@ -23744,11 +23529,11 @@ var E_ALREADY_LOCKED = new Error("mutex already locked");
23744
23529
  var E_CANCELED = new Error("request for lock canceled");
23745
23530
  var __awaiter$2 = function(thisArg, _arguments, P, generator) {
23746
23531
  function adopt(value) {
23747
- return value instanceof P ? value : new P(function(resolve6) {
23748
- resolve6(value);
23532
+ return value instanceof P ? value : new P(function(resolve7) {
23533
+ resolve7(value);
23749
23534
  });
23750
23535
  }
23751
- return new (P || (P = Promise))(function(resolve6, reject) {
23536
+ return new (P || (P = Promise))(function(resolve7, reject) {
23752
23537
  function fulfilled(value) {
23753
23538
  try {
23754
23539
  step(generator.next(value));
@@ -23764,7 +23549,7 @@ var __awaiter$2 = function(thisArg, _arguments, P, generator) {
23764
23549
  }
23765
23550
  }
23766
23551
  function step(result4) {
23767
- result4.done ? resolve6(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23552
+ result4.done ? resolve7(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23768
23553
  }
23769
23554
  step((generator = generator.apply(thisArg, _arguments || [])).next());
23770
23555
  });
@@ -23779,8 +23564,8 @@ var Semaphore = class {
23779
23564
  acquire(weight = 1, priority = 0) {
23780
23565
  if (weight <= 0)
23781
23566
  throw new Error(`invalid weight ${weight}: must be positive`);
23782
- return new Promise((resolve6, reject) => {
23783
- const task = { resolve: resolve6, reject, weight, priority };
23567
+ return new Promise((resolve7, reject) => {
23568
+ const task = { resolve: resolve7, reject, weight, priority };
23784
23569
  const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
23785
23570
  if (i === -1 && weight <= this._value) {
23786
23571
  this._dispatchItem(task);
@@ -23805,10 +23590,10 @@ var Semaphore = class {
23805
23590
  if (this._couldLockImmediately(weight, priority)) {
23806
23591
  return Promise.resolve();
23807
23592
  } else {
23808
- return new Promise((resolve6) => {
23593
+ return new Promise((resolve7) => {
23809
23594
  if (!this._weightedWaiters[weight - 1])
23810
23595
  this._weightedWaiters[weight - 1] = [];
23811
- insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve6, priority });
23596
+ insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve7, priority });
23812
23597
  });
23813
23598
  }
23814
23599
  }
@@ -23891,11 +23676,11 @@ function findIndexFromEnd(a, predicate) {
23891
23676
  }
23892
23677
  var __awaiter$1 = function(thisArg, _arguments, P, generator) {
23893
23678
  function adopt(value) {
23894
- return value instanceof P ? value : new P(function(resolve6) {
23895
- resolve6(value);
23679
+ return value instanceof P ? value : new P(function(resolve7) {
23680
+ resolve7(value);
23896
23681
  });
23897
23682
  }
23898
- return new (P || (P = Promise))(function(resolve6, reject) {
23683
+ return new (P || (P = Promise))(function(resolve7, reject) {
23899
23684
  function fulfilled(value) {
23900
23685
  try {
23901
23686
  step(generator.next(value));
@@ -23911,7 +23696,7 @@ var __awaiter$1 = function(thisArg, _arguments, P, generator) {
23911
23696
  }
23912
23697
  }
23913
23698
  function step(result4) {
23914
- result4.done ? resolve6(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23699
+ result4.done ? resolve7(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23915
23700
  }
23916
23701
  step((generator = generator.apply(thisArg, _arguments || [])).next());
23917
23702
  });
@@ -24075,7 +23860,7 @@ async function saveCliPendingUserMessages(args2) {
24075
23860
  if (ops.length) await args2.store.batch(ops);
24076
23861
  }
24077
23862
  async function readCliPendingUserMessages(store, dialogId) {
24078
- const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-M3F76NIP.js");
23863
+ const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-MCQVRWBR.js");
24079
23864
  const rows = await readDialogMessageRecords({ store, dialogId });
24080
23865
  const uncertain = rows.filter(({ record: record2 }) => record2.metadata?.cliBatchPhase === "requested" && !record2.metadata?.cliBatchResolution);
24081
23866
  const recovery = uncertain.length ? {
@@ -24174,15 +23959,15 @@ async function readNoloProcessStream(readable) {
24174
23959
  async function runNoloWorkspaceCliTool(call, args2) {
24175
23960
  const cliArgs = buildNoloWorkspaceCommandArgs(call);
24176
23961
  const bunSpawn = globalThis.Bun?.spawn;
24177
- const spawn5 = args2.spawn ?? (typeof bunSpawn === "function" ? bunSpawn : nodeSpawnFallback);
23962
+ const spawn2 = args2.spawn ?? (typeof bunSpawn === "function" ? bunSpawn : nodeSpawnFallback);
24178
23963
  const execPath = args2.processExecPath ?? process.execPath;
24179
23964
  const entrypoint = args2.cliEntrypoint;
24180
23965
  const cmd = entrypoint && entrypoint !== execPath ? [execPath, entrypoint, ...cliArgs] : [execPath, ...cliArgs];
24181
- const proc = spawn5({
23966
+ const proc = spawn2({
24182
23967
  cmd,
24183
23968
  stdout: "pipe",
24184
23969
  stderr: "pipe",
24185
- env: call.name === "listAgents" ? { ...process.env, ...args2.env, NOLO_PLANNING_CALLER: JSON.stringify(args2.planningCaller ?? {}) } : args2.env
23970
+ env: workspaceChildEnv(call.name === "listAgents" ? { ...process.env, ...args2.env, NOLO_PLANNING_CALLER: JSON.stringify(args2.planningCaller ?? {}) } : args2.env)
24186
23971
  });
24187
23972
  const [stdout, stderr, exitCode] = await Promise.all([
24188
23973
  readNoloProcessStream(proc.stdout),
@@ -24204,7 +23989,15 @@ async function runNoloWorkspaceCliTool(call, args2) {
24204
23989
  }
24205
23990
  };
24206
23991
  }
24207
- async function readDialogInProcess(call, store, env) {
23992
+ function isLocalExclusiveDialog(dialogId, meta, localChildDialogIds) {
23993
+ if (localChildDialogIds?.has(dialogId)) return true;
23994
+ const record2 = meta;
23995
+ if (!record2 || typeof record2 !== "object") return false;
23996
+ if (record2.triggerType === "cli-agent-run") return true;
23997
+ return Boolean(record2.localRuntime) && record2.executionMode === "background";
23998
+ }
23999
+ var fallback = (reason) => ({ outcome: "fallback", reason });
24000
+ async function readDialogInProcess(call, store, ctx) {
24208
24001
  const args2 = parseNoloWorkspaceToolArguments(call.arguments);
24209
24002
  const dialogInput = noloStringArg(args2.dialog ?? args2.dialogId ?? args2.id);
24210
24003
  if (!dialogInput) throw new Error("readDialog requires dialog.");
@@ -24212,9 +24005,18 @@ async function readDialogInProcess(call, store, env) {
24212
24005
  if (mode && mode !== "full" && mode !== "status") {
24213
24006
  throw new Error(`readDialog mode must be "full" or "status", got "${mode}".`);
24214
24007
  }
24215
- const userId = noloStringArg(args2.user ?? args2.userId ?? args2.owner) || env?.NOLO_LOCAL_USER_ID || env?.NOLO_USER_ID || "";
24216
- const { dbKey: dialogKey, dialogId } = resolveNoloDialogInput(dialogInput, userId);
24217
- const meta = await store.read(dialogKey, { remote: false });
24008
+ if (noloStringArg(args2.user ?? args2.userId ?? args2.owner)) return fallback("explicit-user");
24009
+ if (noloStringArg(args2.server ?? args2.serverBase ?? args2.serverUrl)) return fallback("explicit-server");
24010
+ const currentUserId = ctx.currentUserId;
24011
+ if (!currentUserId) return fallback("no-current-user");
24012
+ const { dbKey: dialogKey, dialogId, ownerId } = resolveNoloDialogInput(dialogInput, currentUserId);
24013
+ if (ownerId !== currentUserId) return fallback("foreign-owner");
24014
+ const meta = await store.read(dialogKey);
24015
+ if (!meta) return fallback("local-miss");
24016
+ if (isTombstoneRecord(meta)) return fallback("tombstone");
24017
+ if (!isLocalExclusiveDialog(dialogId, meta, ctx.localChildDialogIds)) {
24018
+ return fallback("cross-device-sync");
24019
+ }
24218
24020
  if (mode === "status") {
24219
24021
  const result4 = {
24220
24022
  dialogId,
@@ -24225,8 +24027,11 @@ async function readDialogInProcess(call, store, env) {
24225
24027
  source: "in-process"
24226
24028
  };
24227
24029
  return {
24228
- content: JSON.stringify(result4, null, 2),
24229
- metadata: { noloWorkspaceTool: true, readDialog: true, inProcess: true, mode: "status" }
24030
+ outcome: "hit",
24031
+ result: {
24032
+ content: JSON.stringify(result4, null, 2),
24033
+ metadata: { noloWorkspaceTool: true, readDialog: true, inProcess: true, mode: "status" }
24034
+ }
24230
24035
  };
24231
24036
  }
24232
24037
  const limitNum = noloPositiveIntegerString(args2.limit);
@@ -24235,15 +24040,18 @@ async function readDialogInProcess(call, store, env) {
24235
24040
  maxResponseChars: DEFAULT_READ_DIALOG_MAX_RESPONSE_CHARS,
24236
24041
  ...limit !== void 0 ? { maxMessages: limit } : {}
24237
24042
  });
24043
+ let hasMessages = false;
24238
24044
  if (store.iterator) {
24239
24045
  const { start, end: end3 } = dialogMessageRange(dialogId);
24240
24046
  for await (const [, value] of store.iterator({ gte: start, lte: end3 })) {
24241
24047
  const message = localDialogMessageRecordToRuntimeMessage(value) ?? value;
24242
24048
  if (message) {
24049
+ hasMessages = true;
24243
24050
  projector.addMessage(message);
24244
24051
  }
24245
24052
  }
24246
24053
  }
24054
+ if (!hasMessages) return fallback("no-local-messages");
24247
24055
  const projected = projector.finish(meta);
24248
24056
  const built = buildDialogReadEnvelope({
24249
24057
  meta: projected.meta,
@@ -24257,22 +24065,83 @@ async function readDialogInProcess(call, store, env) {
24257
24065
  }
24258
24066
  });
24259
24067
  return {
24260
- content: built.serialized,
24261
- metadata: { noloWorkspaceTool: true, readDialog: true, inProcess: true }
24068
+ outcome: "hit",
24069
+ result: {
24070
+ content: built.serialized,
24071
+ metadata: { noloWorkspaceTool: true, readDialog: true, inProcess: true }
24072
+ }
24262
24073
  };
24263
24074
  }
24264
24075
  function buildNoloWorkspaceCliToolExecutors(args2) {
24265
24076
  const executors = {};
24266
24077
  for (const toolName of CLI_NOLO_WORKSPACE_TOOL_NAMES) {
24267
24078
  if (toolName === "loadSkill") continue;
24268
- if (toolName === "readDialog" && args2.store) {
24269
- executors[toolName] = (call) => readDialogInProcess(call, args2.store, args2.env);
24079
+ const inProcess = args2.inProcessExecutors?.[toolName];
24080
+ const storeBackedRead = toolName === "readDialog" && Boolean(args2.store || args2.resolveDialogStore);
24081
+ if (inProcess || storeBackedRead) {
24082
+ executors[toolName] = createInProcessWithCliFallback(args2, inProcess);
24270
24083
  continue;
24271
24084
  }
24272
24085
  executors[toolName] = (call) => runNoloWorkspaceCliTool(call, args2);
24273
24086
  }
24274
24087
  return executors;
24275
24088
  }
24089
+ function createInProcessWithCliFallback(args2, inProcess) {
24090
+ return async (call) => {
24091
+ let fallbackReason;
24092
+ try {
24093
+ if (inProcess) {
24094
+ const result4 = await inProcess(call, { env: args2.env });
24095
+ if (result4) return result4;
24096
+ fallbackReason = "local-miss";
24097
+ } else {
24098
+ const currentUserId = resolveHostCurrentUserId(args2);
24099
+ const store = await resolveInProcessDialogStore(args2);
24100
+ const outcome = store ? await readDialogInProcess(call, store, {
24101
+ env: args2.env,
24102
+ currentUserId,
24103
+ localChildDialogIds: resolveLocalChildDialogIds(args2)
24104
+ }) : { outcome: "fallback", reason: "no-store" };
24105
+ if (outcome.outcome === "hit") return outcome.result;
24106
+ fallbackReason = outcome.reason;
24107
+ }
24108
+ } catch (error) {
24109
+ fallbackReason = error instanceof Error ? error.message : String(error);
24110
+ }
24111
+ const bridged = await runNoloWorkspaceCliTool(call, args2);
24112
+ return {
24113
+ ...bridged,
24114
+ metadata: { ...bridged.metadata, inProcessFallback: fallbackReason }
24115
+ };
24116
+ };
24117
+ }
24118
+ async function resolveInProcessDialogStore(args2) {
24119
+ if (args2.store) return args2.store;
24120
+ if (!args2.resolveDialogStore) return void 0;
24121
+ try {
24122
+ return await args2.resolveDialogStore();
24123
+ } catch {
24124
+ return void 0;
24125
+ }
24126
+ }
24127
+ function resolveLocalChildDialogIds(args2) {
24128
+ try {
24129
+ return args2.resolveLocalChildDialogIds?.();
24130
+ } catch {
24131
+ return void 0;
24132
+ }
24133
+ }
24134
+ function resolveHostCurrentUserId(args2) {
24135
+ try {
24136
+ const injected = args2.resolveCurrentUserId?.();
24137
+ if (injected && injected.trim()) return injected.trim();
24138
+ if (args2.resolveCurrentUserId) return void 0;
24139
+ const derived = resolveLocalUserId(args2.env ?? {});
24140
+ return derived && derived.trim() ? derived.trim() : void 0;
24141
+ } catch {
24142
+ return void 0;
24143
+ }
24144
+ }
24276
24145
  var nodeSpawnFallback = (options) => {
24277
24146
  return spawnToWebStreams({ cmd: options.cmd, env: options.env });
24278
24147
  };
@@ -24290,10 +24159,10 @@ function buildLoadSkillExecutor(args2) {
24290
24159
  metadata: { loadSkill: true, resolved: false }
24291
24160
  };
24292
24161
  }
24293
- const { resolveSkillByName } = await import("./skillDiscovery-I37M5KJC.js");
24162
+ const { resolveSkillByName } = await import("./skillDiscovery-MDDKPTW3.js");
24294
24163
  const resolved = resolveSkillByName(args2.cwd, name);
24295
24164
  if (!resolved) {
24296
- const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-BAE2LDXF.js");
24165
+ const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-VRCMQ77Q.js");
24297
24166
  const builtin = resolveBuiltinSkillByName(name);
24298
24167
  if (builtin) {
24299
24168
  const denied = await rejectDisabledBuiltin(args2.agentSkillSource, builtin.slug, name, args2.resolveAgentSkillSource);
@@ -24320,8 +24189,8 @@ ${builtin.content}`,
24320
24189
  };
24321
24190
  }
24322
24191
  try {
24323
- const { readFileSync } = await import("node:fs");
24324
- const body = readFileSync(resolved, "utf8");
24192
+ const { readFileSync: readFileSync2 } = await import("node:fs");
24193
+ const body = readFileSync2(resolved, "utf8");
24325
24194
  return {
24326
24195
  content: `Skill "${name}" loaded inline. Follow its instructions.
24327
24196
 
@@ -24372,7 +24241,7 @@ async function loadPreciseSkill(cwd, parsed, agentSkillSource, resolveAgentSkill
24372
24241
  if (!nonEmpty(parsed.slug) || has2("projectBinding") || has2("relativePath")) {
24373
24242
  return reject("builtin requires only an exact slug.");
24374
24243
  }
24375
- const { listBuiltinSkills } = await import("./builtinSkillRegistry-BAE2LDXF.js");
24244
+ const { listBuiltinSkills } = await import("./builtinSkillRegistry-VRCMQ77Q.js");
24376
24245
  const builtin = listBuiltinSkills().find((entry) => entry.slug === parsed.slug);
24377
24246
  if (!builtin) return reject("builtin slug not found.");
24378
24247
  const denied = await rejectDisabledBuiltin(agentSkillSource, builtin.slug, builtin.slug, resolveAgentSkillSource);
@@ -24397,29 +24266,29 @@ ${builtin.content}`,
24397
24266
  return reject("project requires projectBinding and relativePath only.");
24398
24267
  }
24399
24268
  try {
24400
- const { realpathSync, statSync, readFileSync } = await import("node:fs");
24401
- const { resolve: resolve6, relative: relative6, isAbsolute: isAbsolute5, basename: basename4, sep: sep3 } = await import("node:path");
24269
+ const { realpathSync: realpathSync2, statSync: statSync2, readFileSync: readFileSync2 } = await import("node:fs");
24270
+ const { resolve: resolve7, relative: relative7, isAbsolute: isAbsolute6, basename: basename4, sep: sep4 } = await import("node:path");
24402
24271
  const inside = (root, target) => {
24403
- const rel = relative6(root, target);
24404
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute5(rel);
24272
+ const rel = relative7(root, target);
24273
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute6(rel);
24405
24274
  };
24406
- const realCwd = realpathSync(cwd);
24407
- if (!isAbsolute5(parsed.projectBinding) || realpathSync(parsed.projectBinding) !== realCwd) {
24275
+ const realCwd = realpathSync2(cwd);
24276
+ if (!isAbsolute6(parsed.projectBinding) || realpathSync2(parsed.projectBinding) !== realCwd) {
24408
24277
  return reject("projectBinding does not match the authorized cwd.");
24409
24278
  }
24410
- if (isAbsolute5(parsed.relativePath) || basename4(parsed.relativePath) !== "SKILL.md") {
24279
+ if (isAbsolute6(parsed.relativePath) || basename4(parsed.relativePath) !== "SKILL.md") {
24411
24280
  return reject("relativePath must reference a project SKILL.md.");
24412
24281
  }
24413
- const skillsRoot = resolve6(realCwd, ".agents", "skills");
24414
- const candidate = resolve6(realCwd, parsed.relativePath);
24282
+ const skillsRoot = resolve7(realCwd, ".agents", "skills");
24283
+ const candidate = resolve7(realCwd, parsed.relativePath);
24415
24284
  if (!inside(skillsRoot, candidate)) return reject("path is outside cwd/.agents/skills/.");
24416
- const realRoot = realpathSync(skillsRoot);
24417
- const realPath = realpathSync(candidate);
24285
+ const realRoot = realpathSync2(skillsRoot);
24286
+ const realPath = realpathSync2(candidate);
24418
24287
  if (realRoot !== skillsRoot || !inside(realRoot, realPath) || basename4(realPath) !== "SKILL.md") {
24419
24288
  return reject("skill path escapes cwd/.agents/skills/ or is not SKILL.md.");
24420
24289
  }
24421
- if (!statSync(realPath).isFile()) return reject("SKILL.md is not a file.");
24422
- const body = readFileSync(realPath, "utf8");
24290
+ if (!statSync2(realPath).isFile()) return reject("SKILL.md is not a file.");
24291
+ const body = readFileSync2(realPath, "utf8");
24423
24292
  return {
24424
24293
  content: `Skill "${parsed.relativePath}" loaded inline. Follow its instructions.
24425
24294
 
@@ -24438,7 +24307,7 @@ ${body}`,
24438
24307
  }
24439
24308
  }
24440
24309
  async function formatUnknownSkillMessage(cwd, requestedName) {
24441
- const { discoverSkills } = await import("./skillDiscovery-I37M5KJC.js");
24310
+ const { discoverSkills } = await import("./skillDiscovery-MDDKPTW3.js");
24442
24311
  let available = [];
24443
24312
  try {
24444
24313
  available = discoverSkills(cwd).map((s) => s.name);
@@ -25010,17 +24879,17 @@ function createDevinProvider(options) {
25010
24879
  }
25011
24880
 
25012
24881
  // packages/agent-runtime/executionLeaseValidation.ts
25013
- import { isAbsolute as isAbsolute4, relative as relative5, resolve as resolve5 } from "node:path";
24882
+ import { isAbsolute as isAbsolute5, relative as relative6, resolve as resolve6 } from "node:path";
25014
24883
  function withinRoot(root, child) {
25015
- if (!isAbsolute4(root) || !isAbsolute4(child)) return false;
25016
- const canonicalRoot = resolve5(root);
25017
- const canonicalChild = resolve5(child);
25018
- const suffix = relative5(canonicalRoot, canonicalChild);
25019
- return suffix === "" || suffix !== ".." && !suffix.startsWith("../") && !suffix.startsWith("..\\") && !isAbsolute4(suffix);
24884
+ if (!isAbsolute5(root) || !isAbsolute5(child)) return false;
24885
+ const canonicalRoot = resolve6(root);
24886
+ const canonicalChild = resolve6(child);
24887
+ const suffix = relative6(canonicalRoot, canonicalChild);
24888
+ return suffix === "" || suffix !== ".." && !suffix.startsWith("../") && !suffix.startsWith("..\\") && !isAbsolute5(suffix);
25020
24889
  }
25021
24890
  function subsetOf(allowed, actual) {
25022
24891
  return actual.every(
25023
- (root) => isAbsolute4(root) && allowed.some((parent) => withinRoot(parent, root))
24892
+ (root) => isAbsolute5(root) && allowed.some((parent) => withinRoot(parent, root))
25024
24893
  );
25025
24894
  }
25026
24895
  function validateConfiguredRootExecutionLease(ticket, lease) {
@@ -25077,18 +24946,17 @@ function verifyOwnerRouteAck(headers, expectedRequestId) {
25077
24946
  }
25078
24947
 
25079
24948
  export {
25080
- createHostCredentialBrokerChain,
25081
- createStrictHostCredentialBroker,
25082
24949
  readCommandActionGatePayload,
25083
24950
  readActionGate,
25084
24951
  orderDialogHistory,
24952
+ dialogTurnUserMessageId,
25085
24953
  Option_exports,
25086
24954
  Duration_exports,
25087
24955
  Exit_exports,
25088
24956
  Effect_exports,
25089
- scrubSecrets,
25090
24957
  isDestructiveShellCommand,
25091
24958
  evaluateShellCommandPolicy,
24959
+ readAgentsMdLayerFromDisk,
25092
24960
  filterRetainedLedgerRecords,
25093
24961
  isLineRangeCovered,
25094
24962
  runTaskStop,
@@ -25112,6 +24980,12 @@ export {
25112
24980
  runExecShellGates,
25113
24981
  executeLocalToolWithPolicy,
25114
24982
  LOCAL_TURN_ABORTED_CODE,
24983
+ isSubtaskRun,
24984
+ RUN_WAKE_CHANNEL_ENV,
24985
+ hasRunWakeChannel,
24986
+ filterToolNamesForRunKind,
24987
+ findSummaryAnchorIndex,
24988
+ validateStoredSummary,
25115
24989
  projectContextProvenance,
25116
24990
  hashToolDefinitions,
25117
24991
  LOCAL_AGENT_CONFIG_MISSING_CODE,
@@ -25126,12 +25000,12 @@ export {
25126
25000
  executeOpenAiCompatibleChatCompletion,
25127
25001
  describeOpenAiCompatibleRequestBudget,
25128
25002
  resolveOpenAiCompatibleProviderConfig,
25129
- dialogMessageRecordToAgentRuntimeMessage,
25130
25003
  buildAgentRuntimeDialogWritePlan,
25131
25004
  shouldCacheHybridRemoteRecord,
25132
25005
  parseSyncServersEnv,
25133
25006
  DEFAULT_HYBRID_READ_TIMEOUT_MS,
25134
25007
  createHybridRecordStore,
25008
+ dialogOwnerKey,
25135
25009
  registerDialogOwner,
25136
25010
  localDialogMessageRecordToRuntimeMessage,
25137
25011
  buildLocalDialogWritePlan,