nolo-cli 0.228.0-alpha.2 → 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 (235) hide show
  1. package/README.md +3 -5
  2. package/{_executeModel-VYCHHZVT.js → _executeModel-GIFVXKDT.js} +88 -83
  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-QWQKT54A.js → agentDeleteCommand-UF7XVELS.js} +118 -111
  8. package/{agentEmailCommands-EISMBIRE.js → agentEmailCommands-SFHRPQYC.js} +118 -107
  9. package/{agentListCommands-4WLG32IW.js → agentListCommands-IXKBP3W5.js} +208 -177
  10. package/{agentMachineCommands-DC6NKWTU.js → agentMachineCommands-7NX6PWQ6.js} +55 -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-QM7ETUTX.js → agentRunCommand-LCR4XADM.js} +125 -111
  15. package/{agentRunControl-MBG4U6SL.js → agentRunControl-RN2P6AOD.js} +11 -9
  16. package/{agentRuntimeLocal-HOXKWCYO.js → agentRuntimeLocal-LVXPQ7QA.js} +56 -43
  17. package/{agentSlice-UG76KEBH.js → agentSlice-ZGMOH6TE.js} +15 -14
  18. package/{appDeleteCommands-WWCC6WA5.js → appDeleteCommands-BESCJOQM.js} +55 -48
  19. package/{appDeployCommands-AU4IUN33.js → appDeployCommands-LPTR6IOX.js} +55 -48
  20. package/{appDeployStatusCommands-STUW7WXL.js → appDeployStatusCommands-BZ7KZ5RD.js} +55 -48
  21. package/{appGetCommands-BGTLIQ4K.js → appGetCommands-EDWGJV4S.js} +55 -48
  22. package/{appListCommands-CUCPRUXW.js → appListCommands-OPRWYPM6.js} +55 -48
  23. package/{authCommand-OZ2KTP4Z.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-VQ5N5GSV.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-3VZLEKV2.js → chunk-3DJJ4CFG.js} +11 -11
  32. package/{chunk-TSPMLCWI.js → chunk-4IQN6FWY.js} +5 -5
  33. package/{chunk-XAG3FWBE.js → chunk-4OXPN3WC.js} +6 -6
  34. package/chunk-4ZCTKB27.js +31 -0
  35. package/chunk-53W5BXLN.js +340 -0
  36. package/{chunk-42OKN2LI.js → chunk-5HUO7SEX.js} +9 -107
  37. package/chunk-6ASGEP5D.js +21 -0
  38. package/{chunk-MJI3UAXN.js → chunk-6CXQ3YNJ.js} +40 -36
  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-TCZ2VJZQ.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-WFDNADFX.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-TQEKUOTI.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-YVFH2MFB.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-GAYNXB6T.js → chunk-FTWAOKFU.js} +756 -333
  73. package/chunk-GAHJLSDO.js +107 -0
  74. package/{chunk-2X7WFDT6.js → chunk-GX6DITLQ.js} +1 -1
  75. package/{chunk-HXB4VDGK.js → chunk-HCCQEMTK.js} +28 -28
  76. package/{chunk-CMMI3DAT.js → chunk-HZDK56EK.js} +33 -26
  77. package/{chunk-OTKSESZR.js → chunk-IIOSZAJX.js} +4 -4
  78. package/chunk-IIRJ4P4I.js +24 -0
  79. package/{chunk-OJ45MEEI.js → chunk-IJZC2KIJ.js} +1 -1
  80. package/{chunk-MNEZUL5S.js → chunk-ITBX27W6.js} +92 -31
  81. package/{chunk-LYD6C7OU.js → chunk-J2VIGDJN.js} +6 -6
  82. package/{chunk-M3OZRQNH.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-EGHP7KOY.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-MZG5CETE.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-HF7BLF3F.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-U2HBB7RS.js → chunk-MYYNZG2M.js} +132 -32
  101. package/{chunk-DBUR22G5.js → chunk-MZVCFV3T.js} +19 -15
  102. package/{chunk-WCFFRBL5.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-4QYJPWHH.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-XFXFPUO7.js → chunk-QMNVV3YM.js} +10 -37
  114. package/{chunk-CNMY2XM6.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-45CAVC35.js → chunk-RMWDKLBE.js} +1489 -286
  118. package/{chunk-ZEVQHCLM.js → chunk-RR3MB26M.js} +2 -2
  119. package/{chunk-OOJNQK6V.js → chunk-S25VJYXV.js} +8 -2
  120. package/{chunk-DLXMMTGM.js → chunk-SCMYAGQE.js} +1067 -705
  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-5YMA6DDZ.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-XTJKU3Z4.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-R6Z5S5GA.js → chunk-WQDTSK5U.js} +51 -14
  140. package/{chunk-X3E6EHJW.js → chunk-X22AUZKL.js} +149 -165
  141. package/{chunk-4ZGPHFLE.js → chunk-X3OZ655T.js} +2 -2
  142. package/{chunk-RRDRQOEC.js → chunk-XCA4WHX5.js} +95 -77
  143. package/{chunk-TI2EPRHE.js → chunk-XJSEST7D.js} +3 -3
  144. package/{chunk-3QIYD3VM.js → chunk-XNTZD4AE.js} +870 -1068
  145. package/chunk-XSRSAU3O.js +133 -0
  146. package/{chunk-7FEP5USX.js → chunk-Y4NPF2UN.js} +3 -3
  147. package/{chunk-FJSNBZXR.js → chunk-YDRRGVT5.js} +1 -1
  148. package/{chunk-7BCG67EI.js → chunk-YFW4H6DL.js} +405 -338
  149. package/{chunk-JQZRSXS5.js → chunk-YGDYYFRX.js} +9 -13
  150. package/{chunk-4N6G2CKP.js → chunk-YHNUDTU4.js} +49 -3
  151. package/chunk-YJPK35HB.js +175 -0
  152. package/{chunk-6OVNSQHN.js → chunk-YLAHYLDQ.js} +5 -0
  153. package/{chunk-FPBJM2BW.js → chunk-Z7KE4K3H.js} +195 -126
  154. package/{chunk-DGYCDA6W.js → chunk-ZM5AZTQG.js} +20 -13
  155. package/{chunk-CBUZ6DKA.js → chunk-ZQ6K57FJ.js} +1 -1
  156. package/{cliAgentConfigHelpers-BTRHMPW2.js → cliAgentConfigHelpers-37ZNEY5Y.js} +9 -9
  157. package/{cliAuthorityBrokerClient-XHH7MH2P.js → cliAuthorityBrokerClient-SFPC3WVK.js} +1 -1
  158. package/{cliLocalAgentRecordReader-H3HYQRRR.js → cliLocalAgentRecordReader-MCQVRWBR.js} +58 -47
  159. package/{commandRegistry-FVYPE2IN.js → commandRegistry-NTH5IAN5.js} +104 -92
  160. package/{contentThunks-GNFPG32S.js → contentThunks-SPXTX5U2.js} +38 -36
  161. package/{cooldownCommands-YB5H5BBK.js → cooldownCommands-TIFCHCUN.js} +1 -1
  162. package/{createAgentAutomationAction-PB4QIFQ4.js → createAgentAutomationAction-KUQKCOXB.js} +38 -36
  163. package/{createDialogAction-EVTOPY7A.js → createDialogAction-HJN5U3XS.js} +39 -37
  164. package/{createPageAction-2UYF2IDZ.js → createPageAction-ZAHRDOAU.js} +43 -41
  165. package/{db-M7FU2GNK.js → db-CMUTP3W5.js} +2 -2
  166. package/{dbSlice-XRUZOGSU.js → dbSlice-656PMWR2.js} +13 -12
  167. package/{deleteFile-6URDHYRB.js → deleteFile-ZCQESEEQ.js} +10 -7
  168. package/{dialogCommands-6SZD4TYP.js → dialogCommands-KZTZLWPZ.js} +60 -54
  169. package/dialogMessageRecord-OAV77LT7.js +7 -0
  170. package/{dialogNotifyCommand-SHGPCU22.js → dialogNotifyCommand-PST75COP.js} +11 -11
  171. package/{dialogSlice-5EQ2A6LY.js → dialogSlice-BXIERQHO.js} +39 -37
  172. package/{dialogUsageCommand-W2WCSGKF.js → dialogUsageCommand-6RW2FY6K.js} +5 -5
  173. package/{docCreateCommands-25E6PGN3.js → docCreateCommands-26HJ5NAY.js} +54 -47
  174. package/{docDeleteCommands-F7ZVGEHW.js → docDeleteCommands-UAOHH5XK.js} +56 -49
  175. package/{docReadCommands-JY2E5XEN.js → docReadCommands-4ADG7YE6.js} +54 -47
  176. package/{docStore-OKKIKLT3.js → docStore-FZ75HWP2.js} +15 -14
  177. package/{docUpdateCommands-OZ4CUSIQ.js → docUpdateCommands-OGFJZENF.js} +54 -47
  178. package/fetchMessages-TQEUZD7H.js +1 -1
  179. package/{getPricing-LF5C4XSI.js → getPricing-FCHYVRJU.js} +4 -4
  180. package/{handleSendMessageAction-LNT7SZND.js → handleSendMessageAction-KP6GGBFY.js} +82 -78
  181. package/{hostCredentialCreate-XUU2CSHI.js → hostCredentialCreate-23TX56G7.js} +117 -105
  182. package/index.js +8 -8
  183. package/{lib-OT5OTXRU.js → lib-62SWPXNF.js} +3 -7
  184. package/{localDialogRead-CCOCVGAP.js → localDialogRead-CIOTQM5T.js} +1 -1
  185. package/{localRuntimeAdapter-IBSTMSX7.js → localRuntimeAdapter-MTUWOYPN.js} +124 -111
  186. package/{localRuntimeAuthority-IBJAT62G.js → localRuntimeAuthority-TYHQCTZN.js} +5 -3
  187. package/{localRuntimeDb-N7KHDXS2.js → localRuntimeDb-BO7IVWAZ.js} +1 -1
  188. package/{machineCommands-HSQHDHOT.js → machineCommands-4WJUJQHW.js} +241 -321
  189. package/{machineWsRunDispatch-L6H7J66T.js → machineWsRunDispatch-V3U4JM67.js} +113 -102
  190. package/markdownToSlate-KIYM7B3P.js +8 -0
  191. package/mcpLocalAuthorizeCommand-TI656UWC.js +106 -0
  192. package/{memberThunks-7Y3OYSJQ.js → memberThunks-JFYC4Z5L.js} +20 -15
  193. package/{models-H5NNZRLH.js → models-EP7VG6N2.js} +2 -2
  194. package/{overlay-BBQZXGYI.js → overlay-JA3SPVUS.js} +5 -3
  195. package/package.json +1 -1
  196. package/{projectArchive-FQO654Z3.js → projectArchive-NU2Z5HOR.js} +45 -43
  197. package/{providerPresetApply-WHAMP2D5.js → providerPresetApply-4H7YP5D7.js} +6 -6
  198. package/{providerRegistry-ZI2KORJ7.js → providerRegistry-F3UPOTIY.js} +6 -6
  199. package/{read-TYMBGEXO.js → read-BRZHXUJ6.js} +9 -8
  200. package/{readDocTool-SKQVHBLO.js → readDocTool-N7RVFQEE.js} +1 -1
  201. package/{readlineWorkspace-7U272DSA.js → readlineWorkspace-T56MRMS5.js} +6423 -3669
  202. package/rememberExplicit-CPAPONSI.js +15 -0
  203. package/{removeDialogAgentAction-F5QE2O2B.js → removeDialogAgentAction-J7XU7OUX.js} +19 -18
  204. package/{runAgentClientLoop-AF4JQIJ7.js → runAgentClientLoop-O2GRCGRZ.js} +96 -76
  205. package/{runtimeDoctorCommands-RRKPBGVO.js → runtimeDoctorCommands-RDRJXMXC.js} +8 -8
  206. package/{secretCommands-KZWBZIYS.js → secretCommands-2FEMRUFM.js} +3 -3
  207. package/{setDialogExtraReferencesAction-72L27ERM.js → setDialogExtraReferencesAction-Q4V2ZZW2.js} +16 -15
  208. package/{setPrimaryDialogAgentAction-GJJDUSGJ.js → setPrimaryDialogAgentAction-742H5S6T.js} +19 -18
  209. package/{settingThunks-ZRGWVGZD.js → settingThunks-T4FXSV6M.js} +185 -66
  210. package/{skillDiscovery-BHHPCUHZ.js → skillDiscovery-MDDKPTW3.js} +4 -3
  211. package/{spaceCommands-5VNWMDBE.js → spaceCommands-W5TAVFDT.js} +58 -51
  212. package/{streamAgentChatTurn-YSPEFY4K.js → streamAgentChatTurn-OWDJMU5E.js} +234 -177
  213. package/{switchDialogAgentAction-IIJBPND3.js → switchDialogAgentAction-HLDLHRRA.js} +17 -16
  214. package/{tableCommands-FTAOCBTX.js → tableCommands-44GC4N6J.js} +8 -5
  215. package/{toolApiClient-OGQEBQVX.js → toolApiClient-N5PYW2R3.js} +8 -6
  216. package/{tools-M35PTIFB.js → tools-O7SGGVA3.js} +65 -62
  217. package/{tuiRestart-2IL37YIB.js → tuiRestart-EOGC2BYY.js} +10 -10
  218. package/{tuiSummaryLlmCaller-W2QN4VAC.js → tuiSummaryLlmCaller-TM5BU73J.js} +16 -15
  219. package/{updateCommands-CPATDG6J.js → updateCommands-FBYA5WVG.js} +3 -3
  220. package/{updateDialogTitleAction-IMIRJRQQ.js → updateDialogTitleAction-EXSZGTLL.js} +40 -38
  221. package/{usageCommand-2BF74MKF.js → usageCommand-L4OFWXEU.js} +2 -2
  222. package/{usageRebuildCommand-UHB55BQM.js → usageRebuildCommand-7JR33UHS.js} +3 -3
  223. package/webapi-QVV65DQF.js +2487 -0
  224. package/{windowsSelfUpdate-ZFD6J5HF.js → windowsSelfUpdate-M4V77OUB.js} +2 -2
  225. package/workContext-Y3ADAPZU.js +14 -0
  226. package/workContextAccess-VU5I4LKZ.js +11 -0
  227. package/workContextWriteNotice-YCSSMHN4.js +7 -0
  228. package/{workloadLifecycle-HFJIN5IZ.js → workloadLifecycle-ZCSQCHG3.js} +2 -2
  229. package/agentRecordCommands-IZYUVHME.js +0 -177
  230. package/chunk-5ZMIIR23.js +0 -265
  231. package/chunk-62HXNQVV.js +0 -134
  232. package/chunk-TUSTONB3.js +0 -81
  233. package/chunk-ZXF6D3I6.js +0 -359
  234. package/{chunk-W6RFEDN4.js → chunk-AETZ7AD6.js} +3 -3
  235. /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-U2HBB7RS.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,14 +32,7 @@ import {
30
32
  evaluateRequestBudget,
31
33
  hasImageInRuntimeMessages,
32
34
  stripImagePartsFromMessages
33
- } from "./chunk-XAG3FWBE.js";
34
- import {
35
- resolveToolExecutionContract
36
- } from "./chunk-LKA64WH4.js";
37
- import {
38
- resolveAgentImageInputSupport,
39
- resolveToolImagePolicy
40
- } from "./chunk-DUUDXSLX.js";
35
+ } from "./chunk-4OXPN3WC.js";
41
36
  import {
42
37
  applyShapingCounts,
43
38
  attachProjectionFacts,
@@ -48,7 +43,7 @@ import {
48
43
  projectUserPartForModel,
49
44
  resolveOutboundDiagnosticSink,
50
45
  writeThinkingFacts
51
- } from "./chunk-QYB23WUH.js";
46
+ } from "./chunk-2FK2KZSL.js";
52
47
  import {
53
48
  createThinkParserState,
54
49
  createToolCallAccumulator,
@@ -57,16 +52,9 @@ import {
57
52
  finalizeAccumulatedToolCalls
58
53
  } from "./chunk-56GBUMO5.js";
59
54
  import {
60
- CREDENTIAL_HYGIENE_RULE,
61
- DELETE_SAFETY_RED_LINE,
62
- DISPATCH_BACKEND_POLICY,
63
- DISPATCH_CANDIDATE_POLICY,
64
- PARALLEL_DISPATCH_DEFAULT_RULE,
65
- PLATFORM_RISK_CONTROL_RULE,
66
55
  TOOL_GUIDED_SECTION_ORDER,
67
- VERIFY_BEFORE_CONCLUDING_RULE,
68
- buildConsultationModeBlock,
69
56
  buildIdentityBlock,
57
+ buildPlatformStaticScopedBlocks,
70
58
  buildRuntimeGuidanceBlocks,
71
59
  detectDispatchIntent,
72
60
  detectDispatchIntentFromMessages,
@@ -74,7 +62,22 @@ import {
74
62
  hashStablePrefixContent,
75
63
  resolveResponseGuidelines,
76
64
  resolveToolGuidedSections
77
- } from "./chunk-FPBJM2BW.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";
78
81
  import {
79
82
  classifyUnparsableToolArgs,
80
83
  collectStablePromptPrefix,
@@ -98,7 +101,7 @@ import {
98
101
  toOpenAiCompatibleMessages,
99
102
  toResponsesTools,
100
103
  transferDowngradedToolTurnOrigin
101
- } from "./chunk-EEOOBRA7.js";
104
+ } from "./chunk-W3HSD32M.js";
102
105
  import {
103
106
  TOOL_HAD_IMAGES,
104
107
  TOOL_IMAGES,
@@ -113,24 +116,14 @@ import {
113
116
  withoutToolImages
114
117
  } from "./chunk-X4O7FJF5.js";
115
118
  import {
116
- BRIDGE_STREAM_MAX_CHARS,
117
- CLI_NOLO_WORKSPACE_TOOL_NAMES,
118
- DEFAULT_READ_DIALOG_MAX_RESPONSE_CHARS,
119
- NOLO_WORKSPACE_TOOL_NAMES,
120
- buildDialogReadEnvelope,
121
- buildNoloWorkspaceCommandArgs,
122
- buildNoloWorkspaceOpenAiTools,
123
- createStreamingDialogReadProjector,
124
- noloPositiveIntegerString,
125
- noloStringArg,
126
- parseNoloWorkspaceToolArguments,
127
- readTextStreamUpToChars,
128
- resolveNoloDialogInput
129
- } from "./chunk-MNEZUL5S.js";
119
+ resolveToolExecutionContract
120
+ } from "./chunk-DMPZMYH4.js";
130
121
  import {
131
- applyToolSurfaceConstraints
132
- } from "./chunk-VS276URX.js";
122
+ resolveAgentImageInputSupport,
123
+ resolveToolImagePolicy
124
+ } from "./chunk-SX6AWTNK.js";
133
125
  import {
126
+ isContextOverflowText,
134
127
  isQuotaExhaustedError
135
128
  } from "./chunk-TLE77UJ5.js";
136
129
  import {
@@ -149,7 +142,7 @@ import {
149
142
  } from "./chunk-WFGNWWJI.js";
150
143
  import {
151
144
  isAgentSkillDisabled
152
- } from "./chunk-FJSNBZXR.js";
145
+ } from "./chunk-YDRRGVT5.js";
153
146
  import {
154
147
  buildDialogFallbackTitleFromUserInput
155
148
  } from "./chunk-2MBTWINN.js";
@@ -161,16 +154,18 @@ import {
161
154
  resolveEmptyAssistantFallbackMessage,
162
155
  resolveEmptyAssistantOutcome,
163
156
  resolveTruncatedReasoningTailLog
164
- } from "./chunk-QRGDJA4B.js";
157
+ } from "./chunk-LTVEOOZL.js";
165
158
  import {
166
159
  COMPACTION_SUMMARY_SCHEMA_VERSION,
167
160
  COMPACTION_SUMMARY_SYSTEM_PROMPT,
168
- buildBoundedCompactionRequest,
169
161
  buildCompactionMetricsFromPlan,
162
+ buildHistoricalCompactionRequest,
170
163
  buildSummarySourceDiagnostics,
164
+ buildSummarySourceSegments,
171
165
  classifySummaryError,
172
166
  computeSummarySourceMetadata,
173
167
  createSummaryBudget,
168
+ diffSummarySourceSegments,
174
169
  formatCompactionMetricsLog,
175
170
  getMessageTokenCount,
176
171
  getModelContextWindow,
@@ -182,10 +177,9 @@ import {
182
177
  resolveCompressionTriggerRatio,
183
178
  resolveEffectiveCompactionBudgets,
184
179
  runSummaryWithContract,
185
- sha256Hex,
186
180
  summaryCompletionTokens,
187
181
  truncateToolOutputForContext
188
- } from "./chunk-L32W3PRP.js";
182
+ } from "./chunk-MAA42MMV.js";
189
183
  import {
190
184
  createProviderCallTimingTracker,
191
185
  finalizeProviderCallTiming,
@@ -193,21 +187,15 @@ import {
193
187
  observeMeaningfulProviderResponse,
194
188
  withProviderCallTimingFields
195
189
  } from "./chunk-H57T64RA.js";
190
+ import {
191
+ sha256Hex
192
+ } from "./chunk-SR4FE5VD.js";
196
193
  import {
197
194
  clipCompactText
198
195
  } from "./chunk-5MMAK75Q.js";
199
196
  import {
200
197
  asRecordOrEmpty
201
198
  } from "./chunk-KX6YBIHG.js";
202
- import {
203
- assertCredentialRef
204
- } from "./chunk-OQHIVPG4.js";
205
- import {
206
- isAbortError
207
- } from "./chunk-7DPNBQSV.js";
208
- import {
209
- isLevelNotFoundError
210
- } from "./chunk-OW765XBU.js";
211
199
  import {
212
200
  TOOL_OUTPUT_SPILL_BYTES,
213
201
  TOOL_OUTPUT_SPILL_LINES,
@@ -234,25 +222,51 @@ import {
234
222
  spillLargeToolOutput,
235
223
  spillToolOutput,
236
224
  toProcessTaskView,
237
- truncateToolOutput
238
- } from "./chunk-VMJVAJ6W.js";
225
+ truncateToolOutput,
226
+ workspaceChildEnv
227
+ } from "./chunk-CTIEJRTP.js";
239
228
  import {
240
229
  estimateTokenCount
241
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";
242
247
  import {
243
248
  resolveNoloStateDir
244
249
  } from "./chunk-6UBGXX2W.js";
245
250
  import {
246
- WORKTREE_ISOLATION_PRELUDE
247
- } from "./chunk-G7IUT2V3.js";
251
+ isTombstoneRecord
252
+ } from "./chunk-BV3FLP2L.js";
248
253
  import {
249
- canonicalizeToolName,
250
- canonicalizeToolNames
251
- } from "./chunk-6OVNSQHN.js";
254
+ dialogMessageRecordToAgentRuntimeMessage
255
+ } from "./chunk-4ZCTKB27.js";
252
256
  import {
253
257
  dialogMessageKey,
254
258
  dialogMessageRange
255
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";
256
270
  import {
257
271
  asTrimmedNonEmptyStringArray
258
272
  } from "./chunk-I42VC5KR.js";
@@ -260,20 +274,12 @@ import {
260
274
  asOptionalPositiveFiniteNumber
261
275
  } from "./chunk-U6VC4MU4.js";
262
276
  import {
263
- buildAgentsMdLayer,
264
- buildAgentsMdLayerHeader,
265
- buildDialogSummaryLayer
266
- } from "./chunk-42OKN2LI.js";
267
- import {
268
- buildUserResponseLanguageContext
269
- } from "./chunk-JQZRSXS5.js";
277
+ toErrorMessage
278
+ } from "./chunk-HNMXYYJR.js";
270
279
  import {
271
280
  buildProviderAuthHeaders,
272
281
  buildProviderExecutionPlan
273
- } from "./chunk-RTHFJZ6M.js";
274
- import {
275
- toErrorMessage
276
- } from "./chunk-HNMXYYJR.js";
282
+ } from "./chunk-K26XPZRB.js";
277
283
  import {
278
284
  asTrimmedString
279
285
  } from "./chunk-3EUW3WEO.js";
