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,6 +1,16 @@
1
+ import {
2
+ confirmMcpOnHost,
3
+ createConnectorApprovalPort,
4
+ createMcpLocalRuntimeAdapter,
5
+ getHostApprovalRenderer,
6
+ openMcpLocalRuntimeManagement,
7
+ parsePendingApprovalResult,
8
+ runConnectorToolWithHostApproval,
9
+ withHostApprovalRequest
10
+ } from "./chunk-KLAMJNKQ.js";
1
11
  import {
2
12
  BROWSER_SHELL_BRIDGE_ENV
3
- } from "./chunk-2YGBI2XB.js";
13
+ } from "./chunk-FE7G6DSP.js";
4
14
  import {
5
15
  adoptRequiredClaudeCodeVersion,
6
16
  anthropicRefresh,
@@ -12,17 +22,12 @@ import {
12
22
  resolveClaudeCodeVersion,
13
23
  resolveServerSyncConfig,
14
24
  xaiRefresh
15
- } from "./chunk-XSW4EXQV.js";
25
+ } from "./chunk-6TVYUQRM.js";
16
26
  import {
17
27
  clearCredentialAvailability,
18
28
  markCredentialUnavailable,
19
29
  readCredentialEntry
20
30
  } from "./chunk-WWTSEBDF.js";
21
- import {
22
- DialogNotifyError,
23
- deliverDialogNotification,
24
- sha256Hex
25
- } from "./chunk-M4SFKP5L.js";
26
31
  import {
27
32
  SANDBOX_HELPER_PATH,
28
33
  SANDBOX_OUTPUT_LIMITS,
@@ -31,13 +36,13 @@ import {
31
36
  buildWorkspaceHelperSource,
32
37
  dockerExecutionToolNames,
33
38
  parseToolOutput
34
- } from "./chunk-HGDKT2D6.js";
39
+ } from "./chunk-VTHWBTRE.js";
35
40
  import {
36
41
  createChromeConnectorClientResolver,
37
42
  createVerifiedChromeConnectorClient,
38
43
  executeChromeConnectorTool,
39
44
  validateChromeConnectorPayload
40
- } from "./chunk-UAIHKQIA.js";
45
+ } from "./chunk-U6RD332P.js";
41
46
  import {
42
47
  customNativeAuthHeaders,
43
48
  detectDeclaredCustomNativeWire,
@@ -45,9 +50,14 @@ import {
45
50
  resolveCustomNativeApiKeyHeader,
46
51
  resolveCustomNativeEndpoint
47
52
  } from "./chunk-WOAZVUSN.js";
53
+ import {
54
+ DialogNotifyError,
55
+ deliverDialogNotification,
56
+ sha256Hex
57
+ } from "./chunk-OHUYN3YU.js";
48
58
  import {
49
59
  createTuiSummaryLlmCaller
50
- } from "./chunk-TSPMLCWI.js";
60
+ } from "./chunk-4IQN6FWY.js";
51
61
  import {
52
62
  CliProviderQuotaError,
53
63
  executeCli,
@@ -59,20 +69,10 @@ import {
59
69
  import {
60
70
  buildCliPrompt
61
71
  } from "./chunk-ATNTHIZI.js";
62
- import {
63
- extractLastUserText,
64
- localTurnHasSubjectRefs,
65
- resolveLocalUserId,
66
- withResolvedRuntimeToolSurface
67
- } from "./chunk-HHFGE2WF.js";
68
- import {
69
- inferCaptureIntent,
70
- resolveUserSkillRuntime
71
- } from "./chunk-ZXF6D3I6.js";
72
72
  import {
73
73
  inlineImageUrlsForCustomProvider,
74
74
  prepareTools
75
- } from "./chunk-OTKSESZR.js";
75
+ } from "./chunk-IIOSZAJX.js";
76
76
  import {
77
77
  getServerProviderSecret
78
78
  } from "./chunk-HS7MLR74.js";
@@ -95,20 +95,25 @@ import {
95
95
  resolveCliLocalSpawnDispatch,
96
96
  resolveRunContextFacts,
97
97
  resolveStartAgentRunCwd
98
- } from "./chunk-GAYNXB6T.js";
98
+ } from "./chunk-FTWAOKFU.js";
99
99
  import {
100
100
  deriveCredentialGroup,
101
101
  deriveCustomProviderCredentialGroup
102
- } from "./chunk-RRDRQOEC.js";
102
+ } from "./chunk-XCA4WHX5.js";
103
+ import {
104
+ resolveUserSkillRuntime
105
+ } from "./chunk-XSRSAU3O.js";
103
106
  import {
104
107
  normalizeEnabledPromptSkills,
105
108
  resolveUserEnabledSkills
106
- } from "./chunk-RBPUNSG5.js";
109
+ } from "./chunk-UOUMPHS5.js";
107
110
  import {
108
- prepareTokenUsageData,
109
- runKeyed,
110
111
  validateAskChoiceInput
111
- } from "./chunk-7BCG67EI.js";
112
+ } from "./chunk-ODBYGVO2.js";
113
+ import {
114
+ prepareTokenUsageData,
115
+ runKeyed
116
+ } from "./chunk-YFW4H6DL.js";
112
117
  import {
113
118
  applyTokenUsageToDayStats,
114
119
  require_format
@@ -119,22 +124,20 @@ import {
119
124
  } from "./chunk-523DITKR.js";
120
125
  import {
121
126
  fetchServerSyncedCredential
122
- } from "./chunk-WCFFRBL5.js";
127
+ } from "./chunk-N74XL3NI.js";
123
128
  import {
124
- defaultLoopbackRequest
125
- } from "./chunk-VP3BINY7.js";
129
+ defaultLoopbackRequest,
130
+ loadLocalRunChildDialogIds
131
+ } from "./chunk-CIGCTSBF.js";
126
132
  import {
127
133
  CREDENTIAL_STORE_SESSION_FALLBACK_WARNING,
128
134
  OAUTH_PROVIDER_REFS,
129
135
  getSharedSessionCredentialBroker
130
- } from "./chunk-TQEKUOTI.js";
136
+ } from "./chunk-CIUZXD5D.js";
131
137
  import {
132
138
  fetchWithTransientRetry,
133
139
  isTransientFetchError
134
140
  } from "./chunk-DXWGFL2Z.js";
135
- import {
136
- getDefaultCliLocalRuntimeDb
137
- } from "./chunk-N5Z2V73W.js";
138
141
  import {
139
142
  _readQueueEntriesLocked,
140
143
  ackRunRecord,
@@ -143,6 +146,7 @@ import {
143
146
  checkStaleRun,
144
147
  claimRunRecord,
145
148
  commitRunRecordClaim,
149
+ defaultGenerateRunId,
146
150
  findRunRecord,
147
151
  gcRunRecords,
148
152
  isRunTerminalStatus,
@@ -159,12 +163,7 @@ import {
159
163
  terminateRunProcess,
160
164
  transitionRunToTerminal,
161
165
  withQueueLock
162
- } from "./chunk-OWKNSIXL.js";
163
- import {
164
- remoteDialogSyncTimeout,
165
- resolveRuntimeAuthToken,
166
- resolveRuntimeServerUrl
167
- } from "./chunk-2X7WFDT6.js";
166
+ } from "./chunk-AEZBAFC6.js";
168
167
  import {
169
168
  TASK_PREVIEW_MAX,
170
169
  formatControlRunMessageCard,
@@ -181,21 +180,22 @@ import {
181
180
  resolveAgentRunName,
182
181
  resolveRunLabel,
183
182
  shortRunId
184
- } from "./chunk-OOJNQK6V.js";
183
+ } from "./chunk-S25VJYXV.js";
185
184
  import {
186
- isTombstoneRecord
187
- } from "./chunk-BV3FLP2L.js";
185
+ getDefaultCliLocalRuntimeDb
186
+ } from "./chunk-BFKJ2RS3.js";
188
187
  import {
189
188
  readAgentFromStore,
190
189
  readDialogMessageRecords,
191
190
  readDialogMessages,
192
191
  resolveBuiltinLocalCliAgentConfig
193
- } from "./chunk-TCZ2VJZQ.js";
192
+ } from "./chunk-7UVVLYKC.js";
194
193
  import {
195
- LOCAL_CODEX_AGENT_KEY,
196
- isLocalCliAgentKey,
197
- resolveCliAgentKeyInput
198
- } from "./chunk-BR3GT6MR.js";
194
+ applyPublicAgentCatalogOverride
195
+ } from "./chunk-MZVCFV3T.js";
196
+ import {
197
+ applyBuiltinAgentRuntimeOverride
198
+ } from "./chunk-JP2BH4NC.js";
199
199
  import {
200
200
  DEFAULT_HYBRID_READ_TIMEOUT_MS,
201
201
  Duration_exports,
@@ -212,25 +212,25 @@ import {
212
212
  buildNoloWorkspaceCliToolExecutors,
213
213
  codexStreamFailureStatus,
214
214
  createDevinProvider,
215
- createHostCredentialBrokerChain,
216
215
  createHybridRecordStore,
217
216
  createLocalWorkspaceToolExecutors,
218
217
  createResponsesStreamCollector,
219
- createStrictHostCredentialBroker,
220
218
  deriveStableUuid,
221
219
  describeOpenAiCompatibleRequestBudget,
222
- dialogMessageRecordToAgentRuntimeMessage,
223
220
  executeLocalToolWithPolicy,
224
221
  executeOpenAiCompatibleChatCompletion,
225
222
  filterRetainedLedgerRecords,
223
+ filterToolNamesForRunKind,
226
224
  getAgentRuntimeToolParametersIndex,
227
225
  getLocalShellLifecycle,
226
+ hasRunWakeChannel,
228
227
  hashToolDefinitions,
229
228
  internalListWorkspaceEntries,
230
229
  internalSearchWorkspace,
231
230
  isCommandExecutingTool,
232
231
  isLineRangeCovered,
233
232
  isStableSessionIdentityEnabled,
233
+ isSubtaskRun,
234
234
  normalizeLocalToolName,
235
235
  orderDialogHistory,
236
236
  parseSyncServersEnv,
@@ -246,11 +246,16 @@ import {
246
246
  runExecShellGates,
247
247
  validateConfiguredRootExecutionLease,
248
248
  verifyOwnerRouteAck
249
- } from "./chunk-3QIYD3VM.js";
249
+ } from "./chunk-XNTZD4AE.js";
250
+ import {
251
+ createHostCredentialBrokerChain,
252
+ createStrictHostCredentialBroker
253
+ } from "./chunk-LHCGKAFO.js";
250
254
  import {
251
255
  accumulateGeminiChunks,
252
256
  buildGeminiGenerateContentRequest,
253
257
  fetchAntigravityCloudCodeCompletion,
258
+ hasAssembledAgentPrompt,
254
259
  isGemini3Model,
255
260
  parseSseDataLineJson,
256
261
  parseSseDataLineObject,
@@ -258,7 +263,7 @@ import {
258
263
  resolveAntigravityFinishReason,
259
264
  resolveGeminiModelQuirks,
260
265
  shouldUseGeminiNativeToolRoute
261
- } from "./chunk-U2HBB7RS.js";
266
+ } from "./chunk-MYYNZG2M.js";
262
267
  import {
263
268
  readLocalImage
264
269
  } from "./chunk-AL3TYDIF.js";
@@ -273,24 +278,37 @@ import {
273
278
  readPlatformChatSseCompletion,
274
279
  resolvePlatformChatProviderConfig,
275
280
  shouldUsePlatformChatProvider
276
- } from "./chunk-HSSBDZLD.js";
281
+ } from "./chunk-EDT65EUE.js";
277
282
  import {
278
283
  readSseDataValues,
279
284
  readSseFrames
280
285
  } from "./chunk-HNUWUO75.js";
281
286
  import {
282
- resolveAgentImageInputSupport,
283
- resolveCatalogImageSupport,
284
- resolveToolImagePolicy,
285
- withLiveImageSupport
286
- } from "./chunk-DUUDXSLX.js";
287
+ resolveAgentRuntimeConfigFromRecord
288
+ } from "./chunk-4OXPN3WC.js";
289
+ import {
290
+ assertDispatchSelectionAdmission,
291
+ buildNoloWorkspaceOpenAiTools,
292
+ filterClientNoloWorkspaceToolNames,
293
+ parseNoloWorkspaceToolArguments
294
+ } from "./chunk-ITBX27W6.js";
295
+ import {
296
+ MCP_TOOL_NAMES
297
+ } from "./chunk-KXOPLLFP.js";
298
+ import {
299
+ extractQuotaSnapshot,
300
+ isCapacitySaturatedRateLimit,
301
+ mergeAvailabilityDeadline,
302
+ resolveAvailabilityAction,
303
+ resolveCredentialKeyWithFallback
304
+ } from "./chunk-QJTZ76CP.js";
287
305
  import {
288
306
  collectStablePromptPrefix,
289
307
  convertMessagesToResponsesInput,
290
308
  findAgentStatePairingIssues,
291
309
  stablePromptCacheKey,
292
310
  toResponsesTools
293
- } from "./chunk-EEOOBRA7.js";
311
+ } from "./chunk-W3HSD32M.js";
294
312
  import {
295
313
  EMPTY_TOOL_RESULT_TEXT,
296
314
  MAX_TOOL_IMAGES_PER_REQUEST,
@@ -303,32 +321,21 @@ import {
303
321
  toolImages
304
322
  } from "./chunk-X4O7FJF5.js";
305
323
  import {
306
- assertDispatchSelectionAdmission,
307
- buildNoloWorkspaceOpenAiTools,
308
- filterClientNoloWorkspaceToolNames,
309
- parseNoloWorkspaceToolArguments
310
- } from "./chunk-MNEZUL5S.js";
311
- import {
312
- extractQuotaSnapshot,
313
- isCapacitySaturatedRateLimit,
314
- mergeAvailabilityDeadline,
315
- resolveAvailabilityAction,
316
- resolveCredentialKeyWithFallback
317
- } from "./chunk-QJTZ76CP.js";
318
- import {
319
- HIGH_RISK_MUTATION_TOOL_NAMES,
320
- resolveRequestToolSurface
321
- } from "./chunk-VS276URX.js";
322
- import {
323
- resolveAgentCallPlan
324
- } from "./chunk-OBIC6EG7.js";
324
+ resolveAgentImageInputSupport,
325
+ resolveCatalogImageSupport,
326
+ resolveToolImagePolicy,
327
+ withLiveImageSupport
328
+ } from "./chunk-SX6AWTNK.js";
325
329
  import {
326
330
  resolveHistoricalToolContentCap
327
331
  } from "./chunk-WFGNWWJI.js";
332
+ import {
333
+ resolveAgentCallPlan
334
+ } from "./chunk-VUHKG4KS.js";
328
335
  import {
329
336
  resolveAgentRequiredPackIds,
330
337
  resolveAgentSkillConfig
331
- } from "./chunk-FJSNBZXR.js";
338
+ } from "./chunk-YDRRGVT5.js";
332
339
  import {
333
340
  buildDialogFallbackTitleFromUserInput,
334
341
  normalizeDialogTitle
@@ -342,13 +349,14 @@ import {
342
349
  isCodexOAuthAgent,
343
350
  markCodexOAuthCatalogFailure,
344
351
  resolveCodexOAuthEffectiveModel
345
- } from "./chunk-QRGDJA4B.js";
352
+ } from "./chunk-LTVEOOZL.js";
346
353
  import {
347
354
  isDevinOAuthAgent
348
355
  } from "./chunk-5ZUL4CUO.js";
349
356
  import {
350
- normalizeUsage
351
- } from "./chunk-L32W3PRP.js";
357
+ normalizeUsage,
358
+ sanitizeSummarySourceSegments
359
+ } from "./chunk-MAA42MMV.js";
352
360
  import {
353
361
  createProviderCallTimingTracker,
354
362
  finalizeProviderCallTiming,
@@ -367,27 +375,33 @@ import {
367
375
  resolveLocalWorkspaceExecutorOptionsFromPolicy,
368
376
  resolveRequestedRuntimeToolNames
369
377
  } from "./chunk-USGHJSGO.js";
370
- import {
371
- asRecordOrEmpty
372
- } from "./chunk-KX6YBIHG.js";
373
378
  import {
374
379
  createFileCredentialBroker
375
- } from "./chunk-OQHIVPG4.js";
380
+ } from "./chunk-E6A5NHDH.js";
376
381
  import {
377
- compactWhitespace
378
- } from "./chunk-DWLEOOGR.js";
382
+ asRecordOrEmpty
383
+ } from "./chunk-KX6YBIHG.js";
379
384
  import {
380
385
  withShellChildEnvironment
381
- } from "./chunk-VMJVAJ6W.js";
386
+ } from "./chunk-CTIEJRTP.js";
382
387
  import {
383
388
  estimateTokenCount
384
389
  } from "./chunk-PSCNXBYA.js";
390
+ import {
391
+ compactWhitespace
392
+ } from "./chunk-DWLEOOGR.js";
385
393
  import {
386
394
  createOAuthTokenStore,
387
395
  isTokenExpired,
388
396
  readOAuthCredential,
389
397
  resolveFreshAccessToken
390
398
  } from "./chunk-G7Y4GXTY.js";
399
+ import {
400
+ isTombstoneRecord
401
+ } from "./chunk-BV3FLP2L.js";
402
+ import {
403
+ dialogMessageRecordToAgentRuntimeMessage
404
+ } from "./chunk-4ZCTKB27.js";
391
405
  import {
392
406
  FORCED_TOOLS,
393
407
  addDefaultLightWebToolsForConfiguredAgents,
@@ -399,17 +413,15 @@ import {
399
413
  expandEnabledPacks,
400
414
  resolveBuiltinSkillEntry,
401
415
  resolveEffectiveEnabledPacks
402
- } from "./chunk-G7IUT2V3.js";
403
- import {
404
- CHROME_CONNECTOR_ACCEPTED_TOOL_NAMES,
405
- canonicalizeChromeConnectorToolNames,
406
- canonicalizeToolNames
407
- } from "./chunk-6OVNSQHN.js";
416
+ } from "./chunk-6MTVACLN.js";
408
417
  import {
418
+ DIALOG_AGENT_LIST_INDEX_PREFIX,
419
+ TOKEN_DIALOG_INDEX_PREFIX,
409
420
  createTokenDialogIndexKey,
410
421
  createTokenKey,
411
422
  createTokenStatsKey,
412
- createUserKey
423
+ createUserKey,
424
+ isTokenStatsKey
413
425
  } from "./chunk-SYTHYBMI.js";
