nolo-cli 0.228.0-alpha.1 → 0.228.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +3 -5
  2. package/{_executeModel-WZKT6XEU.js → _executeModel-GIFVXKDT.js} +89 -82
  3. package/{accountResolver-QETKNC7T.js → accountResolver-NGICIMEE.js} +1 -1
  4. package/{action-GDZDXPMB.js → action-WZTKEF5H.js} +9 -6
  5. package/{addContentAction-7RO4AMRI.js → addContentAction-MLI6GOBV.js} +14 -13
  6. package/{addDialogAgentAction-EVYBGTXB.js → addDialogAgentAction-ARGQM22H.js} +17 -16
  7. package/{agentDeleteCommand-PZWRHNXY.js → agentDeleteCommand-UF7XVELS.js} +120 -111
  8. package/{agentEmailCommands-QTKMEICX.js → agentEmailCommands-SFHRPQYC.js} +120 -107
  9. package/agentListCommands-IXKBP3W5.js +644 -0
  10. package/{agentMachineCommands-7QGICJLM.js → agentMachineCommands-7NX6PWQ6.js} +56 -48
  11. package/{agentProviderCommands-STI3DQ6A.js → agentProviderCommands-C5T7C5KZ.js} +2 -2
  12. package/{agentPullCommand-KHV4EELF.js → agentPullCommand-4EQZYHU4.js} +1 -1
  13. package/agentRecordCommands-IUNX6XD6.js +188 -0
  14. package/{agentRunCommand-OFQLOF5Y.js → agentRunCommand-LCR4XADM.js} +127 -111
  15. package/{agentRunControl-MBG4U6SL.js → agentRunControl-RN2P6AOD.js} +11 -9
  16. package/{agentRuntimeLocal-TU4LA353.js → agentRuntimeLocal-LVXPQ7QA.js} +57 -43
  17. package/{agentSlice-L4SBGWTB.js → agentSlice-ZGMOH6TE.js} +15 -14
  18. package/{appDeleteCommands-JWP3XPUA.js → appDeleteCommands-BESCJOQM.js} +56 -48
  19. package/{appDeployCommands-6E4TQCWI.js → appDeployCommands-LPTR6IOX.js} +56 -48
  20. package/{appDeployStatusCommands-ALU4SADG.js → appDeployStatusCommands-BZ7KZ5RD.js} +56 -48
  21. package/{appGetCommands-JEY4L6L4.js → appGetCommands-EDWGJV4S.js} +56 -48
  22. package/{appListCommands-PCAVHU7M.js → appListCommands-OPRWYPM6.js} +56 -48
  23. package/{authCommand-CGRIIOOV.js → authCommand-3C3RN4OU.js} +25 -19
  24. package/{authCommands-55OGQGCR.js → authCommands-ZMVEDCQD.js} +12 -6
  25. package/{builtinSkillRegistry-BAE2LDXF.js → builtinSkillRegistry-VRCMQ77Q.js} +7 -7
  26. package/{chromeCommands-G5UDKVSV.js → chromeCommands-O4IIKTBD.js} +384 -7
  27. package/{chromeOpsCommands-WAA45NCS.js → chromeOpsCommands-NZITLHWO.js} +3 -3
  28. package/{chunk-AUAJTAFM.js → chunk-2BKNICGK.js} +4 -4
  29. package/{chunk-QYB23WUH.js → chunk-2FK2KZSL.js} +1 -1
  30. package/chunk-2SXN7LAY.js +15 -0
  31. package/{chunk-H6L2NFHY.js → chunk-3DJJ4CFG.js} +11 -11
  32. package/{chunk-TSPMLCWI.js → chunk-4IQN6FWY.js} +5 -5
  33. package/{chunk-GUXZK7SE.js → chunk-4OXPN3WC.js} +17 -6
  34. package/chunk-4ZCTKB27.js +31 -0
  35. package/chunk-53W5BXLN.js +340 -0
  36. package/{chunk-3P54D2E4.js → chunk-5HUO7SEX.js} +9 -107
  37. package/chunk-6ASGEP5D.js +21 -0
  38. package/{chunk-DDC6P6EH.js → chunk-6CXQ3YNJ.js} +68 -40
  39. package/{chunk-G7IUT2V3.js → chunk-6MTVACLN.js} +365 -64
  40. package/{chunk-ZOHO6MOF.js → chunk-6RSNVJGO.js} +2 -99
  41. package/{chunk-XSW4EXQV.js → chunk-6TVYUQRM.js} +55 -18
  42. package/{chunk-PDCV7P5W.js → chunk-6XIE5ZGI.js} +1 -1
  43. package/{chunk-7Z6EW7AH.js → chunk-6XVPMGXK.js} +97 -11
  44. package/{chunk-ALAES342.js → chunk-73PZD7JZ.js} +9 -5
  45. package/{chunk-2MCB7CD7.js → chunk-7UVVLYKC.js} +9 -9
  46. package/{chunk-S6FDXXZV.js → chunk-ADOOL3PG.js} +2 -2
  47. package/{chunk-OWKNSIXL.js → chunk-AEZBAFC6.js} +334 -77
  48. package/{chunk-PWTNI4N7.js → chunk-ANUP75N2.js} +22 -0
  49. package/{chunk-RG2DGNL6.js → chunk-ARFCL53U.js} +5 -5
  50. package/{chunk-SRCCSTIM.js → chunk-AS6L5KSD.js} +4 -4
  51. package/{chunk-GPOV42YM.js → chunk-BAH3BAUZ.js} +8 -8
  52. package/{chunk-N5Z2V73W.js → chunk-BFKJ2RS3.js} +1 -1
  53. package/{chunk-F6Z6ZCUV.js → chunk-BVEDT6DM.js} +3 -3
  54. package/chunk-C5A54QS7.js +108 -0
  55. package/{chunk-CD3RU7XL.js → chunk-CD2DK5JA.js} +120 -14
  56. package/{chunk-BP5ZJ6B4.js → chunk-CD64YXRB.js} +1 -1
  57. package/{chunk-VP3BINY7.js → chunk-CIGCTSBF.js} +31 -1
  58. package/{chunk-D6YNCNM6.js → chunk-CIUZXD5D.js} +12 -12
  59. package/{chunk-EVGU5P4U.js → chunk-CO6E7YK6.js} +1 -1
  60. package/{chunk-VMJVAJ6W.js → chunk-CTIEJRTP.js} +28 -4
  61. package/{chunk-7JGMNKKG.js → chunk-CTWCZKNS.js} +29 -8
  62. package/{chunk-YFLVRVYK.js → chunk-D25ONVOH.js} +1 -1
  63. package/{chunk-LKA64WH4.js → chunk-DMPZMYH4.js} +37 -1
  64. package/{chunk-262R3XNN.js → chunk-E5RYFR7E.js} +334 -103
  65. package/{chunk-OQHIVPG4.js → chunk-E6A5NHDH.js} +4 -1
  66. package/{chunk-HSSBDZLD.js → chunk-EDT65EUE.js} +6 -6
  67. package/{chunk-IAAIUH64.js → chunk-EQZQUQ33.js} +7 -7
  68. package/{chunk-HBRDSQ3M.js → chunk-ESN4WNWU.js} +3 -2
  69. package/{chunk-2YGBI2XB.js → chunk-FE7G6DSP.js} +11 -1
  70. package/{chunk-547ENH5T.js → chunk-FFFKAOJN.js} +4 -4
  71. package/{chunk-5ZUOVCKT.js → chunk-FGHEF6WI.js} +3 -1
  72. package/{chunk-IXG6YXQM.js → chunk-FTWAOKFU.js} +795 -361
  73. package/chunk-GAHJLSDO.js +107 -0
  74. package/{chunk-2X7WFDT6.js → chunk-GX6DITLQ.js} +1 -1
  75. package/{chunk-GYS5FUYR.js → chunk-HCCQEMTK.js} +28 -28
  76. package/{chunk-CMMI3DAT.js → chunk-HZDK56EK.js} +33 -26
  77. package/{chunk-UE2EVEYS.js → chunk-IIOSZAJX.js} +4 -4
  78. package/chunk-IIRJ4P4I.js +24 -0
  79. package/{chunk-QCB42576.js → chunk-IJZC2KIJ.js} +1 -1
  80. package/{chunk-RYOLWYBK.js → chunk-ITBX27W6.js} +97 -21
  81. package/{chunk-VSYTM22R.js → chunk-J2VIGDJN.js} +6 -6
  82. package/{chunk-QBZCGP34.js → chunk-JEWMQR6J.js} +1 -1
  83. package/{chunk-6QHKRARD.js → chunk-JFRJEPFI.js} +29 -5
  84. package/{chunk-S6K5F3KP.js → chunk-JP2BH4NC.js} +1 -1
  85. package/{chunk-MDZWUD3R.js → chunk-JU7VN4LF.js} +38 -29
  86. package/{chunk-RTHFJZ6M.js → chunk-K26XPZRB.js} +2 -2
  87. package/{chunk-ZYKJBRZ3.js → chunk-K7VIXYTZ.js} +1 -3
  88. package/chunk-KK3FCYZM.js +647 -0
  89. package/chunk-KLAMJNKQ.js +33394 -0
  90. package/{chunk-4JVNURX4.js → chunk-KQHEGELM.js} +68 -16
  91. package/chunk-KXOPLLFP.js +190 -0
  92. package/{chunk-GOCSSER3.js → chunk-KZ5OD2MO.js} +4 -4
  93. package/{chunk-ILHQ2AXT.js → chunk-KZAT2M2V.js} +14 -8
  94. package/chunk-LHCGKAFO.js +739 -0
  95. package/{chunk-XJPLSAPJ.js → chunk-LMGFVH65.js} +107 -104
  96. package/{chunk-QRGDJA4B.js → chunk-LTVEOOZL.js} +19 -6
  97. package/{chunk-L32W3PRP.js → chunk-MAA42MMV.js} +233 -17
  98. package/{chunk-ATEKLSLR.js → chunk-MTM4LRVG.js} +14 -9
  99. package/chunk-MVOZ22RZ.js +26 -0
  100. package/{chunk-2NPD3FTX.js → chunk-MYYNZG2M.js} +139 -39
  101. package/{chunk-DBUR22G5.js → chunk-MZVCFV3T.js} +19 -15
  102. package/{chunk-K67C2JUC.js → chunk-N74XL3NI.js} +9 -9
  103. package/{chunk-VS276URX.js → chunk-NEG5LYK5.js} +1 -1
  104. package/{chunk-RBPUNSG5.js → chunk-OAZP4TSA.js} +18 -108
  105. package/{chunk-SMJEXX2S.js → chunk-ODBYGVO2.js} +232 -10
  106. package/{chunk-M4SFKP5L.js → chunk-OHUYN3YU.js} +3 -3
  107. package/{chunk-HYLRQDEE.js → chunk-OLGFIQN2.js} +6 -6
  108. package/{chunk-M3JEW6N6.js → chunk-OYUMJMC5.js} +15 -0
  109. package/chunk-P27E22MA.js +203 -0
  110. package/{chunk-BIWI5M4E.js → chunk-PBPXXMWZ.js} +1 -1
  111. package/{chunk-OBSEKCVK.js → chunk-PQ63BDV3.js} +210 -51
  112. package/{chunk-4I2MXV5Q.js → chunk-PVFYPUIM.js} +2 -0
  113. package/{chunk-OG6MQOQG.js → chunk-QMNVV3YM.js} +10 -37
  114. package/{chunk-GACR7H6T.js → chunk-R5NRFXGD.js} +5 -5
  115. package/{chunk-5FUN7EG4.js → chunk-RD3QLZQV.js} +83 -47
  116. package/{chunk-4WVJLODK.js → chunk-RHBD22LV.js} +9 -4
  117. package/{chunk-EXJK7TQO.js → chunk-RMWDKLBE.js} +1520 -562
  118. package/{chunk-TGNIKIHR.js → chunk-RR3MB26M.js} +2 -2
  119. package/{chunk-OOJNQK6V.js → chunk-S25VJYXV.js} +8 -2
  120. package/{chunk-STJ6LSQE.js → chunk-SCMYAGQE.js} +1135 -712
  121. package/{chunk-YKY4OVOX.js → chunk-SPU3L3OR.js} +17 -170
  122. package/chunk-SR4FE5VD.js +9 -0
  123. package/{chunk-DUUDXSLX.js → chunk-SX6AWTNK.js} +28 -4
  124. package/{chunk-ZH3KXFHS.js → chunk-TMRJGSK2.js} +1 -1
  125. package/{chunk-S2NTVGA2.js → chunk-U35UUM5K.js} +2 -1
  126. package/{chunk-PPJYZRSQ.js → chunk-U5LOKQ2R.js} +30 -14
  127. package/{chunk-UAIHKQIA.js → chunk-U6RD332P.js} +18 -2
  128. package/{chunk-3U44JB3O.js → chunk-UF6J7NXV.js} +1 -1
  129. package/{chunk-Q3IVPFVO.js → chunk-UHW6SCVK.js} +1 -1
  130. package/chunk-UOUMPHS5.js +103 -0
  131. package/{chunk-HHFGE2WF.js → chunk-UPOW5HTG.js} +5 -5
  132. package/{chunk-DEA37IUY.js → chunk-V4IYI3SB.js} +2 -2
  133. package/{chunk-UWAIJOF2.js → chunk-VKCPKCSS.js} +66 -92
  134. package/{chunk-HGDKT2D6.js → chunk-VTHWBTRE.js} +177 -1
  135. package/{chunk-OBIC6EG7.js → chunk-VUHKG4KS.js} +3 -3
  136. package/{chunk-EEOOBRA7.js → chunk-W3HSD32M.js} +13 -6
  137. package/{chunk-P2ZLUIW2.js → chunk-W6T4FNZP.js} +351 -26
  138. package/chunk-WDWZPASX.js +29 -0
  139. package/chunk-WFGNWWJI.js +326 -0
  140. package/{chunk-R6Z5S5GA.js → chunk-WQDTSK5U.js} +51 -14
  141. package/{chunk-OYU2MA5S.js → chunk-X22AUZKL.js} +152 -167
  142. package/{chunk-4ZGPHFLE.js → chunk-X3OZ655T.js} +2 -2
  143. package/{chunk-NHY322ZU.js → chunk-XCA4WHX5.js} +588 -64
  144. package/{chunk-TI2EPRHE.js → chunk-XJSEST7D.js} +3 -3
  145. package/{chunk-JUSHVFNF.js → chunk-XNTZD4AE.js} +1230 -1356
  146. package/chunk-XSRSAU3O.js +133 -0
  147. package/{chunk-CYWNWA77.js → chunk-Y4NPF2UN.js} +6 -3
  148. package/{chunk-FJSNBZXR.js → chunk-YDRRGVT5.js} +1 -1
  149. package/{chunk-R3NEQZ53.js → chunk-YFW4H6DL.js} +405 -338
  150. package/{chunk-BNMPUQW6.js → chunk-YGDYYFRX.js} +20 -24
  151. package/{chunk-4N6G2CKP.js → chunk-YHNUDTU4.js} +49 -3
  152. package/chunk-YJPK35HB.js +175 -0
  153. package/{chunk-6OVNSQHN.js → chunk-YLAHYLDQ.js} +5 -0
  154. package/{chunk-AGYPUBFW.js → chunk-Z7KE4K3H.js} +195 -123
  155. package/{chunk-DGYCDA6W.js → chunk-ZM5AZTQG.js} +20 -13
  156. package/{chunk-CBUZ6DKA.js → chunk-ZQ6K57FJ.js} +1 -1
  157. package/{cliAgentConfigHelpers-BTRHMPW2.js → cliAgentConfigHelpers-37ZNEY5Y.js} +9 -9
  158. package/{cliAuthorityBrokerClient-XHH7MH2P.js → cliAuthorityBrokerClient-SFPC3WVK.js} +1 -1
  159. package/{cliLocalAgentRecordReader-M3F76NIP.js → cliLocalAgentRecordReader-MCQVRWBR.js} +59 -47
  160. package/{commandRegistry-ZLWHQVAI.js → commandRegistry-NTH5IAN5.js} +104 -92
  161. package/{contentThunks-4ZX2TO7C.js → contentThunks-SPXTX5U2.js} +38 -36
  162. package/{cooldownCommands-YB5H5BBK.js → cooldownCommands-TIFCHCUN.js} +1 -1
  163. package/{createAgentAutomationAction-L4CYUZJG.js → createAgentAutomationAction-KUQKCOXB.js} +38 -36
  164. package/{createDialogAction-QTU2R2Q3.js → createDialogAction-HJN5U3XS.js} +39 -37
  165. package/{createPageAction-F3GJTHW2.js → createPageAction-ZAHRDOAU.js} +43 -41
  166. package/{db-M7FU2GNK.js → db-CMUTP3W5.js} +2 -2
  167. package/{dbSlice-XRUZOGSU.js → dbSlice-656PMWR2.js} +13 -12
  168. package/{deleteFile-6URDHYRB.js → deleteFile-ZCQESEEQ.js} +10 -7
  169. package/{dialogCommands-NRLCOPJR.js → dialogCommands-KZTZLWPZ.js} +61 -54
  170. package/dialogMessageRecord-OAV77LT7.js +7 -0
  171. package/{dialogNotifyCommand-SHGPCU22.js → dialogNotifyCommand-PST75COP.js} +11 -11
  172. package/{dialogSlice-P2S4LXQD.js → dialogSlice-BXIERQHO.js} +39 -37
  173. package/{dialogUsageCommand-W2WCSGKF.js → dialogUsageCommand-6RW2FY6K.js} +5 -5
  174. package/{docCreateCommands-YJRDA3RX.js → docCreateCommands-26HJ5NAY.js} +55 -47
  175. package/{docDeleteCommands-A5QIHZNF.js → docDeleteCommands-UAOHH5XK.js} +57 -49
  176. package/{docReadCommands-CF2LTMYH.js → docReadCommands-4ADG7YE6.js} +55 -47
  177. package/{docStore-6O7NYL6A.js → docStore-FZ75HWP2.js} +15 -14
  178. package/{docUpdateCommands-QRKV4ZXE.js → docUpdateCommands-OGFJZENF.js} +55 -47
  179. package/fetchMessages-TQEUZD7H.js +1 -1
  180. package/{getPricing-LF5C4XSI.js → getPricing-FCHYVRJU.js} +4 -4
  181. package/{handleSendMessageAction-7IHLR37A.js → handleSendMessageAction-KP6GGBFY.js} +84 -79
  182. package/{hostCredentialCreate-VNCQUAFT.js → hostCredentialCreate-23TX56G7.js} +119 -105
  183. package/index.js +8 -8
  184. package/{lib-OT5OTXRU.js → lib-62SWPXNF.js} +3 -7
  185. package/{localDialogRead-CCOCVGAP.js → localDialogRead-CIOTQM5T.js} +1 -1
  186. package/{localRuntimeAdapter-FOWVNMIK.js → localRuntimeAdapter-MTUWOYPN.js} +126 -111
  187. package/{localRuntimeAuthority-IBJAT62G.js → localRuntimeAuthority-TYHQCTZN.js} +5 -3
  188. package/{localRuntimeDb-N7KHDXS2.js → localRuntimeDb-BO7IVWAZ.js} +1 -1
  189. package/{machineCommands-ZGC3J4JB.js → machineCommands-4WJUJQHW.js} +260 -323
  190. package/{machineWsRunDispatch-KK5U4M3G.js → machineWsRunDispatch-V3U4JM67.js} +115 -102
  191. package/markdownToSlate-KIYM7B3P.js +8 -0
  192. package/mcpLocalAuthorizeCommand-TI656UWC.js +106 -0
  193. package/{memberThunks-7Y3OYSJQ.js → memberThunks-JFYC4Z5L.js} +20 -15
  194. package/{models-H5NNZRLH.js → models-EP7VG6N2.js} +2 -2
  195. package/{overlay-BBQZXGYI.js → overlay-JA3SPVUS.js} +5 -3
  196. package/package.json +1 -1
  197. package/{projectArchive-7ZDYBXAX.js → projectArchive-NU2Z5HOR.js} +45 -43
  198. package/{providerPresetApply-WHAMP2D5.js → providerPresetApply-4H7YP5D7.js} +6 -6
  199. package/{providerRegistry-ZI2KORJ7.js → providerRegistry-F3UPOTIY.js} +6 -6
  200. package/{read-TYMBGEXO.js → read-BRZHXUJ6.js} +9 -8
  201. package/{readDocTool-SKQVHBLO.js → readDocTool-N7RVFQEE.js} +1 -1
  202. package/{readlineWorkspace-YHT4SX2C.js → readlineWorkspace-T56MRMS5.js} +6426 -3669
  203. package/rememberExplicit-CPAPONSI.js +15 -0
  204. package/{removeDialogAgentAction-F5QE2O2B.js → removeDialogAgentAction-J7XU7OUX.js} +19 -18
  205. package/{runAgentClientLoop-H4ED5V3K.js → runAgentClientLoop-O2GRCGRZ.js} +97 -75
  206. package/{runtimeDoctorCommands-RRKPBGVO.js → runtimeDoctorCommands-RDRJXMXC.js} +8 -8
  207. package/{secretCommands-KZWBZIYS.js → secretCommands-2FEMRUFM.js} +3 -3
  208. package/{setDialogExtraReferencesAction-72L27ERM.js → setDialogExtraReferencesAction-Q4V2ZZW2.js} +16 -15
  209. package/{setPrimaryDialogAgentAction-GJJDUSGJ.js → setPrimaryDialogAgentAction-742H5S6T.js} +19 -18
  210. package/{settingThunks-ZRGWVGZD.js → settingThunks-T4FXSV6M.js} +185 -66
  211. package/{skillDiscovery-I37M5KJC.js → skillDiscovery-MDDKPTW3.js} +4 -3
  212. package/{spaceCommands-MEH3HJBC.js → spaceCommands-W5TAVFDT.js} +59 -51
  213. package/{streamAgentChatTurn-ZXPOXU33.js → streamAgentChatTurn-OWDJMU5E.js} +238 -178
  214. package/{switchDialogAgentAction-IIJBPND3.js → switchDialogAgentAction-HLDLHRRA.js} +17 -16
  215. package/{tableCommands-FTAOCBTX.js → tableCommands-44GC4N6J.js} +8 -5
  216. package/{toolApiClient-OGQEBQVX.js → toolApiClient-N5PYW2R3.js} +8 -6
  217. package/{tools-2MRWA2PP.js → tools-O7SGGVA3.js} +67 -62
  218. package/{tuiRestart-2IL37YIB.js → tuiRestart-EOGC2BYY.js} +10 -10
  219. package/{tuiSummaryLlmCaller-W2QN4VAC.js → tuiSummaryLlmCaller-TM5BU73J.js} +16 -15
  220. package/{updateCommands-CPATDG6J.js → updateCommands-FBYA5WVG.js} +3 -3
  221. package/{updateDialogTitleAction-RZ3KZSGQ.js → updateDialogTitleAction-EXSZGTLL.js} +40 -38
  222. package/{usageCommand-2BF74MKF.js → usageCommand-L4OFWXEU.js} +2 -2
  223. package/{usageRebuildCommand-UHB55BQM.js → usageRebuildCommand-7JR33UHS.js} +3 -3
  224. package/webapi-QVV65DQF.js +2487 -0
  225. package/{windowsSelfUpdate-ZFD6J5HF.js → windowsSelfUpdate-M4V77OUB.js} +2 -2
  226. package/workContext-Y3ADAPZU.js +14 -0
  227. package/workContextAccess-VU5I4LKZ.js +11 -0
  228. package/workContextWriteNotice-YCSSMHN4.js +7 -0
  229. package/{workloadLifecycle-HFJIN5IZ.js → workloadLifecycle-ZCSQCHG3.js} +2 -2
  230. package/agentListCommands-GUGMORTK.js +0 -1005
  231. package/agentRecordCommands-SLLADS5C.js +0 -175
  232. package/chunk-2WZXXAQD.js +0 -57
  233. package/chunk-5ZMIIR23.js +0 -265
  234. package/chunk-62HXNQVV.js +0 -134
  235. package/chunk-TUSTONB3.js +0 -81
  236. package/chunk-ZXF6D3I6.js +0 -359
  237. package/{chunk-W6RFEDN4.js → chunk-AETZ7AD6.js} +3 -3
  238. /package/{chunk-FJ23FZXF.js → chunk-VIYVRPMJ.js} +0 -0