@@ -288,7 +294,7 @@ import {
288
294
  } from "./chunk-CF7PE763.js";
289
295
  import {
290
296
  PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL
291
- } from "./chunk-OBSEKCVK.js";
297
+ } from "./chunk-PQ63BDV3.js";
292
298
  import {
293
299
  asTrimmedLowercaseString
294
300
  } from "./chunk-QSJ3HFEF.js";
@@ -13697,7 +13703,8 @@ ${args2.input}` : [
13697
13703
  const prefix2 = stableContent ? [{
13698
13704
  role: "system",
13699
13705
  content: stableContent,
13700
- stable_prefix_chars: stableContent.length
13706
+ stable_prefix_chars: stableContent.length,
13707
+ ...args2.prompt?.trim() ? { [AGENT_PROMPT_IN_MESSAGES]: true } : {}
13701
13708
  }] : [];
13702
13709
  const composed2 = composeProviderMessages({
13703
13710
  prefix: prefix2,
@@ -13720,7 +13727,11 @@ ${args2.input}` : [
13720
13727
  }
13721
13728
  const blocks = (args2.contextBlocks ?? []).map((block) => block.trim()).filter(Boolean);
13722
13729
  const systemContent = [args2.prompt?.trim(), ...blocks].filter(Boolean).join("\n\n");