414
426
  import {
415
427
  dialogMessageKey
@@ -417,6 +429,31 @@ import {
417
429
  import {
418
430
  dialogIdFromKey
419
431
  } from "./chunk-YZMNK53S.js";
432
+ import {
433
+ extractLastUserText,
434
+ localTurnHasSubjectRefs,
435
+ resolveLocalUserId,
436
+ withResolvedRuntimeToolSurface
437
+ } from "./chunk-UPOW5HTG.js";
438
+ import {
439
+ LOCAL_CODEX_AGENT_KEY,
440
+ isLocalCliAgentKey,
441
+ resolveCliAgentKeyInput
442
+ } from "./chunk-BR3GT6MR.js";
443
+ import {
444
+ HIGH_RISK_MUTATION_TOOL_NAMES,
445
+ resolveRequestToolSurface
446
+ } from "./chunk-NEG5LYK5.js";
447
+ import {
448
+ remoteDialogSyncTimeout,
449
+ resolveRuntimeAuthToken,
450
+ resolveRuntimeServerUrl
451
+ } from "./chunk-GX6DITLQ.js";
452
+ import {
453
+ CHROME_CONNECTOR_ACCEPTED_TOOL_NAMES,
454
+ canonicalizeChromeConnectorToolNames,
455
+ canonicalizeToolNames
456
+ } from "./chunk-YLAHYLDQ.js";
420
457
  import {
421
458
  asOptionalPositiveFiniteNumber
422
459
  } from "./chunk-U6VC4MU4.js";
@@ -441,17 +478,17 @@ import {
441
478
  import {
442
479
  agentRunCardLabels,
443
480
  t
444
- } from "./chunk-262R3XNN.js";
481
+ } from "./chunk-E5RYFR7E.js";
445
482
  import {
446
483
  isAntigravityOAuthAgent
447
- } from "./chunk-7JGMNKKG.js";
448
- import {
449
- buildProviderSessionHeaders,
450
- resolvePlatformAuthToken
451
- } from "./chunk-RTHFJZ6M.js";
484
+ } from "./chunk-CTWCZKNS.js";
452
485
  import {
453
486
  toErrorMessage
454
487
  } from "./chunk-HNMXYYJR.js";
488
+ import {
489
+ buildProviderSessionHeaders,
490
+ resolvePlatformAuthToken
491
+ } from "./chunk-K26XPZRB.js";
455
492
  import {
456
493
  asTrimmedString
457
494
  } from "./chunk-3EUW3WEO.js";
@@ -459,7 +496,7 @@ import {
459
496
  anthropicOAuthModelMaxOutputTokens,
460
497
  findModelConfig,
461
498
  isAdaptiveThinkingModelId
462
- } from "./chunk-CD3RU7XL.js";
499
+ } from "./chunk-CD2DK5JA.js";
463
500
  import {
464
501
  CLI_PROVIDER_VALUES,
465
502
  isCliProvider
@@ -493,9 +530,9 @@ function createLiveImageSupportResolver(userId, discover, timeoutMs = 5e3) {
493
530
  const raw = config.rawRecord ?? config;
494
531
  const owner = typeof raw.userId === "string" && raw.userId.trim() ? raw.userId.trim() : typeof raw.ownerUserId === "string" ? raw.ownerUserId.trim() : void 0;
495
532
  if (!userId || owner !== userId) return withLiveImageSupport(config, false);
496
- discovery ??= new Promise((resolve7) => {
497
- const timer = setTimeout(() => resolve7({}), timeoutMs);
498
- Promise.resolve().then(discover).then(resolve7, () => resolve7({})).finally(() => clearTimeout(timer));
533
+ discovery ??= new Promise((resolve8) => {
534
+ const timer = setTimeout(() => resolve8({}), timeoutMs);
535
+ Promise.resolve().then(discover).then(resolve8, () => resolve8({})).finally(() => clearTimeout(timer));
499
536
  });
500
537
  const models = await discovery;
501
538
  const model = config.model?.trim() ?? "";
@@ -891,7 +928,7 @@ function buildAnthropicMessagesBody(args) {
891
928
  const mode = resolveCacheMode();
892
929
  const rawMessages = Array.isArray(args.openAiBody.messages) ? args.openAiBody.messages : [];
893
930
  const system = [];
894
- if (args.agentConfig.prompt?.trim()) {
931
+ if (!hasAssembledAgentPrompt(rawMessages) && args.agentConfig.prompt?.trim()) {
895
932
  system.push({ type: "text", text: args.agentConfig.prompt.trim() });
896
933
  }
897
934
  const messages = [];
@@ -1236,6 +1273,57 @@ function clearCliLocalRuntimePreparedAgentCache() {
1236
1273
  preparedAgentRuntimeCache.clear();
1237
1274
  hybridStoreCache.clear();
1238
1275
  }
1276
+ var SCALAR_AGENT_CONFIG_FINGERPRINT_FIELDS = [
1277
+ "apiSource",
1278
+ "customProviderUrl",
1279
+ "model",
1280
+ "name",
1281
+ "prompt",
1282
+ "provider",
1283
+ "revision",
1284
+ "updatedAt",
1285
+ "version"
1286
+ ];
1287
+ var TOOL_LIST_FINGERPRINT_FIELDS = ["toolNames", "tools"];
1288
+ function extractFingerprintToolNames(raw) {
1289
+ if (!Array.isArray(raw)) return void 0;
1290
+ const seen = /* @__PURE__ */ new Set();
1291
+ for (const value of raw) {
1292
+ const rawName = typeof value === "string" ? value : value && typeof value === "object" && !Array.isArray(value) ? typeof value.name === "string" ? value.name : value.function && typeof value.function === "object" && !Array.isArray(value.function) && typeof value.function.name === "string" ? value.function.name : "" : "";
1293
+ const trimmed = rawName.trim();
1294
+ if (trimmed) seen.add(trimmed);
1295
+ }
1296
+ return [...seen].sort((a, b) => a.localeCompare(b));
1297
+ }
1298
+ function buildLocalAgentConfigFingerprint(source) {
1299
+ const record = source && typeof source === "object" ? source : null;
1300
+ const payload = {
1301
+ skillPolicy: Object.entries(resolveAgentSkillConfig(record)).sort(
1302
+ ([a], [b]) => a.localeCompare(b)
1303
+ )
1304
+ };
1305
+ if (record) {
1306
+ for (const field of SCALAR_AGENT_CONFIG_FINGERPRINT_FIELDS) {
1307
+ if (!Object.prototype.hasOwnProperty.call(record, field)) continue;
1308
+ const value = record[field];
1309
+ if (typeof value === "string" || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean") {
1310
+ payload[field] = value;
1311
+ }
1312
+ }
1313
+ for (const field of TOOL_LIST_FINGERPRINT_FIELDS) {
1314
+ if (!Object.prototype.hasOwnProperty.call(record, field)) continue;
1315
+ const names = extractFingerprintToolNames(record[field]);
1316
+ if (names !== void 0) {
1317
+ payload[field] = names;
1318
+ }
1319
+ }
1320
+ }
1321
+ const ordered = {};
1322
+ for (const key of Object.keys(payload).sort((a, b) => a.localeCompare(b))) {
1323
+ ordered[key] = payload[key];
1324
+ }
1325
+ return JSON.stringify(ordered);
1326
+ }
1239
1327
  async function defaultLocalRuntimeDb() {
1240
1328
  return getDefaultCliLocalRuntimeDb();
1241
1329
  }
@@ -1292,44 +1380,6 @@ var REGISTRY_INJECTED_TOOL_NAMES = /* @__PURE__ */ new Set([
1292
1380
  "read_xhs_profile"
1293
1381
  ]);
1294
1382
 
1295
- // packages/agent-runtime/agentRunIsolation.ts
1296
- var ORCHESTRATION_TOOL_NAMES = /* @__PURE__ */ new Set([
1297
- "startAgentRun",
1298
- "controlAgentRun",
1299
- "listAgents",
1300
- "readAgent",
1301
- "runStreamingAgent"
1302
- ]);
1303
- var INTERACTION_REQUIRED_TOOL_NAMES = /* @__PURE__ */ new Set([
1304
- "ask_user",
1305
- // 凭据请求:需要宿主交互面板(Block 1a);desktop 无通道时同 ask_user 剥离。
1306
- "secret-request"
1307
- ]);
1308
- var SELF_MUTATION_TOOL_NAMES = /* @__PURE__ */ new Set([
1309
- "updateSelf",
1310
- "updateAgent"
1311
- ]);
1312
- var SUBTASK_REMOVED_TOOL_NAMES = /* @__PURE__ */ new Set([
1313
- ...ORCHESTRATION_TOOL_NAMES,
1314
- ...INTERACTION_REQUIRED_TOOL_NAMES,
1315
- ...SELF_MUTATION_TOOL_NAMES
1316
- ]);
1317
- function isSubtaskRun(env) {
1318
- if (!env) return false;
1319
- const value = env.NOLO_AGENT_RUN_CHILD;
1320
- return typeof value === "string" && value.length > 0 && value !== "0";
1321
- }
1322
- var RUN_WAKE_CHANNEL_ENV = "NOLO_RUN_WAKE";
1323
- function hasRunWakeChannel(env) {
1324
- if (!env) return false;
1325
- const value = env[RUN_WAKE_CHANNEL_ENV];
1326
- return typeof value === "string" && value.length > 0 && value !== "0";
1327
- }
1328
- function filterToolNamesForRunKind(toolNames, isSubtask) {
1329
- if (!isSubtask) return [...toolNames];
1330
- return toolNames.filter((name) => !SUBTASK_REMOVED_TOOL_NAMES.has(name));
1331
- }
1332
-
1333
1383
  // packages/cli/client/localRuntimeTools.ts
1334
1384
  var CLI_CHROME_CONNECTOR_TOOL_NAME_SET = new Set(
1335
1385
  CHROME_CONNECTOR_ACCEPTED_TOOL_NAMES
@@ -1502,7 +1552,7 @@ function resolveCliRequestedToolNames(agentConfig, env, systemBuiltinSkills) {
1502
1552
  filtered,
1503
1553
  agentConfig?.disabledTools
1504
1554
  );
1505
- return filterToolNamesForRunKind(afterDisabled, isSubtask);
1555
+ return filterToolNamesForRunKind(afterDisabled.filter((name) => !MCP_TOOL_NAMES.includes(name) || agentConfig.key === "agent-0e95801d90-gpt-6-1-sol" && Array.isArray(agentConfig.toolNames) && agentConfig.toolNames.includes(name)), isSubtask);
1506
1556
  }
1507
1557
  function resolveProviderOpenAiToolBundle(agentConfig, env, buildTools = buildOpenAiTools, additionalToolNames = []) {
1508
1558
  const requestedToolNames = [
@@ -1530,6 +1580,7 @@ function buildLocalWorkspaceToolsetForEnv(args) {
1530
1580
  return toolset;
1531
1581
  }
1532
1582
  function buildLocalPolicyToolNames(args) {
1583
+ if (args.toolNames?.length === 0) return [];
1533
1584
  const schemaBuilder = args.buildProviderOpenAiTools ?? buildOpenAiTools;
1534
1585
  const tools = schemaBuilder({
1535
1586
  agentKey: args.agentKey,
@@ -2444,7 +2495,7 @@ var resolveCliProviderTransport = async (ctx) => {
2444
2495
  import { createHash } from "node:crypto";
2445
2496
  import { randomUUID as randomUUID2 } from "node:crypto";
2446
2497
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
2447
- var CODEX_CLIENT_VERSION = "0.162.1";
2498
+ var CODEX_CLIENT_VERSION = "0.169.0";
2448
2499
  var CODEX_ORIGINATOR = "codex_cli_rs";
2449
2500
  var CODEX_OPENAI_BETA = "responses=experimental";
2450
2501
  var OPENAI_AUTH_CLAIM = "https://api.openai.com/auth";
@@ -2575,8 +2626,9 @@ function buildCodexRequestBody(args, identity = createCodexRequestIdentity(), se
2575
2626
  routeKind: "codex/responses",
2576
2627
  legacySupportsToolImages: false
2577
2628
  }));
2578
- const instructions = collectInstructions(rawMessages, args.agentConfig.prompt);
2579
- const stableInstructions = collectStablePromptPrefix(rawMessages, args.agentConfig.prompt);
2629
+ const fallbackPrompt = hasAssembledAgentPrompt(rawMessages) ? void 0 : args.agentConfig.prompt;
2630
+ const instructions = collectInstructions(rawMessages, fallbackPrompt);
2631
+ const stableInstructions = collectStablePromptPrefix(rawMessages, fallbackPrompt);
2580
2632
  const tools = toResponsesTools(
2581
2633
  Array.isArray(args.openAiBody.tools) ? args.openAiBody.tools : void 0
2582
2634
  );
@@ -2628,7 +2680,7 @@ function throwIfAborted(signal) {
2628
2680
  }
2629
2681
  function waitBackoff(ms, signal, injectedSleep) {
2630
2682
  throwIfAborted(signal);
2631
- return new Promise((resolve7, reject) => {
2683
+ return new Promise((resolve8, reject) => {
2632
2684
  let timer;
2633
2685
  const cleanup = () => {
2634
2686
  signal?.removeEventListener("abort", onAbort);
@@ -2643,7 +2695,7 @@ function waitBackoff(ms, signal, injectedSleep) {
2643
2695
  injectedSleep(ms).then(
2644
2696
  () => {
2645
2697
  cleanup();
2646
- resolve7();
2698
+ resolve8();
2647
2699
  },
2648
2700
  (error) => {
2649
2701
  cleanup();
@@ -2653,7 +2705,7 @@ function waitBackoff(ms, signal, injectedSleep) {
2653
2705
  } else {
2654
2706
  timer = setTimeout(() => {
2655
2707
  cleanup();
2656
- resolve7();
2708
+ resolve8();
2657
2709
  }, ms);
2658
2710
  }
2659
2711
  });
@@ -2906,14 +2958,14 @@ function countCodexInputChars(messages) {
2906
2958
  }
2907
2959
  function abortableSleep(sleepFn, ms, signal) {
2908
2960
  let timer;
2909
- const waitOnce = () => sleepFn ? Promise.resolve(sleepFn(ms)) : new Promise((resolve7) => {
2910
- timer = setTimeout(resolve7, ms);
2961
+ const waitOnce = () => sleepFn ? Promise.resolve(sleepFn(ms)) : new Promise((resolve8) => {
2962
+ timer = setTimeout(resolve8, ms);
2911
2963
  });
2912
2964
  if (!signal) return waitOnce().then(() => void 0);
2913
2965
  if (signal.aborted) {
2914
2966
  return Promise.reject(signal.reason ?? new DOMException("aborted", "AbortError"));
2915
2967
  }
2916
- return new Promise((resolve7, reject) => {
2968
+ return new Promise((resolve8, reject) => {
2917
2969
  let settled = false;
2918
2970
  const finish = (settle) => {
2919
2971
  if (settled) return;
@@ -2927,7 +2979,7 @@ function abortableSleep(sleepFn, ms, signal) {
2927
2979
  );
2928
2980
  signal.addEventListener("abort", onAbort, { once: true });
2929
2981
  waitOnce().then(
2930
- () => finish(resolve7),
2982
+ () => finish(resolve8),
2931
2983
  (error) => finish(() => reject(error))
2932
2984
  );
2933
2985
  });
@@ -3830,7 +3882,7 @@ function waitWithAbort(ms, signal) {
3830
3882
  if (signal?.aborted) {
3831
3883
  return Promise.reject(signal.reason ?? new Error("owner-required proxy aborted"));
3832
3884
  }
3833
- return new Promise((resolve7, reject) => {
3885
+ return new Promise((resolve8, reject) => {
3834
3886
  let timer;
3835
3887
  const cleanup = () => {
3836
3888
  if (timer !== void 0) clearTimeout(timer);
@@ -3842,7 +3894,7 @@ function waitWithAbort(ms, signal) {
3842
3894
  };
3843
3895
  timer = setTimeout(() => {
3844
3896
  cleanup();
3845
- resolve7();
3897
+ resolve8();
3846
3898
  }, ms);
3847
3899
  signal?.addEventListener("abort", onAbort, { once: true });
3848
3900
  });
@@ -4463,7 +4515,7 @@ function resolveLocalRunExecutionIsolationFact(args) {
4463
4515
  isolation: "none",
4464
4516
  sandbox: "host",
4465
4517
  reason: "host-no-sandbox",
4466
- note: "\u672C run \u5728\u5BBF\u4E3B\u6267\u884C\u4E14**\u65E0\u9694\u79BB**\uFF08\u672A\u8D70 docker \u901A\u9053\uFF0C\u4E5F\u6CA1\u6709\u53EF\u7528\u7684 bwrap workload\uFF09\u3002\u5199\u64CD\u4F5C\u76F4\u63A5\u4F5C\u7528\u4E8E\u5BBF\u4E3B\u5DE5\u4F5C\u533A\uFF1B\u6D3E\u53D1\u578B run \u7684\u9ED8\u8BA4\u843D\u70B9\u662F\u672C\u673A docker \u6C99\u76D2\uFF0C\u4EA4\u4E92\u5F0F run \u53EF\u7528 --runtime-key docker\uFF08\u6216 --local \u663E\u5F0F\u58F0\u660E\u672C\u673A\u6267\u884C\uFF09\u3002",
4518
+ note: "\u672C run \u5728\u5BBF\u4E3B\u6267\u884C\u4E14**\u65E0\u9694\u79BB**\uFF08\u672A\u8D70 docker \u901A\u9053\uFF0C\u4E5F\u6CA1\u6709\u53EF\u7528\u7684 bwrap workload\uFF09\u3002\u5199\u64CD\u4F5C\u76F4\u63A5\u4F5C\u7528\u4E8E\u5BBF\u4E3B\u5DE5\u4F5C\u533A\uFF1BCLI \u672A\u70B9\u540D\u5199\u578B\u6D3E\u53D1\u9ED8\u8BA4\u5BBF\u4E3B\u4E14\u987B allowHostWrites: true\uFF0C\u4EA4\u4E92\u5F0F run \u53EF\u7528 --runtime-key docker\uFF08\u6216 --local \u663E\u5F0F\u58F0\u660E\u672C\u673A\u6267\u884C\uFF09\u3002",
4467
4519
  recordedAt
4468
4520
  });
4469
4521
  }
@@ -4534,8 +4586,8 @@ function recordLocalRunExecutionIsolation(args) {
4534
4586
  }
4535
4587
  function joinPath(dir, name) {
4536
4588
  if (!dir) return name;
4537
- const sep2 = dir.includes("\\") && !dir.includes("/") ? "\\" : "/";
4538
- return dir.endsWith(sep2) ? `${dir}${name}` : `${dir}${sep2}${name}`;
4589
+ const sep3 = dir.includes("\\") && !dir.includes("/") ? "\\" : "/";
4590
+ return dir.endsWith(sep3) ? `${dir}${name}` : `${dir}${sep3}${name}`;
4539
4591
  }
4540
4592
 
4541
4593
  // packages/core/settingsSyncFreshness.ts
@@ -4602,7 +4654,7 @@ function isBusyProviderStreamError(error) {
4602
4654
  return BUSY_STREAM_ERROR_RE.test(toErrorMessage(error));
4603
4655
  }
4604
4656
  async function defaultSleep(ms) {
4605
- await new Promise((resolve7) => setTimeout(resolve7, ms));
4657
+ await new Promise((resolve8) => setTimeout(resolve8, ms));
4606
4658
  }
4607
4659
  function isRetryableProviderStreamError(error) {
4608
4660
  const message = toErrorMessage(error);
@@ -4794,6 +4846,8 @@ function parseBackgroundRuns(text) {
4794
4846
  tasks.push({
4795
4847
  title: title || agent || runId || SUBJECT_RUN.label,
4796
4848
  ...runId ? { identifier: runId } : {},
4849
+ ...status ? { runStatus: status } : {},
4850
+ ...attrValue(attrs, "childDialogId") && attrValue(attrs, "childDialogId") !== "missing" ? { childDialogId: decodeXmlAttribute(attrValue(attrs, "childDialogId")) } : {},
4797
4851
  outcome,
4798
4852
  outcomeLabel: OUTCOME_LABEL[outcome],
4799
4853
  ...duration ? { duration } : {},
@@ -5076,11 +5130,120 @@ function hasReservedBatchAuthority(metadata) {
5076
5130
  (field) => key === field || key.startsWith(`${field}.`) || key === `metadata.${field}` || key.startsWith(`metadata.${field}.`)
5077
5131
  ));
5078
5132
  }
5133
+ var LOCAL_ONLY_EVIDENCE_KEY_PREFIXES = [
5134
+ `${TOKEN_DIALOG_INDEX_PREFIX}-`,
5135
+ `${DIALOG_AGENT_LIST_INDEX_PREFIX}-`,
5136
+ "idx-tokendlg-backfill-",
5137
+ "token-charge-stats-",
5138
+ "usage-backup-"
5139
+ ];
5140
+ function isRemoteDialogEvidenceExcludedKey(key) {
5141
+ if (!key) return true;
5142
+ if (isTokenStatsKey(key)) return true;
5143
+ return LOCAL_ONLY_EVIDENCE_KEY_PREFIXES.some(
5144
+ (prefix) => key.startsWith(prefix)
5145
+ );
5146
+ }
5147
+ var MAX_REMOTE_ERROR_DETAIL_CHARS = 120;
5148
+ var SAFE_SHORT_ERROR_CODE_RE = /^[A-Za-z0-9_.:-]{1,48}$/;
5149
+ function sanitizeRemoteDiagnosticText(raw) {
5150
+ const singleLine = raw.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, " ").replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
5151
+ if (!singleLine) return "";
5152
+ return singleLine.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{6,}/gi, "Bearer [REDACTED]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]+)?/g, "[REDACTED]").replace(/\b(?:sk|rk|pk|nolo|tok)_[A-Za-z0-9_-]{8,}/gi, "[REDACTED]").replace(/\bvault-cred-[A-Za-z0-9_-]+/gi, "[REDACTED]");
5153
+ }
5154
+ function clampSingleLine(text, maxLen) {
5155
+ if (text.length <= maxLen) return text;
5156
+ if (maxLen <= 3) return text.slice(0, maxLen);
5157
+ return `${text.slice(0, maxLen - 3)}...`;
5158
+ }
5159
+ function extractSafeRemoteErrorDetail(status, bodyText) {
5160
+ if (status < 400 || status >= 500 || !bodyText) return "";
5161
+ let parsed;
5162
+ try {
5163
+ parsed = JSON.parse(bodyText);
5164
+ } catch {
5165
+ return "";
5166
+ }
5167
+ if (!isRecord(parsed)) return "";
5168
+ const rawCodeCandidates = [
5169
+ parsed.code,
5170
+ isRecord(parsed.error) ? parsed.error.code : void 0,
5171
+ typeof parsed.error === "string" ? parsed.error : void 0,
5172
+ parsed.reason
5173
+ ];
5174
+ let code = "";
5175
+ let fallbackMessageFromError = "";
5176
+ for (const candidate of rawCodeCandidates) {
5177
+ if (typeof candidate !== "string") continue;
5178
+ const cleaned = sanitizeRemoteDiagnosticText(candidate);
5179
+ if (!cleaned) continue;
5180
+ if (SAFE_SHORT_ERROR_CODE_RE.test(cleaned)) {
5181
+ code = cleaned;
5182
+ break;
5183
+ }
5184
+ if (!fallbackMessageFromError) {
5185
+ fallbackMessageFromError = cleaned;
5186
+ }
5187
+ }
5188
+ const rawMessageCandidates = [
5189
+ parsed.message,
5190
+ isRecord(parsed.error) ? parsed.error.message : void 0,
5191
+ fallbackMessageFromError
5192
+ ];
5193
+ let message = "";
5194
+ for (const candidate of rawMessageCandidates) {
5195
+ if (typeof candidate !== "string") continue;
5196
+ const cleaned = sanitizeRemoteDiagnosticText(candidate);
5197
+ if (cleaned && cleaned !== code) {
5198
+ message = cleaned;
5199
+ break;
5200
+ }
5201
+ }
5202
+ if (!code && !message) return "";
5203
+ const payload = {};
5204
+ if (code) payload.code = code;
5205
+ if (message) payload.message = message;
5206
+ let serialized = JSON.stringify(payload);
5207
+ if (serialized.length <= MAX_REMOTE_ERROR_DETAIL_CHARS) {
5208
+ return serialized;
5209
+ }
5210
+ if (code && message) {
5211
+ const baseLen = JSON.stringify({ code, message: "" }).length;
5212
+ const budget = MAX_REMOTE_ERROR_DETAIL_CHARS - baseLen;
5213
+ if (budget >= 8) {
5214
+ serialized = JSON.stringify({
5215
+ code,
5216
+ message: clampSingleLine(message, budget)
5217
+ });
5218
+ if (serialized.length <= MAX_REMOTE_ERROR_DETAIL_CHARS) return serialized;
5219
+ }
5220
+ serialized = JSON.stringify({ code });
5221
+ return serialized.length <= MAX_REMOTE_ERROR_DETAIL_CHARS ? serialized : clampSingleLine(serialized, MAX_REMOTE_ERROR_DETAIL_CHARS);
5222
+ }
5223
+ if (message) {
5224
+ const baseLen = JSON.stringify({ message: "" }).length;
5225
+ const budget = MAX_REMOTE_ERROR_DETAIL_CHARS - baseLen;
5226
+ return budget > 0 ? JSON.stringify({ message: clampSingleLine(message, budget) }) : "";
5227
+ }
5228
+ return clampSingleLine(serialized, MAX_REMOTE_ERROR_DETAIL_CHARS);
5229
+ }
5079
5230
  function prepareRemoteDialogEvidenceRecord(key, value, options) {
5080
5231
  const record = isRecord(value) ? { ...value } : {};
5081
- if (key.includes("-msg-") && typeof record.type !== "string") {
5232
+ if (key.includes("-msg-") && (typeof record.type !== "string" || !record.type.trim() || record.type === "message")) {
5082
5233
  record.type = "msg";
5083
5234
  }
5235
+ if (key.startsWith("token-") && !isTokenStatsKey(key)) {
5236
+ if (typeof record.type !== "string" || !record.type.trim()) {
5237
+ record.type = "token";
5238
+ }
5239
+ const hasAgentId = typeof record.agentId === "string" && record.agentId.trim().length > 0;
5240
+ const hasCybotId = typeof record.cybotId === "string" && record.cybotId.trim().length > 0;
5241
+ const fallbackAgent = asOptionalTrimmedString(options?.fallbackAgentKey);
5242
+ if (!hasAgentId && !hasCybotId && fallbackAgent) {
5243
+ record.agentId = fallbackAgent;
5244
+ record.cybotId = fallbackAgent;
5245
+ }
5246
+ }
5084
5247
  const metadata = record.metadata;
5085
5248
  if (key.includes("-msg-") && record.role === "user" && isRecord(metadata) && metadata.queueState === "accepted" && (metadata.cliBatchPhase === "requested" || metadata.cliBatchPhase === "completed" || typeof metadata.cliBatchId === "string" && metadata.cliBatchId.length > 0 || options?.isAcceptedBatchMember === true) && !hasReservedBatchAuthority(metadata)) {
5086
5249
  const { queueState: _localQueueState, ...evidenceMetadata } = metadata;
@@ -5191,7 +5354,7 @@ function buildLocalParentWakeMessage(args) {
5191
5354
  var EVIDENCE_WRITE_BATCH_SIZE = 4;
5192
5355
  var EVIDENCE_WRITE_BATCH_GAP_MS = 300;
5193
5356
  async function defaultEvidenceSleep(ms) {
5194
- await new Promise((resolve7) => setTimeout(resolve7, ms));
5357
+ await new Promise((resolve8) => setTimeout(resolve8, ms));
5195
5358
  }
5196
5359
  async function runThrottledBatches(items, run, options = {}) {
5197
5360
  const batchSize = options.batchSize ?? EVIDENCE_WRITE_BATCH_SIZE;
@@ -5219,6 +5382,7 @@ async function postRemoteRecord(args) {
5219
5382
  customKey: args.key,
5220
5383
  userId: args.userId,
5221
5384
  data: prepareRemoteDialogEvidenceRecord(args.key, args.data, {
5385
+ fallbackAgentKey: args.fallbackAgentKey,
5222
5386
  isAcceptedBatchMember: args.isAcceptedBatchMember
5223
5387
  })
5224
5388
  }),
@@ -5237,8 +5401,9 @@ async function postRemoteRecord(args) {
5237
5401
  );
5238
5402
  if (!response.ok) {
5239
5403
  const text = await response.text().catch(() => "");
5404
+ const detail = extractSafeRemoteErrorDetail(response.status, text);
5240
5405
  throw new Error(
5241
- `remote dialog evidence write failed: HTTP ${response.status} ${text.slice(0, 500)}`
5406
+ detail ? `remote dialog evidence write failed: HTTP ${response.status} ${detail}` : `remote dialog evidence write failed: HTTP ${response.status}`
5242
5407
  );
5243
5408
  }
5244
5409
  }
@@ -5313,8 +5478,9 @@ async function maybeWakeParentDialogAfterLocalSync(args) {
5313
5478
  });
5314
5479
  if (!wakeResponse.ok) {
5315
5480
  const text = await wakeResponse.text().catch(() => "");
5481
+ const detail = extractSafeRemoteErrorDetail(wakeResponse.status, text);
5316
5482
  throw new Error(
5317
- `parent dialog wake failed: HTTP ${wakeResponse.status} ${text.slice(0, 500)}`
5483
+ detail ? `parent dialog wake failed: HTTP ${wakeResponse.status} ${detail}` : `parent dialog wake failed: HTTP ${wakeResponse.status}`
5318
5484
  );
5319
5485
  }
5320
5486
  const notifiedAt = Date.now();
@@ -5339,13 +5505,14 @@ async function maybeWakeParentDialogAfterLocalSync(args) {
5339
5505
  async function syncLocalDialogEvidenceToRemote(args) {
5340
5506
  const serverUrl = resolveRuntimeServerUrl(args.env);
5341
5507
  const authToken = resolveRuntimeAuthToken(args.env);
5342
- if (!serverUrl || !authToken) {
5508
+ if (!serverUrl || !authToken || args.userId === "local") {
5343
5509
  return { attempted: false };
5344
5510
  }
5345
5511
  const orderedOps = [];
5346
5512
  const nonMsgOps = [];
5347
5513
  for (const op of args.ops) {
5348
5514
  if (op.type !== "put") continue;
5515
+ if (isRemoteDialogEvidenceExcludedKey(op.key)) continue;
5349
5516
  if (op.key.includes("-msg-")) {
5350
5517
  orderedOps.push(op);
5351
5518
  } else {
@@ -5354,11 +5521,13 @@ async function syncLocalDialogEvidenceToRemote(args) {
5354
5521
  }
5355
5522
  orderedOps.push(...nonMsgOps);
5356
5523
  const acceptedBatchKeys = await collectAcceptedUserBatchMessageKeys(orderedOps, args.localStore);
5524
+ const fallbackAgentKey = asOptionalTrimmedString(args.input?.agentKey);
5357
5525
  await runThrottledBatches(
5358
5526
  orderedOps.filter((op) => op.type === "put"),
5359
5527
  (op) => postRemoteRecord({
5360
5528
  authToken,
5361
5529
  data: op.value,
5530
+ fallbackAgentKey,
5362
5531
  fetchImpl: args.fetchImpl,
5363
5532
  isAcceptedBatchMember: acceptedBatchKeys.has(op.key),
5364
5533
  key: op.key,
@@ -5367,9 +5536,7 @@ async function syncLocalDialogEvidenceToRemote(args) {
5367
5536
  }),
5368
5537
  args.sleep ? { sleep: args.sleep } : {}
5369
5538
  );
5370
- const childDialogOp = args.ops.find(
5371
- (op) => op.type === "put" && !op.key.includes("-msg-")
5372
- );
5539
+ const childDialogOp = nonMsgOps.find((op) => op.key.startsWith("dialog-")) ?? nonMsgOps[0];
5373
5540
  const childDialogRecord = childDialogOp?.value && typeof childDialogOp.value === "object" ? childDialogOp.value : null;
5374
5541
  if (childDialogOp && childDialogRecord) {
5375
5542
  try {
@@ -5397,25 +5564,24 @@ async function syncLocalDialogEvidenceToRemote(args) {
5397
5564
  // packages/cli/client/childShellApprovalHostResolver.ts
5398
5565
  function createChildShellApprovalHostResolver(args) {
5399
5566
  return async (agentKey) => {
5400
- const config = await args.readAgentConfig(agentKey);
5401
- const record = config?.rawRecord;
5402
- const ownerUserId = asOptionalTrimmedString(record?.userId) ?? asOptionalTrimmedString(record?.ownerUserId);
5403
- if (!ownerUserId) return void 0;
5404
- const deviceId = asOptionalTrimmedString(await args.resolveDeviceId());
5405
- if (!deviceId) return void 0;
5567
+ const binding = await resolveChildApprovalBinding({ ...args, agentKey });
5568
+ if (!binding) return void 0;
5406
5569
  return {
5407
- binding: {
5408
- runId: "pending-spawn",
5409
- agentKey,
5410
- ownerUserId,
5411
- deviceId,
5412
- workspaceRoot: args.workspaceRoot
5413
- },
5570
+ binding,
5414
5571
  confirm: args.session.confirm,
5415
5572
  signal: args.session.signal
5416
5573
  };
5417
5574
  };
5418
5575
  }
5576
+ async function resolveChildApprovalBinding(args) {
5577
+ const config = await args.readAgentConfig(args.agentKey);
5578
+ const record = config?.rawRecord;
5579
+ const ownerUserId = asOptionalTrimmedString(record?.userId) ?? asOptionalTrimmedString(record?.ownerUserId);
5580
+ if (!ownerUserId) return void 0;
5581
+ const deviceId = asOptionalTrimmedString(await args.resolveDeviceId());
5582
+ if (!deviceId) return void 0;
5583
+ return { runId: "pending-spawn", agentKey: args.agentKey, ownerUserId, deviceId, workspaceRoot: args.workspaceRoot };
5584
+ }
5419
5585
 
5420
5586
  // packages/cli/client/cliDialogHistoryState.ts
5421
5587
  var STATE_KEY_PREFIX = "cli-dialog-history-state";
@@ -5839,253 +6005,27 @@ async function fetchRemoteDialogMessageRecordsViaBridge(args) {
5839
6005
  // packages/cli/client/browserShellApprovalBridge.ts
5840
6006
  import { createServer } from "node:http";
5841
6007
  import { randomBytes, timingSafeEqual } from "node:crypto";
5842
-
5843
- // packages/cli/client/hostApprovalFlow.ts
5844
- var HOST_APPROVAL_SUMMARY_LIMIT = 2500;
5845
- function clipApprovalSummary(text, limit = HOST_APPROVAL_SUMMARY_LIMIT) {
5846
- const value = String(text ?? "").replace(/\r\n?/g, "\n").trim();
5847
- if (value.length <= limit) return value;
5848
- const tailChars = Math.max(1, Math.round(limit * 0.3));
5849
- const headChars = Math.max(1, limit - tailChars);
5850
- const head = value.slice(0, headChars);
5851
- const tail = value.slice(value.length - tailChars);
5852
- const omitted = value.length - head.length - tail.length;
5853
- return `${head}
5854
- \u2026\uFF08\u4E2D\u95F4 ${omitted} \u5B57\u7B26\u672A\u663E\u793A\uFF0C\u4EE5\u4E0B\u662F\u7ED3\u5C3E\uFF1B\u5168\u6587 ${value.length} \u5B57\u7B26\uFF09\u2026
5855
- ${tail}`;
5856
- }
5857
- function toEpochMs(value) {
5858
- if (typeof value === "number" && Number.isFinite(value)) {
5859
- return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
5860
- }
5861
- if (typeof value === "string" && value.trim()) {
5862
- const asNumber = Number(value);
5863
- if (Number.isFinite(asNumber)) return toEpochMs(asNumber);
5864
- const parsed = Date.parse(value);
5865
- if (Number.isFinite(parsed)) return parsed;
5866
- }
5867
- return void 0;
5868
- }
5869
- function remainingApprovalMs(expiresAt, now) {
5870
- return Math.max(0, expiresAt - now);
5871
- }
5872
- function formatApprovalRemaining(expiresAt, now) {
5873
- const totalSeconds = Math.ceil(remainingApprovalMs(expiresAt, now) / 1e3);
5874
- if (totalSeconds <= 0) return "0s";
5875
- const minutes = Math.floor(totalSeconds / 60);
5876
- const seconds = totalSeconds % 60;
5877
- return minutes > 0 ? `${minutes}m${seconds}s` : `${seconds}s`;
5878
- }
5879
- function isRecordLike(value) {
5880
- return typeof value === "object" && value !== null;
5881
- }
5882
- function asTrimmedString2(value) {
5883
- return typeof value === "string" ? value.trim() : "";
5884
- }
5885
- function normalizePendingApproval(raw) {
5886
- if (!isRecordLike(raw)) return null;
5887
- const approvalId = asTrimmedString2(raw.approvalId);
5888
- const expiresAt = toEpochMs(raw.expiresAt ?? raw.expiresAtMs);
5889
- if (!approvalId || expiresAt === void 0) return null;
5890
- const tabId = asTrimmedString2(raw.tabId);
5891
- return {
5892
- approvalId,
5893
- actionLabel: asTrimmedString2(raw.action) || "unknown",
5894
- ...asTrimmedString2(raw.target) ? { target: asTrimmedString2(raw.target) } : {},
5895
- origin: asTrimmedString2(raw.origin),
5896
- // Passed through verbatim (the connector's preview already has the identity line, the head and
5897
- // the stated tail); only an upper-bound guard may touch it, see clipApprovalSummary.
5898
- summary: clipApprovalSummary(asTrimmedString2(raw.summary)),
5899
- expiresAt,
5900
- ...tabId ? { tabId } : {}
5901
- };
5902
- }
5903
- function parsePendingApprovalResult(result) {
5904
- let parsed;
5905
- try {
5906
- parsed = JSON.parse(result.content);
5907
- } catch {
5908
- return null;
5909
- }
5910
- if (!isRecordLike(parsed)) return null;
5911
- const errorBlock = isRecordLike(parsed.error) ? parsed.error : void 0;
5912
- const details = isRecordLike(errorBlock?.details) ? errorBlock.details : void 0;
5913
- const verdict = isRecordLike(parsed.result) ? parsed.result : void 0;
5914
- const candidates = [verdict, errorBlock, details].filter(isRecordLike);
5915
- const pending = candidates.find((entry) => entry.code === "USER_APPROVAL_PENDING");
5916
- if (!pending) return null;
5917
- const ordered = [pending, details, verdict].filter(isRecordLike);
5918
- const readField = (key) => {
5919
- for (const entry of ordered) {
5920
- const value = asTrimmedString2(entry[key]);
5921
- if (value) return value;
5922
- }
5923
- return "";
5924
- };
5925
- const approvalId = readField("approvalId");
5926
- if (!approvalId) return null;
5927
- let expiresAt;
5928
- for (const entry of ordered) {
5929
- const candidate = toEpochMs(entry.expiresAt ?? entry.expiresAtMs);
5930
- if (candidate !== void 0) {
5931
- expiresAt = candidate;
5932
- break;
5933
- }
5934
- }
5935
- const message = readField("message");
5936
- return {
5937
- approvalId,
5938
- action: readField("action"),
5939
- ...expiresAt !== void 0 ? { expiresAt } : {},
5940
- ...message ? { message } : {}
5941
- };
5942
- }
5943
- function withApprovalId(call, approvalId) {
5944
- let payload;
5945
- try {
5946
- const parsed = JSON.parse(call.arguments || "{}");
5947
- payload = isRecordLike(parsed) ? { ...parsed } : {};
5948
- } catch {
5949
- return call;
5950
- }
5951
- payload.approvalId = approvalId;
5952
- return { ...call, arguments: JSON.stringify(payload) };
5953
- }
5954
- function withHostApprovalRequest(call) {
5955
- let payload;
5956
- try {
5957
- const parsed = JSON.parse(call.arguments || "{}");
5958
- payload = isRecordLike(parsed) ? { ...parsed } : {};
5959
- } catch {
5960
- return call;
5961
- }
5962
- payload.hostApproval = true;
5963
- return { ...call, arguments: JSON.stringify(payload) };
5964
- }
5965
- function createConnectorApprovalPort(getClient) {
5966
- return {
5967
- async listPendingApprovals() {
5968
- const raw = await getClient().request("list_pending_approvals", {});
5969
- const list = isRecordLike(raw) && Array.isArray(raw.approvals) ? raw.approvals : [];
5970
- return list.map(normalizePendingApproval).filter((entry) => entry !== null);
5971
- },
5972
- async submitApprovalDecision(approvalId, decision) {
5973
- try {
5974
- const raw = await getClient().request("submit_approval_decision", {
5975
- approvalId,
5976
- decision
5977
- });
5978
- if (isRecordLike(raw) && raw.ok === false) {
5979
- return { failed: asTrimmedString2(raw.code) || "USER_APPROVAL_REJECTED" };
5980
- }
5981
- const status = isRecordLike(raw) && raw.status === "denied" ? "denied" : "allowed";
5982
- return { status };
5983
- } catch (error) {
5984
- const code = asTrimmedString2(error?.code);
5985
- return { failed: code || "CHROME_CONNECTOR_ERROR" };
5986
- }
5987
- }
5988
- };
5989
- }
5990
- function approvalFailure(code, message, action, extra) {
5991
- return {
5992
- content: JSON.stringify({ ok: false, error: { code, message } }),
5993
- metadata: { chromeConnector: true, error: true, code, action, ...extra ?? {} }
5994
- };
5995
- }
5996
- async function runConnectorToolWithHostApproval(args) {
5997
- const first = await args.execute(
5998
- withHostApprovalRequest(args.call)
5999
- );
6000
- const pending = parsePendingApprovalResult(first);
6001
- if (!pending || !args.awaitHostApproval) return first;
6002
- const now = args.now ?? Date.now;
6003
- let listed;
6004
- try {
6005
- listed = await args.connector.listPendingApprovals();
6006
- } catch {
6007
- return first;
6008
- }
6009
- const card = listed.find((entry) => entry.approvalId === pending.approvalId);
6010
- if (!card) {
6011
- return approvalFailure(
6012
- "USER_APPROVAL_EXPIRED",
6013
- "\u5BA1\u6279\u5DF2\u8FC7\u671F\u6216\u4E0D\u518D\u5F85\u6279\uFF0C\u52A8\u4F5C\u672A\u6267\u884C\u3002",
6014
- args.call.name
6015
- );
6016
- }
6017
- if (card.expiresAt <= now()) {
6018
- return approvalFailure("USER_APPROVAL_EXPIRED", "\u5BA1\u6279\u5DF2\u8FC7\u671F\uFF0C\u52A8\u4F5C\u672A\u6267\u884C\u3002", args.call.name);
6019
- }
6020
- const decision = await args.awaitHostApproval(card);
6021
- if (decision === "deny") {
6022
- await args.connector.submitApprovalDecision(card.approvalId, "deny");
6023
- return approvalFailure("USER_APPROVAL_DENIED", "\u7528\u6237\u5DF2\u62D2\u7EDD", args.call.name, {
6024
- approvalId: card.approvalId
6025
- });
6026
- }
6027
- const submitted = await args.connector.submitApprovalDecision(card.approvalId, "allow_once");
6028
- if ("failed" in submitted) {
6029
- return approvalFailure(
6030
- submitted.failed,
6031
- submitted.failed === "USER_APPROVAL_EXPIRED" ? "\u5BA1\u6279\u5DF2\u8FC7\u671F\uFF0C\u52A8\u4F5C\u672A\u6267\u884C\u3002" : "\u5BA1\u6279\u51B3\u5B9A\u672A\u88AB\u8FDE\u63A5\u5668\u63A5\u53D7\uFF0C\u52A8\u4F5C\u672A\u6267\u884C\u3002",
6032
- args.call.name,
6033
- { approvalId: card.approvalId }
6034
- );
6035
- }
6036
- if (submitted.status === "denied") {
6037
- return approvalFailure("USER_APPROVAL_DENIED", "\u7528\u6237\u5DF2\u62D2\u7EDD", args.call.name, {
6038
- approvalId: card.approvalId
6039
- });
6008
+ var VALID_HOST_APPROVAL_RESULTS = /* @__PURE__ */ new Set([
6009
+ "allow_once",
6010
+ "deny",
6011
+ "cancelled",
6012
+ "expired",
6013
+ "unavailable"
6014
+ ]);
6015
+ function mapBlockedOutcome(code, hasRenderer) {
6016
+ switch (code) {
6017
+ case "USER_APPROVAL_CANCELLED":
6018
+ return { outcome: "cancelled", code: "USER_APPROVAL_CANCELLED" };
6019
+ case "USER_APPROVAL_EXPIRED":
6020
+ return { outcome: "expired", code: "USER_APPROVAL_EXPIRED" };
6021
+ case "USER_APPROVAL_UNAVAILABLE":
6022
+ return { outcome: "unavailable", code: "USER_APPROVAL_UNAVAILABLE" };
6023
+ case "USER_APPROVAL_DENIED":
6024
+ return { outcome: "denied", code: "USER_APPROVAL_DENIED" };
6025
+ default:
6026
+ return hasRenderer ? { outcome: "denied", code: typeof code === "string" && code ? code : "USER_APPROVAL_DENIED" } : { outcome: "unavailable", code: "USER_APPROVAL_UNAVAILABLE" };
6040
6027
  }
6041
- return args.execute(withApprovalId(args.call, card.approvalId));
6042
6028
  }
6043
- function createHostApprovalCardQueue() {
6044
- const waiting = [];
6045
- let active = false;
6046
- const drain = async () => {
6047
- if (active) return;
6048
- active = true;
6049
- try {
6050
- while (waiting.length > 0) {
6051
- waiting.sort((a, b) => a.card.expiresAt - b.card.expiresAt);
6052
- const entry = waiting.shift();
6053
- let decision = "deny";
6054
- try {
6055
- decision = await entry.present(entry.card);
6056
- } catch {
6057
- decision = "deny";
6058
- }
6059
- entry.resolve(decision);
6060
- }
6061
- } finally {
6062
- active = false;
6063
- }
6064
- };
6065
- return {
6066
- /** Resolves with the user's answer once this card reaches the head of the queue. */
6067
- present(card, present) {
6068
- return new Promise((resolve7) => {
6069
- waiting.push({ card, present, resolve: resolve7 });
6070
- void Promise.resolve().then(drain);
6071
- });
6072
- },
6073
- /** Cards currently queued or being shown (tests/telemetry). */
6074
- size: () => waiting.length + (active ? 1 : 0)
6075
- };
6076
- }
6077
- var registeredRenderer = null;
6078
- function registerHostApprovalRenderer(renderer) {
6079
- registeredRenderer = renderer;
6080
- return () => {
6081
- if (registeredRenderer === renderer) registeredRenderer = null;
6082
- };
6083
- }
6084
- function getHostApprovalRenderer() {
6085
- return registeredRenderer ?? void 0;
6086
- }
6087
-
6088
- // packages/cli/client/browserShellApprovalBridge.ts
6089
6029
  async function createBrowserShellApprovalBridge(args) {
6090
6030
  const timeoutMs = args.timeoutMs ?? 6e4;
6091
6031
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 6e4) throw new Error("Invalid bridge timeout");
@@ -6102,10 +6042,15 @@ async function createBrowserShellApprovalBridge(args) {
6102
6042
  if (!active()) throw new Error("Browser approval bridge revoked");
6103
6043
  };
6104
6044
  const server = createServer(async (request, response) => {
6105
- const reply = (status, result) => {
6045
+ const reply = (status, result, extra) => {
6106
6046
  if (!response.destroyed) {
6107
6047
  response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
6108
- response.end(JSON.stringify({ status, ...result === void 0 ? {} : { result } }));
6048
+ response.end(JSON.stringify({
6049
+ status,
6050
+ ...extra?.outcome ? { outcome: extra.outcome } : {},
6051
+ ...extra?.code ? { code: extra.code } : {},
6052
+ ...result === void 0 ? {} : { result }
6053
+ }));
6109
6054
  }
6110
6055
  };
6111
6056
  const disconnect = () => {
@@ -6134,8 +6079,9 @@ async function createBrowserShellApprovalBridge(args) {
6134
6079
  const current = binding;
6135
6080
  let calls = 0;
6136
6081
  let retry = false;
6137
- await runConnectorToolWithHostApproval({
6082
+ const flowResult = await runConnectorToolWithHostApproval({
6138
6083
  call: current.call,
6084
+ signal: lifetime.signal,
6139
6085
  execute: async () => {
6140
6086
  requireActive();
6141
6087
  if (calls++ === 0) return current.pending;
@@ -6160,22 +6106,31 @@ async function createBrowserShellApprovalBridge(args) {
6160
6106
  },
6161
6107
  ...args.awaitHostApproval ? { awaitHostApproval: async (card) => {
6162
6108
  requireActive();
6163
- const decision = await new Promise((resolve7, reject) => {
6109
+ const decision = await new Promise((resolve8, reject) => {
6164
6110
  const abort = () => reject(new Error("Browser approval bridge revoked"));
6165
6111
  lifetime.signal.addEventListener("abort", abort, { once: true });
6166
6112
  Promise.resolve().then(() => {
6167
6113
  requireActive();
6168
6114
  return args.awaitHostApproval(card, lifetime.signal);
6169
- }).then(resolve7, reject).finally(() => lifetime.signal.removeEventListener("abort", abort));
6115
+ }).then(resolve8, reject).finally(() => lifetime.signal.removeEventListener("abort", abort));
6170
6116
  });
6171
6117
  requireActive();
6172
- if (decision !== "allow_once" && decision !== "deny") throw new Error("Invalid host decision");
6118
+ if (!VALID_HOST_APPROVAL_RESULTS.has(decision)) throw new Error("Invalid host decision");
6173
6119
  return decision;
6174
6120
  } } : {}
6175
6121
  });
6176
- reply(active() && retry ? "retry_once" : "blocked");
6122
+ if (active() && retry) {
6123
+ reply("retry_once", void 0, { outcome: "allowed" });
6124
+ } else {
6125
+ const metaCode = flowResult.metadata?.code;
6126
+ reply("blocked", void 0, mapBlockedOutcome(metaCode, Boolean(args.awaitHostApproval)));
6127
+ }
6177
6128
  } catch {
6178
- reply("blocked");
6129
+ reply(
6130
+ "blocked",
6131
+ void 0,
6132
+ lifetime.signal.aborted ? { outcome: "cancelled", code: "USER_APPROVAL_CANCELLED" } : { outcome: "unavailable", code: "USER_APPROVAL_UNAVAILABLE" }
6133
+ );
6179
6134
  }
6180
6135
  });
6181
6136
  server.requestTimeout = timeoutMs;
@@ -6189,17 +6144,17 @@ async function createBrowserShellApprovalBridge(args) {
6189
6144
  clearTimeout(timer);
6190
6145
  args.signal?.removeEventListener("abort", onAbort);
6191
6146
  bindings.clear();
6192
- closing = new Promise((resolve7) => {
6193
- server.close(() => resolve7());
6147
+ closing = new Promise((resolve8) => {
6148
+ server.close(() => resolve8());
6194
6149
  server.closeAllConnections();
6195
6150
  });
6196
6151
  return closing;
6197
6152
  }
6198
- await new Promise((resolve7, reject) => {
6153
+ await new Promise((resolve8, reject) => {
6199
6154
  server.once("error", reject);
6200
6155
  server.listen(0, "127.0.0.1", () => {
6201
6156
  server.removeListener("error", reject);
6202
- resolve7();
6157
+ resolve8();
6203
6158
  });
6204
6159
  });
6205
6160
  const address = server.address();
@@ -6246,7 +6201,10 @@ async function createBrowserShellApprovalBridge(args) {
6246
6201
 
6247
6202
  // packages/cli/client/browserShellApprovalHost.ts
6248
6203
  async function withBrowserShellApproval(args, run) {
6249
- if (!args.requestUserChoice) return run();
6204
+ const resolveRenderer = () => args.awaitHostApproval ?? getHostApprovalRenderer();
6205
+ if (!resolveRenderer()) {
6206
+ return withShellChildEnvironment({ [BROWSER_SHELL_BRIDGE_ENV]: "" }, run);
6207
+ }
6250
6208
  const resolveClient = createChromeConnectorClientResolver();
6251
6209
  const bridges = [];
6252
6210
  try {
@@ -6257,28 +6215,30 @@ async function withBrowserShellApproval(args, run) {
6257
6215
  browser,
6258
6216
  signal: args.signal,
6259
6217
  connector: createConnectorApprovalPort(client),
6260
- executeInitial: async (call) => ({ content: JSON.stringify({ ok: true, result: await client().request(call.name, JSON.parse(call.arguments)) }) }),
6218
+ executeInitial: async (call) => ({
6219
+ content: JSON.stringify({
6220
+ ok: true,
6221
+ result: await client().request(call.name, JSON.parse(call.arguments))
6222
+ })
6223
+ }),
6261
6224
  awaitHostApproval: async (card, signal) => {
6262
- if (card.actionLabel !== "eval_script" && (!card.target?.trim() || card.target.trim() === "\u672A\u547D\u540D\u63A7\u4EF6")) return "deny";
6263
- if (card.actionLabel === "eval_script" && !card.summary.trim()) return "deny";
6264
- const tab = card.tabId;
6265
- const approvalText = `Browser action requires one-time approval
6266
- Action/risk: ${card.actionLabel} (may change page or external state)
6267
- Browser: ${browser}
6268
- Tab: ${tab ?? "unknown"}
6269
- Origin: ${card.origin}
6270
- Target: ${card.target ?? "script in the bound tab"}
6271
- Script/option summary:
6272
- ${card.summary}
6273
- Expires: ${new Date(card.expiresAt).toISOString()}`;
6274
- const result = await args.requestUserChoice({
6275
- question: "Approve this browser action once?",
6276
- approvalDisplay: { kind: "browser-approval", text: approvalText },
6277
- choices: [{ label: "Allow once", userMessage: "browser-allow-once" }, { label: "Deny", userMessage: "browser-deny" }],
6278
- blocking: true,
6279
- signal
6280
- });
6281
- return !signal.aborted && result.kind === "selected" && result.userMessage === "browser-allow-once" ? "allow_once" : "deny";
6225
+ if (card.actionLabel !== "eval_script" && (!card.target?.trim() || card.target.trim() === "\u672A\u547D\u540D\u63A7\u4EF6")) {
6226
+ return "deny";
6227
+ }
6228
+ if (card.actionLabel === "eval_script" && !card.summary.trim()) {
6229
+ return "deny";
6230
+ }
6231
+ const renderer = resolveRenderer();
6232
+ if (!renderer || signal.aborted) return "unavailable";
6233
+ if (card.expiresAt <= Date.now()) return "expired";
6234
+ const result = await renderer(
6235
+ { ...card, browser },
6236
+ { requestId: card.approvalId, signal, expiresAt: card.expiresAt }
6237
+ );
6238
+ if (signal.aborted) return "cancelled";
6239
+ if (card.expiresAt <= Date.now()) return "expired";
6240
+ if (result === "allow_once" || result === "deny") return result;
6241
+ return result === "cancelled" || result === "expired" || result === "unavailable" ? result : "unavailable";
6282
6242
  }
6283
6243
  });
6284
6244
  bridges.push(bridge);
@@ -6427,11 +6387,9 @@ function buildServerPlatformToolExecutors(args) {
6427
6387
  return text;
6428
6388
  };
6429
6389
  const guardExplicitTableCapture = (call) => {
6430
- if (inferCaptureIntent(String(call.userInput ?? "")) === "strong")
6431
- return null;
6432
6390
  return JSON.stringify({
6433
6391
  error: "knowledge_capture_requires_confirmation",
6434
- message: "\u5F53\u524D\u672C\u5730\u8FD0\u884C\u4E0D\u5141\u8BB8\u81EA\u52A8\u5199\u5165\u8868\u683C\u3002\u53EA\u6709\u5F53\u7528\u6237\u5728\u5F53\u524D\u8BF7\u6C42\u91CC\u660E\u786E\u8981\u6C42\u4FDD\u5B58\u3001\u5EFA\u8868\u3001\u5199\u5165 table \u6216\u505A\u6210\u6570\u636E\u96C6\u65F6\uFF0C\u624D\u80FD\u7EE7\u7EED\uFF1B\u5426\u5219\u8BF7\u5148\u8BE2\u95EE\u7528\u6237\u3002",
6392
+ message: "\u5F53\u524D\u6267\u884C\u9762\u6CA1\u6709\u53EF\u4FE1\u786E\u8BA4\u91CD\u653E\u80FD\u529B\uFF1B\u8BF7\u5728\u652F\u6301\u786E\u8BA4\u7684\u754C\u9762\u6838\u5BF9\u5177\u4F53\u5185\u5BB9\u548C\u76EE\u6807\u540E\u4FDD\u5B58\u3002",
6435
6393
  policy: {
6436
6394
  capability: "knowledge_capture",
6437
6395
  target: "table",
@@ -6535,7 +6493,7 @@ function buildServerPlatformToolExecutors(args) {
6535
6493
  const shortHash = (value, len) => createHash2("sha256").update(value).digest("hex").slice(0, len);
6536
6494
  const localMemoryContext = async () => {
6537
6495
  const openCliLocalRuntimeDb = async () => {
6538
- const { getDefaultCliLocalRuntimeDb: getDefaultCliLocalRuntimeDb2 } = await import("./localRuntimeDb-N7KHDXS2.js");
6496
+ const { getDefaultCliLocalRuntimeDb: getDefaultCliLocalRuntimeDb2 } = await import("./localRuntimeDb-BO7IVWAZ.js");
6539
6497
  return getDefaultCliLocalRuntimeDb2({ env: args.env });
6540
6498
  };
6541
6499
  try {
@@ -6566,7 +6524,7 @@ function buildServerPlatformToolExecutors(args) {
6566
6524
  const hits = recallMemoryVNextLocal({
6567
6525
  query,
6568
6526
  entities: catalog.entities,
6569
- states: catalog.states.filter((s) => !s.retiredAt && s.text.trim())
6527
+ states: catalog.states.filter((s) => !s.retiredAt && s.facet !== "work-context" && s.text.trim())
6570
6528
  });
6571
6529
  if (hits.length === 0) return null;
6572
6530
  const { mergeAndDedupUserData } = await import("./userDataMerge-HT2ZVHBJ.js");
@@ -6589,6 +6547,7 @@ function buildServerPlatformToolExecutors(args) {
6589
6547
  activationCount: 1,
6590
6548
  importance: typeof value.importance === "number" ? value.importance : 0.9,
6591
6549
  ...typeof value.confidence === "number" && Number.isFinite(value.confidence) ? { confidence: value.confidence } : {},
6550
+ ...["verified", "stated", "inferred"].includes(value.provenance) ? { provenance: value.provenance } : {},
6592
6551
  ...typeof value.sourceKind === "string" ? { sourceKind: value.sourceKind } : {},
6593
6552
  ...typeof value.sourceDialogId === "string" ? { sourceDialogId: value.sourceDialogId } : {},
6594
6553
  evidence,
@@ -6616,7 +6575,7 @@ function buildServerPlatformToolExecutors(args) {
6616
6575
  for (let i = ordered.length - 1; i >= 0; i -= 1) {
6617
6576
  if (isTombstoneRecord2(ordered[i])) ordered.splice(i, 1);
6618
6577
  }
6619
- const { buildMemoryOverlay, DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET } = await import("./overlay-BBQZXGYI.js");
6578
+ const { buildMemoryOverlay, DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET } = await import("./overlay-JA3SPVUS.js");
6620
6579
  const promptBlock = buildMemoryOverlay(ordered, {
6621
6580
  maxTokens: DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET
6622
6581
  });
@@ -6625,6 +6584,40 @@ function buildServerPlatformToolExecutors(args) {
6625
6584
  const writeLocalMemory = async (input) => {
6626
6585
  const ctx = await localMemoryContext();
6627
6586
  if (!ctx) return false;
6587
+ if (input.topicKey) {
6588
+ const { normalizeTopicKey, rememberExplicitVNext } = await import("./rememberExplicit-CPAPONSI.js");
6589
+ const topicKey = normalizeTopicKey(input.topicKey);
6590
+ if (topicKey) {
6591
+ const now = input.createdAt || (/* @__PURE__ */ new Date()).toISOString();
6592
+ const kind = ["episodic", "semantic", "procedural"].includes(input.kind) ? input.kind : "episodic";
6593
+ const validSubjectTypes = ["user", "agent", "space", "project", "system"];
6594
+ const hasValidSubject = typeof input.subjectType === "string" && validSubjectTypes.includes(input.subjectType) && typeof input.subjectId === "string" && input.subjectId.trim().length > 0;
6595
+ const trimmedAgentKey = args.agentKey?.trim() || "";
6596
+ const useAgentSubject = (input.scope ?? "auto") === "auto" && Boolean(trimmedAgentKey);
6597
+ const subjectType = hasValidSubject ? input.subjectType : useAgentSubject ? "agent" : "user";
6598
+ const subjectId = hasValidSubject ? input.subjectId.trim() : useAgentSubject ? trimmedAgentKey : ctx.userId;
6599
+ await rememberExplicitVNext(ctx.db, {
6600
+ id: "",
6601
+ ownerType: "user",
6602
+ ownerId: ctx.userId,
6603
+ visibility: "private",
6604
+ subjectType,
6605
+ subjectId,
6606
+ kind,
6607
+ content: input.content,
6608
+ createdAt: now,
6609
+ lastActivatedAt: now,
6610
+ activationCount: 0,
6611
+ importance: kind === "procedural" ? 0.88 : 0.82,
6612
+ confidence: input.confidence,
6613
+ ...input.tags?.length ? { tags: input.tags } : {},
6614
+ ...input.provenance === "verified" || input.provenance === "stated" || input.provenance === "inferred" ? { provenance: input.provenance } : {},
6615
+ ...input.sourceKind === "explicit-user-directive" || input.sourceKind === "agent-tool" || input.sourceKind === "inferred-understanding" || input.sourceKind === "dialog-learning" ? { sourceKind: input.sourceKind } : {},
6616
+ topicKey
6617
+ });
6618
+ return true;
6619
+ }
6620
+ }
6628
6621
  const [{ putMemoryEntityVNext, putMemoryStateVNext, putMemoryEvidenceVNext }, { buildLegacyMemoryEvidence }] = await Promise.all([
6629
6622
  import("./store-Z53ICFL3.js"),
6630
6623
  import("./legacyMigration-TF4SYJCZ.js")
@@ -6667,6 +6660,8 @@ function buildServerPlatformToolExecutors(args) {
6667
6660
  kind: input.kind,
6668
6661
  contentKey,
6669
6662
  origin: "cli-local",
6663
+ ...input.provenance ? { provenance: input.provenance } : {},
6664
+ ...input.sourceKind ? { sourceKind: input.sourceKind } : {},
6670
6665
  ...input.tags?.length ? { tags: input.tags } : {}
6671
6666
  },
6672
6667
  text: input.content,
@@ -6722,8 +6717,47 @@ function buildServerPlatformToolExecutors(args) {
6722
6717
  }
6723
6718
  return { retired, localOnlyRetired, skippedRemoteMiss };
6724
6719
  };
6720
+ const workMemory = async (call, parsed, write) => {
6721
+ const context = call.runtimeContext;
6722
+ const dialogId = context?.dialogId;
6723
+ const userMessageId = context?.userMessageId;
6724
+ if (typeof dialogId !== "string" || write && typeof userMessageId !== "string") throw new Error("work memory requires host dialogId and persisted userMessageId");
6725
+ const fields = write ? ["itemKey", "activityId", "expectedRevision", "changeId", "patch"] : ["activityId", "status", "query", "limit", "discovery"];
6726
+ const payload = Object.fromEntries(fields.filter((k) => parsed[k] !== void 0 && parsed[k] !== "").map((k) => [k, parsed[k]]));
6727
+ if (parsed.storage !== void 0 && parsed.storage !== "server" && parsed.storage !== "local") throw new Error("invalid work storage");
6728
+ const { formatWorkContextWriteNotice } = await import("./workContextWriteNotice-YCSSMHN4.js");
6729
+ const writeResult = (result2, priorNotice, storage) => ({
6730
+ ...result2,
6731
+ notice: [formatWorkContextWriteNotice(result2, storage ? { storage } : void 0), priorNotice].filter((v) => typeof v === "string" && v !== "").join("\n")
6732
+ });
6733
+ const workMetadata = { serverPlatformTool: true, memoryWrite: write, memoryRead: !write };
6734
+ if (parsed.storage === "server") {
6735
+ const content2 = await postServer(write ? "/api/memory/remember" : "/api/memory/query", { mode: "work", ...payload, dialogId, ...write ? { userMessageId } : {} });
6736
+ if (!write) return { content: content2, metadata: workMetadata };
6737
+ let served;
6738
+ try {
6739
+ served = JSON.parse(content2);
6740
+ } catch {
6741
+ return { content: content2, metadata: workMetadata };
6742
+ }
6743
+ return { content: JSON.stringify(writeResult(served, typeof served?.notice === "string" ? served.notice : void 0, "server")), metadata: workMetadata };
6744
+ }
6745
+ const ctx = await localMemoryContext();
6746
+ if (!ctx) throw new Error("local work memory unavailable");
6747
+ const { resolveLocalUserId: resolveLocalUserId2 } = await import("./cliAgentConfigHelpers-37ZNEY5Y.js");
6748
+ const localUserId = resolveLocalUserId2(args.env);
6749
+ const { resolveWorkContextAccess } = await import("./workContextAccess-VU5I4LKZ.js");
6750
+ const { updateWorkContext, readWorkContexts } = await import("./workContext-Y3ADAPZU.js");
6751
+ const { scope, sourceRef } = await resolveWorkContextAccess(ctx.db, localUserId, dialogId, write ? userMessageId : void 0);
6752
+ if (scope.spaceId) throw new Error("local work memory cannot verify space membership");
6753
+ const result = write ? await updateWorkContext(ctx.db, scope, { ...payload.activityId !== void 0 ? { activityId: payload.activityId, expectedRevision: payload.expectedRevision } : { itemKey: payload.itemKey, originRef: sourceRef }, changeId: payload.changeId, sourceRefs: [sourceRef], patch: payload.patch }) : await readWorkContexts(ctx.db, scope, payload);
6754
+ const storageNotice = "Local and server stores are independent; changeId deduplication covers actual changes only.";
6755
+ const content = write ? { ...writeResult(result, storageNotice, "local"), storage: "local" } : { ...result, storage: "local", notice: storageNotice };
6756
+ return { content: JSON.stringify(content), metadata: workMetadata };
6757
+ };
6725
6758
  const queryMemory = async (call) => {
6726
6759
  const parsed = parseNoloWorkspaceToolArguments(call.arguments);
6760
+ if (parsed.mode === "work") return workMemory(call, parsed, false);
6727
6761
  const query = typeof parsed.query === "string" ? parsed.query.trim() : "";
6728
6762
  if (!query) {
6729
6763
  return {
@@ -6760,6 +6794,7 @@ function buildServerPlatformToolExecutors(args) {
6760
6794
  };
6761
6795
  const rememberMemory = async (call) => {
6762
6796
  const parsed = parseNoloWorkspaceToolArguments(call.arguments);
6797
+ if (parsed.mode === "work") return workMemory(call, parsed, true);
6763
6798
  const content = typeof parsed.content === "string" ? parsed.content.trim() : "";
6764
6799
  if (!content) {
6765
6800
  return {
@@ -6775,9 +6810,28 @@ function buildServerPlatformToolExecutors(args) {
6775
6810
  kind: parsed.kind ?? "episodic",
6776
6811
  source: "agent-inferred"
6777
6812
  };
6813
+ if (["verified", "stated", "inferred"].includes(parsed.provenance)) body.provenance = parsed.provenance;
6778
6814
  if (typeof parsed.recurrenceEvidence === "string" && parsed.recurrenceEvidence.trim()) {
6779
6815
  body.recurrenceEvidence = parsed.recurrenceEvidence.trim();
6780
6816
  }
6817
+ if (parsed.topicKey !== void 0 && parsed.topicKey !== null) {
6818
+ if (typeof parsed.topicKey !== "string") {
6819
+ return {
6820
+ content: JSON.stringify({ error: "rememberMemory: topicKey must be a string" }),
6821
+ metadata: { serverPlatformTool: true, memoryWrite: false }
6822
+ };
6823
+ }
6824
+ const { normalizeTopicKey } = await import("./rememberExplicit-CPAPONSI.js");
6825
+ try {
6826
+ const normalizedTopicKey = normalizeTopicKey(parsed.topicKey);
6827
+ if (normalizedTopicKey) body.topicKey = normalizedTopicKey;
6828
+ } catch (err) {
6829
+ return {
6830
+ content: JSON.stringify({ error: err?.message ?? "invalid topicKey" }),
6831
+ metadata: { serverPlatformTool: true, memoryWrite: false }
6832
+ };
6833
+ }
6834
+ }
6781
6835
  if (args.agentKey) body.agentKey = args.agentKey;
6782
6836
  const raw = await postServer("/api/memory/remember", body, {
6783
6837
  retryTransient: true
@@ -6790,12 +6844,21 @@ function buildServerPlatformToolExecutors(args) {
6790
6844
  } catch {
6791
6845
  }
6792
6846
  const saved = Array.isArray(serverResult?.savedItems) ? serverResult.savedItems[0] : null;
6847
+ const resolvedTopicKey = typeof saved?.topicKey === "string" ? saved.topicKey : typeof body.topicKey === "string" ? body.topicKey : void 0;
6848
+ const validSubjectTypes = ["user", "agent", "space", "project", "system"];
6849
+ const savedSubjectType = typeof saved?.subjectType === "string" && validSubjectTypes.includes(saved.subjectType) ? saved.subjectType : void 0;
6850
+ const savedSubjectId = typeof saved?.subjectId === "string" && saved.subjectId.trim() ? saved.subjectId.trim() : void 0;
6793
6851
  localSaved = await writeLocalMemory({
6794
6852
  content: typeof saved?.content === "string" && saved.content.trim() ? saved.content : content,
6795
6853
  kind: String(saved?.kind ?? serverResult?.savedKind ?? body.kind ?? "episodic"),
6796
6854
  createdAt: typeof saved?.createdAt === "string" && saved.createdAt ? saved.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
6797
6855
  confidence: typeof saved?.confidence === "number" ? saved.confidence : 0.8,
6798
- tags: Array.isArray(saved?.tags) ? saved.tags.map(String) : void 0
6856
+ provenance: typeof saved?.provenance === "string" ? saved.provenance : void 0,
6857
+ sourceKind: typeof saved?.sourceKind === "string" ? saved.sourceKind : void 0,
6858
+ tags: Array.isArray(saved?.tags) ? saved.tags.map(String) : void 0,
6859
+ scope: typeof body.scope === "string" ? body.scope : "auto",
6860
+ ...savedSubjectType && savedSubjectId ? { subjectType: savedSubjectType, subjectId: savedSubjectId } : {},
6861
+ ...resolvedTopicKey ? { topicKey: resolvedTopicKey } : {}
6799
6862
  });
6800
6863
  } catch {
6801
6864
  }
@@ -6929,11 +6992,160 @@ function buildServerPlatformToolExecutors(args) {
6929
6992
  };
6930
6993
  }
6931
6994
 
6995
+ // packages/cli/client/workspaceIsolation.ts
6996
+ import * as fs from "node:fs";
6997
+ import { execFileSync } from "node:child_process";
6998
+ import { createHash as createHash3 } from "node:crypto";
6999
+ import { homedir } from "node:os";
7000
+ import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
7001
+ var WorkspaceIsolationError = class extends Error {
7002
+ code = "workspace_isolation_refused";
7003
+ };
7004
+ var dependencies = /* @__PURE__ */ new Set(["node_modules", ".venv"]);
7005
+ var refuse = (reason) => {
7006
+ throw new WorkspaceIsolationError(`${reason}\uFF1B\u8BF7\u7F29\u5C0F\u5230\u5177\u4F53\u5B50\u6587\u4EF6\u5939\u540E\u91CD\u8BD5 workspaceIsolation:auto`);
7007
+ };
7008
+ function prepareWorkspaceIsolation(options) {
7009
+ const { baseCwd, runId, mode = "none", readOnly, platform = process.platform } = options;
7010
+ if (mode !== "auto" || readOnly === true) return { mode, kind: "none", effectiveCwd: baseCwd };
7011
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(runId)) refuse("\u4E0D\u5B89\u5168\u7684 runId");
7012
+ const exec = options.execFile ?? execFileSync;
7013
+ const command = (file, args) => String(exec(file, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 3e4, env: { ...process.env, LC_ALL: "C", LANG: "C" } }));
7014
+ const source = fs.realpathSync(baseCwd);
7015
+ let repoRoot;
7016
+ try {
7017
+ repoRoot = command("git", ["-C", source, "rev-parse", "--show-toplevel"]).trim();
7018
+ } catch (error) {
7019
+ if (error.code === "ENOENT") {
7020
+ for (let ancestor = source; ; ancestor = dirname2(ancestor)) {
7021
+ try {
7022
+ fs.lstatSync(join2(ancestor, ".git"));
7023
+ throw new WorkspaceIsolationError("\u68C0\u6D4B\u5230 Git \u4ED3\u5E93\uFF0C\u4F46 Git \u547D\u4EE4\u672A\u5B89\u88C5\uFF1B\u8BF7\u5B89\u88C5 Git \u540E\u91CD\u8BD5");
7024
+ } catch (markerError) {
7025
+ if (markerError.code !== "ENOENT") throw markerError;
7026
+ }
7027
+ if (ancestor === dirname2(ancestor)) break;
7028
+ }
7029
+ } else if (!String(error.stderr).includes("not a git repository")) {
7030
+ throw error;
7031
+ }
7032
+ }
7033
+ const linkDependencies = (from, to) => {
7034
+ for (const name of dependencies) {
7035
+ const target = join2(from, name), link = join2(to, name);
7036
+ try {
7037
+ if (fs.statSync(target).isDirectory() && !fs.existsSync(link)) fs.symlinkSync(target, link, platform === "win32" ? "junction" : "dir");
7038
+ } catch {
7039
+ }
7040
+ }
7041
+ };
7042
+ if (repoRoot) {
7043
+ repoRoot = fs.realpathSync(repoRoot);
7044
+ const subRel = relative(repoRoot, source);
7045
+ if (isAbsolute(subRel) || subRel.split(/[\\/]/).includes("..")) refuse("\u76EE\u5F55\u4E0D\u5728\u4ED3\u5E93\u5185");
7046
+ const shortId = createHash3("sha256").update(runId).digest("hex").slice(0, 12);
7047
+ const commonDirOutput = command("git", ["-C", source, "rev-parse", "--git-common-dir"]).trim();
7048
+ const commonDir = fs.realpathSync(resolve(source, commonDirOutput));
7049
+ const worktreeHostRoot = basename(commonDir) === ".git" ? dirname2(commonDir) : repoRoot;
7050
+ const root2 = join2(worktreeHostRoot, ".worktrees", `run-${shortId}`), branch = `nolo/run-${shortId}`;
7051
+ if (platform === "win32" && root2.length > 210) refuse("\u9694\u79BB\u76EE\u5F55\u8DEF\u5F84\u8FC7\u957F");
7052
+ command("git", ["-C", repoRoot, "-c", "checkout.workers=0", "-c", "core.longpaths=true", "worktree", "add", root2, "-b", branch, "HEAD"]);
7053
+ linkDependencies(repoRoot, root2);
7054
+ if (worktreeHostRoot !== repoRoot) linkDependencies(worktreeHostRoot, root2);
7055
+ return { mode, kind: "git-worktree", effectiveCwd: join2(root2, subRel), root: root2, sourceRoot: repoRoot, branch };
7056
+ }
7057
+ if (source === dirname2(source) || source === fs.realpathSync(homedir())) refuse("\u4E0D\u80FD\u9694\u79BB\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u6216\u7528\u6237\u4E3B\u76EE\u5F55");
7058
+ let files = 0, bytes = 0, entries = 0;
7059
+ const scan = (dir, top, depth = 0) => {
7060
+ if (depth > 64) refuse("\u76EE\u5F55\u5D4C\u5957\u8D85\u8FC7 64 \u5C42\u4E0A\u9650");
7061
+ const handle = fs.opendirSync(dir);
7062
+ try {
7063
+ let entry;
7064
+ while (entry = handle.readSync()) {
7065
+ if (top && dependencies.has(entry.name)) continue;
7066
+ if (++entries > 4e3) refuse("\u76EE\u5F55\u6761\u76EE\u8D85\u8FC7 4000 \u4E0A\u9650");
7067
+ const path = join2(dir, entry.name), stat = fs.lstatSync(path);
7068
+ if (stat.isSymbolicLink() || !stat.isDirectory() && !stat.isFile()) refuse("\u666E\u901A\u4E1A\u52A1\u76EE\u5F55\u542B\u7B26\u53F7\u94FE\u63A5\u6216\u7279\u6B8A\u6587\u4EF6\uFF0C\u4E0D\u80FD\u5B89\u5168\u590D\u5236");
7069
+ if (stat.isDirectory()) scan(path, false, depth + 1);
7070
+ else if (++files > (options.maxFiles ?? 2e3) || (bytes += stat.size) > (options.maxBytes ?? 200 * 1024 * 1024)) refuse("\u76EE\u5F55\u8D85\u8FC7\u6587\u4EF6\u6570\u6216\u603B\u5927\u5C0F\u4E0A\u9650\uFF082000 \u6587\u4EF6 / 200 MiB\uFF09");
7071
+ }
7072
+ } finally {
7073
+ handle.closeSync();
7074
+ }
7075
+ };
7076
+ scan(source, true);
7077
+ const root = resolve(options.noloHome ?? join2(homedir(), ".nolo"), "workspaces", runId);
7078
+ const rel = relative(source, root);
7079
+ if (!rel || !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel)) refuse("\u5FEB\u7167\u76EE\u6807\u4E0D\u80FD\u4F4D\u4E8E\u6E90\u76EE\u5F55\u5185");
7080
+ fs.mkdirSync(dirname2(root), { recursive: true });
7081
+ fs.mkdirSync(root);
7082
+ try {
7083
+ for (const entry of fs.readdirSync(source)) {
7084
+ if (dependencies.has(entry)) continue;
7085
+ const from = join2(source, entry), to = join2(root, entry);
7086
+ let copied = false;
7087
+ try {
7088
+ if (platform === "darwin") {
7089
+ command("cp", ["-cR", from, to]);
7090
+ copied = true;
7091
+ } else if (platform === "linux") {
7092
+ command("cp", ["-a", "--reflink=always", "--", from, to]);
7093
+ copied = true;
7094
+ }
7095
+ } catch {
7096
+ }
7097
+ if (!copied) fs.cpSync(from, to, { recursive: true, force: true, dereference: false });
7098
+ }
7099
+ linkDependencies(source, root);
7100
+ } catch (error) {
7101
+ try {
7102
+ rollbackWorkspaceIsolation({ mode, kind: "directory-snapshot", effectiveCwd: root, root, sourceRoot: source });
7103
+ } catch (cleanupError) {
7104
+ throw new AggregateError([error, cleanupError], `\u590D\u5236\u5931\u8D25\uFF1B\u9694\u79BB\u76EE\u5F55\u4FDD\u7559\u5F85\u5904\u7406: ${root}`);
7105
+ }
7106
+ throw error;
7107
+ }
7108
+ return { mode, kind: "directory-snapshot", effectiveCwd: root, root, sourceRoot: source };
7109
+ }
7110
+ function rollbackWorkspaceIsolation(workspace) {
7111
+ const { root, sourceRoot, branch, kind } = workspace;
7112
+ if (!root || !sourceRoot) return;
7113
+ if (kind === "git-worktree") {
7114
+ const git = (args) => String(execFileSync("git", ["-C", sourceRoot, ...args], { encoding: "utf8" }));
7115
+ for (const name of dependencies) {
7116
+ const link = join2(root, name), original = join2(sourceRoot, name);
7117
+ if (!git(["-C", root, "ls-files", "--", name]).trim()) {
7118
+ try {
7119
+ if (fs.lstatSync(link).isSymbolicLink() && fs.realpathSync(link) === fs.realpathSync(original)) fs.unlinkSync(link);
7120
+ } catch (error) {
7121
+ if (error.code !== "ENOENT") throw error;
7122
+ }
7123
+ }
7124
+ }
7125
+ if (git(["-C", root, "status", "--porcelain", "--ignored"]).trim()) throw new Error(`\u9694\u79BB\u76EE\u5F55\u542B\u672A\u9A8C\u8BC1\u5185\u5BB9\uFF0C\u4FDD\u7559 ${root}`);
7126
+ execFileSync("git", ["-C", sourceRoot, "merge-base", "--is-ancestor", branch, "HEAD"]);
7127
+ git(["worktree", "remove", root]);
7128
+ git(["branch", "-d", branch]);
7129
+ } else if (kind === "directory-snapshot") {
7130
+ const verify = (path) => {
7131
+ for (const entry of fs.readdirSync(path)) {
7132
+ const target = join2(path, entry), original = join2(sourceRoot, relative(root, target));
7133
+ const stat = fs.lstatSync(target);
7134
+ if (path === root && dependencies.has(entry) && stat.isSymbolicLink() && fs.realpathSync(target) === fs.realpathSync(original)) continue;
7135
+ if (stat.isDirectory() && fs.statSync(original).isDirectory()) verify(target);
7136
+ else if (!stat.isFile() || !fs.statSync(original).isFile() || !fs.readFileSync(target).equals(fs.readFileSync(original))) throw new Error(`\u9694\u79BB\u526F\u672C\u6709\u552F\u4E00\u5185\u5BB9\uFF0C\u4FDD\u7559 ${root}`);
7137
+ }
7138
+ };
7139
+ verify(root);
7140
+ fs.rmSync(root, { recursive: true });
7141
+ }
7142
+ }
7143
+
6932
7144
  // packages/cli/client/childRunImages.ts
6933
- import { isAbsolute } from "node:path";
7145
+ import { isAbsolute as isAbsolute2 } from "node:path";
6934
7146
  function validateChildImagePaths(value) {
6935
7147
  if (value === void 0) return [];
6936
- if (!Array.isArray(value) || value.length < 1 || value.length > MAX_TOOL_IMAGES_PER_REQUEST || value.some((path) => typeof path !== "string" || !isAbsolute(path) || path.includes("\0"))) {
7148
+ if (!Array.isArray(value) || value.length < 1 || value.length > MAX_TOOL_IMAGES_PER_REQUEST || value.some((path) => typeof path !== "string" || !isAbsolute2(path) || path.includes("\0"))) {
6937
7149
  throw new Error("image_input_invalid: expected 1\u20134 absolute local image paths");
6938
7150
  }
6939
7151
  return value;
@@ -6966,8 +7178,8 @@ async function normalizeCliRunImages(inputs, normalizeRemote) {
6966
7178
  }
6967
7179
 
6968
7180
  // packages/cli/agentRunArgs.ts
6969
- import { readFileSync } from "node:fs";
6970
- import { isAbsolute as isAbsolute2 } from "node:path";
7181
+ import { readFileSync as readFileSync2 } from "node:fs";
7182
+ import { isAbsolute as isAbsolute3 } from "node:path";
6971
7183
  function readFlagValue(args, flag) {
6972
7184
  const index = args.indexOf(flag);
6973
7185
  if (index < 0) return void 0;
@@ -7108,7 +7320,7 @@ function parseAgentRunArgs(args, options = {}) {
7108
7320
  const agentKey = rawAgentKey ? resolveCliAgentKeyInput(rawAgentKey) : void 0;
7109
7321
  const explicitMsg = readFlagValue(args, "--msg");
7110
7322
  const msgFile = readFlagValue(args, "--msg-file");
7111
- const fileMessage = msgFile ? (options.readTextFile ?? ((path) => readFileSync(path, "utf8")))(msgFile) : void 0;
7323
+ const fileMessage = msgFile ? (options.readTextFile ?? ((path) => readFileSync2(path, "utf8")))(msgFile) : void 0;
7112
7324
  const rawMessage = explicitMsg ?? fileMessage ?? positional.slice(isNoLoginRunShorthand ? 0 : 1).join(" ");
7113
7325
  if (!agentKey || !rawMessage.trim()) return null;
7114
7326
  const message = rawMessage.trim();
@@ -7169,7 +7381,7 @@ function parseAgentRunArgs(args, options = {}) {
7169
7381
  if (!rawInstaboxArtifactDir) {
7170
7382
  throw new Error("--runtime-key instabox \u5FC5\u987B\u6307\u5B9A --instabox-artifact-dir <\u7EDD\u5BF9\u8DEF\u5F84>");
7171
7383
  }
7172
- if (!isAbsolute2(rawInstaboxArtifactDir) || rawInstaboxArtifactDir.includes("\0") || rawInstaboxArtifactDir.split("/").includes("..")) {
7384
+ if (!isAbsolute3(rawInstaboxArtifactDir) || rawInstaboxArtifactDir.includes("\0") || rawInstaboxArtifactDir.split("/").includes("..")) {
7173
7385
  throw new Error(`--instabox-artifact-dir \u5FC5\u987B\u4E3A\u5408\u6CD5\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B .. \u6216\u7A7A\u5B57\u7B26: "${rawInstaboxArtifactDir}"`);
7174
7386
  }
7175
7387
  if (rawInstaboxWorkspace === "snapshot" && !rawInstaboxManifest) {
@@ -7274,7 +7486,7 @@ function parseAgentRunArgs(args, options = {}) {
7274
7486
  }
7275
7487
 
7276
7488
  // packages/cli/client/cliAgentRunToolExecutors.ts
7277
- import { join as join3, resolve as resolve3 } from "node:path";
7489
+ import { dirname as dirname4, join as join4, resolve as resolve4 } from "node:path";
7278
7490
  import { randomUUID as randomUUID3 } from "node:crypto";
7279
7491
  import * as nodeFs2 from "node:fs";
7280
7492
 
@@ -7338,7 +7550,7 @@ function waitForRunTerminal(args) {
7338
7550
  }
7339
7551
 
7340
7552
  // packages/cli/client/cliAgentRunToolExecutors.ts
7341
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
7553
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
7342
7554
 
7343
7555
  // packages/cli/client/agentRunSnapshot.ts
7344
7556
  function readString(value) {
@@ -7458,13 +7670,13 @@ function isFailureStatus(status) {
7458
7670
  function isOrphanedStatus(status) {
7459
7671
  return status === "orphaned";
7460
7672
  }
7461
- function toEpochMs2(iso) {
7673
+ function toEpochMs(iso) {
7462
7674
  if (!iso) return void 0;
7463
7675
  const ms = Date.parse(iso);
7464
7676
  return Number.isFinite(ms) ? ms : void 0;
7465
7677
  }
7466
7678
  function isOverTimeout(run, nowMs, timeoutMs) {
7467
- const startedMs = toEpochMs2(run.startedAt);
7679
+ const startedMs = toEpochMs(run.startedAt);
7468
7680
  if (startedMs === void 0) return false;
7469
7681
  return nowMs - startedMs >= timeoutMs;
7470
7682
  }
@@ -7510,7 +7722,7 @@ function aggregateBatch(input) {
7510
7722
  const { batchId, runs, now } = input;
7511
7723
  const timeoutMs = input.timeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS;
7512
7724
  const notified = new Set(input.notifiedReasons ?? []);
7513
- const nowMs = toEpochMs2(now) ?? 0;
7725
+ const nowMs = toEpochMs(now) ?? 0;
7514
7726
  let success = 0;
7515
7727
  let failed = 0;
7516
7728
  let orphaned = 0;
@@ -7584,47 +7796,47 @@ function deriveAgentRunTodoStatus(input) {
7584
7796
  }
7585
7797
 
7586
7798
  // packages/cli/client/fileSystemStores.ts
7587
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
7799
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "node:fs";
7588
7800
  import { homedir as nodeHomedir } from "node:os";
7589
- import { dirname as dirname2, join as join2 } from "node:path";
7801
+ import { dirname as dirname3, join as join3 } from "node:path";
7590
7802
  var nodeFs = {
7591
- mkdirSync,
7803
+ mkdirSync: mkdirSync2,
7592
7804
  writeFileSync,
7593
- readFileSync: readFileSync2,
7594
- existsSync: existsSync2
7805
+ readFileSync: readFileSync3,
7806
+ existsSync: existsSync3
7595
7807
  };
7596
- function resolveNoloHome(env, homedir2) {
7808
+ function resolveNoloHome(env, homedir3) {
7597
7809
  const custom = env?.NOLO_HOME;
7598
7810
  if (custom && custom.trim()) return custom.trim();
7599
7811
  const ambient = process.env.NOLO_HOME?.trim();
7600
7812
  if (ambient) return ambient;
7601
- return join2(homedir2(), ".nolo");
7813
+ return join3(homedir3(), ".nolo");
7602
7814
  }
7603
- function ensureDir(dir, fs) {
7604
- fs.mkdirSync(dir, { recursive: true });
7815
+ function ensureDir(dir, fs2) {
7816
+ fs2.mkdirSync(dir, { recursive: true });
7605
7817
  }
7606
- function readJson(path, fs) {
7607
- if (!fs.existsSync(path)) return void 0;
7818
+ function readJson(path, fs2) {
7819
+ if (!fs2.existsSync(path)) return void 0;
7608
7820
  try {
7609
- const raw = fs.readFileSync(path, "utf8");
7821
+ const raw = fs2.readFileSync(path, "utf8");
7610
7822
  return JSON.parse(String(raw));
7611
7823
  } catch {
7612
7824
  return void 0;
7613
7825
  }
7614
7826
  }
7615
- function writeJson(path, data, fs) {
7616
- fs.writeFileSync(path, JSON.stringify(data, null, 2));
7827
+ function writeJson(path, data, fs2) {
7828
+ fs2.writeFileSync(path, JSON.stringify(data, null, 2));
7617
7829
  }
7618
7830
  function createFileSystemTodoStore(opts = {}) {
7619
7831
  const env = opts.env ?? process.env;
7620
- const homedir2 = opts.homedir ?? nodeHomedir;
7621
- const fs = opts.fs ?? nodeFs;
7622
- const noloHome = resolveNoloHome(env, homedir2);
7623
- const filePath = opts.filePath ?? join2(noloHome, "agent_run_todos.json");
7624
- const oldFilePath = join2(noloHome, "todos.json");
7832
+ const homedir3 = opts.homedir ?? nodeHomedir;
7833
+ const fs2 = opts.fs ?? nodeFs;
7834
+ const noloHome = resolveNoloHome(env, homedir3);
7835
+ const filePath = opts.filePath ?? join3(noloHome, "agent_run_todos.json");
7836
+ const oldFilePath = join3(noloHome, "todos.json");
7625
7837
  const loadMap = () => {
7626
- if (!opts.filePath && !fs.existsSync(filePath) && fs.existsSync(oldFilePath)) {
7627
- const oldData = readJson(oldFilePath, fs);
7838
+ if (!opts.filePath && !fs2.existsSync(filePath) && fs2.existsSync(oldFilePath)) {
7839
+ const oldData = readJson(oldFilePath, fs2);
7628
7840
  const map2 = /* @__PURE__ */ new Map();
7629
7841
  if (oldData?.todos) {
7630
7842
  for (const item of oldData.todos) {
@@ -7646,11 +7858,11 @@ function createFileSystemTodoStore(opts = {}) {
7646
7858
  }
7647
7859
  }
7648
7860
  }
7649
- ensureDir(dirname2(filePath), fs);
7650
- writeJson(filePath, { todos: [...map2.values()] }, fs);
7861
+ ensureDir(dirname3(filePath), fs2);
7862
+ writeJson(filePath, { todos: [...map2.values()] }, fs2);
7651
7863
  return map2;
7652
7864
  }
7653
- const data = readJson(filePath, fs);
7865
+ const data = readJson(filePath, fs2);
7654
7866
  const map = /* @__PURE__ */ new Map();
7655
7867
  if (data?.todos) {
7656
7868
  for (const todo of data.todos) {
@@ -7660,8 +7872,8 @@ function createFileSystemTodoStore(opts = {}) {
7660
7872
  return map;
7661
7873
  };
7662
7874
  const persist = (map) => {
7663
- ensureDir(dirname2(filePath), fs);
7664
- writeJson(filePath, { todos: [...map.values()] }, fs);
7875
+ ensureDir(dirname3(filePath), fs2);
7876
+ writeJson(filePath, { todos: [...map.values()] }, fs2);
7665
7877
  };
7666
7878
  return {
7667
7879
  async getTodo(id) {
@@ -7691,13 +7903,13 @@ function createFileSystemTodoStore(opts = {}) {
7691
7903
  }
7692
7904
 
7693
7905
  // packages/cli/client/instaboxRunConfig.ts
7694
- import { lstatSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
7695
- import { isAbsolute as isAbsolute3, normalize, resolve as resolve2 } from "node:path";
7906
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
7907
+ import { isAbsolute as isAbsolute4, normalize, resolve as resolve3 } from "node:path";
7696
7908
 
7697
7909
  // packages/cli/client/localInstaboxWorkspaceDelivery.ts
7698
7910
  import { constants } from "node:fs";
7699
7911
  import { open, realpath } from "node:fs/promises";
7700
- import { createHash as createHash3 } from "node:crypto";
7912
+ import { createHash as createHash4 } from "node:crypto";
7701
7913
 
7702
7914
  // packages/agent-runtime/instaboxBackend.ts
7703
7915
  var INSTABOX_BACKEND_ID = "instabox";
@@ -7872,7 +8084,7 @@ var InstaboxBackend = class {
7872
8084
  ...rawBody === void 0 ? {} : { body: rawBody }
7873
8085
  });
7874
8086
  });
7875
- this.#sleep = options.sleepImpl ?? ((ms) => new Promise((resolve7) => setTimeout(resolve7, ms)));
8087
+ this.#sleep = options.sleepImpl ?? ((ms) => new Promise((resolve8) => setTimeout(resolve8, ms)));
7876
8088
  this.#machineTimeoutSeconds = options.machineTimeoutSeconds ?? 1800;
7877
8089
  this.#createTimeoutMs = options.createTimeoutMs ?? 18e4;
7878
8090
  this.#deleteTimeoutMs = options.deleteTimeoutMs ?? 12e4;
@@ -8429,8 +8641,8 @@ var InstaboxBackend = class {
8429
8641
  try {
8430
8642
  await Promise.race([
8431
8643
  this.#sleep(Math.min(this.#pollIntervalMs, remaining())),
8432
- new Promise((resolve7) => {
8433
- timer = setTimeout(resolve7, remaining());
8644
+ new Promise((resolve8) => {
8645
+ timer = setTimeout(resolve8, remaining());
8434
8646
  })
8435
8647
  ]);
8436
8648
  } finally {
@@ -8733,8 +8945,8 @@ var InstaboxBackend = class {
8733
8945
  try {
8734
8946
  return await Promise.race([
8735
8947
  this.#call({ ...args, timeoutMs: void 0 }),
8736
- new Promise((resolve7) => {
8737
- timer = setTimeout(() => resolve7({ status: 0, payload: null, transportError: "Timeout" }), args.timeoutMs);
8948
+ new Promise((resolve8) => {
8949
+ timer = setTimeout(() => resolve8({ status: 0, payload: null, transportError: "Timeout" }), args.timeoutMs);
8738
8950
  })
8739
8951
  ]);
8740
8952
  } finally {
@@ -8872,7 +9084,7 @@ function extractInstaboxErrorCode(payload) {
8872
9084
 
8873
9085
  // packages/cli/client/localInstaboxWorkspaceDelivery.ts
8874
9086
  var SNAPSHOT_LIMITS = { files: 256, fileBytes: 8 * 1024 * 1024, totalBytes: 32 * 1024 * 1024, chunkBytes: 384 * 1024 };
8875
- var hash = (bytes) => createHash3("sha256").update(bytes).digest("hex");
9087
+ var hash = (bytes) => createHash4("sha256").update(bytes).digest("hex");
8876
9088
  var fail = (code) => {
8877
9089
  throw new Error(`instabox_workspace_delivery:${code}`);
8878
9090
  };
@@ -9094,14 +9306,14 @@ function resolveInstaboxRunConfigPath(options) {
9094
9306
  fail2("missing_path", `\u73AF\u5883\u53D8\u91CF ${INSTABOX_RUN_CONFIG_ENV} \u672A\u8BBE\u7F6E\u6216\u4E3A\u7A7A`);
9095
9307
  }
9096
9308
  const runsDir = options?.runsDir ?? resolveRunsDir(env);
9097
- const normalizedRunsDir = normalize(resolve2(runsDir));
9098
- const resolvedTarget = isAbsolute3(explicitPath) ? normalize(explicitPath) : normalize(resolve2(normalizedRunsDir, explicitPath));
9309
+ const normalizedRunsDir = normalize(resolve3(runsDir));
9310
+ const resolvedTarget = isAbsolute4(explicitPath) ? normalize(explicitPath) : normalize(resolve3(normalizedRunsDir, explicitPath));
9099
9311
  if (resolvedTarget !== normalizedRunsDir && !resolvedTarget.startsWith(normalizedRunsDir.endsWith("/") ? normalizedRunsDir : `${normalizedRunsDir}/`)) {
9100
9312
  fail2("path_traversal", `\u914D\u7F6E\u8DEF\u5F84 "${explicitPath}" \u8D8A\u51FA\u4E86\u9650\u5B9A\u7684 runs \u76EE\u5F55 "${normalizedRunsDir}"`);
9101
9313
  }
9102
9314
  let stats;
9103
9315
  try {
9104
- stats = lstatSync(resolvedTarget);
9316
+ stats = lstatSync2(resolvedTarget);
9105
9317
  } catch (err) {
9106
9318
  fail2("file_unreadable", `\u914D\u7F6E\u6587\u4EF6\u4E0D\u53EF\u8BFB\u6216\u4E0D\u5B58\u5728: ${resolvedTarget}`);
9107
9319
  }
@@ -9115,8 +9327,8 @@ function resolveInstaboxRunConfigPath(options) {
9115
9327
  fail2("file_too_large", `\u914D\u7F6E\u6587\u4EF6\u5927\u5C0F (${stats.size} \u5B57\u8282) \u8D85\u8FC7\u4E0A\u9650 (${INSTABOX_RUN_CONFIG_MAX_BYTES} \u5B57\u8282)`);
9116
9328
  }
9117
9329
  try {
9118
- const realTarget = realpathSync2(resolvedTarget);
9119
- const realRuns = realpathSync2(normalizedRunsDir);
9330
+ const realTarget = realpathSync3(resolvedTarget);
9331
+ const realRuns = realpathSync3(normalizedRunsDir);
9120
9332
  if (realTarget !== realRuns && !realTarget.startsWith(realRuns.endsWith("/") ? realRuns : `${realRuns}/`)) {
9121
9333
  fail2("symlink_traversal", `\u914D\u7F6E\u771F\u5B9E\u8DEF\u5F84 "${realTarget}" \u8D8A\u51FA runs \u771F\u5B9E\u76EE\u5F55 "${realRuns}"`);
9122
9334
  }
@@ -9128,7 +9340,7 @@ function loadInstaboxRunConfig(options) {
9128
9340
  const { resolvedPath } = resolveInstaboxRunConfigPath(options);
9129
9341
  let rawText;
9130
9342
  try {
9131
- rawText = readFileSync3(resolvedPath, "utf8");
9343
+ rawText = readFileSync4(resolvedPath, "utf8");
9132
9344
  } catch (err) {
9133
9345
  fail2("file_read_failed", `\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`);
9134
9346
  }
@@ -9177,7 +9389,7 @@ function loadInstaboxRunConfig(options) {
9177
9389
  if (!artifactRootRaw) {
9178
9390
  fail2("missing_artifact_root", "artifactRoot (artifact\u76EE\u7684\u76EE\u5F55) \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u672A\u914D\u7F6E\u6216\u9ED8\u8BA4\u5747\u88AB\u62D2\u7EDD");
9179
9391
  }
9180
- if (!isAbsolute3(artifactRootRaw) || artifactRootRaw.includes("\0") || artifactRootRaw.split("/").includes("..")) {
9392
+ if (!isAbsolute4(artifactRootRaw) || artifactRootRaw.includes("\0") || artifactRootRaw.split("/").includes("..")) {
9181
9393
  fail2("invalid_artifact_root", `artifactRoot \u5FC5\u987B\u4E3A\u5408\u6CD5\u7EDD\u5BF9\u8DEF\u5F84: "${artifactRootRaw}"`);
9182
9394
  }
9183
9395
  const artifactRoot = normalize(artifactRootRaw);
@@ -9296,7 +9508,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9296
9508
  }
9297
9509
  }
9298
9510
  if (effectiveAvailableMb === null) {
9299
- const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u63A2\u6D4B\u5931\u8D25\u6216\u672A\u77E5\uFF08${memoryDiagnosis}\uFF09\uFF1B\u65E0\u6CD5\u5224\u65AD\u662F\u5426\u4F4E\u4E8E\u9884\u7B97\uFF08${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u4FDD\u6301\u9ED8\u8BA4\u672C\u5730\u6C99\u76D2\uFF0C\u4E0D\u81EA\u52A8\u8FC1\u79FB\u3002`;
9511
+ const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u63A2\u6D4B\u5931\u8D25\u6216\u672A\u77E5\uFF08${memoryDiagnosis}\uFF09\uFF1B\u65E0\u6CD5\u5224\u65AD\u662F\u5426\u4F4E\u4E8E\u9884\u7B97\uFF08${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u4FDD\u6301\u9ED8\u8BA4\u5BBF\u4E3B\uFF08\u5199\u578B\u6D3E\u53D1\u4ECD\u987B allowHostWrites: true\uFF09\uFF0C\u4E0D\u81EA\u52A8\u8FC1\u79FB\u3002`;
9300
9512
  return {
9301
9513
  selectedRuntimeKey: void 0,
9302
9514
  reason: "memory_unknown",
@@ -9313,7 +9525,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9313
9525
  }
9314
9526
  const autoEnabled = input.autoEnabled === true || input.env?.NOLO_INSTABOX_AUTO === "1" || typeof process !== "undefined" && process.env?.NOLO_INSTABOX_AUTO === "1";
9315
9527
  if (!autoEnabled) {
9316
- const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u4F46\u672A\u542F\u7528\u81EA\u52A8 Instabox\uFF08\u9700\u8BBE\u7F6E NOLO_INSTABOX_AUTO=1 \u6216\u914D\u7F6E\u5F00\u542F\uFF09\uFF1B\u4FDD\u6301\u9ED8\u8BA4 docker \u6C99\u76D2\u3002`;
9528
+ const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u4F46\u672A\u542F\u7528\u81EA\u52A8 Instabox\uFF08\u9700\u8BBE\u7F6E NOLO_INSTABOX_AUTO=1 \u6216\u914D\u7F6E\u5F00\u542F\uFF09\uFF1B\u4FDD\u6301\u9ED8\u8BA4\u5BBF\u4E3B\uFF08\u5199\u578B\u6D3E\u53D1\u4ECD\u987B allowHostWrites: true\uFF09\u3002`;
9317
9529
  return {
9318
9530
  selectedRuntimeKey: void 0,
9319
9531
  reason: "auto_disabled",
@@ -9328,7 +9540,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9328
9540
  });
9329
9541
  } catch (error) {
9330
9542
  const errorMsg = error instanceof Error ? error.message : String(error);
9331
- const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u6539\u7528 Instabox \u53D7\u963B\uFF1A${errorMsg}\uFF1B\u4FDD\u6301\u9ED8\u8BA4 docker \u6C99\u76D2\u3002`;
9543
+ const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u6539\u7528 Instabox \u53D7\u963B\uFF1A${errorMsg}\uFF1B\u4FDD\u6301\u9ED8\u8BA4\u5BBF\u4E3B\uFF08\u5199\u578B\u6D3E\u53D1\u4ECD\u987B allowHostWrites: true\uFF09\u3002`;
9332
9544
  return {
9333
9545
  selectedRuntimeKey: void 0,
9334
9546
  reason: "config_unavailable",
@@ -9340,7 +9552,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9340
9552
  try {
9341
9553
  const readiness = await input.checkReadiness();
9342
9554
  if (readiness && readiness.ready === false) {
9343
- const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u6539\u7528 Instabox \u4F46\u88AB\u670D\u52A1\u7AEF\u51C6\u5165/\u5C31\u7EEA\u660E\u786E\u62D2\u7EDD\uFF1A${readiness.reason ?? "\u670D\u52A1\u7AEF\u672A\u5C31\u7EEA"}\uFF1B\u4FDD\u6301\u9ED8\u8BA4 docker \u6C99\u76D2\u3002`;
9555
+ const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u6539\u7528 Instabox \u4F46\u88AB\u670D\u52A1\u7AEF\u51C6\u5165/\u5C31\u7EEA\u660E\u786E\u62D2\u7EDD\uFF1A${readiness.reason ?? "\u670D\u52A1\u7AEF\u672A\u5C31\u7EEA"}\uFF1B\u4FDD\u6301\u9ED8\u8BA4\u5BBF\u4E3B\uFF08\u5199\u578B\u6D3E\u53D1\u4ECD\u987B allowHostWrites: true\uFF09\u3002`;
9344
9556
  return {
9345
9557
  selectedRuntimeKey: void 0,
9346
9558
  reason: "readiness_rejected",
@@ -9350,7 +9562,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9350
9562
  }
9351
9563
  } catch (error) {
9352
9564
  const errorMsg = error instanceof Error ? error.message : String(error);
9353
- const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u6539\u7528 Instabox \u4F46\u5C31\u7EEA\u68C0\u67E5\u629B\u9519\uFF1A${errorMsg}\uFF1B\u4FDD\u6301\u9ED8\u8BA4 docker \u6C99\u76D2\u3002`;
9565
+ const note2 = `\u5BBF\u4E3B\u53EF\u7528\u5185\u5B58\u7D27\u7F3A\uFF08${effectiveAvailableMb}MB < ${LOCAL_TOOL_MEMORY_BUDGET_MB}MB\uFF09\uFF0C\u5C1D\u8BD5\u81EA\u52A8\u6539\u7528 Instabox \u4F46\u5C31\u7EEA\u68C0\u67E5\u629B\u9519\uFF1A${errorMsg}\uFF1B\u4FDD\u6301\u9ED8\u8BA4\u5BBF\u4E3B\uFF08\u5199\u578B\u6D3E\u53D1\u4ECD\u987B allowHostWrites: true\uFF09\u3002`;
9354
9566
  return {
9355
9567
  selectedRuntimeKey: void 0,
9356
9568
  reason: "readiness_error",
@@ -9410,10 +9622,10 @@ var parseCallArgs = (call) => {
9410
9622
  return {};
9411
9623
  }
9412
9624
  };
9413
- var resolveFs = (deps) => deps.fs ?? { existsSync: existsSync3, readFileSync: readFileSync4 };
9625
+ var resolveFs = (deps) => deps.fs ?? { existsSync: existsSync4, readFileSync: readFileSync5 };
9414
9626
  var probeRunCwd = (deps) => {
9415
- const fs = deps.fs;
9416
- const stat = fs?.statSync ?? nodeFs2.statSync;
9627
+ const fs2 = deps.fs;
9628
+ const stat = fs2?.statSync ?? nodeFs2.statSync;
9417
9629
  return (absolutePath) => {
9418
9630
  try {
9419
9631
  return stat(absolutePath).isDirectory() ? "directory" : "not-a-directory";
@@ -9422,10 +9634,10 @@ var probeRunCwd = (deps) => {
9422
9634
  }
9423
9635
  };
9424
9636
  };
9425
- var tailFile = (logPath, tailLines, fs) => {
9426
- if (!fs.existsSync(logPath)) return void 0;
9637
+ var tailFile = (logPath, tailLines, fs2) => {
9638
+ if (!fs2.existsSync(logPath)) return void 0;
9427
9639
  try {
9428
- const content = fs.readFileSync(logPath, "utf8");
9640
+ const content = fs2.readFileSync(logPath, "utf8");
9429
9641
  const lines = String(content).split(/\r?\n/);
9430
9642
  if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
9431
9643
  return lines.slice(Math.max(0, lines.length - tailLines)).join("\n");
@@ -9587,36 +9799,36 @@ function createCliStartAgentRunExecutor(deps = {}) {
9587
9799
  let previousCacheHitRatio = previousRecord?.cacheHitRatio;
9588
9800
  if (previousRecord && previousCacheHitRatio === void 0 && previousRecord.resultFile) {
9589
9801
  try {
9590
- const fs = deps.fs ?? nodeFs2;
9591
- const runsDir = resolve3(resolveRunsDir(deps.env, deps.homedir));
9592
- const expected = resolve3(runsDir, `${previousRecord.runId}.result.md`);
9593
- if (previousRecord.runId.includes("/") || previousRecord.runId.includes("\\") || resolve3(previousRecord.resultFile) !== expected || !fs.realpathSync || !fs.lstatSync) throw new Error("Unverified result path");
9594
- const stat = fs.lstatSync(expected);
9802
+ const fs2 = deps.fs ?? nodeFs2;
9803
+ const runsDir = resolve4(resolveRunsDir(deps.env, deps.homedir));
9804
+ const expected = resolve4(runsDir, `${previousRecord.runId}.result.md`);
9805
+ if (previousRecord.runId.includes("/") || previousRecord.runId.includes("\\") || resolve4(previousRecord.resultFile) !== expected || !fs2.realpathSync || !fs2.lstatSync) throw new Error("Unverified result path");
9806
+ const stat = fs2.lstatSync(expected);
9595
9807
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Non-regular result file");
9596
- const canonicalDir = String(fs.realpathSync(runsDir));
9597
- if (String(fs.realpathSync(expected)) !== join3(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Result escapes runs directory");
9598
- if ((deps.platform ?? process.platform) !== "linux" || !fs.fstatSync || !fs.readSync || !fs.closeSync || !nodeFs2.constants.O_NOFOLLOW || !nodeFs2.constants.O_DIRECTORY) throw new Error("FD proof unavailable");
9808
+ const canonicalDir = String(fs2.realpathSync(runsDir));
9809
+ if (String(fs2.realpathSync(expected)) !== join4(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Result escapes runs directory");
9810
+ if ((deps.platform ?? process.platform) !== "linux" || !fs2.fstatSync || !fs2.readSync || !fs2.closeSync || !nodeFs2.constants.O_NOFOLLOW || !nodeFs2.constants.O_DIRECTORY) throw new Error("FD proof unavailable");
9599
9811
  let dirFd;
9600
9812
  let resultFd;
9601
9813
  let text = "";
9602
9814
  try {
9603
- dirFd = fs.openSync(runsDir, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_DIRECTORY | nodeFs2.constants.O_NOFOLLOW);
9604
- if (!fs.fstatSync(dirFd).isDirectory() || String(fs.realpathSync(`/proc/self/fd/${dirFd}`)) !== canonicalDir) throw new Error("Unverified directory fd");
9605
- resultFd = fs.openSync(`/proc/self/fd/${dirFd}/${previousRecord.runId}.result.md`, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_NOFOLLOW | nodeFs2.constants.O_NONBLOCK);
9606
- if (!fs.fstatSync(resultFd).isFile() || String(fs.realpathSync(`/proc/self/fd/${resultFd}`)) !== join3(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Unverified result fd");
9815
+ dirFd = fs2.openSync(runsDir, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_DIRECTORY | nodeFs2.constants.O_NOFOLLOW);
9816
+ if (!fs2.fstatSync(dirFd).isDirectory() || String(fs2.realpathSync(`/proc/self/fd/${dirFd}`)) !== canonicalDir) throw new Error("Unverified directory fd");
9817
+ resultFd = fs2.openSync(`/proc/self/fd/${dirFd}/${previousRecord.runId}.result.md`, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_NOFOLLOW | nodeFs2.constants.O_NONBLOCK);
9818
+ if (!fs2.fstatSync(resultFd).isFile() || String(fs2.realpathSync(`/proc/self/fd/${resultFd}`)) !== join4(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Unverified result fd");
9607
9819
  const bytes = Buffer.alloc(16 * 1024);
9608
9820
  let offset = 0;
9609
9821
  while (offset < bytes.length) {
9610
- const count2 = fs.readSync(resultFd, bytes, offset, bytes.length - offset, offset);
9822
+ const count2 = fs2.readSync(resultFd, bytes, offset, bytes.length - offset, offset);
9611
9823
  if (count2 === 0) break;
9612
9824
  offset += count2;
9613
9825
  }
9614
9826
  text = bytes.subarray(0, offset).toString("utf8");
9615
9827
  } finally {
9616
9828
  try {
9617
- if (resultFd !== void 0) fs.closeSync(resultFd);
9829
+ if (resultFd !== void 0) fs2.closeSync(resultFd);
9618
9830
  } finally {
9619
- if (dirFd !== void 0) fs.closeSync(dirFd);
9831
+ if (dirFd !== void 0) fs2.closeSync(dirFd);
9620
9832
  }
9621
9833
  }
9622
9834
  const header = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1];
@@ -9641,9 +9853,9 @@ function createCliStartAgentRunExecutor(deps = {}) {
9641
9853
  const bindingMachineId = agentKey && deps.resolveAgentRuntimeBindingMachineId ? await deps.resolveAgentRuntimeBindingMachineId(agentKey) : void 0;
9642
9854
  const localMachineId = deps.resolveLocalMachineId ? await deps.resolveLocalMachineId() : void 0;
9643
9855
  let memoryPlacementNote;
9644
- let effectiveRuntimeKey = args.runtimeKey;
9856
+ let effectiveRuntimeKey = args.workspaceIsolation === "auto" && args.readOnly !== true && !args.runtimeKey?.trim() ? "local" : args.runtimeKey;
9645
9857
  const autoPlacement = await evaluateAutoInstaboxPlacement({
9646
- runtimeKey: args.runtimeKey,
9858
+ runtimeKey: effectiveRuntimeKey,
9647
9859
  cwd: args.cwd,
9648
9860
  readOnly: args.readOnly === true,
9649
9861
  env: deps.env,
@@ -9663,7 +9875,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9663
9875
  const dispatch = resolveCliLocalSpawnDispatch({
9664
9876
  runtimeKey: effectiveRuntimeKey,
9665
9877
  readOnly: args.readOnly === true,
9666
- // F1:runtimeKey=local 是「在宿主文件系统上改代码」,需要调用方的显式确认
9878
+ // F1:默认写型派发及 runtimeKey=local 是「在宿主文件系统上改代码」,需要调用方的显式确认
9667
9879
  // (allowHostWrites: true);缺失即派发前拒绝(零 spawn、零 run 记录)。
9668
9880
  allowHostWrites: args.allowHostWrites,
9669
9881
  // 政策第 5 条:显式宿主 cwd × 沙盒落点必须在派发前失败(沙盒不兑现宿主
@@ -9675,6 +9887,8 @@ function createCliStartAgentRunExecutor(deps = {}) {
9675
9887
  ...bindingMachineId ? { bindingMachineId } : {},
9676
9888
  ...localMachineId ? { localMachineId } : {}
9677
9889
  });
9890
+ if (args.workspaceIsolation !== void 0 && args.workspaceIsolation !== "none" && args.workspaceIsolation !== "auto") throw new Error("workspaceIsolation \u5FC5\u987B\u4E3A none \u6216 auto");
9891
+ if (args.workspaceIsolation === "auto" && args.readOnly !== true && dispatch.target !== "host") throw new Error("workspaceIsolation:auto \u53EA\u652F\u6301\u672C\u5730 CLI \u5BBF\u4E3B\u5199\u578B\u4EFB\u52A1\uFF0C\u6C99\u76D2\u4E0D\u80FD\u5151\u73B0\u5BBF\u4E3B\u76EE\u5F55\u9694\u79BB");
9678
9892
  const task = typeof args.task === "string" ? args.task.trim() : "";
9679
9893
  const runTitle = normalizeRunTitle(args.title);
9680
9894
  if (!agentKey) throw new Error(t("agentRunTool.missingAgentKey"));
@@ -9717,7 +9931,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9717
9931
  const manifest = typeof args.instaboxManifest === "string" ? args.instaboxManifest.trim() : "";
9718
9932
  if (workspace === "snapshot" && !manifest) throw new Error("instaboxWorkspace=snapshot \u5FC5\u987B\u63D0\u4F9B instaboxManifest");
9719
9933
  if (workspace === "empty" && args.instaboxManifest !== void 0) throw new Error("instaboxWorkspace=empty \u4E0D\u5F97\u63D0\u4F9B instaboxManifest");
9720
- const artifactDir = args.instaboxArtifactDir ?? join3(
9934
+ const artifactDir = args.instaboxArtifactDir ?? join4(
9721
9935
  resolveRunsDir(deps.env, deps.homedir),
9722
9936
  "instabox-artifacts",
9723
9937
  randomUUID3()
@@ -9745,7 +9959,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9745
9959
  ...args.ephemeral === true ? ["--ephemeral"] : [],
9746
9960
  // 只读角色安全收敛:审查类任务物理剥离写/改/删工具,遵循最小特权原则。
9747
9961
  ...isReadOnlyTask ? ["--read-only"] : [],
9748
- // 执行后端(默认 docker 沙盒;只读派发留宿主):唯一产出 `--runtime-key`
9962
+ // 执行后端(默认宿主;写型须确认,沙盒须显式指定):唯一产出 `--runtime-key`
9749
9963
  // 的地方,成对不变式在 buildCliLocalRuntimeForwardArgs 内机械断言。
9750
9964
  ...buildCliLocalRuntimeForwardArgs(dispatch),
9751
9965
  ...instaboxArgs,
@@ -9770,44 +9984,64 @@ function createCliStartAgentRunExecutor(deps = {}) {
9770
9984
  });
9771
9985
  const dodCommands = Array.isArray(args.dodCommands) ? args.dodCommands.filter((c) => typeof c === "string" && c.trim().length > 0).map((c) => c.trim()) : typeof args.dod === "string" && args.dod.trim().length > 0 ? [args.dod.trim()] : Array.isArray(args.dod) ? args.dod.filter((c) => typeof c === "string" && c.trim().length > 0).map((c) => c.trim()) : void 0;
9772
9986
  const childPolicy = parseAgentRunArgs(rawArgs, { readTextFile: () => message });
9773
- const { runId, batchId: resolvedBatchId } = await spawnLocalBackgroundRun(
9774
- {
9775
- selectionCheck,
9776
- ...evidenceScope ? { evidenceScope } : {},
9777
- ...dispatchUserId ? { dispatchSpeedProvenance: {
9778
- version: 1,
9779
- source: "cli-startAgentRun",
9780
- userId: dispatchUserId
9781
- } } : {},
9782
- rawArgs,
9783
- commandPath: ["agent", "run"],
9784
- cliEntrypointPath: deps.cliEntrypoint,
9785
- agentKey,
9786
- ...agentName ? { agentName } : {},
9787
- ...runTitle ? { title: runTitle } : {},
9788
- ...batchId ? { batchId } : {},
9789
- ...credentialGroup ? { credentialGroup } : {},
9790
- ...parentDialogId ? { parentDialogId } : {},
9791
- // 续跑目标对话:spawn 时落盘,让"开着这条对话的 TUI"在 running 期间就能
9792
- // 看到另一边在跑(dock 按 dialogId 也能匹配到这条 run)。
9793
- ...continueDialogId ? { dialogId: continueDialogId } : {},
9794
- ...dodCommands && dodCommands.length > 0 ? { dodCommands } : {},
9795
- cwd: requestedCwd ?? deps.cwd ?? process.cwd(),
9796
- ...dispatch.runtimeKey === "local" && !isReadOnlyTask ? { claimLocalWrites: true } : {},
9797
- ...dispatch.target === "host" ? { localExecution: {
9798
- runtimeKey: "local",
9799
- hostWritesAuthorized: args.allowHostWrites === true,
9800
- readOnly: isReadOnlyTask,
9801
- ...childPolicy?.allowedToolNames ? { allowedToolNames: childPolicy.allowedToolNames } : {},
9802
- ...childPolicy?.blockedToolNames ? { blockedToolNames: childPolicy.blockedToolNames } : {},
9803
- provenance: "cli-tool-dispatch-authorized"
9804
- } } : {},
9805
- message,
9806
- ...args.ephemeral === true ? { ephemeral: true } : {},
9807
- output: noopOutput
9808
- },
9809
- { ...deps, shellApprovalHost: deps.shellApprovalHostForAgent ? await deps.shellApprovalHostForAgent(agentKey) : deps.shellApprovalHost }
9810
- );
9987
+ const isolationEnabled = args.workspaceIsolation === "auto" && !isReadOnlyTask;
9988
+ const isolationRunId = isolationEnabled ? (deps.generateRunId ?? defaultGenerateRunId)() : void 0;
9989
+ const baseCwd = requestedCwd ?? deps.cwd ?? process.cwd();
9990
+ const workspaceIsolation = isolationEnabled ? (deps.prepareIsolation ?? prepareWorkspaceIsolation)({
9991
+ baseCwd,
9992
+ runId: isolationRunId,
9993
+ mode: "auto",
9994
+ noloHome: dirname4(resolveRunsDir(deps.env, deps.homedir))
9995
+ }) : { mode: args.workspaceIsolation ?? "none", kind: "none", effectiveCwd: baseCwd };
9996
+ let spawned;
9997
+ try {
9998
+ spawned = await spawnLocalBackgroundRun(
9999
+ {
10000
+ selectionCheck,
10001
+ ...evidenceScope ? { evidenceScope } : {},
10002
+ ...dispatchUserId ? { dispatchSpeedProvenance: {
10003
+ version: 1,
10004
+ source: "cli-startAgentRun",
10005
+ userId: dispatchUserId
10006
+ } } : {},
10007
+ rawArgs,
10008
+ commandPath: ["agent", "run"],
10009
+ cliEntrypointPath: deps.cliEntrypoint,
10010
+ agentKey,
10011
+ ...agentName ? { agentName } : {},
10012
+ ...runTitle ? { title: runTitle } : {},
10013
+ ...batchId ? { batchId } : {},
10014
+ ...credentialGroup ? { credentialGroup } : {},
10015
+ ...parentDialogId ? { parentDialogId } : {},
10016
+ // 续跑目标对话:spawn 时落盘,让"开着这条对话的 TUI"在 running 期间就能
10017
+ // 看到另一边在跑(dock 按 dialogId 也能匹配到这条 run)。
10018
+ ...continueDialogId ? { dialogId: continueDialogId } : {},
10019
+ ...dodCommands && dodCommands.length > 0 ? { dodCommands } : {},
10020
+ cwd: workspaceIsolation.effectiveCwd,
10021
+ ...dispatch.runtimeKey === "local" && !isReadOnlyTask ? { claimLocalWrites: true } : {},
10022
+ ...dispatch.target === "host" ? { localExecution: {
10023
+ runtimeKey: "local",
10024
+ hostWritesAuthorized: args.allowHostWrites === true,
10025
+ readOnly: isReadOnlyTask,
10026
+ ...childPolicy?.allowedToolNames ? { allowedToolNames: childPolicy.allowedToolNames } : {},
10027
+ ...childPolicy?.blockedToolNames ? { blockedToolNames: childPolicy.blockedToolNames } : {},
10028
+ provenance: "cli-tool-dispatch-authorized"
10029
+ } } : {},
10030
+ message,
10031
+ ...args.ephemeral === true ? { ephemeral: true } : {},
10032
+ output: noopOutput
10033
+ },
10034
+ { ...deps, ...isolationRunId !== void 0 ? { generateRunId: () => isolationRunId } : {}, mcpApprovalHost: deps.mcpApprovalHostForAgent ? await deps.mcpApprovalHostForAgent(agentKey) : deps.mcpApprovalHost, shellApprovalHost: deps.shellApprovalHostForAgent ? await deps.shellApprovalHostForAgent(agentKey) : deps.shellApprovalHost }
10035
+ );
10036
+ } catch (error) {
10037
+ try {
10038
+ if (isolationEnabled) (deps.rollbackIsolation ?? rollbackWorkspaceIsolation)(workspaceIsolation);
10039
+ } catch (cleanupError) {
10040
+ throw new AggregateError([error, cleanupError], `\u542F\u52A8\u5931\u8D25\uFF1B\u9694\u79BB\u76EE\u5F55\u4FDD\u7559\u5F85\u5904\u7406: ${workspaceIsolation.root}`);
10041
+ }
10042
+ throw error;
10043
+ }
10044
+ const { runId, batchId: resolvedBatchId } = spawned;
9811
10045
  const displayName = resolveRunLabel({ agentName, agentKey, runId });
9812
10046
  const labels = agentRunCardLabels();
9813
10047
  const taskPreview = typeof args.task === "string" ? args.task.replace(/\s+/g, " ").trim().slice(0, TASK_PREVIEW_MAX) : "";
@@ -9842,6 +10076,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9842
10076
  agentKey,
9843
10077
  status: "running",
9844
10078
  selectionCheck,
10079
+ ...args.workspaceIsolation !== void 0 ? { workspaceIsolation } : {},
9845
10080
  ...contextFacts,
9846
10081
  ...continuationEvidence,
9847
10082
  // batchId is always returned so the caller can later filter by it —
@@ -9914,7 +10149,7 @@ async function spawnContinuationRun(reconciled, message, userInput, deps) {
9914
10149
  continuedFrom,
9915
10150
  output: noopOutput
9916
10151
  },
9917
- { ...deps, shellApprovalHost: deps.shellApprovalHostForAgent ? await deps.shellApprovalHostForAgent(agentKey) : deps.shellApprovalHost }
10152
+ { ...deps, mcpApprovalHost: deps.mcpApprovalHostForAgent ? await deps.mcpApprovalHostForAgent(agentKey) : deps.mcpApprovalHost, shellApprovalHost: deps.shellApprovalHostForAgent ? await deps.shellApprovalHostForAgent(agentKey) : deps.shellApprovalHost }
9918
10153
  );
9919
10154
  const taskPreview = userInput.replace(/\s+/g, " ").trim().slice(0, TASK_PREVIEW_MAX);
9920
10155
  return {
@@ -10122,7 +10357,7 @@ function createCliControlAgentRunExecutor(deps = {}) {
10122
10357
  };
10123
10358
  }
10124
10359
  if (action === "append") {
10125
- if (["runtimeKey", "allowHostWrites", "readOnly", "allowedToolNames", "blockedToolNames", "cwd"].some((key) => args[key] !== void 0)) {
10360
+ if (["runtimeKey", "allowHostWrites", "readOnly", "allowedToolNames", "blockedToolNames", "cwd", "workspaceIsolation"].some((key) => args[key] !== void 0)) {
10126
10361
  throw new Error("[local-continuation] scope overrides are not supported; dispatch a fresh authorized run");
10127
10362
  }
10128
10363
  const dialogKeyArg = typeof args.dialogKey === "string" ? args.dialogKey.trim() : "";
@@ -10162,8 +10397,8 @@ ${userInput}` : userInput;
10162
10397
  const afterCheck = checkStaleRun(reconciled2.runId, deps) ?? reconciled2;
10163
10398
  if (isAgentRunTerminalStatus(afterCheck.status)) {
10164
10399
  return await withQueueLock(queuePath, deps, async () => {
10165
- const fs = deps.fs ?? nodeFs2;
10166
- const remainingEntries = _readQueueEntriesLocked(queuePath, fs);
10400
+ const fs2 = deps.fs ?? nodeFs2;
10401
+ const remainingEntries = _readQueueEntriesLocked(queuePath, fs2);
10167
10402
  const ourEntryFound = remainingEntries.some((e) => e.id === entryId);
10168
10403
  if (!ourEntryFound) {
10169
10404
  return {
@@ -10193,11 +10428,11 @@ ${userInput}` : userInput;
10193
10428
  ${entry.text}`).join("\n\n");
10194
10429
  const result = await spawnContinuationRun(afterCheck, mergedMessage, userInput, deps);
10195
10430
  const transferred = new Set(remainingEntries.map((entry) => entry.id));
10196
- const current = _readQueueEntriesLocked(queuePath, fs);
10197
- if (typeof fs.renameSync !== "function") throw new Error("atomic queue replacement requires renameSync");
10431
+ const current = _readQueueEntriesLocked(queuePath, fs2);
10432
+ if (typeof fs2.renameSync !== "function") throw new Error("atomic queue replacement requires renameSync");
10198
10433
  const pendingQueue = `${queuePath}.${randomUUID3()}.tmp`;
10199
- fs.writeFileSync(pendingQueue, serializeQueueEntries(current.filter((entry) => !transferred.has(entry.id))), { encoding: "utf8", flag: "wx" });
10200
- fs.renameSync(pendingQueue, queuePath);
10434
+ fs2.writeFileSync(pendingQueue, serializeQueueEntries(current.filter((entry) => !transferred.has(entry.id))), { encoding: "utf8", flag: "wx" });
10435
+ fs2.renameSync(pendingQueue, queuePath);
10201
10436
  return result;
10202
10437
  });
10203
10438
  }
@@ -10348,11 +10583,21 @@ function buildCliChromeConnectorToolExecutors(args) {
10348
10583
  return Object.fromEntries(
10349
10584
  CHROME_CONNECTOR_ACCEPTED_TOOL_NAMES.map((toolName) => [
10350
10585
  toolName,
10351
- (call) => {
10586
+ (call, options) => {
10352
10587
  const target = approvalTargetForCall(call);
10353
10588
  const connector = createConnectorApprovalPort(() => clientForTarget(target));
10354
10589
  return runConnectorToolWithHostApproval({
10355
10590
  call,
10591
+ signal: options?.abortSignal,
10592
+ // Foreground TUI turns have dialogId/turnId, not a persisted runId.
10593
+ // Preserve runId only when supplied by a real host owner; never mint
10594
+ // one from call.id or turnId (neither identifies a background run).
10595
+ context: {
10596
+ requestId: call.id,
10597
+ dialogId: call.runtimeContext?.dialogId,
10598
+ turnId: call.runtimeContext?.turnId,
10599
+ runId: call.runtimeContext?.runId
10600
+ },
10356
10601
  execute: (nextCall) => executeChromeConnectorTool({ clientForTarget, call: nextCall }),
10357
10602
  connector,
10358
10603
  // Read the registry per call so a TUI that installs its renderer after the table is
@@ -10484,11 +10729,19 @@ function pickAgentRunResolverDeps(args) {
10484
10729
  };
10485
10730
  }
10486
10731
  function buildCliWorkspaceToolExecutors(args) {
10732
+ const resolveDialogStore = args.resolveDialogStore;
10487
10733
  return buildNoloWorkspaceCliToolExecutors({
10488
10734
  cliEntrypoint: args.cliEntrypoint ?? process.argv[1] ?? "",
10489
10735
  env: args.env,
10490
10736
  metadataKind: "cliWorkspaceTool",
10491
- planningCaller: args.planningCaller
10737
+ planningCaller: args.planningCaller,
10738
+ // 只放开 readDialog(本机独占对话)的进程内直读;listDialogs 一律保持
10739
+ // 权威跨端合并路径——本地库只是缓存,抢答会静默漏掉 Web/手机端新对话。
10740
+ ...resolveDialogStore ? {
10741
+ resolveDialogStore,
10742
+ resolveCurrentUserId: () => resolveLocalUserId(args.env),
10743
+ resolveLocalChildDialogIds: args.resolveLocalChildDialogIds ?? (() => loadLocalRunChildDialogIds({ env: args.env }))
10744
+ } : {}
10492
10745
  });
10493
10746
  }
10494
10747
  function buildLocalToolExecutors(args) {
@@ -10514,7 +10767,9 @@ function buildLocalToolExecutors(args) {
10514
10767
  ...buildCliWorkspaceToolExecutors({
10515
10768
  planningCaller: args.planningCaller,
10516
10769
  env: args.env,
10517
- cliEntrypoint: args.cliEntrypoint
10770
+ cliEntrypoint: args.cliEntrypoint,
10771
+ ...args.resolveDialogStore ? { resolveDialogStore: args.resolveDialogStore } : {},
10772
+ ...args.resolveLocalChildDialogIds ? { resolveLocalChildDialogIds: args.resolveLocalChildDialogIds } : {}
10518
10773
  }),
10519
10774
  // loadSkill resolves SKILL.md from the agent's workspace root (local-fs,
10520
10775
  // no `nolo` CLI subcommand), so it is wired here instead of inside
@@ -10662,6 +10917,7 @@ function buildLocalToolExecutors(args) {
10662
10917
  // (复用 ~/.nolo/runs/ 注册表,MED-1 修复)。
10663
10918
  startAgentRun: createCliStartAgentRunExecutor({
10664
10919
  shellApprovalHostForAgent: args.shellApprovalHostForAgent,
10920
+ mcpApprovalHostForAgent: args.mcpApprovalHostForAgent,
10665
10921
  ...pickAgentRunResolverDeps(args),
10666
10922
  // α:展示名回读器——resolveAgentRunName 的读取来源(显式 agentName 优先,绝不覆盖)。
10667
10923
  resolveAgentName: args.resolveAgentName,
@@ -10673,6 +10929,7 @@ function buildLocalToolExecutors(args) {
10673
10929
  controlAgentRun: createCliControlAgentRunExecutor({
10674
10930
  source: { parentDialogId: args.sourceParentDialogId, agentKey: args.agentKey },
10675
10931
  shellApprovalHostForAgent: args.shellApprovalHostForAgent,
10932
+ mcpApprovalHostForAgent: args.mcpApprovalHostForAgent,
10676
10933
  cwd: args.workspaceRoot,
10677
10934
  cliEntrypoint: args.cliEntrypoint,
10678
10935
  env: args.env
@@ -10681,14 +10938,15 @@ function buildLocalToolExecutors(args) {
10681
10938
  // Nolo Browser Connector: the CLI drives the user's real Chrome through the same verified
10682
10939
  // client + executor as the desktop runtime (before this, every chrome_* call answered
10683
10940
  // "only executable in the Nolo desktop local runtime").
10684
- ...buildCliChromeConnectorToolExecutors(
10685
- args.chromeConnectorClient ? { client: args.chromeConnectorClient } : {}
10686
- ),
10941
+ ...buildCliChromeConnectorToolExecutors({
10942
+ ...args.chromeConnectorClient ? { client: args.chromeConnectorClient } : {},
10943
+ ...args.hostApprovalRenderer ? { awaitHostApproval: args.hostApprovalRenderer } : {}
10944
+ }),
10687
10945
  ...args.localToolExecutors ?? {}
10688
10946
  };
10689
10947
  const execShell = executors.execShell;
10690
10948
  const lifecycle = (run, signal) => withBrowserShellApproval({
10691
- requestUserChoice: args.requestUserChoice,
10949
+ awaitHostApproval: args.hostApprovalRenderer,
10692
10950
  client: args.chromeConnectorClient,
10693
10951
  signal
10694
10952
  }, run);
@@ -10853,8 +11111,8 @@ function createOAuthApiKeyRefResolver(options = {}) {
10853
11111
  }
10854
11112
 
10855
11113
  // packages/agent-runtime/localSandboxWorkload.ts
10856
- import { existsSync as existsSync4 } from "node:fs";
10857
- import { resolve as resolve5 } from "node:path";
11114
+ import { existsSync as existsSync5 } from "node:fs";
11115
+ import { resolve as resolve6 } from "node:path";
10858
11116
 
10859
11117
  // packages/agent-runtime/executionChannel.ts
10860
11118
  var EXECUTION_SHELL_TOOL = "execShell";
@@ -10940,12 +11198,12 @@ import {
10940
11198
  openSync,
10941
11199
  readlinkSync,
10942
11200
  rmdirSync,
10943
- unlinkSync,
11201
+ unlinkSync as unlinkSync2,
10944
11202
  writeSync
10945
11203
  } from "node:fs";
10946
11204
  import { access } from "node:fs/promises";
10947
11205
  import { tmpdir } from "node:os";
10948
- import { isAbsolute as isAbsolute4, join as join4, relative, resolve as resolve4 } from "node:path";
11206
+ import { isAbsolute as isAbsolute5, join as join5, relative as relative2, resolve as resolve5 } from "node:path";
10949
11207
 
10950
11208
  // packages/agent-runtime/linuxSandboxSeccomp.ts
10951
11209
  var AUDIT_ARCH_X86_64 = 3221225534;
@@ -11038,14 +11296,14 @@ var MAX_OUTPUT_BYTES = 1024 * 1024;
11038
11296
  var PSEUDO_FS = ["/proc", "/sys", "/dev", "/run"];
11039
11297
  var SANDBOX_MOUNTS = ["/", "/usr", "/bin", "/lib", "/lib64", "/tmp"];
11040
11298
  var inside = (parent, child) => {
11041
- const rel = relative(parent, child);
11042
- return rel === "" || rel !== ".." && !rel.startsWith("../") && !isAbsolute4(rel);
11299
+ const rel = relative2(parent, child);
11300
+ return rel === "" || rel !== ".." && !rel.startsWith("../") && !isAbsolute5(rel);
11043
11301
  };
11044
11302
  function openRootHandle(path) {
11045
- if (typeof path !== "string" || !isAbsolute4(path) || path.includes("\0")) {
11303
+ if (typeof path !== "string" || !isAbsolute5(path) || path.includes("\0")) {
11046
11304
  throw new Error("Sandbox root must be absolute");
11047
11305
  }
11048
- const expected = resolve4(path);
11306
+ const expected = resolve5(path);
11049
11307
  if (SANDBOX_MOUNTS.includes(expected) || PSEUDO_FS.some((reserved) => inside(reserved, expected))) {
11050
11308
  throw new Error("Sandbox root overlaps a reserved sandbox/pseudo filesystem path");
11051
11309
  }
@@ -11069,8 +11327,8 @@ function openRootHandle(path) {
11069
11327
  }
11070
11328
  var SECCOMP_TEMP_DIR_PREFIX = "nolo-bwrap-seccomp-";
11071
11329
  function openSeccompFd(program) {
11072
- const dir = mkdtempSync(join4(tmpdir(), SECCOMP_TEMP_DIR_PREFIX));
11073
- const file = join4(dir, "filter.bpf");
11330
+ const dir = mkdtempSync(join5(tmpdir(), SECCOMP_TEMP_DIR_PREFIX));
11331
+ const file = join5(dir, "filter.bpf");
11074
11332
  let writer = -1;
11075
11333
  let reader = -1;
11076
11334
  try {
@@ -11089,7 +11347,7 @@ function openSeccompFd(program) {
11089
11347
  } finally {
11090
11348
  if (writer >= 0) closeSync(writer);
11091
11349
  try {
11092
- unlinkSync(file);
11350
+ unlinkSync2(file);
11093
11351
  } catch {
11094
11352
  }
11095
11353
  try {
@@ -11228,7 +11486,7 @@ var LinuxBubblewrapBackend = class {
11228
11486
  if (request.timeoutMs !== void 0 && (!Number.isFinite(request.timeoutMs) || request.timeoutMs <= 0)) {
11229
11487
  throw new Error("Sandbox timeout must be finite and positive");
11230
11488
  }
11231
- if (request.cwd && !active.writable.some(({ path: root }) => isAbsolute4(request.cwd) && inside(root, resolve4(request.cwd)))) {
11489
+ if (request.cwd && !active.writable.some(({ path: root }) => isAbsolute5(request.cwd) && inside(root, resolve5(request.cwd)))) {
11232
11490
  throw new Error("Command cwd outside writable sandbox roots");
11233
11491
  }
11234
11492
  if (!validateConfiguredRootExecutionLease(active.ticket, active.lease)) {
@@ -11385,7 +11643,7 @@ async function createLocalSandboxWorkload(args) {
11385
11643
  const envRoots = typeof env.NOLO_LOCAL_SANDBOX_ROOTS === "string" ? env.NOLO_LOCAL_SANDBOX_ROOTS.split(":").map((entry) => entry.trim()) : [];
11386
11644
  const readableRoots = normalizeRoots(
11387
11645
  args.readableRoots && args.readableRoots.length > 0 ? args.readableRoots : [...DEFAULT_SANDBOX_READABLE_ROOTS, ...envRoots]
11388
- ).filter((root) => !FORBIDDEN_EXTRA_ROOTS.has(resolve5(root)));
11646
+ ).filter((root) => !FORBIDDEN_EXTRA_ROOTS.has(resolve6(root)));
11389
11647
  const backend = args.backend ?? new LinuxBubblewrapBackend();
11390
11648
  const ticket = {
11391
11649
  version: 1,
@@ -11433,7 +11691,7 @@ async function createLocalSandboxWorkload(args) {
11433
11691
  if (canonicalToolName(toolName) !== EXECUTION_SHELL_TOOL) return null;
11434
11692
  const callArgs = toolArgs ?? {};
11435
11693
  const command = typeof callArgs.command === "string" ? callArgs.command : "";
11436
- const mountedBins = readableRoots.map((root) => `${root}/bin`).filter((dir) => existsSync4(dir));
11694
+ const mountedBins = readableRoots.map((root) => `${root}/bin`).filter((dir) => existsSync5(dir));
11437
11695
  const sandboxPath = [
11438
11696
  ...mountedBins,
11439
11697
  process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"
@@ -11863,12 +12121,12 @@ async function executeWorkspaceDelivery(plan, runtime, deps = {}) {
11863
12121
  }
11864
12122
  const tmpDir = deps.tmpDir ?? (await import("node:os")).tmpdir();
11865
12123
  const writeTempFile = deps.writeTempFile ?? (async (filePath, content) => {
11866
- const fs = await import("node:fs/promises");
11867
- await fs.writeFile(filePath, content, "utf8");
12124
+ const fs2 = await import("node:fs/promises");
12125
+ await fs2.writeFile(filePath, content, "utf8");
11868
12126
  });
11869
12127
  const removeTempFile = deps.removeTempFile ?? (async (filePath) => {
11870
- const fs = await import("node:fs/promises");
11871
- await fs.rm(filePath, { force: true });
12128
+ const fs2 = await import("node:fs/promises");
12129
+ await fs2.rm(filePath, { force: true });
11872
12130
  });
11873
12131
  let hostBaselineTemp = null;
11874
12132
  if (plan.baselineUpload) {
@@ -11968,10 +12226,10 @@ async function applyDockerWorkspaceDelivery(runtime, selection) {
11968
12226
 
11969
12227
  // packages/cli/client/localWorkspaceArchive.ts
11970
12228
  import { spawnSync } from "node:child_process";
11971
- import { mkdtempSync as mkdtempSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
12229
+ import { mkdtempSync as mkdtempSync2, statSync as statSync3, writeFileSync as writeFileSync2 } from "node:fs";
11972
12230
  import { rm } from "node:fs/promises";
11973
12231
  import { tmpdir as tmpdir2 } from "node:os";
11974
- import { join as join5 } from "node:path";
12232
+ import { join as join6 } from "node:path";
11975
12233
  var runHostCommand = (argv, { cwd }) => {
11976
12234
  const result = spawnSync(argv[0], argv.slice(1), {
11977
12235
  cwd,
@@ -12031,11 +12289,11 @@ function prepareHostWorkspaceDelivery(args) {
12031
12289
  `\u5DE5\u4F5C\u533A\u6587\u4EF6\u6570 ${tracked.length} \u8D85\u8FC7\u4E0A\u9650 ${MAX_DELIVERY_FILE_COUNT}\uFF1A\u7591\u4F3C\u628A node_modules / \u6784\u5EFA\u4EA7\u7269\u6253\u8FDB\u4E86\u5F52\u6863\uFF08\u5F52\u6863\u53EA\u53D6 git ls-files\uFF09\u3002`
12032
12290
  );
12033
12291
  }
12034
- const stagingDir = mkdtempSync2(join5(args.tmpDir ?? tmpdir2(), "nolo-workspace-delivery-"));
12292
+ const stagingDir = mkdtempSync2(join6(args.tmpDir ?? tmpdir2(), "nolo-workspace-delivery-"));
12035
12293
  const stamp = `${process.pid}-${Date.now()}`;
12036
- const archivePath = join5(stagingDir, `workspace-${stamp}.tar.gz`);
12037
- const bundlePath = join5(stagingDir, `workspace-${stamp}.bundle`);
12038
- const listPath = join5(stagingDir, `filelist-${stamp}.z`);
12294
+ const archivePath = join6(stagingDir, `workspace-${stamp}.tar.gz`);
12295
+ const bundlePath = join6(stagingDir, `workspace-${stamp}.bundle`);
12296
+ const listPath = join6(stagingDir, `filelist-${stamp}.z`);
12039
12297
  const removeFile = args.removeFile ?? (async (filePath) => {
12040
12298
  await rm(filePath, { force: true });
12041
12299
  });
@@ -12116,7 +12374,7 @@ function prepareHostWorkspaceDelivery(args) {
12116
12374
  }
12117
12375
  let archiveSizeBytes = 0;
12118
12376
  try {
12119
- archiveSizeBytes = statSync2(archivePath).size;
12377
+ archiveSizeBytes = statSync3(archivePath).size;
12120
12378
  } catch (error) {
12121
12379
  return fail3(
12122
12380
  "host_workspace_archive_failed",
@@ -12176,7 +12434,7 @@ function buildHostBundle(args) {
12176
12434
  }
12177
12435
  let sizeBytes = 0;
12178
12436
  try {
12179
- sizeBytes = statSync2(args.bundlePath).size;
12437
+ sizeBytes = statSync3(args.bundlePath).size;
12180
12438
  } catch (error) {
12181
12439
  return {
12182
12440
  ok: false,
@@ -12279,8 +12537,8 @@ async function createLocalDockerWorkload(args) {
12279
12537
  }
12280
12538
  const createLifecycle = args.createLifecycle ?? (async () => {
12281
12539
  const [{ DockerWorkloadLifecycle, createDockerBindingAuthorizer }, accounts] = await Promise.all([
12282
- import("./workloadLifecycle-HFJIN5IZ.js"),
12283
- import("./accountResolver-QETKNC7T.js")
12540
+ import("./workloadLifecycle-ZCSQCHG3.js"),
12541
+ import("./accountResolver-NGICIMEE.js")
12284
12542
  ]);
12285
12543
  const resolveAccount = args.resolveAccount ?? accounts.createDockerAccountResolver({
12286
12544
  env: args.env,
@@ -12375,28 +12633,28 @@ async function createLocalDockerWorkload(args) {
12375
12633
  };
12376
12634
  let rejectReady = () => {
12377
12635
  };
12378
- const ready = new Promise((resolve7, reject) => {
12379
- resolveReady = resolve7;
12636
+ const ready = new Promise((resolve8, reject) => {
12637
+ resolveReady = resolve8;
12380
12638
  rejectReady = reject;
12381
12639
  });
12382
12640
  let releaseRun = () => {
12383
12641
  };
12384
- const releaseGate = new Promise((resolve7) => {
12385
- releaseRun = resolve7;
12642
+ const releaseGate = new Promise((resolve8) => {
12643
+ releaseRun = resolve8;
12386
12644
  });
12387
12645
  const waitForReleaseOrAbort = () => {
12388
12646
  const signal = args.signal;
12389
12647
  if (!signal) return releaseGate;
12390
12648
  if (signal.aborted) return Promise.resolve();
12391
- return new Promise((resolve7) => {
12649
+ return new Promise((resolve8) => {
12392
12650
  const onAbort = () => {
12393
12651
  signal.removeEventListener("abort", onAbort);
12394
- resolve7();
12652
+ resolve8();
12395
12653
  };
12396
12654
  signal.addEventListener("abort", onAbort, { once: true });
12397
12655
  void releaseGate.then(() => {
12398
12656
  signal.removeEventListener("abort", onAbort);
12399
- resolve7();
12657
+ resolve8();
12400
12658
  });
12401
12659
  });
12402
12660
  };
@@ -12890,12 +13148,12 @@ function describeInstaboxBridgeUnavailable(bridge) {
12890
13148
  // packages/cli/client/localInstaboxWorkspaceRecovery.ts
12891
13149
  import { constants as constants3 } from "node:fs";
12892
13150
  import { open as open2 } from "node:fs/promises";
12893
- import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
13151
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
12894
13152
 
12895
13153
  // packages/agent-runtime/artifactStore.ts
12896
- import { createHash as createHash4, createHmac } from "node:crypto";
13154
+ import { createHash as createHash5, createHmac } from "node:crypto";
12897
13155
  import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
12898
- import { dirname as dirname3, resolve as resolve6, sep } from "node:path";
13156
+ import { dirname as dirname5, resolve as resolve7, sep as sep2 } from "node:path";
12899
13157
  var ArtifactStoreError = class extends Error {
12900
13158
  code;
12901
13159
  key;
@@ -12945,12 +13203,12 @@ function isNotFoundError(error) {
12945
13203
  return error?.code === "ENOENT";
12946
13204
  }
12947
13205
  function createLocalArtifactStore(options) {
12948
- const root = resolve6(options.rootDir);
13206
+ const root = resolve7(options.rootDir);
12949
13207
  const now = options.now ?? Date.now;
12950
13208
  const pathFor = (key) => {
12951
13209
  assertArtifactKey(key);
12952
- const target = resolve6(root, key);
12953
- if (target !== root && !target.startsWith(`${root}${sep}`)) {
13210
+ const target = resolve7(root, key);
13211
+ if (target !== root && !target.startsWith(`${root}${sep2}`)) {
12954
13212
  throw new ArtifactStoreError(
12955
13213
  "invalid_key",
12956
13214
  `artifact key \u89E3\u6790\u540E\u8D8A\u51FA rootDir\uFF1A${describeKey(key)}`,
@@ -12964,7 +13222,7 @@ function createLocalArtifactStore(options) {
12964
13222
  const bytes = toBytes(data);
12965
13223
  const target = pathFor(key);
12966
13224
  try {
12967
- await mkdir(dirname3(target), { recursive: true });
13225
+ await mkdir(dirname5(target), { recursive: true });
12968
13226
  await writeFile(target, bytes);
12969
13227
  } catch (error) {
12970
13228
  if (error instanceof ArtifactStoreError) throw error;
@@ -13020,12 +13278,12 @@ function createLocalArtifactStore(options) {
13020
13278
  };
13021
13279
  }
13022
13280
  function sha256Hex2(data) {
13023
- return createHash4("sha256").update(data).digest("hex");
13281
+ return createHash5("sha256").update(data).digest("hex");
13024
13282
  }
13025
13283
  var EMPTY_SHA256 = sha256Hex2("");
13026
13284
 
13027
13285
  // packages/cli/client/localInstaboxWorkspaceRecovery.ts
13028
- var sha = (b) => createHash5("sha256").update(b).digest("hex");
13286
+ var sha = (b) => createHash6("sha256").update(b).digest("hex");
13029
13287
  function fail4(code) {
13030
13288
  throw Object.assign(new Error(`instabox_workspace_recovery:${code}; cleanup_pending`), { code: "instabox_cleanup_pending", cleanupPending: true });
13031
13289
  }
@@ -13530,8 +13788,8 @@ async function createLocalInstaboxWorkload(args) {
13530
13788
  }
13531
13789
 
13532
13790
  // packages/cli/client/localRunArtifactExport.ts
13533
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "node:fs";
13534
- import { dirname as dirname4, join as join6 } from "node:path";
13791
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
13792
+ import { dirname as dirname6, join as join7 } from "node:path";
13535
13793
 
13536
13794
  // packages/agent-runtime/runArtifactExport.ts
13537
13795
  var RUN_DIFF_COMMAND = "git add -A && git diff --cached --binary";
@@ -13739,13 +13997,13 @@ function serializeRunArtifactAudit(record) {
13739
13997
  // packages/cli/client/localRunArtifactExport.ts
13740
13998
  function resolveRunArtifactsRootDir(runsDir) {
13741
13999
  const normalized = runsDir.replace(/[/\\]+$/, "");
13742
- return join6(dirname4(normalized || runsDir), "artifacts");
14000
+ return join7(dirname6(normalized || runsDir), "artifacts");
13743
14001
  }
13744
14002
  function writeRunArtifactAudit(args) {
13745
- const fs = args.fs ?? { mkdirSync: mkdirSync2, writeFileSync: writeFileSync3 };
13746
- const path = join6(args.runsDir, `${args.record.runId}.artifacts.json`);
13747
- fs.mkdirSync?.(args.runsDir, { recursive: true });
13748
- fs.writeFileSync(path, serializeRunArtifactAudit(args.record));
14003
+ const fs2 = args.fs ?? { mkdirSync: mkdirSync3, writeFileSync: writeFileSync3 };
14004
+ const path = join7(args.runsDir, `${args.record.runId}.artifacts.json`);
14005
+ fs2.mkdirSync?.(args.runsDir, { recursive: true });
14006
+ fs2.writeFileSync(path, serializeRunArtifactAudit(args.record));
13749
14007
  return path;
13750
14008
  }
13751
14009
  function createDockerRunTerminalExport(args) {
@@ -14095,9 +14353,9 @@ function buildTokenDialogIndexOps(args) {
14095
14353
 
14096
14354
  // packages/cli/client/localRuntimeDialog.ts
14097
14355
  var import_format = __toESM(require_format(), 1);
14098
- import { appendFileSync, mkdirSync as mkdirSync3 } from "fs";
14099
- import { homedir } from "os";
14100
- import { join as join7 } from "path";
14356
+ import { appendFileSync, mkdirSync as mkdirSync4 } from "fs";
14357
+ import { homedir as homedir2 } from "os";
14358
+ import { join as join8 } from "path";
14101
14359
 
14102
14360
  // packages/cli/client/cliCompletedTurnCapture.ts
14103
14361
  async function readCliCaptureSources(args) {
@@ -14217,11 +14475,11 @@ function projectRawUsage(usage) {
14217
14475
  function debugCaptureRawUsage(item) {
14218
14476
  if (!process.env.NOLO_DEBUG_RAW_USAGE) return;
14219
14477
  try {
14220
- const noloHome = process.env.NOLO_HOME?.trim() || join7(homedir(), ".nolo");
14221
- const dir = join7(noloHome, "logs");
14222
- mkdirSync3(dir, { recursive: true });
14478
+ const noloHome = process.env.NOLO_HOME?.trim() || join8(homedir2(), ".nolo");
14479
+ const dir = join8(noloHome, "logs");
14480
+ mkdirSync4(dir, { recursive: true });
14223
14481
  appendFileSync(
14224
- join7(dir, "raw-usage.jsonl"),
14482
+ join8(dir, "raw-usage.jsonl"),
14225
14483
  JSON.stringify({
14226
14484
  ts: Date.now(),
14227
14485
  model: item.model,
@@ -14464,14 +14722,26 @@ async function writeDialog(args) {
14464
14722
  existingDialog,
14465
14723
  cwd: args.cwd
14466
14724
  });
14467
- for (const id of plan.captureUserMessageIds) {
14468
- const op = plan.ops.find((op2) => op2.value.id === id && op2.value.role === "user");
14469
- const existing = await args.store.read(op.key, { remote: false });
14470
- if (existing) {
14471
- if (existing.id !== id || existing.dialogId !== plan.dialogId || existing.userId !== args.userId || existing.role !== "user" || JSON.stringify(existing.content) !== JSON.stringify(op.value.content)) {
14472
- throw new Error("CLI persisted turn source conflict");
14725
+ const prefetchedUserMessages = /* @__PURE__ */ new Map();
14726
+ if (plan.captureUserMessageIds.length > 0) {
14727
+ const captureEntries = plan.captureUserMessageIds.map((id) => ({
14728
+ id,
14729
+ op: plan.ops.find((op) => op.value.id === id && op.value.role === "user")
14730
+ }));
14731
+ const uniqueKeys = [...new Set(captureEntries.map((entry) => entry.op.key))];
14732
+ const readResults = await Promise.all(
14733
+ uniqueKeys.map(async (key) => [key, await args.store.read(key, { remote: false })])
14734
+ );
14735
+ const existingByKey = new Map(readResults);
14736
+ for (const { id, op } of captureEntries) {
14737
+ const existing = existingByKey.get(op.key);
14738
+ if (existing) {
14739
+ if (existing.id !== id || existing.dialogId !== plan.dialogId || existing.userId !== args.userId || existing.role !== "user" || JSON.stringify(existing.content) !== JSON.stringify(op.value.content)) {
14740
+ throw new Error("CLI persisted turn source conflict");
14741
+ }
14742
+ op.value = existing;
14473
14743
  }
14474
- op.value = existing;
14744
+ prefetchedUserMessages.set(op.key, op.value);
14475
14745
  }
14476
14746
  }
14477
14747
  const lastInputTokens = extractLastProviderInputTokens(args.input) ?? (typeof existingDialog?.lastInputTokens === "number" && Number.isFinite(existingDialog.lastInputTokens) && existingDialog.lastInputTokens > 0 ? existingDialog.lastInputTokens : void 0);
@@ -14491,9 +14761,12 @@ async function writeDialog(args) {
14491
14761
  source: "cli-local"
14492
14762
  });
14493
14763
  if (args.cliBatchCompletion) {
14494
- for (const batchId of args.cliBatchCompletion.batchIds) {
14495
- plan.ops.push(await buildCliBatchCompletionOp(args.store, plan.dialogId, batchId));
14496
- }
14764
+ const completionOps = await Promise.all(
14765
+ args.cliBatchCompletion.batchIds.map(
14766
+ (batchId) => buildCliBatchCompletionOp(args.store, plan.dialogId, batchId)
14767
+ )
14768
+ );
14769
+ plan.ops.push(...completionOps);
14497
14770
  }
14498
14771
  await args.store.batch(plan.ops);
14499
14772
  if (__perfEnabled) {
@@ -14534,7 +14807,7 @@ async function writeDialog(args) {
14534
14807
  dialogId: plan.dialogId,
14535
14808
  userId: args.userId,
14536
14809
  persistedUserMessageIds: plan.captureUserMessageIds,
14537
- read: (key) => args.store.read(key, { remote: false })
14810
+ read: (key) => prefetchedUserMessages.has(key) ? Promise.resolve(prefetchedUserMessages.get(key)) : args.store.read(key, { remote: false })
14538
14811
  }).catch(() => []);
14539
14812
  const syncAndCapture = async (fetchImpl) => {
14540
14813
  try {
@@ -14619,12 +14892,14 @@ async function loadCliDialogSummary(args) {
14619
14892
  const sourceHash = record.sourceHash;
14620
14893
  const sourceCount = record.sourceCount;
14621
14894
  const schemaVersion = record.schemaVersion;
14895
+ const sourceSegments = sanitizeSummarySourceSegments(record.sourceSegments);
14622
14896
  return {
14623
14897
  summary,
14624
14898
  ...typeof summarizedBeforeId === "string" && summarizedBeforeId ? { summarizedBeforeId } : {},
14625
14899
  ...typeof sourceHash === "string" && sourceHash ? { sourceHash } : {},
14626
14900
  ...typeof sourceCount === "number" && sourceCount > 0 ? { sourceCount } : {},
14627
14901
  ..."schemaVersion" in record ? { schemaVersion } : {},
14902
+ ...sourceSegments ? { sourceSegments } : {},
14628
14903
  ...Array.isArray(record.referenceKeys) ? { referenceKeys: record.referenceKeys.filter((key) => typeof key === "string") } : {}
14629
14904
  };
14630
14905
  }
@@ -14633,6 +14908,7 @@ async function saveCliDialogSummary(args) {
14633
14908
  const existing = await args.store.read(dialogKey) ?? {};
14634
14909
  const bareId = typeof existing.id === "string" && existing.id ? existing.id : args.dialogId.startsWith("dialog-") ? dialogIdFromKey(dialogKey) : args.dialogId;
14635
14910
  const compressionCount = typeof existing.compressionCount === "number" ? existing.compressionCount + 1 : 1;
14911
+ const sanitizedSourceSegments = sanitizeSummarySourceSegments(args.sourceSegments);
14636
14912
  await registerDialogOwner({
14637
14913
  store: { get: (key) => args.store.read(key, { remote: false }), put: (key, value) => args.store.write(key, value) },
14638
14914
  dialogId: bareId,
@@ -14650,6 +14926,7 @@ async function saveCliDialogSummary(args) {
14650
14926
  ...args.sourceHash !== void 0 ? { sourceHash: args.sourceHash } : {},
14651
14927
  ...args.sourceCount !== void 0 ? { sourceCount: args.sourceCount } : {},
14652
14928
  ...args.schemaVersion !== void 0 ? { schemaVersion: args.schemaVersion } : {},
14929
+ ...sanitizedSourceSegments !== void 0 ? { sourceSegments: sanitizedSourceSegments } : {},
14653
14930
  referenceKeys: Array.from(/* @__PURE__ */ new Set([
14654
14931
  ...Array.isArray(existing.referenceKeys) ? existing.referenceKeys.filter((key) => typeof key === "string") : [],
14655
14932
  ...args.referenceKeys ?? []
@@ -14921,6 +15198,17 @@ function createCliLocalRuntimeAdapter(deps) {
14921
15198
  const defaultCompactionSummary = createTuiSummaryLlmCaller(deps.env, { fetchImpl, platformPrimary: true });
14922
15199
  const loopbackRequest = deps.loopbackRequest ?? (deps.fetchImpl ? void 0 : defaultLoopbackRequest);
14923
15200
  const userId = resolveLocalUserId(deps.env);
15201
+ const prependManualCompactHistory = async (dialogId, history) => {
15202
+ const record = await (await getOrCreateSharedStore(deps)).read(`dialog-${userId}-${dialogId}`);
15203
+ if (!Array.isArray(record?.manualCompactHistory)) return history;
15204
+ const { dialogMessageRecordToAgentRuntimeMessage: dialogMessageRecordToAgentRuntimeMessage2 } = await import("./dialogMessageRecord-OAV77LT7.js");
15205
+ const seed = record.manualCompactHistory.map((message) => {
15206
+ const parsed = dialogMessageRecordToAgentRuntimeMessage2(message);
15207
+ if (!parsed) throw new Error("Invalid manual compact history");
15208
+ return parsed;
15209
+ });
15210
+ return [...seed, ...history];
15211
+ };
14924
15212
  const resolveLiveImageSupport = createLiveImageSupportResolver(userId, async () => {
14925
15213
  const token = await createOAuthApiKeyRefResolver({
14926
15214
  migration: { enableLegacyMigration: true },
@@ -15096,15 +15384,15 @@ function createCliLocalRuntimeAdapter(deps) {
15096
15384
  const runId = asOptionalTrimmedString(deps.env?.NOLO_AGENT_RUN_ID) ?? "interactive";
15097
15385
  emitRunIsolationNotice(fact, { runId });
15098
15386
  try {
15099
- const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync4 } = await import("node:fs");
15100
- const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-MBG4U6SL.js");
15387
+ const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync5 } = await import("node:fs");
15388
+ const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-RN2P6AOD.js");
15101
15389
  recordLocalRunExecutionIsolation({
15102
15390
  runId,
15103
15391
  runsDir: resolveRunsDir2(deps.env),
15104
15392
  fact,
15105
15393
  fs: {
15106
15394
  writeFileSync: (path, data) => writeFileSync4(path, data),
15107
- mkdirSync: (path, options) => mkdirSync4(path, options)
15395
+ mkdirSync: (path, options) => mkdirSync5(path, options)
15108
15396
  }
15109
15397
  });
15110
15398
  getLogger("cli.localRuntimeAdapter").info(
@@ -15122,7 +15410,7 @@ function createCliLocalRuntimeAdapter(deps) {
15122
15410
  dockerWorkloadReleased = true;
15123
15411
  dockerWorkloadLoad = null;
15124
15412
  if (loaded) {
15125
- const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-MBG4U6SL.js");
15413
+ const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-RN2P6AOD.js");
15126
15414
  const exportRunDiff = deps.exportDockerRunDiffArtifact ?? exportDockerRunDiffArtifact;
15127
15415
  const warn = (message) => process.stderr.write(`[nolo] ${message}
15128
15416
  `);
@@ -15203,7 +15491,6 @@ function createCliLocalRuntimeAdapter(deps) {
15203
15491
  }
15204
15492
  };
15205
15493
  let runtimeToolExecutionLimits = {};
15206
- const skillPolicyFingerprint = (source) => JSON.stringify(Object.entries(resolveAgentSkillConfig(source)).sort(([a], [b]) => a.localeCompare(b)));
15207
15494
  let reviewAgentConfig;
15208
15495
  let planningCaller = {};
15209
15496
  const isCanonicalAutoReviewAdmitted = (visits) => {
@@ -15223,6 +15510,10 @@ function createCliLocalRuntimeAdapter(deps) {
15223
15510
  readXPost: deps.readXPost,
15224
15511
  readXhsProfile: deps.readXhsProfile,
15225
15512
  cliEntrypoint: CLI_ENTRYPOINT,
15513
+ // 本地进程内直连:readDialog / listDialogs 走已在手的共享 store
15514
+ // (local-first,未命中才远端回退),不再 spawn `nolo` 子进程 + 试探
15515
+ // 多个 HTTP 端点;本地答不了时 executor 内部自行回退 CLI 桥。
15516
+ resolveDialogStore: () => getOrCreateSharedStore(deps),
15226
15517
  resolveAgentCredentialGroup,
15227
15518
  resolveAgentDisplayName,
15228
15519
  // α:spawn 前从 agent 配置回读真实 name(resolveAgentRunName 的读取来源)。
@@ -15249,6 +15540,20 @@ function createCliLocalRuntimeAdapter(deps) {
15249
15540
  },
15250
15541
  resolveAgentRuntimeBindingMachineId,
15251
15542
  resolveLocalMachineId,
15543
+ mcpApprovalHostForAgent: async (childAgentKey) => {
15544
+ const approvalSignal = deps.mcpApprovalSignal ?? deps.shellApprovalSession?.signal;
15545
+ if (!getHostApprovalRenderer() || !approvalSignal || approvalSignal.aborted) return void 0;
15546
+ const binding = await resolveChildApprovalBinding({
15547
+ readAgentConfig: async (key) => readAgentFromStore({ agentRef: key, store: await getOrCreateSharedStore(deps), userId }),
15548
+ resolveDeviceId: async () => {
15549
+ const { detectMachineInfo } = await import("./machineInfo-LWHTEBHJ.js");
15550
+ return (await detectMachineInfo({ probeLaunchable: false }))?.machineId;
15551
+ },
15552
+ workspaceRoot,
15553
+ agentKey: childAgentKey
15554
+ });
15555
+ return binding ? { binding, signal: approvalSignal, confirm: confirmMcpOnHost } : void 0;
15556
+ },
15252
15557
  ...deps.shellApprovalSession ? {
15253
15558
  shellApprovalHostForAgent: createChildShellApprovalHostResolver({
15254
15559
  readAgentConfig: async (childAgentKey) => readAgentFromStore({
@@ -15281,6 +15586,13 @@ function createCliLocalRuntimeAdapter(deps) {
15281
15586
  } } : {},
15282
15587
  ...runtimeToolExecutionLimits
15283
15588
  });
15589
+ let localMcpManagement;
15590
+ const getLocalMcpManagement = () => localMcpManagement ??= openMcpLocalRuntimeManagement({
15591
+ authenticatedUserId: userId,
15592
+ env: deps.env,
15593
+ createOAuthManager: deps.createMcpOAuthManager
15594
+ });
15595
+ const localMcpSessions = /* @__PURE__ */ new Map();
15284
15596
  let localToolExecutors = buildCurrentToolExecutors();
15285
15597
  const credentialBroker = createHostCredentialBrokerChain({
15286
15598
  strict: createStrictHostCredentialBroker(),
@@ -15419,7 +15731,17 @@ function createCliLocalRuntimeAdapter(deps) {
15419
15731
  const cached = deps.pastedTextStore ? void 0 : preparedAgentRuntimeCache.get(cacheKey);
15420
15732
  if (cached) {
15421
15733
  const localRecord = await sharedStore.read(cached.agentConfig.key, { remote: false }).catch(() => null);
15422
- const unchanged = !localRecord || cached.localAgentSkillFingerprint !== void 0 && cached.localAgentSkillFingerprint === skillPolicyFingerprint(localRecord);
15734
+ const effectiveLocalRecord = localRecord && typeof localRecord === "object" ? applyBuiltinAgentRuntimeOverride(
15735
+ agentRef,
15736
+ resolveAgentRuntimeConfigFromRecord(
15737
+ cached.agentConfig.key,
15738
+ applyPublicAgentCatalogOverride(
15739
+ localRecord,
15740
+ cached.agentConfig.key
15741
+ )
15742
+ )
15743
+ ).rawRecord : null;
15744
+ const unchanged = !localRecord || cached.localAgentConfigFingerprint !== void 0 && effectiveLocalRecord != null && cached.localAgentConfigFingerprint === buildLocalAgentConfigFingerprint(effectiveLocalRecord);
15423
15745
  if (!unchanged) preparedAgentRuntimeCache.delete(cacheKey);
15424
15746
  if (unchanged) {
15425
15747
  activeAgentToolNames = cached.activeAgentToolNames;
@@ -15458,10 +15780,10 @@ function createCliLocalRuntimeAdapter(deps) {
15458
15780
  const userPromptPatches = accountAutoReviewPrompt ? [...userSkills.skillPromptPatches, accountAutoReviewPrompt] : userSkills.skillPromptPatches;
15459
15781
  const agentConfig = packAgentConfig && userPromptPatches.length ? {
15460
15782
  ...packAgentConfig,
15461
- prompt: [
15462
- packAgentConfig.prompt,
15463
- ...userPromptPatches.filter((patch) => !String(packAgentConfig.prompt ?? "").includes(patch))
15464
- ].filter(Boolean).join("\n\n")
15783
+ // Patches are admitted by the account skill graph and arrive once per
15784
+ // canonical skill identity. Keep them separate from arbitrary prompt
15785
+ // text: substring matching cannot establish runtime contribution ownership.
15786
+ prompt: [packAgentConfig.prompt, ...userPromptPatches].filter(Boolean).join("\n\n")
15465
15787
  } : packAgentConfig;
15466
15788
  const requestedToolNames = agentConfig ? resolveCliRequestedToolNames(
15467
15789
  agentConfig,
@@ -15507,7 +15829,9 @@ function createCliLocalRuntimeAdapter(deps) {
15507
15829
  if (exposedAgentConfig && !deps.pastedTextStore) {
15508
15830
  preparedAgentRuntimeCache.set(cacheKey, {
15509
15831
  agentConfig: exposedAgentConfig,
15510
- localAgentSkillFingerprint: skillPolicyFingerprint(exposedAgentConfig.rawRecord),
15832
+ localAgentConfigFingerprint: buildLocalAgentConfigFingerprint(
15833
+ exposedAgentConfig.rawRecord
15834
+ ),
15511
15835
  activeAgentToolNames,
15512
15836
  runtimeToolExecutionLimits
15513
15837
  });
@@ -15521,21 +15845,25 @@ function createCliLocalRuntimeAdapter(deps) {
15521
15845
  env: deps.env,
15522
15846
  fetchImpl
15523
15847
  });
15524
- return loaded.messages;
15848
+ return prependManualCompactHistory(dialogId, loaded.messages);
15525
15849
  },
15526
15850
  // Source-aware variant so a cross-machine resume that could not load the
15527
15851
  // remote history reports `none` instead of looking like a new dialog.
15528
- loadDialogHistoryWithSource: async (dialogId, options) => loadCliDialogHistoryWithSource({
15529
- strictContinueHistory: options?.strictContinueHistory,
15530
- freshDialog: options?.freshDialog,
15531
- dialogId,
15532
- store: await getOrCreateSharedStore(deps),
15533
- env: deps.env,
15534
- fetchImpl,
15535
- log: (message) => {
15536
- logLocalRuntimeDiagnostic("dialog-history", { dialogId, message });
15537
- }
15538
- }),
15852
+ loadDialogHistoryWithSource: async (dialogId, options) => {
15853
+ const loaded = await loadCliDialogHistoryWithSource({
15854
+ strictContinueHistory: options?.strictContinueHistory,
15855
+ freshDialog: options?.freshDialog,
15856
+ dialogId,
15857
+ store: await getOrCreateSharedStore(deps),
15858
+ env: deps.env,
15859
+ fetchImpl,
15860
+ log: (message) => {
15861
+ logLocalRuntimeDiagnostic("dialog-history", { dialogId, message });
15862
+ }
15863
+ });
15864
+ const messages = await prependManualCompactHistory(dialogId, loaded.messages);
15865
+ return { ...loaded, messages };
15866
+ },
15539
15867
  loadDialogSummary: async (dialogId) => loadCliDialogSummary({
15540
15868
  store: await getOrCreateSharedStore(deps),
15541
15869
  userId,
@@ -15550,6 +15878,7 @@ function createCliLocalRuntimeAdapter(deps) {
15550
15878
  sourceHash: input.sourceHash,
15551
15879
  sourceCount: input.sourceCount,
15552
15880
  schemaVersion: input.schemaVersion,
15881
+ ...input.sourceSegments !== void 0 ? { sourceSegments: input.sourceSegments } : {},
15553
15882
  referenceKeys: input.referenceKeys
15554
15883
  }),
15555
15884
  loadLastContextUsage: async (dialogId) => {
@@ -15905,7 +16234,43 @@ function createCliLocalRuntimeAdapter(deps) {
15905
16234
  workspaceRoot,
15906
16235
  execShellApproval: deps.execShellApproval,
15907
16236
  ...runtimeToolExecutionLimits,
15908
- executors: localToolExecutors,
16237
+ executors: call.name === "listMcpConnections" || call.name === "listMcpTools" || call.name === "callMcpTool" ? { ...localToolExecutors, [call.name]: async (mcpCall) => {
16238
+ const dialogId = opts?.runtimeContext?.dialogId ?? deps.parentDialogId;
16239
+ const agentKey = planningCaller.agentKey;
16240
+ const signal = opts?.abortSignal;
16241
+ if (!userId || !agentKey || typeof dialogId !== "string" || !dialogId || !signal) {
16242
+ return { content: JSON.stringify({ ok: false, error: { code: "forbidden" } }) };
16243
+ }
16244
+ try {
16245
+ let entries = localMcpSessions.get(signal);
16246
+ if (!entries) {
16247
+ entries = /* @__PURE__ */ new Map();
16248
+ localMcpSessions.set(signal, entries);
16249
+ signal.addEventListener("abort", () => {
16250
+ localMcpSessions.delete(signal);
16251
+ for (const pending2 of entries.values()) void pending2.then((mcp2) => mcp2.close()).catch(() => {
16252
+ });
16253
+ }, { once: true });
16254
+ }
16255
+ const key = JSON.stringify([agentKey, dialogId]);
16256
+ let pending = entries.get(key);
16257
+ if (!pending) {
16258
+ pending = getLocalMcpManagement().then((repository) => createMcpLocalRuntimeAdapter({
16259
+ repository,
16260
+ identity: { authenticatedUserId: userId, agentKey, dialogId },
16261
+ signal: deps.mcpApprovalSignal ? AbortSignal.any([signal, deps.mcpApprovalSignal]) : signal,
16262
+ confirm: deps.mcpConfirmation
16263
+ }));
16264
+ entries.set(key, pending);
16265
+ }
16266
+ const mcp = await pending;
16267
+ const input = JSON.parse(mcpCall.arguments);
16268
+ const output = call.name === "listMcpConnections" ? await mcp.listMcpConnections() : call.name === "listMcpTools" ? await mcp.listMcpTools(input) : await mcp.callMcpTool(input);
16269
+ return { content: JSON.stringify(output) };
16270
+ } catch {
16271
+ return { content: JSON.stringify({ ok: false, error: { code: signal.aborted ? "cancelled" : "transport_error" } }) };
16272
+ }
16273
+ } } : localToolExecutors,
15909
16274
  // 沙盒分支的 gate 已经跑过(channel 未接管才会落回这里):把
15910
16275
  // confirmed 传下去,避免破坏性确认在同一调用里弹第二次。
15911
16276
  ...sandboxGatePassed ? { confirmed: true } : {},
@@ -15986,17 +16351,14 @@ export {
15986
16351
  readTimestamp,
15987
16352
  parseAgentRunEvent,
15988
16353
  isLiveAgentRunObservation,
15989
- formatApprovalRemaining,
15990
- createHostApprovalCardQueue,
15991
- registerHostApprovalRenderer,
15992
- isSubtaskRun,
15993
- RUN_WAKE_CHANNEL_ENV,
15994
16354
  createOriginShellGrant,
16355
+ createCliHybridRecordStore,
15995
16356
  preparedAgentRuntimeCache,
15996
16357
  hybridStoreCache,
15997
16358
  normalizeRuntimeCacheCwd,
15998
16359
  buildPreparedAgentCacheKey,
15999
16360
  clearCliLocalRuntimePreparedAgentCache,
16361
+ buildLocalAgentConfigFingerprint,
16000
16362
  defaultLocalRuntimeDb,
16001
16363
  createFallbackId,
16002
16364
  logLocalRuntimeDiagnostic,