@@ -1,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-UE2EVEYS.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-IXG6YXQM.js";
98
+ } from "./chunk-FTWAOKFU.js";
99
99
  import {
100
100
  deriveCredentialGroup,
101
101
  deriveCustomProviderCredentialGroup
102
- } from "./chunk-NHY322ZU.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-R3NEQZ53.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-K67C2JUC.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-D6YNCNM6.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-2MCB7CD7.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-JUSHVFNF.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-2NPD3FTX.js";
266
+ } from "./chunk-MYYNZG2M.js";
262
267
  import {
263
268
  readLocalImage
264
269
  } from "./chunk-AL3TYDIF.js";
@@ -273,27 +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
- resolveHistoricalToolContentCap
283
- } from "./chunk-2WZXXAQD.js";
287
+ resolveAgentRuntimeConfigFromRecord
288
+ } from "./chunk-4OXPN3WC.js";
284
289
  import {
285
- resolveAgentImageInputSupport,
286
- resolveCatalogImageSupport,
287
- resolveToolImagePolicy,
288
- withLiveImageSupport
289
- } from "./chunk-DUUDXSLX.js";
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";
290
305
  import {
291
306
  collectStablePromptPrefix,
292
307
  convertMessagesToResponsesInput,
293
308
  findAgentStatePairingIssues,
294
309
  stablePromptCacheKey,
295
310
  toResponsesTools
296
- } from "./chunk-EEOOBRA7.js";
311
+ } from "./chunk-W3HSD32M.js";
297
312
  import {
298
313
  EMPTY_TOOL_RESULT_TEXT,
299
314
  MAX_TOOL_IMAGES_PER_REQUEST,
@@ -306,29 +321,21 @@ import {
306
321
  toolImages
307
322
  } from "./chunk-X4O7FJF5.js";
308
323
  import {
309
- assertDispatchSelectionAdmission,
310
- buildNoloWorkspaceOpenAiTools,
311
- filterClientNoloWorkspaceToolNames,
312
- parseNoloWorkspaceToolArguments
313
- } from "./chunk-RYOLWYBK.js";
314
- import {
315
- extractQuotaSnapshot,
316
- isCapacitySaturatedRateLimit,
317
- mergeAvailabilityDeadline,
318
- resolveAvailabilityAction,
319
- resolveCredentialKeyWithFallback
320
- } from "./chunk-QJTZ76CP.js";
324
+ resolveAgentImageInputSupport,
325
+ resolveCatalogImageSupport,
326
+ resolveToolImagePolicy,
327
+ withLiveImageSupport
328
+ } from "./chunk-SX6AWTNK.js";
321
329
  import {
322
- HIGH_RISK_MUTATION_TOOL_NAMES,
323
- resolveRequestToolSurface
324
- } from "./chunk-VS276URX.js";
330
+ resolveHistoricalToolContentCap
331
+ } from "./chunk-WFGNWWJI.js";
325
332
  import {
326
333
  resolveAgentCallPlan
327
- } from "./chunk-OBIC6EG7.js";
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 {
@@ -6558,7 +6516,7 @@ function buildServerPlatformToolExecutors(args) {
6558
6516
  return null;
6559
6517
  }
6560
6518
  const remoteItems = Array.isArray(remote?.selectedItems) ? remote.selectedItems : [];
6561
- const [{ loadMemoryVNextCatalog }, { recallMemoryVNextLocal }] = await Promise.all([
6519
+ const [{ loadMemoryVNextCatalog, getMemoryEvidenceVNextStrict }, { recallMemoryVNextLocal }] = await Promise.all([
6562
6520
  import("./store-Z53ICFL3.js"),
6563
6521
  import("./localRecall-BDYKXB46.js")
6564
6522
  ]);
@@ -6566,12 +6524,15 @@ 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");
6573
- const localItems = hits.map((hit) => {
6531
+ const localItems = await Promise.all(hits.map(async (hit) => {
6574
6532
  const value = hit.state.value ?? {};
6533
+ const evidence = (await Promise.all((hit.state.evidenceIds ?? []).map(
6534
+ (id) => getMemoryEvidenceVNextStrict(ctx.db, ctx.principal, id)
6535
+ ))).filter((item) => item != null && item.ownerId === ctx.principal);
6575
6536
  return {
6576
6537
  id: `vnext-state-${hit.state.id}`,
6577
6538
  ownerType: "user",
@@ -6585,10 +6546,14 @@ function buildServerPlatformToolExecutors(args) {
6585
6546
  lastActivatedAt: hit.state.createdAt,
6586
6547
  activationCount: 1,
6587
6548
  importance: typeof value.importance === "number" ? value.importance : 0.9,
6588
- confidence: typeof value.confidence === "number" ? value.confidence : 0.9,
6549
+ ...typeof value.confidence === "number" && Number.isFinite(value.confidence) ? { confidence: value.confidence } : {},
6550
+ ...["verified", "stated", "inferred"].includes(value.provenance) ? { provenance: value.provenance } : {},
6551
+ ...typeof value.sourceKind === "string" ? { sourceKind: value.sourceKind } : {},
6552
+ ...typeof value.sourceDialogId === "string" ? { sourceDialogId: value.sourceDialogId } : {},
6553
+ evidence,
6589
6554
  sourceOrigin: "local"
6590
6555
  };
6591
- });
6556
+ }));
6592
6557
  const merged = mergeAndDedupUserData(localItems, [{ data: { data: remoteItems } }]);
6593
6558
  const hasNewLocal = merged.some((item) => item.sourceOrigin === "local");
6594
6559
  if (!hasNewLocal) return null;
@@ -6610,7 +6575,7 @@ function buildServerPlatformToolExecutors(args) {
6610
6575
  for (let i = ordered.length - 1; i >= 0; i -= 1) {
6611
6576
  if (isTombstoneRecord2(ordered[i])) ordered.splice(i, 1);
6612
6577
  }
6613
- 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");
6614
6579
  const promptBlock = buildMemoryOverlay(ordered, {
6615
6580
  maxTokens: DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET
6616
6581
  });
@@ -6619,6 +6584,40 @@ function buildServerPlatformToolExecutors(args) {
6619
6584
  const writeLocalMemory = async (input) => {
6620
6585
  const ctx = await localMemoryContext();
6621
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
+ }
6622
6621
  const [{ putMemoryEntityVNext, putMemoryStateVNext, putMemoryEvidenceVNext }, { buildLegacyMemoryEvidence }] = await Promise.all([
6623
6622
  import("./store-Z53ICFL3.js"),
6624
6623
  import("./legacyMigration-TF4SYJCZ.js")
@@ -6661,6 +6660,8 @@ function buildServerPlatformToolExecutors(args) {
6661
6660
  kind: input.kind,
6662
6661
  contentKey,
6663
6662
  origin: "cli-local",
6663
+ ...input.provenance ? { provenance: input.provenance } : {},
6664
+ ...input.sourceKind ? { sourceKind: input.sourceKind } : {},
6664
6665
  ...input.tags?.length ? { tags: input.tags } : {}
6665
6666
  },
6666
6667
  text: input.content,
@@ -6716,8 +6717,47 @@ function buildServerPlatformToolExecutors(args) {
6716
6717
  }
6717
6718
  return { retired, localOnlyRetired, skippedRemoteMiss };
6718
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
+ };
6719
6758
  const queryMemory = async (call) => {
6720
6759
  const parsed = parseNoloWorkspaceToolArguments(call.arguments);
6760
+ if (parsed.mode === "work") return workMemory(call, parsed, false);
6721
6761
  const query = typeof parsed.query === "string" ? parsed.query.trim() : "";
6722
6762
  if (!query) {
6723
6763
  return {
@@ -6725,14 +6765,25 @@ function buildServerPlatformToolExecutors(args) {
6725
6765
  metadata: { serverPlatformTool: true, memoryRead: false }
6726
6766
  };
6727
6767
  }
6768
+ if (parsed.source !== void 0 && parsed.source !== "archive") {
6769
+ return { content: JSON.stringify({ error: "Invalid memory source" }), metadata: { serverPlatformTool: true, memoryRead: false } };
6770
+ }
6771
+ if (parsed.source === void 0 && (parsed.limit !== void 0 || parsed.cursor !== void 0)) {
6772
+ return { content: JSON.stringify({ error: "Pagination requires source archive" }), metadata: { serverPlatformTool: true, memoryRead: false } };
6773
+ }
6728
6774
  const body = { userInput: query };
6775
+ if (parsed.source === "archive") {
6776
+ body.source = parsed.source;
6777
+ if (parsed.limit !== void 0) body.limit = parsed.limit;
6778
+ if (parsed.cursor !== void 0) body.cursor = parsed.cursor;
6779
+ }
6729
6780
  if (args.agentKey) body.agentKey = args.agentKey;
6730
6781
  const raw = await postServer("/api/memory/query", body, {
6731
6782
  retryTransient: true
6732
6783
  });
6733
6784
  let content = raw;
6734
6785
  try {
6735
- const merged = await mergeLocalMemoryIntoQuery(query, raw);
6786
+ const merged = parsed.source === "archive" ? null : await mergeLocalMemoryIntoQuery(query, raw);
6736
6787
  if (merged) content = merged;
6737
6788
  } catch {
6738
6789
  }
@@ -6743,6 +6794,7 @@ function buildServerPlatformToolExecutors(args) {
6743
6794
  };
6744
6795
  const rememberMemory = async (call) => {
6745
6796
  const parsed = parseNoloWorkspaceToolArguments(call.arguments);
6797
+ if (parsed.mode === "work") return workMemory(call, parsed, true);
6746
6798
  const content = typeof parsed.content === "string" ? parsed.content.trim() : "";
6747
6799
  if (!content) {
6748
6800
  return {
@@ -6758,9 +6810,28 @@ function buildServerPlatformToolExecutors(args) {
6758
6810
  kind: parsed.kind ?? "episodic",
6759
6811
  source: "agent-inferred"
6760
6812
  };
6813
+ if (["verified", "stated", "inferred"].includes(parsed.provenance)) body.provenance = parsed.provenance;
6761
6814
  if (typeof parsed.recurrenceEvidence === "string" && parsed.recurrenceEvidence.trim()) {
6762
6815
  body.recurrenceEvidence = parsed.recurrenceEvidence.trim();
6763
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
+ }
6764
6835
  if (args.agentKey) body.agentKey = args.agentKey;
6765
6836
  const raw = await postServer("/api/memory/remember", body, {
6766
6837
  retryTransient: true
@@ -6773,12 +6844,21 @@ function buildServerPlatformToolExecutors(args) {
6773
6844
  } catch {
6774
6845
  }
6775
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;
6776
6851
  localSaved = await writeLocalMemory({
6777
6852
  content: typeof saved?.content === "string" && saved.content.trim() ? saved.content : content,
6778
6853
  kind: String(saved?.kind ?? serverResult?.savedKind ?? body.kind ?? "episodic"),
6779
6854
  createdAt: typeof saved?.createdAt === "string" && saved.createdAt ? saved.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
6780
6855
  confidence: typeof saved?.confidence === "number" ? saved.confidence : 0.8,
6781
- 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 } : {}
6782
6862
  });
6783
6863
  } catch {
6784
6864
  }
@@ -6912,11 +6992,160 @@ function buildServerPlatformToolExecutors(args) {
6912
6992
  };
6913
6993
  }
6914
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
+
6915
7144
  // packages/cli/client/childRunImages.ts
6916
- import { isAbsolute } from "node:path";
7145
+ import { isAbsolute as isAbsolute2 } from "node:path";
6917
7146
  function validateChildImagePaths(value) {
6918
7147
  if (value === void 0) return [];
6919
- 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"))) {
6920
7149
  throw new Error("image_input_invalid: expected 1\u20134 absolute local image paths");
6921
7150
  }
6922
7151
  return value;
@@ -6949,8 +7178,8 @@ async function normalizeCliRunImages(inputs, normalizeRemote) {
6949
7178
  }
6950
7179
 
6951
7180
  // packages/cli/agentRunArgs.ts
6952
- import { readFileSync } from "node:fs";
6953
- import { isAbsolute as isAbsolute2 } from "node:path";
7181
+ import { readFileSync as readFileSync2 } from "node:fs";
7182
+ import { isAbsolute as isAbsolute3 } from "node:path";
6954
7183
  function readFlagValue(args, flag) {
6955
7184
  const index = args.indexOf(flag);
6956
7185
  if (index < 0) return void 0;
@@ -7091,7 +7320,7 @@ function parseAgentRunArgs(args, options = {}) {
7091
7320
  const agentKey = rawAgentKey ? resolveCliAgentKeyInput(rawAgentKey) : void 0;
7092
7321
  const explicitMsg = readFlagValue(args, "--msg");
7093
7322
  const msgFile = readFlagValue(args, "--msg-file");
7094
- 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;
7095
7324
  const rawMessage = explicitMsg ?? fileMessage ?? positional.slice(isNoLoginRunShorthand ? 0 : 1).join(" ");
7096
7325
  if (!agentKey || !rawMessage.trim()) return null;
7097
7326
  const message = rawMessage.trim();
@@ -7152,7 +7381,7 @@ function parseAgentRunArgs(args, options = {}) {
7152
7381
  if (!rawInstaboxArtifactDir) {
7153
7382
  throw new Error("--runtime-key instabox \u5FC5\u987B\u6307\u5B9A --instabox-artifact-dir <\u7EDD\u5BF9\u8DEF\u5F84>");
7154
7383
  }
7155
- if (!isAbsolute2(rawInstaboxArtifactDir) || rawInstaboxArtifactDir.includes("\0") || rawInstaboxArtifactDir.split("/").includes("..")) {
7384
+ if (!isAbsolute3(rawInstaboxArtifactDir) || rawInstaboxArtifactDir.includes("\0") || rawInstaboxArtifactDir.split("/").includes("..")) {
7156
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}"`);
7157
7386
  }
7158
7387
  if (rawInstaboxWorkspace === "snapshot" && !rawInstaboxManifest) {
@@ -7257,7 +7486,7 @@ function parseAgentRunArgs(args, options = {}) {
7257
7486
  }
7258
7487
 
7259
7488
  // packages/cli/client/cliAgentRunToolExecutors.ts
7260
- import { join as join3, resolve as resolve3 } from "node:path";
7489
+ import { dirname as dirname4, join as join4, resolve as resolve4 } from "node:path";
7261
7490
  import { randomUUID as randomUUID3 } from "node:crypto";
7262
7491
  import * as nodeFs2 from "node:fs";
7263
7492
 
@@ -7321,7 +7550,7 @@ function waitForRunTerminal(args) {
7321
7550
  }
7322
7551
 
7323
7552
  // packages/cli/client/cliAgentRunToolExecutors.ts
7324
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
7553
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
7325
7554
 
7326
7555
  // packages/cli/client/agentRunSnapshot.ts
7327
7556
  function readString(value) {
@@ -7441,13 +7670,13 @@ function isFailureStatus(status) {
7441
7670
  function isOrphanedStatus(status) {
7442
7671
  return status === "orphaned";
7443
7672
  }
7444
- function toEpochMs2(iso) {
7673
+ function toEpochMs(iso) {
7445
7674
  if (!iso) return void 0;
7446
7675
  const ms = Date.parse(iso);
7447
7676
  return Number.isFinite(ms) ? ms : void 0;
7448
7677
  }
7449
7678
  function isOverTimeout(run, nowMs, timeoutMs) {
7450
- const startedMs = toEpochMs2(run.startedAt);
7679
+ const startedMs = toEpochMs(run.startedAt);
7451
7680
  if (startedMs === void 0) return false;
7452
7681
  return nowMs - startedMs >= timeoutMs;
7453
7682
  }
@@ -7493,7 +7722,7 @@ function aggregateBatch(input) {
7493
7722
  const { batchId, runs, now } = input;
7494
7723
  const timeoutMs = input.timeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS;
7495
7724
  const notified = new Set(input.notifiedReasons ?? []);
7496
- const nowMs = toEpochMs2(now) ?? 0;
7725
+ const nowMs = toEpochMs(now) ?? 0;
7497
7726
  let success = 0;
7498
7727
  let failed = 0;
7499
7728
  let orphaned = 0;
@@ -7567,47 +7796,47 @@ function deriveAgentRunTodoStatus(input) {
7567
7796
  }
7568
7797
 
7569
7798
  // packages/cli/client/fileSystemStores.ts
7570
- 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";
7571
7800
  import { homedir as nodeHomedir } from "node:os";
7572
- import { dirname as dirname2, join as join2 } from "node:path";
7801
+ import { dirname as dirname3, join as join3 } from "node:path";
7573
7802
  var nodeFs = {
7574
- mkdirSync,
7803
+ mkdirSync: mkdirSync2,
7575
7804
  writeFileSync,
7576
- readFileSync: readFileSync2,
7577
- existsSync: existsSync2
7805
+ readFileSync: readFileSync3,
7806
+ existsSync: existsSync3
7578
7807
  };
7579
- function resolveNoloHome(env, homedir2) {
7808
+ function resolveNoloHome(env, homedir3) {
7580
7809
  const custom = env?.NOLO_HOME;
7581
7810
  if (custom && custom.trim()) return custom.trim();
7582
7811
  const ambient = process.env.NOLO_HOME?.trim();
7583
7812
  if (ambient) return ambient;
7584
- return join2(homedir2(), ".nolo");
7813
+ return join3(homedir3(), ".nolo");
7585
7814
  }
7586
- function ensureDir(dir, fs) {
7587
- fs.mkdirSync(dir, { recursive: true });
7815
+ function ensureDir(dir, fs2) {
7816
+ fs2.mkdirSync(dir, { recursive: true });
7588
7817
  }
7589
- function readJson(path, fs) {
7590
- if (!fs.existsSync(path)) return void 0;
7818
+ function readJson(path, fs2) {
7819
+ if (!fs2.existsSync(path)) return void 0;
7591
7820
  try {
7592
- const raw = fs.readFileSync(path, "utf8");
7821
+ const raw = fs2.readFileSync(path, "utf8");
7593
7822
  return JSON.parse(String(raw));
7594
7823
  } catch {
7595
7824
  return void 0;
7596
7825
  }
7597
7826
  }
7598
- function writeJson(path, data, fs) {
7599
- fs.writeFileSync(path, JSON.stringify(data, null, 2));
7827
+ function writeJson(path, data, fs2) {
7828
+ fs2.writeFileSync(path, JSON.stringify(data, null, 2));
7600
7829
  }
7601
7830
  function createFileSystemTodoStore(opts = {}) {
7602
7831
  const env = opts.env ?? process.env;
7603
- const homedir2 = opts.homedir ?? nodeHomedir;
7604
- const fs = opts.fs ?? nodeFs;
7605
- const noloHome = resolveNoloHome(env, homedir2);
7606
- const filePath = opts.filePath ?? join2(noloHome, "agent_run_todos.json");
7607
- 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");
7608
7837
  const loadMap = () => {
7609
- if (!opts.filePath && !fs.existsSync(filePath) && fs.existsSync(oldFilePath)) {
7610
- const oldData = readJson(oldFilePath, fs);
7838
+ if (!opts.filePath && !fs2.existsSync(filePath) && fs2.existsSync(oldFilePath)) {
7839
+ const oldData = readJson(oldFilePath, fs2);
7611
7840
  const map2 = /* @__PURE__ */ new Map();
7612
7841
  if (oldData?.todos) {
7613
7842
  for (const item of oldData.todos) {
@@ -7629,11 +7858,11 @@ function createFileSystemTodoStore(opts = {}) {
7629
7858
  }
7630
7859
  }
7631
7860
  }
7632
- ensureDir(dirname2(filePath), fs);
7633
- writeJson(filePath, { todos: [...map2.values()] }, fs);
7861
+ ensureDir(dirname3(filePath), fs2);
7862
+ writeJson(filePath, { todos: [...map2.values()] }, fs2);
7634
7863
  return map2;
7635
7864
  }
7636
- const data = readJson(filePath, fs);
7865
+ const data = readJson(filePath, fs2);
7637
7866
  const map = /* @__PURE__ */ new Map();
7638
7867
  if (data?.todos) {
7639
7868
  for (const todo of data.todos) {
@@ -7643,8 +7872,8 @@ function createFileSystemTodoStore(opts = {}) {
7643
7872
  return map;
7644
7873
  };
7645
7874
  const persist = (map) => {
7646
- ensureDir(dirname2(filePath), fs);
7647
- writeJson(filePath, { todos: [...map.values()] }, fs);
7875
+ ensureDir(dirname3(filePath), fs2);
7876
+ writeJson(filePath, { todos: [...map.values()] }, fs2);
7648
7877
  };
7649
7878
  return {
7650
7879
  async getTodo(id) {
@@ -7674,13 +7903,13 @@ function createFileSystemTodoStore(opts = {}) {
7674
7903
  }
7675
7904
 
7676
7905
  // packages/cli/client/instaboxRunConfig.ts
7677
- import { lstatSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
7678
- 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";
7679
7908
 
7680
7909
  // packages/cli/client/localInstaboxWorkspaceDelivery.ts
7681
7910
  import { constants } from "node:fs";
7682
7911
  import { open, realpath } from "node:fs/promises";
7683
- import { createHash as createHash3 } from "node:crypto";
7912
+ import { createHash as createHash4 } from "node:crypto";
7684
7913
 
7685
7914
  // packages/agent-runtime/instaboxBackend.ts
7686
7915
  var INSTABOX_BACKEND_ID = "instabox";
@@ -7688,6 +7917,7 @@ var INSTABOX_DEFAULT_BASE_URL = "https://api.instabox.sh/v1";
7688
7917
  var INSTABOX_MAX_EXEC_SECONDS = 600;
7689
7918
  var INSTABOX_MAX_STDIN_BYTES = 1024 * 1024;
7690
7919
  var SAFE_MESSAGE = {
7920
+ instabox_download_failed: "Instabox file download failed",
7691
7921
  instabox_upload_failed: "Instabox file upload failed",
7692
7922
  instabox_recovery_failed: "Instabox recovery persistence or authority validation failed",
7693
7923
  instabox_recovery_unknown: "Instabox machine identity is unknown; manual reconciliation required",
@@ -7854,7 +8084,7 @@ var InstaboxBackend = class {
7854
8084
  ...rawBody === void 0 ? {} : { body: rawBody }
7855
8085
  });
7856
8086
  });
7857
- this.#sleep = options.sleepImpl ?? ((ms) => new Promise((resolve7) => setTimeout(resolve7, ms)));
8087
+ this.#sleep = options.sleepImpl ?? ((ms) => new Promise((resolve8) => setTimeout(resolve8, ms)));
7858
8088
  this.#machineTimeoutSeconds = options.machineTimeoutSeconds ?? 1800;
7859
8089
  this.#createTimeoutMs = options.createTimeoutMs ?? 18e4;
7860
8090
  this.#deleteTimeoutMs = options.deleteTimeoutMs ?? 12e4;
@@ -8029,7 +8259,7 @@ var InstaboxBackend = class {
8029
8259
  if (machine.name !== plan.name) mismatches.push("name mismatch");
8030
8260
  if (template?.id !== plan.templateId) mismatches.push("template mismatch");
8031
8261
  if (spec?.vcpus !== plan.vcpus || spec?.memMiB !== plan.memMiB || spec?.persistentDiskGiB !== expectedSpec.persistentDiskGiB) mismatches.push("spec mismatch");
8032
- if (this.#billingPolicy === "free-only" && machine.maxRunMinutes !== 480) mismatches.push("maxRunMinutes mismatch");
8262
+ if (this.#billingPolicy === "free-only" && (!Number.isSafeInteger(machine.maxRunMinutes) || machine.maxRunMinutes < 0 || machine.maxRunMinutes > plan.maxRunMinutes)) mismatches.push("maxRunMinutes mismatch");
8033
8263
  if (mismatches.length > 0) {
8034
8264
  const reason = mismatches.join("; ");
8035
8265
  this.#assertDeletionAllowed(machineId, reason);
@@ -8078,6 +8308,7 @@ var InstaboxBackend = class {
8078
8308
  const usageBaselineRunningMs = baseline === null ? null : Math.round(baseline.runningSeconds * 1e3);
8079
8309
  const leaseId = `${machineId}:${ticket.ticketId}`;
8080
8310
  this.#leases.set(leaseId, {
8311
+ ciWritableRoots: [...ticket.filesystem.writableRoots],
8081
8312
  recovery: context.record,
8082
8313
  machineId,
8083
8314
  ticketId: ticket.ticketId,
@@ -8124,7 +8355,7 @@ var InstaboxBackend = class {
8124
8355
  };
8125
8356
  const fail5 = () => new InstaboxBackendError("instabox_upload_failed");
8126
8357
  checkLease();
8127
- if (!input || typeof input.path !== "string" || !input.path.startsWith("/workspace/") || input.path.endsWith("/") || input.path.split("/").some((p, i) => i > 0 && (!p || p === "." || p === "..")) || /[\\\x00-\x1f\x7f]/.test(input.path) || !(input.bytes instanceof Uint8Array) || input.bytes.byteLength > INSTABOX_MAX_UPLOAD_BYTES || !input.signal || !Number.isFinite(input.deadlineAt)) throw fail5();
8358
+ if (!input || typeof input.path !== "string" || !(input.path.startsWith("/workspace/") || (entry.ciWritableRoots ?? []).some((root) => root.startsWith("/data/home/nolo-ci/") && input.path.startsWith(root + "/"))) || input.path.endsWith("/") || input.path.split("/").some((p, i) => i > 0 && (!p || p === "." || p === "..")) || /[\\\x00-\x1f\x7f]/.test(input.path) || !(input.bytes instanceof Uint8Array) || input.bytes.byteLength > INSTABOX_MAX_UPLOAD_BYTES || !input.signal || !Number.isFinite(input.deadlineAt)) throw fail5();
8128
8359
  let base;
8129
8360
  try {
8130
8361
  base = new URL(this.#baseUrl);
@@ -8189,6 +8420,44 @@ var InstaboxBackend = class {
8189
8420
  controller.abort();
8190
8421
  }
8191
8422
  }
8423
+ /** Raw binary download, bounded and confined to a task-owned lease root. */
8424
+ async downloadFile(lease, input) {
8425
+ const entry = this.#requireEntry(lease);
8426
+ const fail5 = () => new InstaboxBackendError("instabox_download_failed");
8427
+ if (entry.releasedAt !== null || entry.stopState !== null || !Number.isSafeInteger(input.maxBytes) || input.maxBytes < 0 || input.maxBytes > INSTABOX_MAX_UPLOAD_BYTES || !(entry.ciWritableRoots ?? []).some((root) => root.startsWith("/data/home/nolo-ci/") && input.path.startsWith(root + "/")) || input.path.split("/").some((p, i) => i > 0 && (!p || p === "." || p === "..")) || /[\\\x00-\x1f\x7f]/.test(input.path)) throw fail5();
8428
+ const remaining = input.deadlineAt - this.#now();
8429
+ if (input.signal.aborted || remaining <= 0) throw fail5();
8430
+ const signal = AbortSignal.any([input.signal, AbortSignal.timeout(Math.min(remaining, 2147483647))]);
8431
+ const base = new URL(this.#baseUrl);
8432
+ if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash) throw fail5();
8433
+ const response = await this.#fetch(`${this.#baseUrl}/machines/${encodeURIComponent(entry.machineId)}/files/content?path=${encodeURIComponent(input.path)}`, {
8434
+ method: "GET",
8435
+ headers: { "X-API-Key": this.#apiKey },
8436
+ signal,
8437
+ redirect: "error"
8438
+ });
8439
+ const length = response.headers?.get("Content-Length");
8440
+ if (response.status !== 200 || response.redirected || !length || !/^\d+$/.test(length) || Number(length) > input.maxBytes || decodeURIComponent(response.headers?.get("X-Instabox-File-Path") ?? "") !== input.path || !response.body) throw fail5();
8441
+ const reader = response.body.getReader();
8442
+ const chunks = [];
8443
+ let count2 = 0;
8444
+ try {
8445
+ for (; ; ) {
8446
+ signal.throwIfAborted();
8447
+ const part = await reader.read();
8448
+ if (part.done) break;
8449
+ count2 += part.value.byteLength;
8450
+ if (count2 > input.maxBytes || count2 > Number(length)) throw fail5();
8451
+ chunks.push(part.value);
8452
+ }
8453
+ if (count2 !== Number(length)) throw fail5();
8454
+ return Buffer.concat(chunks);
8455
+ } finally {
8456
+ await reader.cancel().catch(() => {
8457
+ });
8458
+ reader.releaseLock();
8459
+ }
8460
+ }
8192
8461
  async execute(lease, request, onEvent) {
8193
8462
  const entry = this.#requireEntry(lease);
8194
8463
  if (entry.releasedAt !== null) {
@@ -8372,8 +8641,8 @@ var InstaboxBackend = class {
8372
8641
  try {
8373
8642
  await Promise.race([
8374
8643
  this.#sleep(Math.min(this.#pollIntervalMs, remaining())),
8375
- new Promise((resolve7) => {
8376
- timer = setTimeout(resolve7, remaining());
8644
+ new Promise((resolve8) => {
8645
+ timer = setTimeout(resolve8, remaining());
8377
8646
  })
8378
8647
  ]);
8379
8648
  } finally {
@@ -8553,12 +8822,13 @@ var InstaboxBackend = class {
8553
8822
  const response = await this.#call({ method: "GET", path: `/machines/${encodeURIComponent(machineId)}` });
8554
8823
  const machine = asRecord(response.payload);
8555
8824
  const spec = asRecord(machine?.spec);
8556
- if (response.status !== 200 || machine?.id !== machineId || machine.orgId !== plan.orgId || machine.name !== plan.name || asRecord(machine.template)?.id !== plan.templateId || spec?.vcpus !== plan.vcpus || spec?.memMiB !== plan.memMiB || spec?.persistentDiskGiB !== record.persistentDiskGiB || typeof machine.free !== "boolean" || record.billingPolicy === "free-only" && (machine.free !== true || machine.maxRunMinutes !== plan.maxRunMinutes)) {
8825
+ if (response.status !== 200 || machine?.id !== machineId || machine.orgId !== plan.orgId || machine.name !== plan.name || asRecord(machine.template)?.id !== plan.templateId || spec?.vcpus !== plan.vcpus || spec?.memMiB !== plan.memMiB || spec?.persistentDiskGiB !== record.persistentDiskGiB || typeof machine.free !== "boolean" || record.billingPolicy === "free-only" && machine.free !== true) {
8557
8826
  throw this.#withRecovery(new InstaboxBackendError("instabox_recovery_failed"), record);
8558
8827
  }
8559
8828
  const leaseId = `${machineId}:${record.ticketId}`;
8560
8829
  if (this.#leases.has(leaseId)) throw this.#withRecovery(new InstaboxBackendError("instabox_lease_mismatch"), record);
8561
8830
  this.#leases.set(leaseId, {
8831
+ ciWritableRoots: [],
8562
8832
  recovery: structuredClone(record),
8563
8833
  machineId,
8564
8834
  ticketId: record.ticketId,
@@ -8675,8 +8945,8 @@ var InstaboxBackend = class {
8675
8945
  try {
8676
8946
  return await Promise.race([
8677
8947
  this.#call({ ...args, timeoutMs: void 0 }),
8678
- new Promise((resolve7) => {
8679
- 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);
8680
8950
  })
8681
8951
  ]);
8682
8952
  } finally {
@@ -8814,7 +9084,7 @@ function extractInstaboxErrorCode(payload) {
8814
9084
 
8815
9085
  // packages/cli/client/localInstaboxWorkspaceDelivery.ts
8816
9086
  var SNAPSHOT_LIMITS = { files: 256, fileBytes: 8 * 1024 * 1024, totalBytes: 32 * 1024 * 1024, chunkBytes: 384 * 1024 };
8817
- var hash = (bytes) => createHash3("sha256").update(bytes).digest("hex");
9087
+ var hash = (bytes) => createHash4("sha256").update(bytes).digest("hex");
8818
9088
  var fail = (code) => {
8819
9089
  throw new Error(`instabox_workspace_delivery:${code}`);
8820
9090
  };
@@ -9036,14 +9306,14 @@ function resolveInstaboxRunConfigPath(options) {
9036
9306
  fail2("missing_path", `\u73AF\u5883\u53D8\u91CF ${INSTABOX_RUN_CONFIG_ENV} \u672A\u8BBE\u7F6E\u6216\u4E3A\u7A7A`);
9037
9307
  }
9038
9308
  const runsDir = options?.runsDir ?? resolveRunsDir(env);
9039
- const normalizedRunsDir = normalize(resolve2(runsDir));
9040
- 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));
9041
9311
  if (resolvedTarget !== normalizedRunsDir && !resolvedTarget.startsWith(normalizedRunsDir.endsWith("/") ? normalizedRunsDir : `${normalizedRunsDir}/`)) {
9042
9312
  fail2("path_traversal", `\u914D\u7F6E\u8DEF\u5F84 "${explicitPath}" \u8D8A\u51FA\u4E86\u9650\u5B9A\u7684 runs \u76EE\u5F55 "${normalizedRunsDir}"`);
9043
9313
  }
9044
9314
  let stats;
9045
9315
  try {
9046
- stats = lstatSync(resolvedTarget);
9316
+ stats = lstatSync2(resolvedTarget);
9047
9317
  } catch (err) {
9048
9318
  fail2("file_unreadable", `\u914D\u7F6E\u6587\u4EF6\u4E0D\u53EF\u8BFB\u6216\u4E0D\u5B58\u5728: ${resolvedTarget}`);
9049
9319
  }
@@ -9057,8 +9327,8 @@ function resolveInstaboxRunConfigPath(options) {
9057
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)`);
9058
9328
  }
9059
9329
  try {
9060
- const realTarget = realpathSync2(resolvedTarget);
9061
- const realRuns = realpathSync2(normalizedRunsDir);
9330
+ const realTarget = realpathSync3(resolvedTarget);
9331
+ const realRuns = realpathSync3(normalizedRunsDir);
9062
9332
  if (realTarget !== realRuns && !realTarget.startsWith(realRuns.endsWith("/") ? realRuns : `${realRuns}/`)) {
9063
9333
  fail2("symlink_traversal", `\u914D\u7F6E\u771F\u5B9E\u8DEF\u5F84 "${realTarget}" \u8D8A\u51FA runs \u771F\u5B9E\u76EE\u5F55 "${realRuns}"`);
9064
9334
  }
@@ -9070,7 +9340,7 @@ function loadInstaboxRunConfig(options) {
9070
9340
  const { resolvedPath } = resolveInstaboxRunConfigPath(options);
9071
9341
  let rawText;
9072
9342
  try {
9073
- rawText = readFileSync3(resolvedPath, "utf8");
9343
+ rawText = readFileSync4(resolvedPath, "utf8");
9074
9344
  } catch (err) {
9075
9345
  fail2("file_read_failed", `\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`);
9076
9346
  }
@@ -9119,7 +9389,7 @@ function loadInstaboxRunConfig(options) {
9119
9389
  if (!artifactRootRaw) {
9120
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");
9121
9391
  }
9122
- if (!isAbsolute3(artifactRootRaw) || artifactRootRaw.includes("\0") || artifactRootRaw.split("/").includes("..")) {
9392
+ if (!isAbsolute4(artifactRootRaw) || artifactRootRaw.includes("\0") || artifactRootRaw.split("/").includes("..")) {
9123
9393
  fail2("invalid_artifact_root", `artifactRoot \u5FC5\u987B\u4E3A\u5408\u6CD5\u7EDD\u5BF9\u8DEF\u5F84: "${artifactRootRaw}"`);
9124
9394
  }
9125
9395
  const artifactRoot = normalize(artifactRootRaw);
@@ -9238,7 +9508,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9238
9508
  }
9239
9509
  }
9240
9510
  if (effectiveAvailableMb === null) {
9241
- 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`;
9242
9512
  return {
9243
9513
  selectedRuntimeKey: void 0,
9244
9514
  reason: "memory_unknown",
@@ -9255,7 +9525,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9255
9525
  }
9256
9526
  const autoEnabled = input.autoEnabled === true || input.env?.NOLO_INSTABOX_AUTO === "1" || typeof process !== "undefined" && process.env?.NOLO_INSTABOX_AUTO === "1";
9257
9527
  if (!autoEnabled) {
9258
- 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`;
9259
9529
  return {
9260
9530
  selectedRuntimeKey: void 0,
9261
9531
  reason: "auto_disabled",
@@ -9270,7 +9540,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9270
9540
  });
9271
9541
  } catch (error) {
9272
9542
  const errorMsg = error instanceof Error ? error.message : String(error);
9273
- 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`;
9274
9544
  return {
9275
9545
  selectedRuntimeKey: void 0,
9276
9546
  reason: "config_unavailable",
@@ -9282,7 +9552,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9282
9552
  try {
9283
9553
  const readiness = await input.checkReadiness();
9284
9554
  if (readiness && readiness.ready === false) {
9285
- 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`;
9286
9556
  return {
9287
9557
  selectedRuntimeKey: void 0,
9288
9558
  reason: "readiness_rejected",
@@ -9292,7 +9562,7 @@ async function evaluateAutoInstaboxPlacement(input) {
9292
9562
  }
9293
9563
  } catch (error) {
9294
9564
  const errorMsg = error instanceof Error ? error.message : String(error);
9295
- 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`;
9296
9566
  return {
9297
9567
  selectedRuntimeKey: void 0,
9298
9568
  reason: "readiness_error",
@@ -9352,10 +9622,10 @@ var parseCallArgs = (call) => {
9352
9622
  return {};
9353
9623
  }
9354
9624
  };
9355
- var resolveFs = (deps) => deps.fs ?? { existsSync: existsSync3, readFileSync: readFileSync4 };
9625
+ var resolveFs = (deps) => deps.fs ?? { existsSync: existsSync4, readFileSync: readFileSync5 };
9356
9626
  var probeRunCwd = (deps) => {
9357
- const fs = deps.fs;
9358
- const stat = fs?.statSync ?? nodeFs2.statSync;
9627
+ const fs2 = deps.fs;
9628
+ const stat = fs2?.statSync ?? nodeFs2.statSync;
9359
9629
  return (absolutePath) => {
9360
9630
  try {
9361
9631
  return stat(absolutePath).isDirectory() ? "directory" : "not-a-directory";
@@ -9364,10 +9634,10 @@ var probeRunCwd = (deps) => {
9364
9634
  }
9365
9635
  };
9366
9636
  };
9367
- var tailFile = (logPath, tailLines, fs) => {
9368
- if (!fs.existsSync(logPath)) return void 0;
9637
+ var tailFile = (logPath, tailLines, fs2) => {
9638
+ if (!fs2.existsSync(logPath)) return void 0;
9369
9639
  try {
9370
- const content = fs.readFileSync(logPath, "utf8");
9640
+ const content = fs2.readFileSync(logPath, "utf8");
9371
9641
  const lines = String(content).split(/\r?\n/);
9372
9642
  if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
9373
9643
  return lines.slice(Math.max(0, lines.length - tailLines)).join("\n");
@@ -9529,36 +9799,36 @@ function createCliStartAgentRunExecutor(deps = {}) {
9529
9799
  let previousCacheHitRatio = previousRecord?.cacheHitRatio;
9530
9800
  if (previousRecord && previousCacheHitRatio === void 0 && previousRecord.resultFile) {
9531
9801
  try {
9532
- const fs = deps.fs ?? nodeFs2;
9533
- const runsDir = resolve3(resolveRunsDir(deps.env, deps.homedir));
9534
- const expected = resolve3(runsDir, `${previousRecord.runId}.result.md`);
9535
- if (previousRecord.runId.includes("/") || previousRecord.runId.includes("\\") || resolve3(previousRecord.resultFile) !== expected || !fs.realpathSync || !fs.lstatSync) throw new Error("Unverified result path");
9536
- 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);
9537
9807
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Non-regular result file");
9538
- const canonicalDir = String(fs.realpathSync(runsDir));
9539
- if (String(fs.realpathSync(expected)) !== join3(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Result escapes runs directory");
9540
- 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");
9541
9811
  let dirFd;
9542
9812
  let resultFd;
9543
9813
  let text = "";
9544
9814
  try {
9545
- dirFd = fs.openSync(runsDir, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_DIRECTORY | nodeFs2.constants.O_NOFOLLOW);
9546
- if (!fs.fstatSync(dirFd).isDirectory() || String(fs.realpathSync(`/proc/self/fd/${dirFd}`)) !== canonicalDir) throw new Error("Unverified directory fd");
9547
- resultFd = fs.openSync(`/proc/self/fd/${dirFd}/${previousRecord.runId}.result.md`, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_NOFOLLOW | nodeFs2.constants.O_NONBLOCK);
9548
- 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");
9549
9819
  const bytes = Buffer.alloc(16 * 1024);
9550
9820
  let offset = 0;
9551
9821
  while (offset < bytes.length) {
9552
- const count2 = fs.readSync(resultFd, bytes, offset, bytes.length - offset, offset);
9822
+ const count2 = fs2.readSync(resultFd, bytes, offset, bytes.length - offset, offset);
9553
9823
  if (count2 === 0) break;
9554
9824
  offset += count2;
9555
9825
  }
9556
9826
  text = bytes.subarray(0, offset).toString("utf8");
9557
9827
  } finally {
9558
9828
  try {
9559
- if (resultFd !== void 0) fs.closeSync(resultFd);
9829
+ if (resultFd !== void 0) fs2.closeSync(resultFd);
9560
9830
  } finally {
9561
- if (dirFd !== void 0) fs.closeSync(dirFd);
9831
+ if (dirFd !== void 0) fs2.closeSync(dirFd);
9562
9832
  }
9563
9833
  }
9564
9834
  const header = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1];
@@ -9583,9 +9853,9 @@ function createCliStartAgentRunExecutor(deps = {}) {
9583
9853
  const bindingMachineId = agentKey && deps.resolveAgentRuntimeBindingMachineId ? await deps.resolveAgentRuntimeBindingMachineId(agentKey) : void 0;
9584
9854
  const localMachineId = deps.resolveLocalMachineId ? await deps.resolveLocalMachineId() : void 0;
9585
9855
  let memoryPlacementNote;
9586
- let effectiveRuntimeKey = args.runtimeKey;
9856
+ let effectiveRuntimeKey = args.workspaceIsolation === "auto" && args.readOnly !== true && !args.runtimeKey?.trim() ? "local" : args.runtimeKey;
9587
9857
  const autoPlacement = await evaluateAutoInstaboxPlacement({
9588
- runtimeKey: args.runtimeKey,
9858
+ runtimeKey: effectiveRuntimeKey,
9589
9859
  cwd: args.cwd,
9590
9860
  readOnly: args.readOnly === true,
9591
9861
  env: deps.env,
@@ -9605,7 +9875,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9605
9875
  const dispatch = resolveCliLocalSpawnDispatch({
9606
9876
  runtimeKey: effectiveRuntimeKey,
9607
9877
  readOnly: args.readOnly === true,
9608
- // F1:runtimeKey=local 是「在宿主文件系统上改代码」,需要调用方的显式确认
9878
+ // F1:默认写型派发及 runtimeKey=local 是「在宿主文件系统上改代码」,需要调用方的显式确认
9609
9879
  // (allowHostWrites: true);缺失即派发前拒绝(零 spawn、零 run 记录)。
9610
9880
  allowHostWrites: args.allowHostWrites,
9611
9881
  // 政策第 5 条:显式宿主 cwd × 沙盒落点必须在派发前失败(沙盒不兑现宿主
@@ -9617,6 +9887,8 @@ function createCliStartAgentRunExecutor(deps = {}) {
9617
9887
  ...bindingMachineId ? { bindingMachineId } : {},
9618
9888
  ...localMachineId ? { localMachineId } : {}
9619
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");
9620
9892
  const task = typeof args.task === "string" ? args.task.trim() : "";
9621
9893
  const runTitle = normalizeRunTitle(args.title);
9622
9894
  if (!agentKey) throw new Error(t("agentRunTool.missingAgentKey"));
@@ -9659,7 +9931,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9659
9931
  const manifest = typeof args.instaboxManifest === "string" ? args.instaboxManifest.trim() : "";
9660
9932
  if (workspace === "snapshot" && !manifest) throw new Error("instaboxWorkspace=snapshot \u5FC5\u987B\u63D0\u4F9B instaboxManifest");
9661
9933
  if (workspace === "empty" && args.instaboxManifest !== void 0) throw new Error("instaboxWorkspace=empty \u4E0D\u5F97\u63D0\u4F9B instaboxManifest");
9662
- const artifactDir = args.instaboxArtifactDir ?? join3(
9934
+ const artifactDir = args.instaboxArtifactDir ?? join4(
9663
9935
  resolveRunsDir(deps.env, deps.homedir),
9664
9936
  "instabox-artifacts",
9665
9937
  randomUUID3()
@@ -9687,7 +9959,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9687
9959
  ...args.ephemeral === true ? ["--ephemeral"] : [],
9688
9960
  // 只读角色安全收敛:审查类任务物理剥离写/改/删工具,遵循最小特权原则。
9689
9961
  ...isReadOnlyTask ? ["--read-only"] : [],
9690
- // 执行后端(默认 docker 沙盒;只读派发留宿主):唯一产出 `--runtime-key`
9962
+ // 执行后端(默认宿主;写型须确认,沙盒须显式指定):唯一产出 `--runtime-key`
9691
9963
  // 的地方,成对不变式在 buildCliLocalRuntimeForwardArgs 内机械断言。
9692
9964
  ...buildCliLocalRuntimeForwardArgs(dispatch),
9693
9965
  ...instaboxArgs,
@@ -9712,44 +9984,64 @@ function createCliStartAgentRunExecutor(deps = {}) {
9712
9984
  });
9713
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;
9714
9986
  const childPolicy = parseAgentRunArgs(rawArgs, { readTextFile: () => message });
9715
- const { runId, batchId: resolvedBatchId } = await spawnLocalBackgroundRun(
9716
- {
9717
- selectionCheck,
9718
- ...evidenceScope ? { evidenceScope } : {},
9719
- ...dispatchUserId ? { dispatchSpeedProvenance: {
9720
- version: 1,
9721
- source: "cli-startAgentRun",
9722
- userId: dispatchUserId
9723
- } } : {},
9724
- rawArgs,
9725
- commandPath: ["agent", "run"],
9726
- cliEntrypointPath: deps.cliEntrypoint,
9727
- agentKey,
9728
- ...agentName ? { agentName } : {},
9729
- ...runTitle ? { title: runTitle } : {},
9730
- ...batchId ? { batchId } : {},
9731
- ...credentialGroup ? { credentialGroup } : {},
9732
- ...parentDialogId ? { parentDialogId } : {},
9733
- // 续跑目标对话:spawn 时落盘,让"开着这条对话的 TUI"在 running 期间就能
9734
- // 看到另一边在跑(dock 按 dialogId 也能匹配到这条 run)。
9735
- ...continueDialogId ? { dialogId: continueDialogId } : {},
9736
- ...dodCommands && dodCommands.length > 0 ? { dodCommands } : {},
9737
- cwd: requestedCwd ?? deps.cwd ?? process.cwd(),
9738
- ...dispatch.runtimeKey === "local" && !isReadOnlyTask ? { claimLocalWrites: true } : {},
9739
- ...dispatch.target === "host" ? { localExecution: {
9740
- runtimeKey: "local",
9741
- hostWritesAuthorized: args.allowHostWrites === true,
9742
- readOnly: isReadOnlyTask,
9743
- ...childPolicy?.allowedToolNames ? { allowedToolNames: childPolicy.allowedToolNames } : {},
9744
- ...childPolicy?.blockedToolNames ? { blockedToolNames: childPolicy.blockedToolNames } : {},
9745
- provenance: "cli-tool-dispatch-authorized"
9746
- } } : {},
9747
- message,
9748
- ...args.ephemeral === true ? { ephemeral: true } : {},
9749
- output: noopOutput
9750
- },
9751
- { ...deps, shellApprovalHost: deps.shellApprovalHostForAgent ? await deps.shellApprovalHostForAgent(agentKey) : deps.shellApprovalHost }
9752
- );
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;
9753
10045
  const displayName = resolveRunLabel({ agentName, agentKey, runId });
9754
10046
  const labels = agentRunCardLabels();
9755
10047
  const taskPreview = typeof args.task === "string" ? args.task.replace(/\s+/g, " ").trim().slice(0, TASK_PREVIEW_MAX) : "";
@@ -9784,6 +10076,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
9784
10076
  agentKey,
9785
10077
  status: "running",
9786
10078
  selectionCheck,
10079
+ ...args.workspaceIsolation !== void 0 ? { workspaceIsolation } : {},
9787
10080
  ...contextFacts,
9788
10081
  ...continuationEvidence,
9789
10082
  // batchId is always returned so the caller can later filter by it —
@@ -9856,7 +10149,7 @@ async function spawnContinuationRun(reconciled, message, userInput, deps) {
9856
10149
  continuedFrom,
9857
10150
  output: noopOutput
9858
10151
  },
9859
- { ...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 }
9860
10153
  );
9861
10154
  const taskPreview = userInput.replace(/\s+/g, " ").trim().slice(0, TASK_PREVIEW_MAX);
9862
10155
  return {
@@ -10064,7 +10357,7 @@ function createCliControlAgentRunExecutor(deps = {}) {
10064
10357
  };
10065
10358
  }
10066
10359
  if (action === "append") {
10067
- 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)) {
10068
10361
  throw new Error("[local-continuation] scope overrides are not supported; dispatch a fresh authorized run");
10069
10362
  }
10070
10363
  const dialogKeyArg = typeof args.dialogKey === "string" ? args.dialogKey.trim() : "";
@@ -10104,8 +10397,8 @@ ${userInput}` : userInput;
10104
10397
  const afterCheck = checkStaleRun(reconciled2.runId, deps) ?? reconciled2;
10105
10398
  if (isAgentRunTerminalStatus(afterCheck.status)) {
10106
10399
  return await withQueueLock(queuePath, deps, async () => {
10107
- const fs = deps.fs ?? nodeFs2;
10108
- const remainingEntries = _readQueueEntriesLocked(queuePath, fs);
10400
+ const fs2 = deps.fs ?? nodeFs2;
10401
+ const remainingEntries = _readQueueEntriesLocked(queuePath, fs2);
10109
10402
  const ourEntryFound = remainingEntries.some((e) => e.id === entryId);
10110
10403
  if (!ourEntryFound) {
10111
10404
  return {
@@ -10135,11 +10428,11 @@ ${userInput}` : userInput;
10135
10428
  ${entry.text}`).join("\n\n");
10136
10429
  const result = await spawnContinuationRun(afterCheck, mergedMessage, userInput, deps);
10137
10430
  const transferred = new Set(remainingEntries.map((entry) => entry.id));
10138
- const current = _readQueueEntriesLocked(queuePath, fs);
10139
- 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");
10140
10433
  const pendingQueue = `${queuePath}.${randomUUID3()}.tmp`;
10141
- fs.writeFileSync(pendingQueue, serializeQueueEntries(current.filter((entry) => !transferred.has(entry.id))), { encoding: "utf8", flag: "wx" });
10142
- 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);
10143
10436
  return result;
10144
10437
  });
10145
10438
  }
@@ -10290,11 +10583,21 @@ function buildCliChromeConnectorToolExecutors(args) {
10290
10583
  return Object.fromEntries(
10291
10584
  CHROME_CONNECTOR_ACCEPTED_TOOL_NAMES.map((toolName) => [
10292
10585
  toolName,
10293
- (call) => {
10586
+ (call, options) => {
10294
10587
  const target = approvalTargetForCall(call);
10295
10588
  const connector = createConnectorApprovalPort(() => clientForTarget(target));
10296
10589
  return runConnectorToolWithHostApproval({
10297
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
+ },
10298
10601
  execute: (nextCall) => executeChromeConnectorTool({ clientForTarget, call: nextCall }),
10299
10602
  connector,
10300
10603
  // Read the registry per call so a TUI that installs its renderer after the table is
@@ -10426,11 +10729,19 @@ function pickAgentRunResolverDeps(args) {
10426
10729
  };
10427
10730
  }
10428
10731
  function buildCliWorkspaceToolExecutors(args) {
10732
+ const resolveDialogStore = args.resolveDialogStore;
10429
10733
  return buildNoloWorkspaceCliToolExecutors({
10430
10734
  cliEntrypoint: args.cliEntrypoint ?? process.argv[1] ?? "",
10431
10735
  env: args.env,
10432
10736
  metadataKind: "cliWorkspaceTool",
10433
- 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
+ } : {}
10434
10745
  });
10435
10746
  }
10436
10747
  function buildLocalToolExecutors(args) {
@@ -10456,7 +10767,9 @@ function buildLocalToolExecutors(args) {
10456
10767
  ...buildCliWorkspaceToolExecutors({
10457
10768
  planningCaller: args.planningCaller,
10458
10769
  env: args.env,
10459
- cliEntrypoint: args.cliEntrypoint
10770
+ cliEntrypoint: args.cliEntrypoint,
10771
+ ...args.resolveDialogStore ? { resolveDialogStore: args.resolveDialogStore } : {},
10772
+ ...args.resolveLocalChildDialogIds ? { resolveLocalChildDialogIds: args.resolveLocalChildDialogIds } : {}
10460
10773
  }),
10461
10774
  // loadSkill resolves SKILL.md from the agent's workspace root (local-fs,
10462
10775
  // no `nolo` CLI subcommand), so it is wired here instead of inside
@@ -10604,6 +10917,7 @@ function buildLocalToolExecutors(args) {
10604
10917
  // (复用 ~/.nolo/runs/ 注册表,MED-1 修复)。
10605
10918
  startAgentRun: createCliStartAgentRunExecutor({
10606
10919
  shellApprovalHostForAgent: args.shellApprovalHostForAgent,
10920
+ mcpApprovalHostForAgent: args.mcpApprovalHostForAgent,
10607
10921
  ...pickAgentRunResolverDeps(args),
10608
10922
  // α:展示名回读器——resolveAgentRunName 的读取来源(显式 agentName 优先,绝不覆盖)。
10609
10923
  resolveAgentName: args.resolveAgentName,
@@ -10615,6 +10929,7 @@ function buildLocalToolExecutors(args) {
10615
10929
  controlAgentRun: createCliControlAgentRunExecutor({
10616
10930
  source: { parentDialogId: args.sourceParentDialogId, agentKey: args.agentKey },
10617
10931
  shellApprovalHostForAgent: args.shellApprovalHostForAgent,
10932
+ mcpApprovalHostForAgent: args.mcpApprovalHostForAgent,
10618
10933
  cwd: args.workspaceRoot,
10619
10934
  cliEntrypoint: args.cliEntrypoint,
10620
10935
  env: args.env
@@ -10623,14 +10938,15 @@ function buildLocalToolExecutors(args) {
10623
10938
  // Nolo Browser Connector: the CLI drives the user's real Chrome through the same verified
10624
10939
  // client + executor as the desktop runtime (before this, every chrome_* call answered
10625
10940
  // "only executable in the Nolo desktop local runtime").
10626
- ...buildCliChromeConnectorToolExecutors(
10627
- args.chromeConnectorClient ? { client: args.chromeConnectorClient } : {}
10628
- ),
10941
+ ...buildCliChromeConnectorToolExecutors({
10942
+ ...args.chromeConnectorClient ? { client: args.chromeConnectorClient } : {},
10943
+ ...args.hostApprovalRenderer ? { awaitHostApproval: args.hostApprovalRenderer } : {}
10944
+ }),
10629
10945
  ...args.localToolExecutors ?? {}
10630
10946
  };
10631
10947
  const execShell = executors.execShell;
10632
10948
  const lifecycle = (run, signal) => withBrowserShellApproval({
10633
- requestUserChoice: args.requestUserChoice,
10949
+ awaitHostApproval: args.hostApprovalRenderer,
10634
10950
  client: args.chromeConnectorClient,
10635
10951
  signal
10636
10952
  }, run);
@@ -10795,8 +11111,8 @@ function createOAuthApiKeyRefResolver(options = {}) {
10795
11111
  }
10796
11112
 
10797
11113
  // packages/agent-runtime/localSandboxWorkload.ts
10798
- import { existsSync as existsSync4 } from "node:fs";
10799
- import { resolve as resolve5 } from "node:path";
11114
+ import { existsSync as existsSync5 } from "node:fs";
11115
+ import { resolve as resolve6 } from "node:path";
10800
11116
 
10801
11117
  // packages/agent-runtime/executionChannel.ts
10802
11118
  var EXECUTION_SHELL_TOOL = "execShell";
@@ -10882,12 +11198,12 @@ import {
10882
11198
  openSync,
10883
11199
  readlinkSync,
10884
11200
  rmdirSync,
10885
- unlinkSync,
11201
+ unlinkSync as unlinkSync2,
10886
11202
  writeSync
10887
11203
  } from "node:fs";
10888
11204
  import { access } from "node:fs/promises";
10889
11205
  import { tmpdir } from "node:os";
10890
- 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";
10891
11207
 
10892
11208
  // packages/agent-runtime/linuxSandboxSeccomp.ts
10893
11209
  var AUDIT_ARCH_X86_64 = 3221225534;
@@ -10980,14 +11296,14 @@ var MAX_OUTPUT_BYTES = 1024 * 1024;
10980
11296
  var PSEUDO_FS = ["/proc", "/sys", "/dev", "/run"];
10981
11297
  var SANDBOX_MOUNTS = ["/", "/usr", "/bin", "/lib", "/lib64", "/tmp"];
10982
11298
  var inside = (parent, child) => {
10983
- const rel = relative(parent, child);
10984
- return rel === "" || rel !== ".." && !rel.startsWith("../") && !isAbsolute4(rel);
11299
+ const rel = relative2(parent, child);
11300
+ return rel === "" || rel !== ".." && !rel.startsWith("../") && !isAbsolute5(rel);
10985
11301
  };
10986
11302
  function openRootHandle(path) {
10987
- if (typeof path !== "string" || !isAbsolute4(path) || path.includes("\0")) {
11303
+ if (typeof path !== "string" || !isAbsolute5(path) || path.includes("\0")) {
10988
11304
  throw new Error("Sandbox root must be absolute");
10989
11305
  }
10990
- const expected = resolve4(path);
11306
+ const expected = resolve5(path);
10991
11307
  if (SANDBOX_MOUNTS.includes(expected) || PSEUDO_FS.some((reserved) => inside(reserved, expected))) {
10992
11308
  throw new Error("Sandbox root overlaps a reserved sandbox/pseudo filesystem path");
10993
11309
  }
@@ -11011,8 +11327,8 @@ function openRootHandle(path) {
11011
11327
  }
11012
11328
  var SECCOMP_TEMP_DIR_PREFIX = "nolo-bwrap-seccomp-";
11013
11329
  function openSeccompFd(program) {
11014
- const dir = mkdtempSync(join4(tmpdir(), SECCOMP_TEMP_DIR_PREFIX));
11015
- const file = join4(dir, "filter.bpf");
11330
+ const dir = mkdtempSync(join5(tmpdir(), SECCOMP_TEMP_DIR_PREFIX));
11331
+ const file = join5(dir, "filter.bpf");
11016
11332
  let writer = -1;
11017
11333
  let reader = -1;
11018
11334
  try {
@@ -11031,7 +11347,7 @@ function openSeccompFd(program) {
11031
11347
  } finally {
11032
11348
  if (writer >= 0) closeSync(writer);
11033
11349
  try {
11034
- unlinkSync(file);
11350
+ unlinkSync2(file);
11035
11351
  } catch {
11036
11352
  }
11037
11353
  try {
@@ -11170,7 +11486,7 @@ var LinuxBubblewrapBackend = class {
11170
11486
  if (request.timeoutMs !== void 0 && (!Number.isFinite(request.timeoutMs) || request.timeoutMs <= 0)) {
11171
11487
  throw new Error("Sandbox timeout must be finite and positive");
11172
11488
  }
11173
- 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)))) {
11174
11490
  throw new Error("Command cwd outside writable sandbox roots");
11175
11491
  }
11176
11492
  if (!validateConfiguredRootExecutionLease(active.ticket, active.lease)) {
@@ -11327,7 +11643,7 @@ async function createLocalSandboxWorkload(args) {
11327
11643
  const envRoots = typeof env.NOLO_LOCAL_SANDBOX_ROOTS === "string" ? env.NOLO_LOCAL_SANDBOX_ROOTS.split(":").map((entry) => entry.trim()) : [];
11328
11644
  const readableRoots = normalizeRoots(
11329
11645
  args.readableRoots && args.readableRoots.length > 0 ? args.readableRoots : [...DEFAULT_SANDBOX_READABLE_ROOTS, ...envRoots]
11330
- ).filter((root) => !FORBIDDEN_EXTRA_ROOTS.has(resolve5(root)));
11646
+ ).filter((root) => !FORBIDDEN_EXTRA_ROOTS.has(resolve6(root)));
11331
11647
  const backend = args.backend ?? new LinuxBubblewrapBackend();
11332
11648
  const ticket = {
11333
11649
  version: 1,
@@ -11375,7 +11691,7 @@ async function createLocalSandboxWorkload(args) {
11375
11691
  if (canonicalToolName(toolName) !== EXECUTION_SHELL_TOOL) return null;
11376
11692
  const callArgs = toolArgs ?? {};
11377
11693
  const command = typeof callArgs.command === "string" ? callArgs.command : "";
11378
- const mountedBins = readableRoots.map((root) => `${root}/bin`).filter((dir) => existsSync4(dir));
11694
+ const mountedBins = readableRoots.map((root) => `${root}/bin`).filter((dir) => existsSync5(dir));
11379
11695
  const sandboxPath = [
11380
11696
  ...mountedBins,
11381
11697
  process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"
@@ -11805,12 +12121,12 @@ async function executeWorkspaceDelivery(plan, runtime, deps = {}) {
11805
12121
  }
11806
12122
  const tmpDir = deps.tmpDir ?? (await import("node:os")).tmpdir();
11807
12123
  const writeTempFile = deps.writeTempFile ?? (async (filePath, content) => {
11808
- const fs = await import("node:fs/promises");
11809
- await fs.writeFile(filePath, content, "utf8");
12124
+ const fs2 = await import("node:fs/promises");
12125
+ await fs2.writeFile(filePath, content, "utf8");
11810
12126
  });
11811
12127
  const removeTempFile = deps.removeTempFile ?? (async (filePath) => {
11812
- const fs = await import("node:fs/promises");
11813
- await fs.rm(filePath, { force: true });
12128
+ const fs2 = await import("node:fs/promises");
12129
+ await fs2.rm(filePath, { force: true });
11814
12130
  });
11815
12131
  let hostBaselineTemp = null;
11816
12132
  if (plan.baselineUpload) {
@@ -11910,10 +12226,10 @@ async function applyDockerWorkspaceDelivery(runtime, selection) {
11910
12226
 
11911
12227
  // packages/cli/client/localWorkspaceArchive.ts
11912
12228
  import { spawnSync } from "node:child_process";
11913
- 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";
11914
12230
  import { rm } from "node:fs/promises";
11915
12231
  import { tmpdir as tmpdir2 } from "node:os";
11916
- import { join as join5 } from "node:path";
12232
+ import { join as join6 } from "node:path";
11917
12233
  var runHostCommand = (argv, { cwd }) => {
11918
12234
  const result = spawnSync(argv[0], argv.slice(1), {
11919
12235
  cwd,
@@ -11973,11 +12289,11 @@ function prepareHostWorkspaceDelivery(args) {
11973
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`
11974
12290
  );
11975
12291
  }
11976
- const stagingDir = mkdtempSync2(join5(args.tmpDir ?? tmpdir2(), "nolo-workspace-delivery-"));
12292
+ const stagingDir = mkdtempSync2(join6(args.tmpDir ?? tmpdir2(), "nolo-workspace-delivery-"));
11977
12293
  const stamp = `${process.pid}-${Date.now()}`;
11978
- const archivePath = join5(stagingDir, `workspace-${stamp}.tar.gz`);
11979
- const bundlePath = join5(stagingDir, `workspace-${stamp}.bundle`);
11980
- 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`);
11981
12297
  const removeFile = args.removeFile ?? (async (filePath) => {
11982
12298
  await rm(filePath, { force: true });
11983
12299
  });
@@ -12058,7 +12374,7 @@ function prepareHostWorkspaceDelivery(args) {
12058
12374
  }
12059
12375
  let archiveSizeBytes = 0;
12060
12376
  try {
12061
- archiveSizeBytes = statSync2(archivePath).size;
12377
+ archiveSizeBytes = statSync3(archivePath).size;
12062
12378
  } catch (error) {
12063
12379
  return fail3(
12064
12380
  "host_workspace_archive_failed",
@@ -12118,7 +12434,7 @@ function buildHostBundle(args) {
12118
12434
  }
12119
12435
  let sizeBytes = 0;
12120
12436
  try {
12121
- sizeBytes = statSync2(args.bundlePath).size;
12437
+ sizeBytes = statSync3(args.bundlePath).size;
12122
12438
  } catch (error) {
12123
12439
  return {
12124
12440
  ok: false,
@@ -12221,8 +12537,8 @@ async function createLocalDockerWorkload(args) {
12221
12537
  }
12222
12538
  const createLifecycle = args.createLifecycle ?? (async () => {
12223
12539
  const [{ DockerWorkloadLifecycle, createDockerBindingAuthorizer }, accounts] = await Promise.all([
12224
- import("./workloadLifecycle-HFJIN5IZ.js"),
12225
- import("./accountResolver-QETKNC7T.js")
12540
+ import("./workloadLifecycle-ZCSQCHG3.js"),
12541
+ import("./accountResolver-NGICIMEE.js")
12226
12542
  ]);
12227
12543
  const resolveAccount = args.resolveAccount ?? accounts.createDockerAccountResolver({
12228
12544
  env: args.env,
@@ -12317,28 +12633,28 @@ async function createLocalDockerWorkload(args) {
12317
12633
  };
12318
12634
  let rejectReady = () => {
12319
12635
  };
12320
- const ready = new Promise((resolve7, reject) => {
12321
- resolveReady = resolve7;
12636
+ const ready = new Promise((resolve8, reject) => {
12637
+ resolveReady = resolve8;
12322
12638
  rejectReady = reject;
12323
12639
  });
12324
12640
  let releaseRun = () => {
12325
12641
  };
12326
- const releaseGate = new Promise((resolve7) => {
12327
- releaseRun = resolve7;
12642
+ const releaseGate = new Promise((resolve8) => {
12643
+ releaseRun = resolve8;
12328
12644
  });
12329
12645
  const waitForReleaseOrAbort = () => {
12330
12646
  const signal = args.signal;
12331
12647
  if (!signal) return releaseGate;
12332
12648
  if (signal.aborted) return Promise.resolve();
12333
- return new Promise((resolve7) => {
12649
+ return new Promise((resolve8) => {
12334
12650
  const onAbort = () => {
12335
12651
  signal.removeEventListener("abort", onAbort);
12336
- resolve7();
12652
+ resolve8();
12337
12653
  };
12338
12654
  signal.addEventListener("abort", onAbort, { once: true });
12339
12655
  void releaseGate.then(() => {
12340
12656
  signal.removeEventListener("abort", onAbort);
12341
- resolve7();
12657
+ resolve8();
12342
12658
  });
12343
12659
  });
12344
12660
  };
@@ -12832,12 +13148,12 @@ function describeInstaboxBridgeUnavailable(bridge) {
12832
13148
  // packages/cli/client/localInstaboxWorkspaceRecovery.ts
12833
13149
  import { constants as constants3 } from "node:fs";
12834
13150
  import { open as open2 } from "node:fs/promises";
12835
- import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
13151
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
12836
13152
 
12837
13153
  // packages/agent-runtime/artifactStore.ts
12838
- import { createHash as createHash4, createHmac } from "node:crypto";
13154
+ import { createHash as createHash5, createHmac } from "node:crypto";
12839
13155
  import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
12840
- 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";
12841
13157
  var ArtifactStoreError = class extends Error {
12842
13158
  code;
12843
13159
  key;
@@ -12887,12 +13203,12 @@ function isNotFoundError(error) {
12887
13203
  return error?.code === "ENOENT";
12888
13204
  }
12889
13205
  function createLocalArtifactStore(options) {
12890
- const root = resolve6(options.rootDir);
13206
+ const root = resolve7(options.rootDir);
12891
13207
  const now = options.now ?? Date.now;
12892
13208
  const pathFor = (key) => {
12893
13209
  assertArtifactKey(key);
12894
- const target = resolve6(root, key);
12895
- if (target !== root && !target.startsWith(`${root}${sep}`)) {
13210
+ const target = resolve7(root, key);
13211
+ if (target !== root && !target.startsWith(`${root}${sep2}`)) {
12896
13212
  throw new ArtifactStoreError(
12897
13213
  "invalid_key",
12898
13214
  `artifact key \u89E3\u6790\u540E\u8D8A\u51FA rootDir\uFF1A${describeKey(key)}`,
@@ -12906,7 +13222,7 @@ function createLocalArtifactStore(options) {
12906
13222
  const bytes = toBytes(data);
12907
13223
  const target = pathFor(key);
12908
13224
  try {
12909
- await mkdir(dirname3(target), { recursive: true });
13225
+ await mkdir(dirname5(target), { recursive: true });
12910
13226
  await writeFile(target, bytes);
12911
13227
  } catch (error) {
12912
13228
  if (error instanceof ArtifactStoreError) throw error;
@@ -12962,12 +13278,12 @@ function createLocalArtifactStore(options) {
12962
13278
  };
12963
13279
  }
12964
13280
  function sha256Hex2(data) {
12965
- return createHash4("sha256").update(data).digest("hex");
13281
+ return createHash5("sha256").update(data).digest("hex");
12966
13282
  }
12967
13283
  var EMPTY_SHA256 = sha256Hex2("");
12968
13284
 
12969
13285
  // packages/cli/client/localInstaboxWorkspaceRecovery.ts
12970
- var sha = (b) => createHash5("sha256").update(b).digest("hex");
13286
+ var sha = (b) => createHash6("sha256").update(b).digest("hex");
12971
13287
  function fail4(code) {
12972
13288
  throw Object.assign(new Error(`instabox_workspace_recovery:${code}; cleanup_pending`), { code: "instabox_cleanup_pending", cleanupPending: true });
12973
13289
  }
@@ -13472,8 +13788,8 @@ async function createLocalInstaboxWorkload(args) {
13472
13788
  }
13473
13789
 
13474
13790
  // packages/cli/client/localRunArtifactExport.ts
13475
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "node:fs";
13476
- 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";
13477
13793
 
13478
13794
  // packages/agent-runtime/runArtifactExport.ts
13479
13795
  var RUN_DIFF_COMMAND = "git add -A && git diff --cached --binary";
@@ -13681,13 +13997,13 @@ function serializeRunArtifactAudit(record) {
13681
13997
  // packages/cli/client/localRunArtifactExport.ts
13682
13998
  function resolveRunArtifactsRootDir(runsDir) {
13683
13999
  const normalized = runsDir.replace(/[/\\]+$/, "");
13684
- return join6(dirname4(normalized || runsDir), "artifacts");
14000
+ return join7(dirname6(normalized || runsDir), "artifacts");
13685
14001
  }
13686
14002
  function writeRunArtifactAudit(args) {
13687
- const fs = args.fs ?? { mkdirSync: mkdirSync2, writeFileSync: writeFileSync3 };
13688
- const path = join6(args.runsDir, `${args.record.runId}.artifacts.json`);
13689
- fs.mkdirSync?.(args.runsDir, { recursive: true });
13690
- 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));
13691
14007
  return path;
13692
14008
  }
13693
14009
  function createDockerRunTerminalExport(args) {
@@ -14037,9 +14353,9 @@ function buildTokenDialogIndexOps(args) {
14037
14353
 
14038
14354
  // packages/cli/client/localRuntimeDialog.ts
14039
14355
  var import_format = __toESM(require_format(), 1);
14040
- import { appendFileSync, mkdirSync as mkdirSync3 } from "fs";
14041
- import { homedir } from "os";
14042
- 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";
14043
14359
 
14044
14360
  // packages/cli/client/cliCompletedTurnCapture.ts
14045
14361
  async function readCliCaptureSources(args) {
@@ -14159,11 +14475,11 @@ function projectRawUsage(usage) {
14159
14475
  function debugCaptureRawUsage(item) {
14160
14476
  if (!process.env.NOLO_DEBUG_RAW_USAGE) return;
14161
14477
  try {
14162
- const noloHome = process.env.NOLO_HOME?.trim() || join7(homedir(), ".nolo");
14163
- const dir = join7(noloHome, "logs");
14164
- 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 });
14165
14481
  appendFileSync(
14166
- join7(dir, "raw-usage.jsonl"),
14482
+ join8(dir, "raw-usage.jsonl"),
14167
14483
  JSON.stringify({
14168
14484
  ts: Date.now(),
14169
14485
  model: item.model,
@@ -14406,14 +14722,26 @@ async function writeDialog(args) {
14406
14722
  existingDialog,
14407
14723
  cwd: args.cwd
14408
14724
  });
14409
- for (const id of plan.captureUserMessageIds) {
14410
- const op = plan.ops.find((op2) => op2.value.id === id && op2.value.role === "user");
14411
- const existing = await args.store.read(op.key, { remote: false });
14412
- if (existing) {
14413
- if (existing.id !== id || existing.dialogId !== plan.dialogId || existing.userId !== args.userId || existing.role !== "user" || JSON.stringify(existing.content) !== JSON.stringify(op.value.content)) {
14414
- 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;
14415
14743
  }
14416
- op.value = existing;
14744
+ prefetchedUserMessages.set(op.key, op.value);
14417
14745
  }
14418
14746
  }
14419
14747
  const lastInputTokens = extractLastProviderInputTokens(args.input) ?? (typeof existingDialog?.lastInputTokens === "number" && Number.isFinite(existingDialog.lastInputTokens) && existingDialog.lastInputTokens > 0 ? existingDialog.lastInputTokens : void 0);
@@ -14433,9 +14761,12 @@ async function writeDialog(args) {
14433
14761
  source: "cli-local"
14434
14762
  });
14435
14763
  if (args.cliBatchCompletion) {
14436
- for (const batchId of args.cliBatchCompletion.batchIds) {
14437
- plan.ops.push(await buildCliBatchCompletionOp(args.store, plan.dialogId, batchId));
14438
- }
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);
14439
14770
  }
14440
14771
  await args.store.batch(plan.ops);
14441
14772
  if (__perfEnabled) {
@@ -14476,7 +14807,7 @@ async function writeDialog(args) {
14476
14807
  dialogId: plan.dialogId,
14477
14808
  userId: args.userId,
14478
14809
  persistedUserMessageIds: plan.captureUserMessageIds,
14479
- 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 })
14480
14811
  }).catch(() => []);
14481
14812
  const syncAndCapture = async (fetchImpl) => {
14482
14813
  try {
@@ -14561,12 +14892,14 @@ async function loadCliDialogSummary(args) {
14561
14892
  const sourceHash = record.sourceHash;
14562
14893
  const sourceCount = record.sourceCount;
14563
14894
  const schemaVersion = record.schemaVersion;
14895
+ const sourceSegments = sanitizeSummarySourceSegments(record.sourceSegments);
14564
14896
  return {
14565
14897
  summary,
14566
14898
  ...typeof summarizedBeforeId === "string" && summarizedBeforeId ? { summarizedBeforeId } : {},
14567
14899
  ...typeof sourceHash === "string" && sourceHash ? { sourceHash } : {},
14568
14900
  ...typeof sourceCount === "number" && sourceCount > 0 ? { sourceCount } : {},
14569
14901
  ..."schemaVersion" in record ? { schemaVersion } : {},
14902
+ ...sourceSegments ? { sourceSegments } : {},
14570
14903
  ...Array.isArray(record.referenceKeys) ? { referenceKeys: record.referenceKeys.filter((key) => typeof key === "string") } : {}
14571
14904
  };
14572
14905
  }
@@ -14575,6 +14908,7 @@ async function saveCliDialogSummary(args) {
14575
14908
  const existing = await args.store.read(dialogKey) ?? {};
14576
14909
  const bareId = typeof existing.id === "string" && existing.id ? existing.id : args.dialogId.startsWith("dialog-") ? dialogIdFromKey(dialogKey) : args.dialogId;
14577
14910
  const compressionCount = typeof existing.compressionCount === "number" ? existing.compressionCount + 1 : 1;
14911
+ const sanitizedSourceSegments = sanitizeSummarySourceSegments(args.sourceSegments);
14578
14912
  await registerDialogOwner({
14579
14913
  store: { get: (key) => args.store.read(key, { remote: false }), put: (key, value) => args.store.write(key, value) },
14580
14914
  dialogId: bareId,
@@ -14592,6 +14926,7 @@ async function saveCliDialogSummary(args) {
14592
14926
  ...args.sourceHash !== void 0 ? { sourceHash: args.sourceHash } : {},
14593
14927
  ...args.sourceCount !== void 0 ? { sourceCount: args.sourceCount } : {},
14594
14928
  ...args.schemaVersion !== void 0 ? { schemaVersion: args.schemaVersion } : {},
14929
+ ...sanitizedSourceSegments !== void 0 ? { sourceSegments: sanitizedSourceSegments } : {},
14595
14930
  referenceKeys: Array.from(/* @__PURE__ */ new Set([
14596
14931
  ...Array.isArray(existing.referenceKeys) ? existing.referenceKeys.filter((key) => typeof key === "string") : [],
14597
14932
  ...args.referenceKeys ?? []
@@ -14863,6 +15198,17 @@ function createCliLocalRuntimeAdapter(deps) {
14863
15198
  const defaultCompactionSummary = createTuiSummaryLlmCaller(deps.env, { fetchImpl, platformPrimary: true });
14864
15199
  const loopbackRequest = deps.loopbackRequest ?? (deps.fetchImpl ? void 0 : defaultLoopbackRequest);
14865
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
+ };
14866
15212
  const resolveLiveImageSupport = createLiveImageSupportResolver(userId, async () => {
14867
15213
  const token = await createOAuthApiKeyRefResolver({
14868
15214
  migration: { enableLegacyMigration: true },
@@ -15038,15 +15384,15 @@ function createCliLocalRuntimeAdapter(deps) {
15038
15384
  const runId = asOptionalTrimmedString(deps.env?.NOLO_AGENT_RUN_ID) ?? "interactive";
15039
15385
  emitRunIsolationNotice(fact, { runId });
15040
15386
  try {
15041
- const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync4 } = await import("node:fs");
15042
- 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");
15043
15389
  recordLocalRunExecutionIsolation({
15044
15390
  runId,
15045
15391
  runsDir: resolveRunsDir2(deps.env),
15046
15392
  fact,
15047
15393
  fs: {
15048
15394
  writeFileSync: (path, data) => writeFileSync4(path, data),
15049
- mkdirSync: (path, options) => mkdirSync4(path, options)
15395
+ mkdirSync: (path, options) => mkdirSync5(path, options)
15050
15396
  }
15051
15397
  });
15052
15398
  getLogger("cli.localRuntimeAdapter").info(
@@ -15064,7 +15410,7 @@ function createCliLocalRuntimeAdapter(deps) {
15064
15410
  dockerWorkloadReleased = true;
15065
15411
  dockerWorkloadLoad = null;
15066
15412
  if (loaded) {
15067
- const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-MBG4U6SL.js");
15413
+ const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-RN2P6AOD.js");
15068
15414
  const exportRunDiff = deps.exportDockerRunDiffArtifact ?? exportDockerRunDiffArtifact;
15069
15415
  const warn = (message) => process.stderr.write(`[nolo] ${message}
15070
15416
  `);
@@ -15145,7 +15491,6 @@ function createCliLocalRuntimeAdapter(deps) {
15145
15491
  }
15146
15492
  };
15147
15493
  let runtimeToolExecutionLimits = {};
15148
- const skillPolicyFingerprint = (source) => JSON.stringify(Object.entries(resolveAgentSkillConfig(source)).sort(([a], [b]) => a.localeCompare(b)));
15149
15494
  let reviewAgentConfig;
15150
15495
  let planningCaller = {};
15151
15496
  const isCanonicalAutoReviewAdmitted = (visits) => {
@@ -15165,6 +15510,10 @@ function createCliLocalRuntimeAdapter(deps) {
15165
15510
  readXPost: deps.readXPost,
15166
15511
  readXhsProfile: deps.readXhsProfile,
15167
15512
  cliEntrypoint: CLI_ENTRYPOINT,
15513
+ // 本地进程内直连:readDialog / listDialogs 走已在手的共享 store
15514
+ // (local-first,未命中才远端回退),不再 spawn `nolo` 子进程 + 试探
15515
+ // 多个 HTTP 端点;本地答不了时 executor 内部自行回退 CLI 桥。
15516
+ resolveDialogStore: () => getOrCreateSharedStore(deps),
15168
15517
  resolveAgentCredentialGroup,
15169
15518
  resolveAgentDisplayName,
15170
15519
  // α:spawn 前从 agent 配置回读真实 name(resolveAgentRunName 的读取来源)。
@@ -15191,6 +15540,20 @@ function createCliLocalRuntimeAdapter(deps) {
15191
15540
  },
15192
15541
  resolveAgentRuntimeBindingMachineId,
15193
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
+ },
15194
15557
  ...deps.shellApprovalSession ? {
15195
15558
  shellApprovalHostForAgent: createChildShellApprovalHostResolver({
15196
15559
  readAgentConfig: async (childAgentKey) => readAgentFromStore({
@@ -15223,6 +15586,13 @@ function createCliLocalRuntimeAdapter(deps) {
15223
15586
  } } : {},
15224
15587
  ...runtimeToolExecutionLimits
15225
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();
15226
15596
  let localToolExecutors = buildCurrentToolExecutors();
15227
15597
  const credentialBroker = createHostCredentialBrokerChain({
15228
15598
  strict: createStrictHostCredentialBroker(),
@@ -15361,7 +15731,17 @@ function createCliLocalRuntimeAdapter(deps) {
15361
15731
  const cached = deps.pastedTextStore ? void 0 : preparedAgentRuntimeCache.get(cacheKey);
15362
15732
  if (cached) {
15363
15733
  const localRecord = await sharedStore.read(cached.agentConfig.key, { remote: false }).catch(() => null);
15364
- 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);
15365
15745
  if (!unchanged) preparedAgentRuntimeCache.delete(cacheKey);
15366
15746
  if (unchanged) {
15367
15747
  activeAgentToolNames = cached.activeAgentToolNames;
@@ -15400,10 +15780,10 @@ function createCliLocalRuntimeAdapter(deps) {
15400
15780
  const userPromptPatches = accountAutoReviewPrompt ? [...userSkills.skillPromptPatches, accountAutoReviewPrompt] : userSkills.skillPromptPatches;
15401
15781
  const agentConfig = packAgentConfig && userPromptPatches.length ? {
15402
15782
  ...packAgentConfig,
15403
- prompt: [
15404
- packAgentConfig.prompt,
15405
- ...userPromptPatches.filter((patch) => !String(packAgentConfig.prompt ?? "").includes(patch))
15406
- ].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")
15407
15787
  } : packAgentConfig;
15408
15788
  const requestedToolNames = agentConfig ? resolveCliRequestedToolNames(
15409
15789
  agentConfig,
@@ -15449,7 +15829,9 @@ function createCliLocalRuntimeAdapter(deps) {
15449
15829
  if (exposedAgentConfig && !deps.pastedTextStore) {
15450
15830
  preparedAgentRuntimeCache.set(cacheKey, {
15451
15831
  agentConfig: exposedAgentConfig,
15452
- localAgentSkillFingerprint: skillPolicyFingerprint(exposedAgentConfig.rawRecord),
15832
+ localAgentConfigFingerprint: buildLocalAgentConfigFingerprint(
15833
+ exposedAgentConfig.rawRecord
15834
+ ),
15453
15835
  activeAgentToolNames,
15454
15836
  runtimeToolExecutionLimits
15455
15837
  });
@@ -15463,21 +15845,25 @@ function createCliLocalRuntimeAdapter(deps) {
15463
15845
  env: deps.env,
15464
15846
  fetchImpl
15465
15847
  });
15466
- return loaded.messages;
15848
+ return prependManualCompactHistory(dialogId, loaded.messages);
15467
15849
  },
15468
15850
  // Source-aware variant so a cross-machine resume that could not load the
15469
15851
  // remote history reports `none` instead of looking like a new dialog.
15470
- loadDialogHistoryWithSource: async (dialogId, options) => loadCliDialogHistoryWithSource({
15471
- strictContinueHistory: options?.strictContinueHistory,
15472
- freshDialog: options?.freshDialog,
15473
- dialogId,
15474
- store: await getOrCreateSharedStore(deps),
15475
- env: deps.env,
15476
- fetchImpl,
15477
- log: (message) => {
15478
- logLocalRuntimeDiagnostic("dialog-history", { dialogId, message });
15479
- }
15480
- }),
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
+ },
15481
15867
  loadDialogSummary: async (dialogId) => loadCliDialogSummary({
15482
15868
  store: await getOrCreateSharedStore(deps),
15483
15869
  userId,
@@ -15492,6 +15878,7 @@ function createCliLocalRuntimeAdapter(deps) {
15492
15878
  sourceHash: input.sourceHash,
15493
15879
  sourceCount: input.sourceCount,
15494
15880
  schemaVersion: input.schemaVersion,
15881
+ ...input.sourceSegments !== void 0 ? { sourceSegments: input.sourceSegments } : {},
15495
15882
  referenceKeys: input.referenceKeys
15496
15883
  }),
15497
15884
  loadLastContextUsage: async (dialogId) => {
@@ -15670,6 +16057,9 @@ function createCliLocalRuntimeAdapter(deps) {
15670
16057
  ...ownerOriginExecution ? { ownerOriginExecution } : {}
15671
16058
  });
15672
16059
  },
16060
+ onWorkingHistoryReplaced: () => {
16061
+ localToolExecutors.readFile?.resetReadLedger?.();
16062
+ },
15673
16063
  executeTool: async (call, opts) => {
15674
16064
  const contextualCall = opts?.runtimeContext ? { ...call, runtimeContext: opts.runtimeContext } : call;
15675
16065
  let injectedCall = contextualCall;
@@ -15844,7 +16234,43 @@ function createCliLocalRuntimeAdapter(deps) {
15844
16234
  workspaceRoot,
15845
16235
  execShellApproval: deps.execShellApproval,
15846
16236
  ...runtimeToolExecutionLimits,
15847
- 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,
15848
16274
  // 沙盒分支的 gate 已经跑过(channel 未接管才会落回这里):把
15849
16275
  // confirmed 传下去,避免破坏性确认在同一调用里弹第二次。
15850
16276
  ...sandboxGatePassed ? { confirmed: true } : {},
@@ -15925,17 +16351,14 @@ export {
15925
16351
  readTimestamp,
15926
16352
  parseAgentRunEvent,
15927
16353
  isLiveAgentRunObservation,
15928
- formatApprovalRemaining,
15929
- createHostApprovalCardQueue,
15930
- registerHostApprovalRenderer,
15931
- isSubtaskRun,
15932
- RUN_WAKE_CHANNEL_ENV,
15933
16354
  createOriginShellGrant,
16355
+ createCliHybridRecordStore,
15934
16356
  preparedAgentRuntimeCache,
15935
16357
  hybridStoreCache,
15936
16358
  normalizeRuntimeCacheCwd,
15937
16359
  buildPreparedAgentCacheKey,
15938
16360
  clearCliLocalRuntimePreparedAgentCache,
16361
+ buildLocalAgentConfigFingerprint,
15939
16362
  defaultLocalRuntimeDb,
15940
16363
  createFallbackId,
15941
16364
  logLocalRuntimeDiagnostic,