13723
- 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
+ }] : [];
13724
13735
  const composed = composeProviderMessages({
13725
13736
  prefix,
13726
13737
  history: args2.history,
@@ -13890,7 +13901,7 @@ function buildToolResultsSignature(toolExecutions) {
13890
13901
  function resolveProgressGuardConfig(options, env = typeof process !== "undefined" ? process.env : {}) {
13891
13902
  const envDisabled = env.NOLO_LOOP_PROGRESS_GUARD_DISABLED === "true" || env.NOLO_LOOP_PROGRESS_GUARD_DISABLED === "1";
13892
13903
  const disabled = options?.disabled ?? envDisabled ?? false;
13893
- const parsePositiveInt = (val, fallback) => {
13904
+ const parsePositiveInt = (val, fallback2) => {
13894
13905
  if (typeof val === "number" && Number.isFinite(val) && val >= 1) {
13895
13906
  return Math.floor(val);
13896
13907
  }
@@ -13900,7 +13911,7 @@ function resolveProgressGuardConfig(options, env = typeof process !== "undefined
13900
13911
  return parsed;
13901
13912
  }
13902
13913
  }
13903
- return fallback;
13914
+ return fallback2;
13904
13915
  };
13905
13916
  const maxConsecutiveIdenticalRounds = parsePositiveInt(
13906
13917
  options?.maxConsecutiveIdenticalRounds ?? env.NOLO_LOOP_MAX_IDENTICAL_ROUNDS,
@@ -14658,9 +14669,9 @@ function normalizeExecShellInput(input) {
14658
14669
  const record2 = input;
14659
14670
  let rawCommand = resolveShellCommandArg(record2);
14660
14671
  if (typeof rawCommand !== "string" || !rawCommand.trim()) {
14661
- const fallback = record2.command ?? record2.cmd;
14662
- if (typeof fallback === "string" && fallback.trim()) {
14663
- rawCommand = fallback;
14672
+ const fallback2 = record2.command ?? record2.cmd;
14673
+ if (typeof fallback2 === "string" && fallback2.trim()) {
14674
+ rawCommand = fallback2;
14664
14675
  }
14665
14676
  }
14666
14677
  const command = typeof rawCommand === "string" ? rawCommand.trim() : "";
@@ -14830,13 +14841,13 @@ async function invokeCapability(capabilityOrName, input, ctx = {}) {
14830
14841
  }
14831
14842
 
14832
14843
  // packages/agent-runtime/localWorkspaceTools.ts
14833
- import { existsSync as existsSync3 } from "node:fs";
14844
+ import { existsSync as existsSync2 } from "node:fs";
14834
14845
  import { createHash as createHash3 } from "node:crypto";
14835
14846
 
14836
14847
  // packages/agent-runtime/agentsMd.ts
14837
- import { existsSync, readFileSync } from "node:fs";
14838
- import { resolve } from "node:path";
14839
- var AGENTS_MD_MAX_BYTES = 8192;
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;
14840
14851
  var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
14841
14852
  var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
14842
14853
  function truncateAgentsMdContent(content, maxBytes = AGENTS_MD_MAX_BYTES) {
@@ -14878,7 +14889,7 @@ var AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS = [
14878
14889
  "\u5220\u9664",
14879
14890
  "\u6D3E\u53D1"
14880
14891
  ];
14881
- var AGENTS_MD_SUMMARY_POINTER_INSTRUCTION = "\u7528 readFile \u8BFB\u5168\u6587\uFF1A%REL%\uFF08cwd\uFF09/ %PATH%\n\u4EC5\u7D22\u5F15\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";
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";
14882
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";
14883
14894
  var clipToChars = (text2, maxChars) => text2.length <= maxChars ? text2 : `${text2.slice(0, maxChars).trimEnd()}\u2026`;
14884
14895
  var parseAgentsMdItem = (body) => {
@@ -15035,11 +15046,21 @@ ${entry.line}`;
15035
15046
  return rendered;
15036
15047
  };
15037
15048
  function readAgentsMdLayerFromDisk(cwd) {
15049
+ if (!cwd) return null;
15050
+ let root;
15051
+ try {
15052
+ root = realpathSync(cwd);
15053
+ } catch {
15054
+ return null;
15055
+ }
15038
15056
  for (const name of AGENTS_MD_CANDIDATES) {
15039
15057
  const filePath = resolve(cwd, name);
15040
- if (!existsSync(filePath)) continue;
15041
15058
  try {
15042
- const raw = readFileSync(filePath, "utf8");
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");
15043
15064
  const content = raw.trim();
15044
15065
  if (!content) continue;
15045
15066
  const totalBytes = Buffer.byteLength(raw, "utf8");
@@ -15078,20 +15099,20 @@ ${marker}`, name);
15078
15099
 
15079
15100
  // packages/agent-runtime/visualRenderer.node.ts
15080
15101
  import { createRequire } from "node:module";
15081
- import { existsSync as existsSync2 } from "node:fs";
15102
+ import { existsSync } from "node:fs";
15082
15103
  import { realpath, stat, readFile } from "node:fs/promises";
15083
- import { isAbsolute, relative, win32 } from "node:path";
15104
+ import { isAbsolute as isAbsolute2, relative as relative2, win32 } from "node:path";
15084
15105
  import { fileURLToPath, pathToFileURL } from "node:url";
15085
15106
  import { lookup as lookup2 } from "node:dns/promises";
15086
15107
  import { isIP } from "node:net";
15087
15108
  function isVisualPathOutside(rel) {
15088
- return rel === ".." || /^\.\.[\\/]/.test(rel) || isAbsolute(rel) || win32.isAbsolute(rel);
15109
+ return rel === ".." || /^\.\.[\\/]/.test(rel) || isAbsolute2(rel) || win32.isAbsolute(rel);
15089
15110
  }
15090
15111
  async function validateVisualUrl(input, workspaceRoot) {
15091
15112
  const url = new URL(input);
15092
15113
  if (url.protocol === "file:") {
15093
15114
  const [root, path] = await Promise.all([realpath(workspaceRoot), realpath(fileURLToPath(url))]);
15094
- const rel = relative(root, path);
15115
+ const rel = relative2(root, path);
15095
15116
  if (isVisualPathOutside(rel)) throw new Error("Renderer file URL is outside workspaceRoot.");
15096
15117
  if (!(await stat(path)).isFile()) throw new Error("Renderer file URL must point to a file, not a directory.");
15097
15118
  return pathToFileURL(path);
@@ -15149,7 +15170,7 @@ function visualRendererCapability() {
15149
15170
  if (process.env.NOLO_VISUAL_RENDERER_DISABLED === "1") return { available: false, reasonCode: "disabled", reason: "Platform renderer disabled by NOLO_VISUAL_RENDERER_DISABLED=1 on this runtime host." };
15150
15171
  try {
15151
15172
  const { chromium } = require2("playwright");
15152
- const executablePath = [chromium.executablePath(), resolveExecutableOnPath("google-chrome"), resolveExecutableOnPath("chromium"), resolveExecutableOnPath("chromium-browser")].find((path) => !!path && existsSync2(path));
15173
+ const executablePath = [chromium.executablePath(), resolveExecutableOnPath("google-chrome"), resolveExecutableOnPath("chromium"), resolveExecutableOnPath("chromium-browser")].find((path) => !!path && existsSync(path));
15153
15174
  if (!executablePath) return { available: false, reasonCode: "missing-browser", reason: "No Chromium renderer installed. Install Playwright Chromium (playwright install chromium) or system Chromium/Google Chrome on the runtime host." };
15154
15175
  return { available: true, chromium, executablePath };
15155
15176
  } catch {
@@ -15165,10 +15186,10 @@ async function renderVisualPage(args2) {
15165
15186
  if (typeof args2.persistScreenshot !== "function") {
15166
15187
  throw new Error("renderVisualPage: persistScreenshot is required (expected a function that stores the PNG bytes)");
15167
15188
  }
15168
- if (!isAbsolute(args2.workspaceRoot)) {
15189
+ if (!isAbsolute2(args2.workspaceRoot)) {
15169
15190
  throw new Error("renderVisualPage: workspaceRoot must be an absolute path");
15170
15191
  }
15171
- 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))) {
15172
15193
  throw new Error("renderVisualPage: screenshotPath must be a file path inside workspaceRoot");
15173
15194
  }
15174
15195
  if (args2.timeoutMs !== void 0 && (typeof args2.timeoutMs !== "number" || !Number.isFinite(args2.timeoutMs) || args2.timeoutMs <= 0)) {
@@ -15396,7 +15417,17 @@ function createHostWindowCapture(options = {}) {
15396
15417
  return {
15397
15418
  ...image,
15398
15419
  content: `${formatImageSummary({ kind: "screenshot", ...image.imageSummary })}
15399
- \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
+ }
15400
15431
  };
15401
15432
  } finally {
15402
15433
  active--;
@@ -15425,7 +15456,7 @@ var captureHostWindow = createHostWindowCapture();
15425
15456
  // packages/agent-runtime/localWorkspaceTools.ts
15426
15457
  import { lstat as lstat2, readdir as readdir2, readFile as readFile4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
15427
15458
  import { homedir } from "node:os";
15428
- import { dirname as dirname2, relative as relative4, resolve as resolve5, sep as sep2 } from "node:path";
15459
+ import { dirname as dirname2, relative as relative5, resolve as resolve5, sep as sep3 } from "node:path";
15429
15460
  import { spawn as spawnChildProcess2 } from "node:child_process";
15430
15461
 
15431
15462
  // packages/agent-runtime/runResultReadProjection.ts
@@ -15508,7 +15539,7 @@ function isLineRangeCovered(request3, covered) {
15508
15539
 
15509
15540
  // packages/agent-runtime/fileTextSearch.ts
15510
15541
  import { readdir, readFile as readFile3, stat as stat3 } from "node:fs/promises";
15511
- import { basename as basename2, relative as relative2, resolve as resolve3 } from "node:path";
15542
+ import { basename as basename2, relative as relative3, resolve as resolve3 } from "node:path";
15512
15543
  import { spawn as spawnChildProcess } from "node:child_process";
15513
15544
 
15514
15545
  // packages/agent-runtime/gitignore.ts
@@ -15548,8 +15579,10 @@ async function hasRootGitignore(workspaceRoot) {
15548
15579
 
15549
15580
  // packages/agent-runtime/fileTextSearch.ts
15550
15581
  var normalizePath = (value) => value.replaceAll("\\", "/");
15551
- 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));
15552
15583
  var COMMAND_LIMIT_HEADROOM = 1;
15584
+ var MAX_SEARCH_FILE_BYTES = 8 * 1024 * 1024;
15585
+ var MAX_SEARCH_LINE_CHARS = 2e3;
15553
15586
  async function runCommand(binary, args2, cwd, maxResults) {
15554
15587
  const recordLimit = maxResults === void 0 ? 0 : Math.max(0, maxResults) + COMMAND_LIMIT_HEADROOM;
15555
15588
  return await new Promise((done4) => {
@@ -15557,7 +15590,12 @@ async function runCommand(binary, args2, cwd, maxResults) {
15557
15590
  try {
15558
15591
  const child = spawnChildProcess(binary, args2, { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
15559
15592
  child.stdout.on("data", (chunk) => {
15560
- 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
+ }
15561
15599
  recordCount = parseMatches(cwd, stdout).length;
15562
15600
  if (recordLimit > 0 && recordCount >= recordLimit && !stopped) {
15563
15601
  stopped = true;
@@ -15587,14 +15625,14 @@ function isGrepExpressibleExclude(pattern) {
15587
15625
  }
15588
15626
  function commandArgs(o, binary, target) {
15589
15627
  const args2 = binary === "rg" ? ["--line-number", "--no-heading", "--color", "never", "--null"] : ["-RIn", "--binary-files=without-match", "--null"];
15590
- 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");
15591
15629
  if (o.regex !== true) args2.push(binary === "rg" ? "--fixed-strings" : "-F");
15592
15630
  else if (binary === "grep") args2.push("-E");
15593
15631
  if (o.caseSensitive === false) args2.push("-i");
15594
15632
  if (binary === "rg") {
15595
15633
  if (o.includeIgnored) args2.push("--no-ignore");
15596
15634
  for (const x of o.exclude ?? []) args2.push("--glob", `!${x}`);
15597
- if (o.include) args2.push("--glob", o.include);
15635
+ if (o.include) args2.push("--type-add", `noloSearch:${o.include}`, "--type", "noloSearch");
15598
15636
  } else {
15599
15637
  for (const x of o.exclude ?? []) {
15600
15638
  const clean = extractGrepExcludeDir(x);
@@ -15614,24 +15652,32 @@ function parseMatches(root, output) {
15614
15652
  return records;
15615
15653
  }
15616
15654
  async function decorate(root, raw, context3, absolute = false) {
15617
- const cache = /* @__PURE__ */ new Map(), out = [];
15655
+ const out = [];
15618
15656
  for (const x of raw) {
15619
- let lines = cache.get(x.file);
15620
- if (!lines) {
15657
+ let lines = [];
15658
+ if (context3 > 0) {
15621
15659
  try {
15622
- 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
+ }
15623
15663
  } catch {
15624
- continue;
15625
15664
  }
15626
- cache.set(x.file, lines);
15627
15665
  }
15628
15666
  const i = x.line - 1;
15629
- 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
+ });
15630
15674
  }
15631
15675
  return out;
15632
15676
  }
15633
15677
  function globMatch(pattern, value) {
15634
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));
15635
15681
  let source = "";
15636
15682
  for (let i = 0; i < p.length; i++) {
15637
15683
  const c = p[i];
@@ -15681,6 +15727,8 @@ async function jsSearch(o, targetPath) {
15681
15727
  const needle = o.caseSensitive === false ? o.query.toLowerCase() : o.query;
15682
15728
  const out = [], context3 = o.contextLines ?? 0;
15683
15729
  for (const file of files) {
15730
+ const info = await stat3(file).catch(() => null);
15731
+ if (!info || info.size > MAX_SEARCH_FILE_BYTES) continue;
15684
15732
  const text2 = await readText(file);
15685
15733
  if (!text2 || text2.includes("\0")) continue;
15686
15734
  const lines = text2.split(/\r\n|\r|\n/);
@@ -15689,7 +15737,7 @@ async function jsSearch(o, targetPath) {
15689
15737
  const hit = matcher ? matcher.test(line) : o.caseSensitive === false ? line.toLowerCase().includes(needle) : line.includes(needle);
15690
15738
  if (!hit) continue;
15691
15739
  if (out.length >= max4) return { matches: out, totalMatches: max4, truncated: true, engine: "js" };
15692
- 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)) });
15693
15741
  }
15694
15742
  }
15695
15743
  return { matches: out, totalMatches: out.length, truncated: false, engine: "js" };
@@ -15722,6 +15770,7 @@ async function searchFileTextMatches(o) {
15722
15770
  if (targetStat.isFile()) return jsSearch(o, targetPath);
15723
15771
  const run2 = o.runCommand ?? runCommand, max4 = o.maxResults;
15724
15772
  for (const entry of COMMAND_ENGINES) {
15773
+ if (entry.engine === "ripgrep" && o.include && /[/\\]/.test(o.include)) continue;
15725
15774
  if (entry.engine === "grep" && !await canGrepFulfillOptions(o)) continue;
15726
15775
  const injectedResolver = o[entry.binaryOption];
15727
15776
  const binary = injectedResolver ? injectedResolver() : resolveExecutableOnPath(entry.binaryName);
@@ -15769,6 +15818,7 @@ var TASK_WAIT_DEFAULT_TIMEOUT_MS = 5 * 6e4;
15769
15818
  var TASK_WAIT_MAX_TIMEOUT_MS = 5 * 6e4;
15770
15819
  var TASK_WAIT_POLL_INTERVAL_MS = 250;
15771
15820
  var TASK_STOP_GRACE_MS = 2e3;
15821
+ var TASK_STOP_POLL_INTERVAL_MS = 40;
15772
15822
  function resolveCleanupReport(evidence, previousStatus) {
15773
15823
  const diagnostic = evidence.diagnostic ? { diagnostic: evidence.diagnostic } : {};
15774
15824
  if (evidence.confirmedStopped) {
@@ -15990,8 +16040,17 @@ async function runTaskStop(args2) {
15990
16040
  )
15991
16041
  };
15992
16042
  }
15993
- if (graceMs > 0) await sleep3(graceMs);
15994
- 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) {
15995
16054
  return {
15996
16055
  outcome: "stopped",
15997
16056
  taskId,
@@ -16036,6 +16095,7 @@ var WORKSPACE_TOOL_NAMES = [
16036
16095
  "writeFile",
16037
16096
  "editFile",
16038
16097
  "globFiles",
16098
+ "searchFiles",
16039
16099
  "captureVisualState",
16040
16100
  "execShell",
16041
16101
  "launchProcess",
@@ -16060,7 +16120,7 @@ function buildWorkspacePathProperty() {
16060
16120
  };
16061
16121
  }
16062
16122
  function buildReadWorkspaceDescription() {
16063
- 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).";
16064
16124
  }
16065
16125
  function buildReadWorkspaceParameters() {
16066
16126
  const path = buildWorkspacePathProperty();
@@ -16076,20 +16136,14 @@ function buildReadWorkspaceParameters() {
16076
16136
  type: "object",
16077
16137
  properties: {
16078
16138
  path,
16079
- files: {
16080
- type: "array",
16081
- minItems: 1,
16082
- maxItems: 8,
16083
- description: "Batch of files with optional individual line ranges; mutually exclusive with path. One shared output budget applies.",
16084
- items: { type: "object", properties: { path, lines, force }, required: ["path"], additionalProperties: false }
16085
- },
16086
16139
  lines,
16087
16140
  force,
16088
16141
  raw: {
16089
16142
  type: "boolean",
16090
16143
  description: "Read original bytes including full runtime acceptance observations in *.result.md. Default compacts only machine observations; report text and physical line numbers are unchanged."
16091
16144
  }
16092
- }
16145
+ },
16146
+ required: ["path"]
16093
16147
  };
16094
16148
  }
16095
16149
  function buildReadWorkspaceFileTool() {
@@ -16391,6 +16445,31 @@ function buildWorkspaceToolDefinition(toolName) {
16391
16445
  if (toolName === "editFile") {
16392
16446
  return buildReplaceWorkspaceTextTool();
16393
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
+ }
16394
16473
  if (toolName === "globFiles") {
16395
16474
  return buildGlobWorkspaceFilesTool();
16396
16475
  }
@@ -16412,10 +16491,10 @@ function filterDeclaredWorkspaceToolNames(args2) {
16412
16491
  // packages/agent-runtime/workspacePathGuard.ts
16413
16492
  import { constants as fsConstants } from "node:fs";
16414
16493
  import { lstat, mkdir, open, readlink, realpath as realpath2 } from "node:fs/promises";
16415
- import { basename as basename3, dirname, isAbsolute as isAbsolute2, join as join2, relative as relative3, resolve as resolve4, 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";
16416
16495
  function isPathInsideRoot(root, targetPath) {
16417
- const rel = relative3(resolve4(root), resolve4(targetPath));
16418
- 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);
16419
16498
  }
16420
16499
  function isNotFoundError(error) {
16421
16500
  const code = error?.code;
@@ -16502,7 +16581,7 @@ async function resolveOpenedFilePath(handle) {
16502
16581
  for (const root of FD_LINK_ROOTS) {
16503
16582
  try {
16504
16583
  const linked = await readlink(`${root}/${handle.fd}`);
16505
- if (isAbsolute2(linked)) return linked.replace(/ \(deleted\)$/, "");
16584
+ if (isAbsolute3(linked)) return linked.replace(/ \(deleted\)$/, "");
16506
16585
  } catch {
16507
16586
  }
16508
16587
  }
@@ -16719,25 +16798,6 @@ async function readRootGitignorePatterns2(workspaceRoot) {
16719
16798
  return readRootGitignorePatterns(workspaceRoot);
16720
16799
  }
16721
16800
  var DEFAULT_LOCAL_API_ORIGIN = "http://127.0.0.1:38123";
16722
- var ALWAYS_EXCLUDED_GLOBS = [
16723
- ".git/**",
16724
- ".nolo/**",
16725
- "node_modules/**",
16726
- "*.tsbuildinfo",
16727
- "dist/**",
16728
- "build/**",
16729
- "out/**",
16730
- "coverage/**",
16731
- ".next/**",
16732
- ".turbo/**",
16733
- "public/assets/**",
16734
- "*.min.js",
16735
- "*.min.css",
16736
- "*.map",
16737
- "*.lock",
16738
- "bun.lockb",
16739
- "*.ldb"
16740
- ];
16741
16801
  function readTrimmedString(value) {
16742
16802
  return asOptionalTrimmedString(value);
16743
16803
  }
@@ -16811,12 +16871,12 @@ function parseWorkspaceToolArguments(raw) {
16811
16871
  }
16812
16872
  }
16813
16873
  function normalizeWorkspaceRelativePath(args2) {
16814
- const relativePath = relative4(args2.workspaceRoot, args2.targetPath);
16874
+ const relativePath = relative5(args2.workspaceRoot, args2.targetPath);
16815
16875
  return relativePath || ".";
16816
16876
  }
16817
16877
  function isPathInsideWorkspace(args2) {
16818
- const relativePath = relative4(args2.workspaceRoot, args2.targetPath);
16819
- return relativePath === "" || !relativePath.startsWith("..") && !relativePath.includes(`..${sep2}`);
16878
+ const relativePath = relative5(args2.workspaceRoot, args2.targetPath);
16879
+ return relativePath === "" || !relativePath.startsWith("..") && !relativePath.includes(`..${sep3}`);
16820
16880
  }
16821
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"];
16822
16882
  var OLD_TEXT_FIELD_ALIASES = ["oldText", "old_string", "oldString", "search", "search_string", "find", "match"];
@@ -17077,7 +17137,7 @@ function resolveRipgrepBinary(env = process.env) {
17077
17137
  const fromEnv = asOptionalTrimmedString(env.NOLO_BUNDLED_RG);
17078
17138
  if (fromEnv) {
17079
17139
  try {
17080
- if (existsSync3(fromEnv)) return fromEnv;
17140
+ if (existsSync2(fromEnv)) return fromEnv;
17081
17141
  } catch {
17082
17142
  }
17083
17143
  }
@@ -17581,7 +17641,7 @@ async function listWorkspaceEntries(args2) {
17581
17641
  if (truncated) break;
17582
17642
  const absolutePath = resolve5(dirPath, name);
17583
17643
  const info = await stat4(absolutePath);
17584
- const relativePath = relative4(args2.dirPath, absolutePath) || ".";
17644
+ const relativePath = relative5(args2.dirPath, absolutePath) || ".";
17585
17645
  const isDirectory = info.isDirectory();
17586
17646
  entries.push(isDirectory ? `${relativePath}/` : relativePath);
17587
17647
  if (args2.maxResults && entries.length >= args2.maxResults) {
@@ -17614,22 +17674,24 @@ async function internalSearchWorkspace(args2) {
17614
17674
  root: inside ? workspaceRoot : searchPath,
17615
17675
  target: inside ? normalizeWorkspaceRelativePath({ workspaceRoot, targetPath: searchPath }) : ".",
17616
17676
  query: args2.query,
17617
- regex: true,
17677
+ regex: args2.regex ?? true,
17618
17678
  caseSensitive: args2.caseSensitive !== false,
17619
17679
  contextLines: args2.contextLines,
17620
17680
  maxResults: args2.maxResults ?? 200,
17621
- includeIgnored: args2.workspaceRoot.includes(".worktrees") || !inside,
17681
+ includeIgnored: args2.includeIgnored ?? (args2.workspaceRoot.includes(".worktrees") || !inside),
17622
17682
  absolutePaths: !inside,
17623
- 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
17624
17687
  });
17625
17688
  const outputLines = result4.matches.flatMap((match7) => [
17626
17689
  ...match7.before.map((line, index) => `${match7.path}:${Math.max(1, match7.line - match7.before.length + index)}-${line}`),
17627
17690
  `${match7.path}:${match7.line}:${match7.text}`,
17628
17691
  ...match7.after.map((line, index) => `${match7.path}:${match7.line + index + 1}-${line}`)
17629
17692
  ]);
17630
- const rawContent = outputLines.join("\n");
17693
+ const rawContent = scrubSecrets(outputLines.join("\n")).cleaned;
17631
17694
  const content = truncateToolOutput(rawContent, SEARCH_OUTPUT_CHAR_LIMIT);
17632
- const matchLines = result4.matches.map((match7) => `${match7.path}:${match7.line}:${match7.text}`);
17633
17695
  return {
17634
17696
  content,
17635
17697
  metadata: {
@@ -17638,6 +17700,7 @@ async function internalSearchWorkspace(args2) {
17638
17700
  searchedPath: inside ? normalizeWorkspaceRelativePath({ workspaceRoot, targetPath: searchPath }) : ".",
17639
17701
  count: outputLines.length,
17640
17702
  matchCount: result4.totalMatches,
17703
+ totalMatches: result4.totalMatches,
17641
17704
  matchedFiles: Array.from(new Set(result4.matches.map((match7) => match7.path))),
17642
17705
  truncated: result4.truncated || content.length !== rawContent.length,
17643
17706
  limitedByMaxResults: result4.truncated,
@@ -17883,7 +17946,14 @@ async function captureVisualStateTool(args2) {
17883
17946
  script: null,
17884
17947
  args: [],
17885
17948
  compatibilityVersion: 2,
17886
- 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
+ }]
17887
17957
  }
17888
17958
  };
17889
17959
  } catch (error) {
@@ -17986,6 +18056,7 @@ async function launchProcessTool(args2) {
17986
18056
  const detached = process.platform !== "win32";
17987
18057
  const proc = spawnChildProcess2(cmdArgs[0] ?? "", cmdArgs.slice(1), {
17988
18058
  cwd: resolve5(args2.workspaceRoot),
18059
+ env: workspaceChildEnv(),
17989
18060
  stdio: ["ignore", "pipe", "pipe"],
17990
18061
  detached,
17991
18062
  windowsHide: true
@@ -18254,6 +18325,36 @@ function createLocalWorkspaceToolExecutors(args2) {
18254
18325
  workspaceRoot: args2.workspaceRoot,
18255
18326
  ...fileAccess
18256
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
+ },
18257
18358
  globFiles: (call) => globFilesTool({
18258
18359
  call,
18259
18360
  workspaceRoot: args2.workspaceRoot,
@@ -18301,12 +18402,25 @@ function createLocalWorkspaceToolExecutors(args2) {
18301
18402
  });
18302
18403
  return await readLocalImage(absolutePath);
18303
18404
  } catch (error) {
18304
- 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}`);
18305
18407
  }
18306
18408
  }));
18307
18409
  return {
18308
18410
  content: results2.map((result4) => result4.content).join("\n"),
18309
- images: results2.flatMap((result4) => result4.images ?? [])
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
+ }
18310
18424
  };
18311
18425
  },
18312
18426
  readFile: Object.assign((call) => readFileTool({
@@ -18474,6 +18588,9 @@ function validateToolArguments(args2) {
18474
18588
  }
18475
18589
  record2 = parsed;
18476
18590
  }
18591
+ if (toolName === "searchFiles" && record2.query === void 0 && typeof record2.pattern === "string" && record2.pattern.length) {
18592
+ record2 = { ...record2, query: record2.pattern };
18593
+ }
18477
18594
  for (const field of requiredFields) {
18478
18595
  if (record2[field] !== void 0) continue;
18479
18596
  if (isAliasSatisfied(record2, field)) continue;
@@ -18558,6 +18675,7 @@ var DEFAULT_LOCAL_TOOLS = /* @__PURE__ */ new Set([
18558
18675
  "writeFile",
18559
18676
  "editFile",
18560
18677
  "globFiles",
18678
+ "searchFiles",
18561
18679
  "execShell",
18562
18680
  "launchProcess",
18563
18681
  "listProcesses",
@@ -18814,6 +18932,78 @@ function emitLoopEvent(boundary, event, bridge) {
18814
18932
  function clip(value, max4 = 240) {
18815
18933
  return clipCompactText(value, max4);
18816
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
+ }
18817
19007
  function projectSafeToolObservationMetadata(metadata) {
18818
19008
  if (!metadata || typeof metadata !== "object") return void 0;
18819
19009
  const safe = {};
@@ -19059,12 +19249,18 @@ async function executeToolCall(args2) {
19059
19249
  }
19060
19250
  }
19061
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
+ }
19062
19258
  const executePromise = input.adapter.executeTool({
19063
19259
  id: toolCall.id,
19064
19260
  name: toolName,
19065
19261
  arguments: unwrappedArguments,
19066
19262
  ...userInputText ? { userInput: userInputText } : {},
19067
- ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {},
19263
+ ...runtimeContext ? { runtimeContext } : {},
19068
19264
  ...args2.runToolNames ? { runToolNames: args2.runToolNames } : {},
19069
19265
  ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
19070
19266
  // 定档信号:来源只由 turn 输入推导,不让模型/参数层参与。
@@ -19073,7 +19269,7 @@ async function executeToolCall(args2) {
19073
19269
  origin: input.background ? "automation" : input.runKind === "subtask" ? "agent" : "chat"
19074
19270
  }, {
19075
19271
  ...input.abortSignal ? { abortSignal: input.abortSignal } : {},
19076
- ...input.runtimeContext ? { runtimeContext: input.runtimeContext } : {}
19272
+ ...runtimeContext ? { runtimeContext } : {}
19077
19273
  });
19078
19274
  const execStartedAtMs = Date.now();
19079
19275
  toolResult = await runAbortableToolTask(input, executePromise, toolName);
@@ -19112,6 +19308,7 @@ ${toolResult.content}` : toolResult.content,
19112
19308
  const finishedAt = Date.now();
19113
19309
  const summary = summarizeToolResult(toolResult.content, toolResult.metadata);
19114
19310
  const safeMetadata = projectSafeToolObservationMetadata(toolResult.metadata);
19311
+ const imageArtifacts = extractToolImageArtifacts(toolName, toolResult);
19115
19312
  loopTiming.mark("toolExecute", round);
19116
19313
  emitLoopEvent(
19117
19314
  boundary,
@@ -19134,7 +19331,8 @@ ${toolResult.content}` : toolResult.content,
19134
19331
  elapsedMs: Math.max(0, finishedAt - startedAt),
19135
19332
  ...summary ? { summary } : {},
19136
19333
  ...typeof toolResult.content === "string" ? { content: toolResult.content } : {},
19137
- metadata: toolResult.metadata
19334
+ metadata: toolResult.metadata,
19335
+ ...imageArtifacts ? { imageArtifacts } : {}
19138
19336
  }
19139
19337
  );
19140
19338
  } catch (error) {
@@ -19313,6 +19511,137 @@ function createTurnUsageLedger(args2) {
19313
19511
  };
19314
19512
  }
19315
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
+
19316
19645
  // packages/agent-runtime/leafFinalHandoff.ts
19317
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.`;
19318
19647
 
@@ -19377,8 +19706,17 @@ function findSummaryAnchorIndex(bridged, anchorId) {
19377
19706
  const index = Number(legacy[1]);
19378
19707
  return Number.isSafeInteger(index) && index < bridged.length ? index : -1;
19379
19708
  }
19380
- function logSummarySourceDiagnostics(phase, dialogId, history, anchor) {
19709
+ function logSummarySourceDiagnostics(phase, dialogId, history, anchor, segmentDiff) {
19381
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
+ }
19382
19720
  const rows = buildSummarySourceDiagnostics(toPlanCompressionMessages(history), anchor);
19383
19721
  for (const row of rows) console.log(`[compaction-source] ${JSON.stringify({
19384
19722
  phase,
@@ -19576,13 +19914,15 @@ async function maybeAutoCompactLocalHistory(args2) {
19576
19914
  let reason;
19577
19915
  if (invalidStored?.schemaVersion !== void 0 && invalidStored.schemaVersion !== COMPACTION_SUMMARY_SCHEMA_VERSION) {
19578
19916
  reason = "schema-version-mismatch";
19579
- } 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) {
19580
19918
  reason = "anchor-not-found";
19581
19919
  } else if (typeof invalidStored?.sourceCount === "number" && history.length < invalidStored.sourceCount) {
19582
19920
  reason = "history-trimmed";
19583
19921
  } else {
19584
19922
  reason = "hash-mismatch";
19585
19923
  }
19924
+ const currentSegments = buildSummarySourceSegments(bridged, invalidStored?.summarizedBeforeId);
19925
+ const segmentDiff = reason === "hash-mismatch" ? diffSummarySourceSegments(invalidStored?.sourceSegments, currentSegments) : void 0;
19586
19926
  console.warn(
19587
19927
  `[localLoop] invalidated dialog summary for ${dialogId} (${reason}); discarding and re-compressing`,
19588
19928
  // 诊断分项(**仅加日志,不改任何哈希/校验/重锚语义**):区分「历史真被改写」
@@ -19595,10 +19935,17 @@ async function maybeAutoCompactLocalHistory(args2) {
19595
19935
  storedSourceCount: typeof invalidStored?.sourceCount === "number" ? invalidStored.sourceCount : null,
19596
19936
  summarizedBeforeId: typeof invalidStored?.summarizedBeforeId === "string" ? invalidStored.summarizedBeforeId : null,
19597
19937
  recomputedHashPrefix: hashSummarySourceSlice(history, invalidStored?.summarizedBeforeId)?.slice(0, 8) ?? null,
19598
- 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 } : {}
19599
19940
  }
19600
19941
  );
19601
- logSummarySourceDiagnostics("invalidated", dialogId, history, invalidStored?.summarizedBeforeId);
19942
+ logSummarySourceDiagnostics(
19943
+ "invalidated",
19944
+ dialogId,
19945
+ history,
19946
+ invalidStored?.summarizedBeforeId,
19947
+ segmentDiff
19948
+ );
19602
19949
  stored = null;
19603
19950
  }
19604
19951
  const existingSummary = typeof stored?.summary === "string" ? stored.summary : "";
@@ -19608,7 +19955,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19608
19955
  const contextWindow = typeof args2.contextWindow === "number" && Number.isFinite(args2.contextWindow) && args2.contextWindow > 0 ? args2.contextWindow : getModelContextWindow(args2.model ?? "");
19609
19956
  const allMsgs = toPlanCompressionMessages(prepareHistoryForNextTurn(history, args2.contextReferenceResolver));
19610
19957
  const maxInputItems = resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint });
19611
- const force = args2.force === true || args2.requestOverBudget?.(
19958
+ const force = args2.force === true || invalidSummary || args2.requestOverBudget?.(
19612
19959
  existingSummary ? projectHistoryWithSummary({ history, summary: existingSummary, summarizedBeforeId }) : history
19613
19960
  ) === true;
19614
19961
  const plan = planCompression({
@@ -19692,7 +20039,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19692
20039
  };
19693
20040
  }
19694
20041
  const msgsToCompress = plan.msgsToCompress;
19695
- const bounded3 = buildBoundedCompactionRequest({
20042
+ const bounded3 = buildHistoricalCompactionRequest({
19696
20043
  msgsToCompress,
19697
20044
  previousSummary: existingSummary,
19698
20045
  contextWindow,
@@ -19845,20 +20192,20 @@ async function maybeAutoCompactLocalHistory(args2) {
19845
20192
  });
19846
20193
  }
19847
20194
  };
19848
- const fallback = args2.summaryFallback?.preferPlatform ? args2.summaryFallback : void 0;
20195
+ const fallback2 = args2.summaryFallback?.preferPlatform ? args2.summaryFallback : void 0;
19849
20196
  let eligibility;
19850
- const routedFallback = fallback ? Object.assign(
20197
+ const routedFallback = fallback2 ? Object.assign(
19851
20198
  async (content, options) => {
19852
20199
  summaryModel = PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL;
19853
20200
  summaryProvider = "nolo";
19854
- return physicalRequest("platform", () => fallback(content, { ...options, attemptId: compactionAttemptId }));
20201
+ return physicalRequest("platform", () => fallback2(content, { ...options, attemptId: compactionAttemptId }));
19855
20202
  },
19856
20203
  {
19857
- preferPlatform: (options) => eligibility ??= fallback.preferPlatform(options),
19858
- ...fallback.complete ? { complete: async (content, options) => {
20204
+ preferPlatform: (options) => eligibility ??= fallback2.preferPlatform(options),
20205
+ ...fallback2.complete ? { complete: async (content, options) => {
19859
20206
  summaryModel = PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL;
19860
20207
  summaryProvider = "nolo";
19861
- return physicalRequest("platform", () => fallback.complete(content, { ...options, attemptId: compactionAttemptId }));
20208
+ return physicalRequest("platform", () => fallback2.complete(content, { ...options, attemptId: compactionAttemptId }));
19862
20209
  } } : {}
19863
20210
  }
19864
20211
  ) : void 0;
@@ -20032,8 +20379,13 @@ async function maybeAutoCompactLocalHistory(args2) {
20032
20379
  }
20033
20380
  };
20034
20381
  }
20382
+ const bridgedHistory = toPlanCompressionMessages(history);
20035
20383
  const sourceMeta = await computeSummarySourceMetadata(
20036
- toPlanCompressionMessages(history),
20384
+ bridgedHistory,
20385
+ bounded3.summarizedBeforeId
20386
+ );
20387
+ const sourceSegments = buildSummarySourceSegments(
20388
+ bridgedHistory,
20037
20389
  bounded3.summarizedBeforeId
20038
20390
  );
20039
20391
  if (Date.now() >= summaryDeadlineMs) throw Object.assign(new Error("Summary deadline exceeded"), { compactionReason: "timeout" });
@@ -20041,7 +20393,7 @@ async function maybeAutoCompactLocalHistory(args2) {
20041
20393
  throw Object.assign(new Error("auto-compaction aborted"), { compactionReason: "aborted" });
20042
20394
  }
20043
20395
  const saveT0 = Date.now();
20044
- await adapter.saveDialogSummary({
20396
+ const summarySavePayload = {
20045
20397
  dialogId,
20046
20398
  summary: newSummary,
20047
20399
  summarizedBeforeId: bounded3.summarizedBeforeId,
@@ -20049,12 +20401,14 @@ async function maybeAutoCompactLocalHistory(args2) {
20049
20401
  sourceHash: sourceMeta?.sourceHash,
20050
20402
  sourceCount: sourceMeta?.sourceCount ?? 0,
20051
20403
  schemaVersion: COMPACTION_SUMMARY_SCHEMA_VERSION,
20404
+ ...sourceSegments.length > 0 ? { sourceSegments } : {},
20052
20405
  referenceKeys: Array.from(
20053
20406
  new Set(
20054
20407
  history.slice(0, sourceMeta?.sourceCount ?? 0).flatMap((message) => extractReferenceKeysFromMessage(message))
20055
20408
  )
20056
20409
  )
20057
- });
20410
+ };
20411
+ await adapter.saveDialogSummary(summarySavePayload);
20058
20412
  saveElapsedMs = Date.now() - saveT0;
20059
20413
  logSummarySourceDiagnostics("saved", dialogId, history, bounded3.summarizedBeforeId);
20060
20414
  console.log(formatCompactionMetricsLog(metrics));
@@ -20237,7 +20591,7 @@ function createTurnCompactionController(args2) {
20237
20591
  return { history: result4.history, applied: result4.history !== history, usage: result4.usage };
20238
20592
  };
20239
20593
  let lastCompactionOutcome;
20240
- const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens) => {
20594
+ const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens, force = false) => {
20241
20595
  lastCompactionOutcome = void 0;
20242
20596
  const contextUsage = args2.getContextUsage();
20243
20597
  let inputTokens = contextUsage ? normalizeUsage(contextUsage).input_tokens : 0;
@@ -20249,8 +20603,8 @@ function createTurnCompactionController(args2) {
20249
20603
  }
20250
20604
  }
20251
20605
  const ratio = inputTokens > 0 ? Math.min(1, inputTokens / args2.contextWindow) : void 0;
20252
- if (!requestOverBudget && ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85 && resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint }) === void 0) {
20253
- 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;
20254
20608
  }
20255
20609
  try {
20256
20610
  const compacted = await maybeAutoCompactLocalHistory({
@@ -20270,6 +20624,7 @@ function createTurnCompactionController(args2) {
20270
20624
  providerEndpoint: args2.providerEndpoint,
20271
20625
  resolveProvider: args2.resolveProvider,
20272
20626
  contextWindow: args2.contextWindow,
20627
+ ...force ? { force: true } : {},
20273
20628
  ...ratio !== void 0 ? { realContextUsagePercent: ratio } : {},
20274
20629
  abortSignal: args2.abortSignal,
20275
20630
  timeoutMs: args2.timeoutMs,
@@ -20296,12 +20651,16 @@ function createTurnCompactionController(args2) {
20296
20651
  args2.onSelectedSummary?.(compacted.selectedSummary ?? { outcome: initial ? "absent" : "unknown" });
20297
20652
  }
20298
20653
  emitObservation(compacted);
20654
+ return Boolean(compacted.compressed && compacted.summaryGenerated);
20299
20655
  } catch (error) {
20300
20656
  lastCompactionOutcome = { ...lastCompactionOutcome, error: classifySummaryError(error) };
20301
20657
  console.warn("[localLoop] in-loop auto-compaction failed:", error);
20658
+ return false;
20302
20659
  }
20303
20660
  };
20304
- return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: () => prepareRequest(), forceCompact, prepareRequest };
20661
+ return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: async () => {
20662
+ await prepareRequest();
20663
+ }, forceCompact, prepareRequest };
20305
20664
  }
20306
20665
 
20307
20666
  // packages/agent-runtime/providerCallTelemetry.ts
@@ -20679,6 +21038,7 @@ function combineRollbackError(primary, rollbackError) {
20679
21038
  return combined;
20680
21039
  }
20681
21040
  async function runLocalAgentTurn(input) {
21041
+ input = { ...input, runtimeContext: input.runtimeContext ? { ...input.runtimeContext } : void 0 };
20682
21042
  const legacyCallbacks = {
20683
21043
  onLoopEvent: input.onLoopEvent,
20684
21044
  onToolEvent: input.onToolEvent,
@@ -20821,8 +21181,16 @@ async function runLocalAgentTurn(input) {
20821
21181
  // 防止 session-scope 的 agentCollaboration 段逐轮翻转击穿前缀缓存。
20822
21182
  dispatchIntent: detectDispatchIntentFromMessages(history) || detectDispatchIntent(
20823
21183
  typeof input.input === "string" ? input.input : void 0
20824
- )
21184
+ ),
21185
+ runKind: input.runKind
20825
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
+ );
20826
21194
  const guidanceScopes = [
20827
21195
  ...input.userLanguage?.trim() ? [buildUserResponseLanguageContext({ language: input.userLanguage })] : [],
20828
21196
  guidanceBlocks.startupProtocol,
@@ -20831,12 +21199,14 @@ async function runLocalAgentTurn(input) {
20831
21199
  // 注入顺序遵循 TOOL_GUIDED_SECTION_ORDER(与 buildSystemPrompt 的显式
20832
21200
  // layer 列表同源),禁止用 Object.values 自行定序。
20833
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] : [],
20834
21208
  ...input.runKind === "subtask" ? [LEAF_FINAL_HANDOFF_INSTRUCTIONS] : []
20835
21209
  ].map((content) => content.trim()).filter((content) => content.length > 0).map((content) => ({ content, cacheScope: "session" }));
20836
- const callerScopes = normalizeContextBlockScopes(
20837
- input.contextBlocks,
20838
- input.contextBlockScopes
20839
- );
20840
21210
  const responseGuidelines = resolveResponseGuidelines(
20841
21211
  input.responseViewport ?? "unknown"
20842
21212
  );
@@ -20850,24 +21220,8 @@ async function runLocalAgentTurn(input) {
20850
21220
  ] : []
20851
21221
  ];
20852
21222
  const mergedContextBlockScopes = [
20853
- // 删除安全红线:系统层最高优先级约束,位于所有块之前(含身份信息块),
20854
- // owner 要求常驻「根本提示词」的最顶部(2026-09-26 批量误删事故)。
20855
- { content: DELETE_SAFETY_RED_LINE, cacheScope: "session" },
20856
- // 凭据纪律:与红线同为系统层固定块,紧随其后(四条装配线同源)。
20857
- { content: CREDENTIAL_HYGIENE_RULE, cacheScope: "session" },
20858
- // 并行是默认:系统层固定块,紧随红线(localLoop 无 static 作用域,用 session 占位,
20859
- // 「最顶」由数组首位保证——与红线同一约定)。
20860
- { content: VERIFY_BEFORE_CONCLUDING_RULE, cacheScope: "session" },
20861
- { content: PARALLEL_DISPATCH_DEFAULT_RULE, cacheScope: "session" },
20862
- // 派发落点:并行派发纪律的下一层(派到哪个执行后端),沿用 session 占位约定。
20863
- { content: DISPATCH_BACKEND_POLICY, cacheScope: "session" },
20864
- { content: DISPATCH_CANDIDATE_POLICY, cacheScope: "session" },
20865
- // 平台风控纪律:无条件系统层块,沿用 session 占位约定。
20866
- { content: PLATFORM_RISK_CONTROL_RULE, cacheScope: "session" },
20867
- { content: buildConsultationModeBlock(), cacheScope: "session" },
20868
- // Git 任务隔离:系统层固定前置,四条装配线同序(请教模式之后、身份信息之前;
20869
- // skill 配置 disabled 也注入)。
20870
- { content: WORKTREE_ISOLATION_PRELUDE, cacheScope: "session" },
21223
+ // 顶部固定平台层(唯一真源见 platformStaticPromptLayers.ts;localLoop 无 static 作用域,session 占位)。
21224
+ ...buildPlatformStaticScopedBlocks(),
20871
21225
  { content: identityBlock, cacheScope: "session" },
20872
21226
  ...guidanceScopes,
20873
21227
  // 回复行为准则:local 线(CLI 非交互 / 桌面 / TUI)的唯一注入边界。
@@ -20997,6 +21351,24 @@ async function runLocalAgentTurn(input) {
20997
21351
  historyCount: history.length,
20998
21352
  capToolMessage
20999
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
+ };
21000
21372
  const userInputText = extractUserInputText(input.input);
21001
21373
  let toolCallCount = 0;
21002
21374
  let requestCalibrationRatio = 1;
@@ -21019,6 +21391,12 @@ async function runLocalAgentTurn(input) {
21019
21391
  let skipFinalAppend = false;
21020
21392
  let partialContent = "";
21021
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
+ });
21022
21400
  let pendingInjectionCommits = [];
21023
21401
  let inFlightTransactions = [];
21024
21402
  let rollbackInjectionCommits = async () => {
@@ -21140,7 +21518,7 @@ async function runLocalAgentTurn(input) {
21140
21518
  });
21141
21519
  imageDowngradeEmitted = true;
21142
21520
  }
21143
- const requestMessages = projectRequest(transcript.working());
21521
+ let requestMessages = projectRequest(transcript.working());
21144
21522
  if (requestOverBudget(requestMessages)) {
21145
21523
  const budget = evaluateLocalRequestBudget({
21146
21524
  messages: requestMessages,
@@ -21161,7 +21539,7 @@ async function runLocalAgentTurn(input) {
21161
21539
  }));
21162
21540
  }
21163
21541
  budgetTrimPhase = contextPhase("budget-trim", requestMessages, { droppedCount: 0 });
21164
- const contextMetrics = {
21542
+ let contextMetrics = {
21165
21543
  ...preparedMessages.metrics,
21166
21544
  messageCount: requestMessages.length,
21167
21545
  contentChars: requestMessages.reduce(
@@ -21183,8 +21561,8 @@ async function runLocalAgentTurn(input) {
21183
21561
  input.onToolEvent || input.onObservationEvent || input.observationBoundary
21184
21562
  );
21185
21563
  let llmStreamActivity = 0;
21186
- const callStartedAt = Date.now();
21187
- const requestTelemetry = buildRequestTelemetry({
21564
+ let callStartedAt = Date.now();
21565
+ let requestTelemetry = buildRequestTelemetry({
21188
21566
  // 无 dialogId 的新对话用本 turn 唯一键,避免不同新对话共用一个槽误报漂移。
21189
21567
  dialogKey: input.continueDialogId || newDialogTelemetryKey,
21190
21568
  messages: requestMessages,
@@ -21201,6 +21579,17 @@ async function runLocalAgentTurn(input) {
21201
21579
  inFlightTransactions = pendingInjectionCommits.splice(0);
21202
21580
  try {
21203
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
+ }
21204
21593
  if (input.abortSignal?.aborted) throw buildAbortedError();
21205
21594
  } catch (error) {
21206
21595
  const toRollback = inFlightTransactions;
@@ -21213,83 +21602,148 @@ async function runLocalAgentTurn(input) {
21213
21602
  throw error;
21214
21603
  }
21215
21604
  }
21216
- let providerInvoked = false;
21217
- try {
21218
- result4 = await runCompleteWithTimeout({
21219
- provider: { complete: (messages2, options) => {
21220
- providerInvoked = true;
21221
- inFlightTransactions = [];
21222
- return provider.complete(messages2, options);
21223
- } },
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,
21224
21634
  messages: requestMessages,
21225
- options: {
21226
- timeoutMs: resolveLlmRequestTimeoutMs(input),
21227
- // 用户取消信号穿进 provider options:providerStreamRetry 据此在
21228
- // 取消后跳过重试,provider 分支(如 antigravity/openai-compatible)
21229
- // 也可把 fetch 绑定到同一信号,实现真正的传输层取消。
21230
- ...input.abortSignal ? { signal: input.abortSignal } : {},
21231
- // 计费归因:续聊轮次带上 dialogId,platform proxy 才能把 token 记录
21232
- // 归到具体对话而不是 chat-proxy 兜底桶。新对话首轮 id 尚未分配。
21233
- ...input.continueDialogId ? { dialogId: input.continueDialogId } : {},
21234
- ...shouldStreamDeltas ? { onTextDelta: (chunk) => {
21235
- llmStreamActivity += 1;
21236
- partialContent += chunk;
21237
- observationBoundary.emit({
21238
- kind: "text-delta",
21239
- chunk,
21240
- round,
21241
- atMs: Date.now()
21242
- });
21243
- } } : {},
21244
- ...shouldStreamReasoning ? { onReasoningDelta: (chunk) => {
21245
- llmStreamActivity += 1;
21246
- observationBoundary.emit({
21247
- kind: "reasoning-delta",
21248
- chunk,
21249
- round,
21250
- atMs: Date.now()
21251
- });
21252
- } } : {},
21253
- ...shouldPassToolEvents ? { onToolEvent: (event) => {
21254
- llmStreamActivity += 1;
21255
- observationBoundary.emit({
21256
- kind: "tool-event",
21257
- event,
21258
- round,
21259
- atMs: Date.now()
21260
- });
21261
- } } : {},
21262
- ...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
21263
21640
  },
21264
- timeoutMs: resolveLlmRequestTimeoutMs(input),
21265
- activityVersion: () => llmStreamActivity,
21266
- round,
21267
- input,
21268
- boundary: observationBoundary,
21269
- context: contextMetrics,
21270
- providerName: agentConfig.provider,
21271
- model: provider.model
21641
+ toolsHash: safeToolNamesHash(agentTools)
21272
21642
  });
21273
- } catch (error) {
21274
- if (!providerInvoked && inFlightTransactions.length > 0) {
21275
- const toRollback = inFlightTransactions;
21276
- inFlightTransactions = [];
21277
- try {
21278
- await rollbackInjectionCommits(toRollback);
21279
- } catch (rbErr) {
21280
- 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
+ }
21281
21731
  }
21732
+ throw error;
21282
21733
  }
21283
- if (providerInvoked) usageLedger.recordProviderCall({
21284
- model: agentConfig.model,
21285
- telemetry: {
21286
- ...requestTelemetry,
21287
- round,
21288
- endTs: Date.now(),
21289
- 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;
21290
21744
  }
21291
- });
21292
- throw error;
21745
+ }
21746
+ break;
21293
21747
  }
21294
21748
  acceptToolImages.discard(requestMessages.flatMap(toolImages).filter((image) => toolImageDelivery(image) === "impossible"));
21295
21749
  acceptToolImages.commit(
@@ -21455,6 +21909,7 @@ ${reasoningTailLog}
21455
21909
  const { toolResult, toolExecMs } = await executeToolCall({
21456
21910
  input: executionInput,
21457
21911
  toolCall,
21912
+ ...prepareDirectWorkMemorySource ? { getDirectWorkSource } : {},
21458
21913
  round,
21459
21914
  boundary: observationBoundary,
21460
21915
  loopTiming,
@@ -21585,6 +22040,15 @@ ${reasoningTailLog}
21585
22040
  };
21586
22041
  break;
21587
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
+ }
21588
22052
  loopTiming.mark("roundEnd", round);
21589
22053
  round += 1;
21590
22054
  }
@@ -22640,765 +23104,14 @@ async function resolveOpenAiCompatibleProviderConfig(args2) {
22640
23104
  };
22641
23105
  }
22642
23106
 
22643
- // packages/agent-runtime/macOsKeychainCredentialBroker.ts
22644
- import { spawn as spawn2 } from "node:child_process";
22645
- var MACOS_KEYCHAIN_SERVICE_PREFIX = "nolo.credentials.keys";
22646
- var MACOS_KEYCHAIN_ACCOUNT = "api-key";
22647
- var SECURITY_ITEM_NOT_FOUND_EXIT = 44;
22648
- var DEFAULT_SECURITY_BIN = "/usr/bin/security";
22649
- function safeCredentialRef(ref) {
22650
- try {
22651
- return assertCredentialRef(ref);
22652
- } catch {
22653
- throw new Error("invalid_ref");
23107
+ // packages/agent-runtime/dialogWritePlan.ts
23108
+ function extractLastUserText(messages) {
23109
+ const lastUser = [...messages].reverse().find((message) => message.role === "user");
23110
+ if (typeof lastUser?.content === "string") return lastUser.content;
23111
+ if (Array.isArray(lastUser?.content)) {
23112
+ return lastUser.content.filter((part) => part.type === "text").map((part) => part.text).join(" ");
22654
23113
  }
22655
- }
22656
- function credentialRefToMacOsKeychainService(ref, servicePrefix = MACOS_KEYCHAIN_SERVICE_PREFIX) {
22657
- const safe = safeCredentialRef(ref);
22658
- const hex = Buffer.from(safe, "utf8").toString("hex");
22659
- if (!hex) {
22660
- throw new Error("invalid_ref");
22661
- }
22662
- return `${servicePrefix}.${hex}`;
22663
- }
22664
- function rethrowBrokerError(op, _error) {
22665
- throw new Error(`credential_broker_${op}_failed`);
22666
- }
22667
- function createDefaultSecurityRunner(securityBin = DEFAULT_SECURITY_BIN) {
22668
- return function defaultSecurityRunner(input) {
22669
- return new Promise((resolve7) => {
22670
- let settled = false;
22671
- const finish = (result4) => {
22672
- if (settled) return;
22673
- settled = true;
22674
- resolve7(result4);
22675
- };
22676
- let child;
22677
- try {
22678
- child = spawn2(securityBin, input.args, {
22679
- stdio: ["pipe", "pipe", "pipe"]
22680
- });
22681
- } catch {
22682
- finish({ exitCode: -1, stdout: "", stderr: "" });
22683
- return;
22684
- }
22685
- let stdout = "";
22686
- let stderr = "";
22687
- child.stdout?.setEncoding("utf8");
22688
- child.stderr?.setEncoding("utf8");
22689
- child.stdout?.on("data", (chunk) => {
22690
- stdout += chunk;
22691
- });
22692
- child.stderr?.on("data", (chunk) => {
22693
- stderr += chunk;
22694
- });
22695
- child.on("error", () => {
22696
- finish({ exitCode: -1, stdout: "", stderr: "" });
22697
- });
22698
- child.on("close", (code) => {
22699
- finish({
22700
- exitCode: typeof code === "number" ? code : -1,
22701
- stdout,
22702
- stderr
22703
- });
22704
- });
22705
- if (input.stdin !== void 0) {
22706
- child.stdin?.write(input.stdin);
22707
- }
22708
- child.stdin?.end();
22709
- });
22710
- };
22711
- }
22712
- function createMacOsKeychainCredentialBroker(options = {}) {
22713
- const runner = options.runner ?? createDefaultSecurityRunner(options.securityBin);
22714
- const servicePrefix = options.servicePrefix ?? MACOS_KEYCHAIN_SERVICE_PREFIX;
22715
- const account = options.account ?? MACOS_KEYCHAIN_ACCOUNT;
22716
- const serviceFor = (ref) => credentialRefToMacOsKeychainService(ref, servicePrefix);
22717
- return {
22718
- async get(ref) {
22719
- const safeRef = safeCredentialRef(ref);
22720
- const service4 = serviceFor(safeRef);
22721
- let result4;
22722
- try {
22723
- result4 = await runner({
22724
- args: [
22725
- "find-generic-password",
22726
- "-a",
22727
- account,
22728
- "-s",
22729
- service4,
22730
- "-w"
22731
- ]
22732
- });
22733
- } catch (error) {
22734
- rethrowBrokerError("get", error);
22735
- }
22736
- if (result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22737
- return null;
22738
- }
22739
- if (result4.exitCode !== 0) {
22740
- rethrowBrokerError("get");
22741
- }
22742
- const secret = result4.stdout.replace(/\n$/, "");
22743
- return secret.length > 0 ? secret : null;
22744
- },
22745
- async put(ref, secret) {
22746
- const safeRef = safeCredentialRef(ref);
22747
- const value = asTrimmedString(secret);
22748
- if (!value) {
22749
- throw new Error("Cannot store an empty credential secret.");
22750
- }
22751
- const service4 = serviceFor(safeRef);
22752
- const stdin = `${value}
22753
- ${value}
22754
- `;
22755
- let result4;
22756
- try {
22757
- result4 = await runner({
22758
- args: [
22759
- "add-generic-password",
22760
- "-a",
22761
- account,
22762
- "-s",
22763
- service4,
22764
- "-U",
22765
- "-w"
22766
- ],
22767
- stdin
22768
- });
22769
- } catch (error) {
22770
- rethrowBrokerError("put", error);
22771
- }
22772
- if (result4.exitCode !== 0) {
22773
- rethrowBrokerError("put");
22774
- }
22775
- },
22776
- async delete(ref) {
22777
- const safeRef = safeCredentialRef(ref);
22778
- const service4 = serviceFor(safeRef);
22779
- let result4;
22780
- try {
22781
- result4 = await runner({
22782
- args: [
22783
- "delete-generic-password",
22784
- "-a",
22785
- account,
22786
- "-s",
22787
- service4
22788
- ]
22789
- });
22790
- } catch (error) {
22791
- rethrowBrokerError("delete", error);
22792
- }
22793
- if (result4.exitCode === 0 || result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22794
- return;
22795
- }
22796
- rethrowBrokerError("delete");
22797
- },
22798
- async has(ref) {
22799
- const safeRef = safeCredentialRef(ref);
22800
- const service4 = serviceFor(safeRef);
22801
- let result4;
22802
- try {
22803
- result4 = await runner({
22804
- args: [
22805
- "find-generic-password",
22806
- "-a",
22807
- account,
22808
- "-s",
22809
- service4
22810
- ]
22811
- });
22812
- } catch (error) {
22813
- rethrowBrokerError("has", error);
22814
- }
22815
- if (result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22816
- return false;
22817
- }
22818
- if (result4.exitCode !== 0) {
22819
- rethrowBrokerError("has");
22820
- }
22821
- return true;
22822
- }
22823
- };
22824
- }
22825
-
22826
- // packages/agent-runtime/windowsCredentialManagerBroker.ts
22827
- import { spawn as spawn3 } from "node:child_process";
22828
- var WINDOWS_CREDENTIAL_TARGET_PREFIX = "nolo.credentials.keys";
22829
- var WIN_ERROR_NOT_FOUND = 1168;
22830
- var WINDOWS_CREDENTIAL_MANAGER_SCRIPT = `
22831
- $ErrorActionPreference = 'Stop'
22832
- try {
22833
- $raw = [Console]::In.ReadToEnd()
22834
- if ([string]::IsNullOrWhiteSpace($raw)) { exit 1 }
22835
- $req = $raw | ConvertFrom-Json
22836
- $op = [string]$req.op
22837
- $target = [string]$req.target
22838
- if ([string]::IsNullOrWhiteSpace($op) -or [string]::IsNullOrWhiteSpace($target)) { exit 1 }
22839
-
22840
- Add-Type @"
22841
- using System;
22842
- using System.Runtime.InteropServices;
22843
- using System.Text;
22844
-
22845
- public class NoloCredNative {
22846
- public const int CRED_TYPE_GENERIC = 1;
22847
- public const int CRED_PERSIST_LOCAL_MACHINE = 2;
22848
- public const int ERROR_NOT_FOUND = 1168;
22849
-
22850
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
22851
- public struct CREDENTIAL {
22852
- public int Flags;
22853
- public int Type;
22854
- public string TargetName;
22855
- public string Comment;
22856
- public long LastWritten;
22857
- public int CredentialBlobSize;
22858
- public IntPtr CredentialBlob;
22859
- public int Persist;
22860
- public int AttributeCount;
22861
- public IntPtr Attributes;
22862
- public string TargetAlias;
22863
- public string UserName;
22864
- }
22865
-
22866
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22867
- public static extern bool CredWriteW(ref CREDENTIAL userCredential, uint flags);
22868
-
22869
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22870
- public static extern bool CredReadW(string target, int type, int reservedFlag, out IntPtr credentialPtr);
22871
-
22872
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22873
- public static extern bool CredDeleteW(string target, int type, int flags);
22874
-
22875
- [DllImport("advapi32.dll", SetLastError = true)]
22876
- public static extern void CredFree(IntPtr buffer);
22877
- }
22878
- "@
22879
-
22880
- if ($op -eq 'get') {
22881
- $ptr = [IntPtr]::Zero
22882
- $ok = [NoloCredNative]::CredReadW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0, [ref]$ptr)
22883
- if (-not $ok) {
22884
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22885
- }
22886
- try {
22887
- $cred = [Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [type][NoloCredNative+CREDENTIAL])
22888
- if ($cred.CredentialBlobSize -le 0 -or $cred.CredentialBlob -eq [IntPtr]::Zero) {
22889
- $payload = @{ secret = '' } | ConvertTo-Json -Compress
22890
- [Console]::Out.Write($payload)
22891
- exit 0
22892
- }
22893
- $bytes = New-Object byte[] $cred.CredentialBlobSize
22894
- [Runtime.InteropServices.Marshal]::Copy($cred.CredentialBlob, $bytes, 0, $cred.CredentialBlobSize)
22895
- $secret = [Text.Encoding]::UTF8.GetString($bytes)
22896
- $payload = @{ secret = $secret } | ConvertTo-Json -Compress
22897
- [Console]::Out.Write($payload)
22898
- exit 0
22899
- } finally {
22900
- [NoloCredNative]::CredFree($ptr)
22901
- }
22902
- }
22903
-
22904
- if ($op -eq 'has') {
22905
- $ptr = [IntPtr]::Zero
22906
- $ok = [NoloCredNative]::CredReadW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0, [ref]$ptr)
22907
- if (-not $ok) {
22908
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22909
- }
22910
- [NoloCredNative]::CredFree($ptr)
22911
- exit 0
22912
- }
22913
-
22914
- if ($op -eq 'put') {
22915
- $secret = [string]$req.secret
22916
- if ([string]::IsNullOrEmpty($secret)) { exit 1 }
22917
- $blob = [Text.Encoding]::UTF8.GetBytes($secret)
22918
- $cred = New-Object NoloCredNative+CREDENTIAL
22919
- $cred.Type = [NoloCredNative]::CRED_TYPE_GENERIC
22920
- $cred.TargetName = $target
22921
- $cred.UserName = 'api-key'
22922
- $cred.Persist = [NoloCredNative]::CRED_PERSIST_LOCAL_MACHINE
22923
- $cred.CredentialBlobSize = $blob.Length
22924
- $cred.CredentialBlob = [Runtime.InteropServices.Marshal]::AllocHGlobal($blob.Length)
22925
- try {
22926
- if ($blob.Length -gt 0) {
22927
- [Runtime.InteropServices.Marshal]::Copy($blob, 0, $cred.CredentialBlob, $blob.Length)
22928
- }
22929
- $ok = [NoloCredNative]::CredWriteW([ref]$cred, 0)
22930
- if (-not $ok) {
22931
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22932
- }
22933
- exit 0
22934
- } finally {
22935
- [Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
22936
- }
22937
- }
22938
-
22939
- if ($op -eq 'delete') {
22940
- $ok = [NoloCredNative]::CredDeleteW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0)
22941
- if (-not $ok) {
22942
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22943
- }
22944
- exit 0
22945
- }
22946
-
22947
- exit 1
22948
- } catch {
22949
- exit 1
22950
- }
22951
- `.trim();
22952
- function safeCredentialRef2(ref) {
22953
- try {
22954
- return assertCredentialRef(ref);
22955
- } catch {
22956
- throw new Error("invalid_ref");
22957
- }
22958
- }
22959
- function credentialRefToWindowsCredentialTarget(ref, targetPrefix = WINDOWS_CREDENTIAL_TARGET_PREFIX) {
22960
- const safe = safeCredentialRef2(ref);
22961
- const hex = Buffer.from(safe, "utf8").toString("hex");
22962
- if (!hex) {
22963
- throw new Error("invalid_ref");
22964
- }
22965
- return `${targetPrefix}.${hex}`;
22966
- }
22967
- function rethrowBrokerError2(op, _error) {
22968
- throw new Error(`credential_broker_${op}_failed`);
22969
- }
22970
- function buildWindowsCredentialPowerShellArgs(script = WINDOWS_CREDENTIAL_MANAGER_SCRIPT) {
22971
- const encoded = Buffer.from(script, "utf16le").toString("base64");
22972
- return [
22973
- "-NoProfile",
22974
- "-NonInteractive",
22975
- "-ExecutionPolicy",
22976
- "Bypass",
22977
- "-EncodedCommand",
22978
- encoded
22979
- ];
22980
- }
22981
- function requestStdin(payload) {
22982
- return JSON.stringify(payload);
22983
- }
22984
- function parseGetSecretFromStdout(stdout) {
22985
- const trimmed = asTrimmedString(stdout);
22986
- if (!trimmed) {
22987
- rethrowBrokerError2("get");
22988
- }
22989
- let parsed;
22990
- try {
22991
- parsed = JSON.parse(trimmed);
22992
- } catch {
22993
- rethrowBrokerError2("get");
22994
- }
22995
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || typeof parsed.secret !== "string") {
22996
- rethrowBrokerError2("get");
22997
- }
22998
- return parsed.secret;
22999
- }
23000
- function spawnShell(bin, args2, stdin) {
23001
- return new Promise((resolve7) => {
23002
- let settled = false;
23003
- const finish = (result4) => {
23004
- if (settled) return;
23005
- settled = true;
23006
- resolve7(result4);
23007
- };
23008
- let child;
23009
- try {
23010
- child = spawn3(bin, args2, {
23011
- stdio: ["pipe", "pipe", "pipe"],
23012
- windowsHide: true
23013
- });
23014
- } catch {
23015
- finish({ exitCode: -1, stdout: "", stderr: "" });
23016
- return;
23017
- }
23018
- let stdout = "";
23019
- let stderr = "";
23020
- child.stdout?.setEncoding("utf8");
23021
- child.stderr?.setEncoding("utf8");
23022
- child.stdout?.on("data", (chunk) => {
23023
- stdout += chunk;
23024
- });
23025
- child.stderr?.on("data", (chunk) => {
23026
- stderr += chunk;
23027
- });
23028
- child.on("error", () => {
23029
- finish({ exitCode: -1, stdout: "", stderr: "" });
23030
- });
23031
- child.on("close", (code) => {
23032
- finish({
23033
- exitCode: typeof code === "number" ? code : -1,
23034
- stdout,
23035
- stderr
23036
- });
23037
- });
23038
- if (stdin !== void 0) {
23039
- child.stdin?.write(stdin);
23040
- }
23041
- child.stdin?.end();
23042
- });
23043
- }
23044
- function createDefaultWindowsCredentialRunner(shellBin) {
23045
- let resolvedBin = shellBin ?? null;
23046
- return async function defaultWindowsCredentialRunner(input) {
23047
- if (resolvedBin) {
23048
- return spawnShell(resolvedBin, input.args, input.stdin);
23049
- }
23050
- const first = await spawnShell("powershell.exe", input.args, input.stdin);
23051
- if (first.exitCode !== -1) {
23052
- resolvedBin = "powershell.exe";
23053
- return first;
23054
- }
23055
- const second = await spawnShell("pwsh", input.args, input.stdin);
23056
- if (second.exitCode !== -1) {
23057
- resolvedBin = "pwsh";
23058
- }
23059
- return second;
23060
- };
23061
- }
23062
- function createWindowsCredentialManagerBroker(options = {}) {
23063
- const runner = options.runner ?? createDefaultWindowsCredentialRunner(options.shellBin);
23064
- const targetPrefix = options.targetPrefix ?? WINDOWS_CREDENTIAL_TARGET_PREFIX;
23065
- const targetFor = (ref) => credentialRefToWindowsCredentialTarget(ref, targetPrefix);
23066
- const staticArgs = buildWindowsCredentialPowerShellArgs();
23067
- return {
23068
- async get(ref) {
23069
- const safeRef = safeCredentialRef2(ref);
23070
- const target = targetFor(safeRef);
23071
- let result4;
23072
- try {
23073
- result4 = await runner({
23074
- args: staticArgs,
23075
- stdin: requestStdin({ op: "get", target })
23076
- });
23077
- } catch (error) {
23078
- rethrowBrokerError2("get", error);
23079
- }
23080
- if (result4.exitCode === WIN_ERROR_NOT_FOUND) {
23081
- return null;
23082
- }
23083
- if (result4.exitCode !== 0) {
23084
- rethrowBrokerError2("get");
23085
- }
23086
- const secret = parseGetSecretFromStdout(result4.stdout);
23087
- return secret.length > 0 ? secret : null;
23088
- },
23089
- async put(ref, secret) {
23090
- const safeRef = safeCredentialRef2(ref);
23091
- const value = asTrimmedString(secret);
23092
- if (!value) {
23093
- throw new Error("Cannot store an empty credential secret.");
23094
- }
23095
- const target = targetFor(safeRef);
23096
- let result4;
23097
- try {
23098
- result4 = await runner({
23099
- args: staticArgs,
23100
- stdin: requestStdin({ op: "put", target, secret: value })
23101
- });
23102
- } catch (error) {
23103
- rethrowBrokerError2("put", error);
23104
- }
23105
- if (result4.exitCode !== 0) {
23106
- rethrowBrokerError2("put");
23107
- }
23108
- },
23109
- async delete(ref) {
23110
- const safeRef = safeCredentialRef2(ref);
23111
- const target = targetFor(safeRef);
23112
- let result4;
23113
- try {
23114
- result4 = await runner({
23115
- args: staticArgs,
23116
- stdin: requestStdin({ op: "delete", target })
23117
- });
23118
- } catch (error) {
23119
- rethrowBrokerError2("delete", error);
23120
- }
23121
- if (result4.exitCode === 0 || result4.exitCode === WIN_ERROR_NOT_FOUND) {
23122
- return;
23123
- }
23124
- rethrowBrokerError2("delete");
23125
- },
23126
- async has(ref) {
23127
- const safeRef = safeCredentialRef2(ref);
23128
- const target = targetFor(safeRef);
23129
- let result4;
23130
- try {
23131
- result4 = await runner({
23132
- args: staticArgs,
23133
- stdin: requestStdin({ op: "has", target })
23134
- });
23135
- } catch (error) {
23136
- rethrowBrokerError2("has", error);
23137
- }
23138
- if (result4.exitCode === WIN_ERROR_NOT_FOUND) {
23139
- return false;
23140
- }
23141
- if (result4.exitCode !== 0) {
23142
- rethrowBrokerError2("has");
23143
- }
23144
- return true;
23145
- }
23146
- };
23147
- }
23148
-
23149
- // packages/agent-runtime/linuxSecretServiceCredentialBroker.ts
23150
- import { spawn as spawn4 } from "node:child_process";
23151
- var LINUX_SECRET_SERVICE_ATTRIBUTE = "nolo-credential";
23152
- var SECRET_TOOL_NO_MATCH_EXIT = 1;
23153
- var DEFAULT_SECRET_TOOL_BIN = "secret-tool";
23154
- function safeCredentialRef3(ref) {
23155
- try {
23156
- return assertCredentialRef(ref);
23157
- } catch {
23158
- throw new Error("invalid_ref");
23159
- }
23160
- }
23161
- function brokerFailure(op) {
23162
- throw new Error(`credential_broker_${op}_failed`);
23163
- }
23164
- function createDefaultSecretToolRunner(secretToolBin = DEFAULT_SECRET_TOOL_BIN) {
23165
- return (input) => new Promise((resolve7) => {
23166
- let stdout = "";
23167
- let stderr = "";
23168
- let settled = false;
23169
- const finish = (result4) => {
23170
- if (settled) return;
23171
- settled = true;
23172
- resolve7(result4);
23173
- };
23174
- let child;
23175
- try {
23176
- child = spawn4(secretToolBin, input.args, {
23177
- stdio: ["pipe", "pipe", "pipe"]
23178
- });
23179
- } catch {
23180
- finish({ exitCode: -1, stdout: "", stderr: "" });
23181
- return;
23182
- }
23183
- child.stdout?.on("data", (chunk) => {
23184
- stdout += chunk;
23185
- });
23186
- child.stderr?.on("data", (chunk) => {
23187
- stderr += chunk;
23188
- });
23189
- child.on("error", () => {
23190
- finish({ exitCode: -1, stdout: "", stderr: "" });
23191
- });
23192
- child.on("close", (code) => {
23193
- finish({
23194
- exitCode: typeof code === "number" ? code : -1,
23195
- stdout,
23196
- stderr
23197
- });
23198
- });
23199
- if (input.stdin !== void 0) {
23200
- child.stdin?.write(input.stdin);
23201
- }
23202
- child.stdin?.end();
23203
- });
23204
- }
23205
- function createLinuxSecretServiceCredentialBroker(options = {}) {
23206
- const runner = options.runner ?? createDefaultSecretToolRunner(options.secretToolBin);
23207
- const attribute = options.attribute ?? LINUX_SECRET_SERVICE_ATTRIBUTE;
23208
- const attrArgs = (ref) => [attribute, ref];
23209
- const lookup3 = async (ref) => {
23210
- try {
23211
- return await runner({ args: ["lookup", ...attrArgs(ref)] });
23212
- } catch {
23213
- brokerFailure("get");
23214
- }
23215
- };
23216
- return {
23217
- async get(ref) {
23218
- const safeRef = safeCredentialRef3(ref);
23219
- const result4 = await lookup3(safeRef);
23220
- if (result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) return null;
23221
- if (result4.exitCode !== 0) brokerFailure("get");
23222
- const secret = result4.stdout.replace(/\n$/, "");
23223
- return secret.length > 0 ? secret : null;
23224
- },
23225
- async put(ref, secret) {
23226
- const safeRef = safeCredentialRef3(ref);
23227
- const value = asTrimmedString(secret);
23228
- if (!value) {
23229
- throw new Error("Cannot store an empty credential secret.");
23230
- }
23231
- const args2 = [
23232
- "store",
23233
- `--label=nolo-credential:${safeRef}`,
23234
- ...attrArgs(safeRef)
23235
- ];
23236
- if (value.includes("\n") || args2.some((arg) => arg.includes(value))) {
23237
- brokerFailure("put");
23238
- }
23239
- let result4;
23240
- try {
23241
- result4 = await runner({ args: args2, stdin: value });
23242
- } catch {
23243
- brokerFailure("put");
23244
- }
23245
- if (result4.exitCode !== 0) brokerFailure("put");
23246
- },
23247
- async delete(ref) {
23248
- const safeRef = safeCredentialRef3(ref);
23249
- let result4;
23250
- try {
23251
- result4 = await runner({ args: ["clear", ...attrArgs(safeRef)] });
23252
- } catch {
23253
- brokerFailure("delete");
23254
- }
23255
- if (result4.exitCode === 0 || result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) {
23256
- return;
23257
- }
23258
- brokerFailure("delete");
23259
- },
23260
- async has(ref) {
23261
- const safeRef = safeCredentialRef3(ref);
23262
- const result4 = await lookup3(safeRef);
23263
- if (result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) return false;
23264
- if (result4.exitCode !== 0) brokerFailure("has");
23265
- return true;
23266
- }
23267
- };
23268
- }
23269
-
23270
- // packages/agent-runtime/desktopHostCredentialBroker.ts
23271
- function createClosedCredentialBroker(code = "credential_store_unavailable") {
23272
- const fail9 = () => {
23273
- throw new Error(code);
23274
- };
23275
- return {
23276
- get: fail9,
23277
- put: fail9,
23278
- delete: fail9,
23279
- has: () => false
23280
- };
23281
- }
23282
- function createHostCredentialBrokerChain(args2) {
23283
- const { strict, session, legacy, notifySessionFallback, notifyLegacyHit } = args2;
23284
- const legacyNoticed = /* @__PURE__ */ new Set();
23285
- let sessionNotified = false;
23286
- const noticeSession = () => {
23287
- if (sessionNotified || !notifySessionFallback) return;
23288
- sessionNotified = true;
23289
- try {
23290
- notifySessionFallback();
23291
- } catch {
23292
- }
23293
- };
23294
- return {
23295
- async get(ref) {
23296
- try {
23297
- const strictValue = await strict.get(ref);
23298
- if (strictValue !== null && strictValue !== void 0) return strictValue;
23299
- } catch {
23300
- }
23301
- const sessionValue = await session.get(ref);
23302
- if (sessionValue !== null && sessionValue !== void 0) return sessionValue;
23303
- if (!legacy) return null;
23304
- const legacyValue = await legacy.get(ref);
23305
- if (legacyValue !== null && legacyValue !== void 0) {
23306
- if (notifyLegacyHit && !legacyNoticed.has(ref)) {
23307
- legacyNoticed.add(ref);
23308
- try {
23309
- notifyLegacyHit(ref);
23310
- } catch {
23311
- }
23312
- }
23313
- return legacyValue;
23314
- }
23315
- return null;
23316
- },
23317
- async put(ref, secret) {
23318
- try {
23319
- await strict.put(ref, secret);
23320
- if (await strict.has(ref)) return;
23321
- } catch {
23322
- }
23323
- await session.put(ref, secret);
23324
- noticeSession();
23325
- },
23326
- async delete(ref) {
23327
- try {
23328
- await strict.delete(ref);
23329
- } catch {
23330
- }
23331
- try {
23332
- await session.delete(ref);
23333
- } catch {
23334
- }
23335
- if (legacy) await legacy.delete(ref);
23336
- },
23337
- async has(ref) {
23338
- try {
23339
- if (await strict.has(ref)) return true;
23340
- } catch {
23341
- }
23342
- if (await session.has(ref)) return true;
23343
- return legacy ? await legacy.has(ref) : false;
23344
- }
23345
- };
23346
- }
23347
- function createStrictHostCredentialBroker(options = {}) {
23348
- const platform = options.platform ?? process.platform;
23349
- const env = options.env ?? process.env;
23350
- const override = String(env.NOLO_DESKTOP_CREDENTIAL_STORE ?? "").trim().toLowerCase();
23351
- if (override === "file") {
23352
- return createClosedCredentialBroker("credential_store_file_not_allowed");
23353
- }
23354
- if (platform === "darwin" || override === "keychain") {
23355
- return options.keychainBroker ?? (options.createKeychainBroker ?? (() => createMacOsKeychainCredentialBroker()))();
23356
- }
23357
- if (platform === "win32" || override === "credman") {
23358
- return options.windowsCredentialBroker ?? (options.createWindowsCredentialBroker ?? (() => createWindowsCredentialManagerBroker()))();
23359
- }
23360
- if (platform === "linux" || override === "secret-service") {
23361
- return options.linuxSecretServiceBroker ?? (options.createLinuxSecretServiceBroker ?? (() => createLinuxSecretServiceCredentialBroker()))();
23362
- }
23363
- return createClosedCredentialBroker("credential_store_unsupported");
23364
- }
23365
-
23366
- // packages/agent-runtime/dialogMessageRecord.ts
23367
- function dialogMessageRecordToAgentRuntimeMessage(record2) {
23368
- if (!record2 || typeof record2 !== "object") return null;
23369
- if (record2.role !== "user" && record2.role !== "assistant" && record2.role !== "tool") return null;
23370
- return {
23371
- ...typeof record2.id === "string" ? { id: record2.id } : {},
23372
- role: record2.role,
23373
- ...Number.isFinite(record2.metadata?.cliHistoryOrder) ? { cliHistoryOrder: record2.metadata.cliHistoryOrder } : {},
23374
- content: record2.content ?? "",
23375
- ...record2.contextReference !== void 0 ? { context_reference: record2.contextReference } : {},
23376
- ...typeof record2.reasoning_content === "string" ? { reasoning_content: record2.reasoning_content } : {},
23377
- ...typeof record2.toolCallId === "string" ? { tool_call_id: record2.toolCallId } : {},
23378
- ...Array.isArray(record2.tool_calls) ? { tool_calls: record2.tool_calls } : {},
23379
- ...record2.toolPayload !== void 0 ? { toolPayload: record2.toolPayload } : {},
23380
- ...typeof record2.toolName === "string" ? { toolName: record2.toolName } : {},
23381
- // 写侧(dialogWritePlan)把 tool_result_metadata 以 `metadata` 字段落库;
23382
- // 回读必须还原,否则跨 turn 投影丢失 metadata 后缀,同一 tool 消息的字节
23383
- // 在 turn 边界漂移 → provider 前缀缓存断裂(stable projection 契约,
23384
- // 见 docs/plans/2026-09-05-tool-output-cache-stability.md)。
23385
- ...record2.metadata && typeof record2.metadata === "object" ? { tool_result_metadata: record2.metadata } : {},
23386
- ...(() => {
23387
- const raw = record2.createdAt;
23388
- const ms = typeof raw === "number" ? raw : typeof raw === "string" ? Date.parse(raw) : NaN;
23389
- return Number.isFinite(ms) ? { createdAt: ms } : {};
23390
- })()
23391
- };
23392
- }
23393
-
23394
- // packages/agent-runtime/dialogWritePlan.ts
23395
- function extractLastUserText(messages) {
23396
- const lastUser = [...messages].reverse().find((message) => message.role === "user");
23397
- if (typeof lastUser?.content === "string") return lastUser.content;
23398
- if (Array.isArray(lastUser?.content)) {
23399
- return lastUser.content.filter((part) => part.type === "text").map((part) => part.text).join(" ");
23400
- }
23401
- return "";
23114
+ return "";
23402
23115
  }
23403
23116
  function resolveDialogTitle(args2) {
23404
23117
  const existing = args2.existingDialog?.title;
@@ -24147,7 +23860,7 @@ async function saveCliPendingUserMessages(args2) {
24147
23860
  if (ops.length) await args2.store.batch(ops);
24148
23861
  }
24149
23862
  async function readCliPendingUserMessages(store, dialogId) {
24150
- const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-H3HYQRRR.js");
23863
+ const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-MCQVRWBR.js");
24151
23864
  const rows = await readDialogMessageRecords({ store, dialogId });
24152
23865
  const uncertain = rows.filter(({ record: record2 }) => record2.metadata?.cliBatchPhase === "requested" && !record2.metadata?.cliBatchResolution);
24153
23866
  const recovery = uncertain.length ? {
@@ -24246,15 +23959,15 @@ async function readNoloProcessStream(readable) {
24246
23959
  async function runNoloWorkspaceCliTool(call, args2) {
24247
23960
  const cliArgs = buildNoloWorkspaceCommandArgs(call);
24248
23961
  const bunSpawn = globalThis.Bun?.spawn;
24249
- const spawn5 = args2.spawn ?? (typeof bunSpawn === "function" ? bunSpawn : nodeSpawnFallback);
23962
+ const spawn2 = args2.spawn ?? (typeof bunSpawn === "function" ? bunSpawn : nodeSpawnFallback);
24250
23963
  const execPath = args2.processExecPath ?? process.execPath;
24251
23964
  const entrypoint = args2.cliEntrypoint;
24252
23965
  const cmd = entrypoint && entrypoint !== execPath ? [execPath, entrypoint, ...cliArgs] : [execPath, ...cliArgs];
24253
- const proc = spawn5({
23966
+ const proc = spawn2({
24254
23967
  cmd,
24255
23968
  stdout: "pipe",
24256
23969
  stderr: "pipe",
24257
- 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)
24258
23971
  });
24259
23972
  const [stdout, stderr, exitCode] = await Promise.all([
24260
23973
  readNoloProcessStream(proc.stdout),
@@ -24276,7 +23989,15 @@ async function runNoloWorkspaceCliTool(call, args2) {
24276
23989
  }
24277
23990
  };
24278
23991
  }
24279
- 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) {
24280
24001
  const args2 = parseNoloWorkspaceToolArguments(call.arguments);
24281
24002
  const dialogInput = noloStringArg(args2.dialog ?? args2.dialogId ?? args2.id);
24282
24003
  if (!dialogInput) throw new Error("readDialog requires dialog.");
@@ -24284,9 +24005,18 @@ async function readDialogInProcess(call, store, env) {
24284
24005
  if (mode && mode !== "full" && mode !== "status") {
24285
24006
  throw new Error(`readDialog mode must be "full" or "status", got "${mode}".`);
24286
24007
  }
24287
- const userId = noloStringArg(args2.user ?? args2.userId ?? args2.owner) || env?.NOLO_LOCAL_USER_ID || env?.NOLO_USER_ID || "";
24288
- const { dbKey: dialogKey, dialogId } = resolveNoloDialogInput(dialogInput, userId);
24289
- 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
+ }
24290
24020
  if (mode === "status") {
24291
24021
  const result4 = {
24292
24022
  dialogId,
@@ -24297,8 +24027,11 @@ async function readDialogInProcess(call, store, env) {
24297
24027
  source: "in-process"
24298
24028
  };
24299
24029
  return {
24300
- content: JSON.stringify(result4, null, 2),
24301
- 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
+ }
24302
24035
  };
24303
24036
  }
24304
24037
  const limitNum = noloPositiveIntegerString(args2.limit);
@@ -24307,15 +24040,18 @@ async function readDialogInProcess(call, store, env) {
24307
24040
  maxResponseChars: DEFAULT_READ_DIALOG_MAX_RESPONSE_CHARS,
24308
24041
  ...limit !== void 0 ? { maxMessages: limit } : {}
24309
24042
  });
24043
+ let hasMessages = false;
24310
24044
  if (store.iterator) {
24311
24045
  const { start, end: end3 } = dialogMessageRange(dialogId);
24312
24046
  for await (const [, value] of store.iterator({ gte: start, lte: end3 })) {
24313
24047
  const message = localDialogMessageRecordToRuntimeMessage(value) ?? value;
24314
24048
  if (message) {
24049
+ hasMessages = true;
24315
24050
  projector.addMessage(message);
24316
24051
  }
24317
24052
  }
24318
24053
  }
24054
+ if (!hasMessages) return fallback("no-local-messages");
24319
24055
  const projected = projector.finish(meta);
24320
24056
  const built = buildDialogReadEnvelope({
24321
24057
  meta: projected.meta,
@@ -24329,22 +24065,83 @@ async function readDialogInProcess(call, store, env) {
24329
24065
  }
24330
24066
  });
24331
24067
  return {
24332
- content: built.serialized,
24333
- 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
+ }
24334
24073
  };
24335
24074
  }
24336
24075
  function buildNoloWorkspaceCliToolExecutors(args2) {
24337
24076
  const executors = {};
24338
24077
  for (const toolName of CLI_NOLO_WORKSPACE_TOOL_NAMES) {
24339
24078
  if (toolName === "loadSkill") continue;
24340
- if (toolName === "readDialog" && args2.store) {
24341
- 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);
24342
24083
  continue;
24343
24084
  }
24344
24085
  executors[toolName] = (call) => runNoloWorkspaceCliTool(call, args2);
24345
24086
  }
24346
24087
  return executors;
24347
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
+ }
24348
24145
  var nodeSpawnFallback = (options) => {
24349
24146
  return spawnToWebStreams({ cmd: options.cmd, env: options.env });
24350
24147
  };
@@ -24362,10 +24159,10 @@ function buildLoadSkillExecutor(args2) {
24362
24159
  metadata: { loadSkill: true, resolved: false }
24363
24160
  };
24364
24161
  }
24365
- const { resolveSkillByName } = await import("./skillDiscovery-BHHPCUHZ.js");
24162
+ const { resolveSkillByName } = await import("./skillDiscovery-MDDKPTW3.js");
24366
24163
  const resolved = resolveSkillByName(args2.cwd, name);
24367
24164
  if (!resolved) {
24368
- const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-BAE2LDXF.js");
24165
+ const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-VRCMQ77Q.js");
24369
24166
  const builtin = resolveBuiltinSkillByName(name);
24370
24167
  if (builtin) {
24371
24168
  const denied = await rejectDisabledBuiltin(args2.agentSkillSource, builtin.slug, name, args2.resolveAgentSkillSource);
@@ -24444,7 +24241,7 @@ async function loadPreciseSkill(cwd, parsed, agentSkillSource, resolveAgentSkill
24444
24241
  if (!nonEmpty(parsed.slug) || has2("projectBinding") || has2("relativePath")) {
24445
24242
  return reject("builtin requires only an exact slug.");
24446
24243
  }
24447
- const { listBuiltinSkills } = await import("./builtinSkillRegistry-BAE2LDXF.js");
24244
+ const { listBuiltinSkills } = await import("./builtinSkillRegistry-VRCMQ77Q.js");
24448
24245
  const builtin = listBuiltinSkills().find((entry) => entry.slug === parsed.slug);
24449
24246
  if (!builtin) return reject("builtin slug not found.");
24450
24247
  const denied = await rejectDisabledBuiltin(agentSkillSource, builtin.slug, builtin.slug, resolveAgentSkillSource);
@@ -24469,28 +24266,28 @@ ${builtin.content}`,
24469
24266
  return reject("project requires projectBinding and relativePath only.");
24470
24267
  }
24471
24268
  try {
24472
- const { realpathSync, statSync, readFileSync: readFileSync2 } = await import("node:fs");
24473
- const { resolve: resolve7, 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");
24474
24271
  const inside = (root, target) => {
24475
- const rel = relative6(root, target);
24476
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute5(rel);
24272
+ const rel = relative7(root, target);
24273
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute6(rel);
24477
24274
  };
24478
- const realCwd = realpathSync(cwd);
24479
- if (!isAbsolute5(parsed.projectBinding) || realpathSync(parsed.projectBinding) !== realCwd) {
24275
+ const realCwd = realpathSync2(cwd);
24276
+ if (!isAbsolute6(parsed.projectBinding) || realpathSync2(parsed.projectBinding) !== realCwd) {
24480
24277
  return reject("projectBinding does not match the authorized cwd.");
24481
24278
  }
24482
- if (isAbsolute5(parsed.relativePath) || basename4(parsed.relativePath) !== "SKILL.md") {
24279
+ if (isAbsolute6(parsed.relativePath) || basename4(parsed.relativePath) !== "SKILL.md") {
24483
24280
  return reject("relativePath must reference a project SKILL.md.");
24484
24281
  }
24485
24282
  const skillsRoot = resolve7(realCwd, ".agents", "skills");
24486
24283
  const candidate = resolve7(realCwd, parsed.relativePath);
24487
24284
  if (!inside(skillsRoot, candidate)) return reject("path is outside cwd/.agents/skills/.");
24488
- const realRoot = realpathSync(skillsRoot);
24489
- const realPath = realpathSync(candidate);
24285
+ const realRoot = realpathSync2(skillsRoot);
24286
+ const realPath = realpathSync2(candidate);
24490
24287
  if (realRoot !== skillsRoot || !inside(realRoot, realPath) || basename4(realPath) !== "SKILL.md") {
24491
24288
  return reject("skill path escapes cwd/.agents/skills/ or is not SKILL.md.");
24492
24289
  }
24493
- if (!statSync(realPath).isFile()) return reject("SKILL.md is not a file.");
24290
+ if (!statSync2(realPath).isFile()) return reject("SKILL.md is not a file.");
24494
24291
  const body = readFileSync2(realPath, "utf8");
24495
24292
  return {
24496
24293
  content: `Skill "${parsed.relativePath}" loaded inline. Follow its instructions.
@@ -24510,7 +24307,7 @@ ${body}`,
24510
24307
  }
24511
24308
  }
24512
24309
  async function formatUnknownSkillMessage(cwd, requestedName) {
24513
- const { discoverSkills } = await import("./skillDiscovery-BHHPCUHZ.js");
24310
+ const { discoverSkills } = await import("./skillDiscovery-MDDKPTW3.js");
24514
24311
  let available = [];
24515
24312
  try {
24516
24313
  available = discoverSkills(cwd).map((s) => s.name);
@@ -25082,17 +24879,17 @@ function createDevinProvider(options) {
25082
24879
  }
25083
24880
 
25084
24881
  // packages/agent-runtime/executionLeaseValidation.ts
25085
- import { isAbsolute as isAbsolute4, relative as relative5, resolve as resolve6 } from "node:path";
24882
+ import { isAbsolute as isAbsolute5, relative as relative6, resolve as resolve6 } from "node:path";
25086
24883
  function withinRoot(root, child) {
25087
- if (!isAbsolute4(root) || !isAbsolute4(child)) return false;
24884
+ if (!isAbsolute5(root) || !isAbsolute5(child)) return false;
25088
24885
  const canonicalRoot = resolve6(root);
25089
24886
  const canonicalChild = resolve6(child);
25090
- const suffix = relative5(canonicalRoot, canonicalChild);
25091
- return suffix === "" || suffix !== ".." && !suffix.startsWith("../") && !suffix.startsWith("..\\") && !isAbsolute4(suffix);
24887
+ const suffix = relative6(canonicalRoot, canonicalChild);
24888
+ return suffix === "" || suffix !== ".." && !suffix.startsWith("../") && !suffix.startsWith("..\\") && !isAbsolute5(suffix);
25092
24889
  }
25093
24890
  function subsetOf(allowed, actual) {
25094
24891
  return actual.every(
25095
- (root) => isAbsolute4(root) && allowed.some((parent) => withinRoot(parent, root))
24892
+ (root) => isAbsolute5(root) && allowed.some((parent) => withinRoot(parent, root))
25096
24893
  );
25097
24894
  }
25098
24895
  function validateConfiguredRootExecutionLease(ticket, lease) {
@@ -25149,11 +24946,10 @@ function verifyOwnerRouteAck(headers, expectedRequestId) {
25149
24946
  }
25150
24947
 
25151
24948
  export {
25152
- createHostCredentialBrokerChain,
25153
- createStrictHostCredentialBroker,
25154
24949
  readCommandActionGatePayload,
25155
24950
  readActionGate,
25156
24951
  orderDialogHistory,
24952
+ dialogTurnUserMessageId,
25157
24953
  Option_exports,
25158
24954
  Duration_exports,
25159
24955
  Exit_exports,
@@ -25184,6 +24980,12 @@ export {
25184
24980
  runExecShellGates,
25185
24981
  executeLocalToolWithPolicy,
25186
24982
  LOCAL_TURN_ABORTED_CODE,
24983
+ isSubtaskRun,
24984
+ RUN_WAKE_CHANNEL_ENV,
24985
+ hasRunWakeChannel,
24986
+ filterToolNamesForRunKind,
24987
+ findSummaryAnchorIndex,
24988
+ validateStoredSummary,
25187
24989
  projectContextProvenance,
25188
24990
  hashToolDefinitions,
25189
24991
  LOCAL_AGENT_CONFIG_MISSING_CODE,
@@ -25198,12 +25000,12 @@ export {
25198
25000
  executeOpenAiCompatibleChatCompletion,
25199
25001
  describeOpenAiCompatibleRequestBudget,
25200
25002
  resolveOpenAiCompatibleProviderConfig,
25201
- dialogMessageRecordToAgentRuntimeMessage,
25202
25003
  buildAgentRuntimeDialogWritePlan,
25203
25004
  shouldCacheHybridRemoteRecord,
25204
25005
  parseSyncServersEnv,
25205
25006
  DEFAULT_HYBRID_READ_TIMEOUT_MS,
25206
25007
  createHybridRecordStore,
25008
+ dialogOwnerKey,
25207
25009
  registerDialogOwner,
25208
25010
  localDialogMessageRecordToRuntimeMessage,
25209
25011
  buildLocalDialogWritePlan,