nolo-cli 0.225.0-alpha.1 → 0.225.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 (245) hide show
  1. package/{_executeModel-L5VHAXSU.js → _executeModel-UCWDB72C.js} +79 -73
  2. package/{action-CK64LS6S.js → action-24MZYW2B.js} +11 -8
  3. package/{addContentAction-EQXMFNPR.js → addContentAction-HEMCSSHT.js} +14 -13
  4. package/{addDialogAgentAction-RSDZDASD.js → addDialogAgentAction-SQYDOXHA.js} +15 -14
  5. package/{agentDeleteCommand-4WC7INCX.js → agentDeleteCommand-P7O3ACNJ.js} +131 -124
  6. package/{agentEmailCommands-3XFR6WY7.js → agentEmailCommands-A5BRSYWK.js} +134 -123
  7. package/{agentFavoriteCommands-2LKGKSUD.js → agentFavoriteCommands-7LOP3HUD.js} +5 -5
  8. package/{agentGrantCommands-QQV4N4JW.js → agentGrantCommands-L6O2HVJI.js} +5 -5
  9. package/{agentListCommands-BBCP5XYW.js → agentListCommands-LDRCOOMO.js} +112 -496
  10. package/{agentMachineCommands-YZDCOLQL.js → agentMachineCommands-AYL53KJV.js} +65 -58
  11. package/{agentProviderCommands-7BSJH7TO.js → agentProviderCommands-N5EA3ED2.js} +6 -6
  12. package/{agentPullCommand-XN6ZPBUW.js → agentPullCommand-QQQZSC6S.js} +6 -6
  13. package/agentRecordCommands-FICBZ57C.js +188 -0
  14. package/{agentRunCommand-NHYBV4G5.js → agentRunCommand-CTXQGDUM.js} +135 -120
  15. package/{agentRunControl-7A2FOXIJ.js → agentRunControl-CO6BASZF.js} +20 -14
  16. package/{agentRuntimeLocal-GSTYFEX4.js → agentRuntimeLocal-5YN4D5WT.js} +48 -41
  17. package/{agentSlice-O6IGTM3Y.js → agentSlice-DJ5D4DU4.js} +18 -17
  18. package/{appDeleteCommands-L7HL4AWF.js → appDeleteCommands-B4E7N7M2.js} +58 -51
  19. package/{appDeployCommands-SGSUNFZR.js → appDeployCommands-E4DTXRRM.js} +58 -51
  20. package/{appDeployStatusCommands-AAA3XD54.js → appDeployStatusCommands-FCNHYHZM.js} +58 -51
  21. package/{appGetCommands-LN72GAOA.js → appGetCommands-4DXSQHUZ.js} +58 -51
  22. package/{appListCommands-IJQQ3VND.js → appListCommands-2NN5E4F6.js} +58 -51
  23. package/{authCommand-7JXW54U4.js → authCommand-47DR6GZT.js} +33 -28
  24. package/{authCommands-YDNAIDEY.js → authCommands-ZZ3L5IFM.js} +16 -11
  25. package/{builtinSkillRegistry-PXH7EGQB.js → builtinSkillRegistry-AYWYQVA4.js} +5 -5
  26. package/{chromeOpsCommands-YKX2QX3A.js → chromeOpsCommands-VZWAY2KR.js} +6 -6
  27. package/{chunk-YDBMZ7FV.js → chunk-24GVXSWK.js} +3 -3
  28. package/{chunk-JCK3EFZS.js → chunk-25OCZXSX.js} +63 -32
  29. package/{chunk-P2ZLUIW2.js → chunk-2BSLGODA.js} +350 -25
  30. package/chunk-2SXN7LAY.js +15 -0
  31. package/{chunk-N5PQJKCY.js → chunk-2XMKW2OY.js} +13 -12
  32. package/{chunk-XI2BWJM5.js → chunk-324FWHUA.js} +20 -3
  33. package/{chunk-UKS7D2NL.js → chunk-3NFWMSTA.js} +111 -26
  34. package/{chunk-TZEP5J4A.js → chunk-3V6JT6WN.js} +2935 -1412
  35. package/{chunk-SBVTHMEG.js → chunk-4FE3IWRE.js} +1 -1
  36. package/{chunk-4JVNURX4.js → chunk-4YFC3DWW.js} +68 -16
  37. package/chunk-4ZCTKB27.js +31 -0
  38. package/chunk-53W5BXLN.js +340 -0
  39. package/{chunk-JWXITTQB.js → chunk-5HUO7SEX.js} +9 -107
  40. package/{chunk-VFBVA3U2.js → chunk-5TJE4QCL.js} +131 -40
  41. package/{chunk-YXMBJ7UH.js → chunk-6BGJHJRN.js} +21 -21
  42. package/chunk-6D25V6CB.js +133 -0
  43. package/chunk-6RSNVJGO.js +279 -0
  44. package/{chunk-IZIN2UNJ.js → chunk-6X3CS6NJ.js} +203 -24
  45. package/{chunk-XZGQ6ZCV.js → chunk-6XBOPKUH.js} +27 -90
  46. package/{chunk-YGMBIXCF.js → chunk-6XRPBZRS.js} +4 -2
  47. package/{chunk-62HXNQVV.js → chunk-776CXKMX.js} +1 -1
  48. package/chunk-7NIBQ4HY.js +138 -0
  49. package/{chunk-7Z6EW7AH.js → chunk-7OTNBI77.js} +13 -6
  50. package/{chunk-HOK3ILHA.js → chunk-7Q7MKJZN.js} +590 -330
  51. package/{chunk-KZU52OJ5.js → chunk-7U2TFUWW.js} +6 -6
  52. package/{chunk-IUD7YR3B.js → chunk-B72AFRR2.js} +15 -15
  53. package/{chunk-4HFTBHBF.js → chunk-BDERPCJW.js} +8 -8
  54. package/chunk-BEM6LPD2.js +734 -0
  55. package/chunk-BIDSIRTS.js +307 -0
  56. package/{chunk-6J4TTPS2.js → chunk-BIJTI5SX.js} +5 -5
  57. package/chunk-BWW6WRX6.js +1438 -0
  58. package/{chunk-AGP3YSEC.js → chunk-C3GOEQJF.js} +46 -1
  59. package/chunk-C5A54QS7.js +108 -0
  60. package/{chunk-MOMR7NMG.js → chunk-C646JEUV.js} +2 -2
  61. package/{chunk-YI5CDUJD.js → chunk-CT6GT2BG.js} +9 -9
  62. package/{chunk-PVZY6P3S.js → chunk-CZLSTOVM.js} +2 -2
  63. package/{chunk-LJSNEV7M.js → chunk-DGUUOHBF.js} +8 -8
  64. package/{chunk-C4WTX5TU.js → chunk-DIBQXNGW.js} +2 -2
  65. package/{chunk-YFLVRVYK.js → chunk-DLT2DN4M.js} +1 -1
  66. package/{chunk-K44HIUBX.js → chunk-DLTMAXLF.js} +13 -13
  67. package/chunk-DVYAFH2Q.js +103 -0
  68. package/{chunk-SOG7OEXX.js → chunk-DWWUVRB5.js} +1 -1
  69. package/{chunk-KFHREHUQ.js → chunk-DXWGFL2Z.js} +89 -1
  70. package/{chunk-GNHMRBYZ.js → chunk-EBKHA63G.js} +106 -14
  71. package/{chunk-KC4SCKXO.js → chunk-EIFSCI4C.js} +990 -1370
  72. package/{chunk-F3YK7KIU.js → chunk-EW37CXCQ.js} +4 -4
  73. package/{chunk-M3JEW6N6.js → chunk-F26GAEH3.js} +10 -0
  74. package/{chunk-2VUZSVAS.js → chunk-F3FQPVHE.js} +57 -20
  75. package/{chunk-ZRAARRA3.js → chunk-FCAMGBLY.js} +1399 -2978
  76. package/{chunk-AK5O76CC.js → chunk-FPMPWNVQ.js} +3 -3
  77. package/{chunk-WQEMD4Z4.js → chunk-FSIEHQNH.js} +420 -120
  78. package/{chunk-FNDSBM4J.js → chunk-FXX6VFMV.js} +571 -348
  79. package/{chunk-7XS4W5KP.js → chunk-G6OPRPXH.js} +128 -149
  80. package/{chunk-PMDVQBGA.js → chunk-GAHJLSDO.js} +14 -7
  81. package/{chunk-2TIQO6TC.js → chunk-GCVFX6ZL.js} +206 -308
  82. package/{chunk-P25E3CKY.js → chunk-H6CHPU6M.js} +4 -4
  83. package/chunk-HNWZJI4N.js +33394 -0
  84. package/{chunk-S2NTVGA2.js → chunk-I2OYPD3Y.js} +1 -1
  85. package/{chunk-KNIIRXHF.js → chunk-IPRPYKBP.js} +46 -8
  86. package/{chunk-C4VAR65S.js → chunk-IUXBKS5L.js} +200 -120
  87. package/{chunk-JVRQ6YVK.js → chunk-JBWXPACD.js} +1 -1
  88. package/{chunk-Z6USB65D.js → chunk-KGIIZXPL.js} +347 -14
  89. package/chunk-KK3FCYZM.js +647 -0
  90. package/{chunk-GBZ4YKEO.js → chunk-KOIDLCAQ.js} +8 -8
  91. package/{chunk-2ZKFCIJJ.js → chunk-LCQJH7KN.js} +1 -1
  92. package/{chunk-N5Z2V73W.js → chunk-LELADM5Q.js} +1 -1
  93. package/{chunk-4NA3YTBC.js → chunk-LMFMV5UC.js} +8 -8
  94. package/{chunk-XN23AUVU.js → chunk-LMZRXDWG.js} +8 -5
  95. package/{chunk-EWPDMS4N.js → chunk-LN4ZVSO7.js} +30 -15
  96. package/{chunk-GOAPXKQU.js → chunk-LT3DMEIB.js} +4 -4
  97. package/{chunk-GGKNJ42M.js → chunk-LYDEFPQP.js} +18 -108
  98. package/{chunk-FTQWYWUI.js → chunk-MDVP5TLI.js} +1 -1
  99. package/{chunk-EOWLBDY6.js → chunk-MM73SP4K.js} +1 -1
  100. package/chunk-MVOZ22RZ.js +26 -0
  101. package/{chunk-3QFLXA24.js → chunk-N6EN3HK3.js} +3 -3
  102. package/{chunk-D726I5AZ.js → chunk-NBB2EBQD.js} +2 -2
  103. package/{chunk-DISQCYPE.js → chunk-NL7J2J5Z.js} +6 -6
  104. package/{chunk-JM5C4EUA.js → chunk-NQQL2DKF.js} +6 -6
  105. package/{chunk-LS2MGTUS.js → chunk-NWWQY2J5.js} +15 -15
  106. package/{chunk-TXGQ4O5S.js → chunk-OATIWAKN.js} +20 -174
  107. package/{chunk-KYH7XW3K.js → chunk-OJRTTERA.js} +77 -2
  108. package/{chunk-VV7TXWOC.js → chunk-OYHJ4TW7.js} +6 -6
  109. package/{chunk-EUCFKKDM.js → chunk-PVFYPUIM.js} +40 -10
  110. package/{chunk-2VA6TU4I.js → chunk-QES2NCVM.js} +17 -14
  111. package/{chunk-WG2LFJYB.js → chunk-QGMIUVBT.js} +39 -30
  112. package/{chunk-HOCHUZQ7.js → chunk-QJTZ76CP.js} +24 -6
  113. package/{chunk-MK2Q7ZJD.js → chunk-R7XWZDOH.js} +58 -24
  114. package/{chunk-5FUN7EG4.js → chunk-RD3QLZQV.js} +83 -47
  115. package/{chunk-AMEOV5VZ.js → chunk-S25VJYXV.js} +41 -35
  116. package/chunk-SR4FE5VD.js +9 -0
  117. package/{chunk-4WVJLODK.js → chunk-T23G6PXQ.js} +8 -3
  118. package/{chunk-GVGOEMNV.js → chunk-T444ENEC.js} +3 -3
  119. package/{chunk-67BE44IS.js → chunk-TE2XH4KH.js} +1 -1
  120. package/{chunk-5RKUPJYL.js → chunk-TFGGNRT6.js} +11 -3
  121. package/{chunk-ZH6MUQEO.js → chunk-TTEBPPUV.js} +1 -1
  122. package/{chunk-QVBXJNZ2.js → chunk-TUSTONB3.js} +1 -1
  123. package/{chunk-AVHRSJUH.js → chunk-TXFYIWAW.js} +32 -25
  124. package/{chunk-KOXKKHFE.js → chunk-TXQVH72L.js} +9 -4
  125. package/{chunk-OBSEKCVK.js → chunk-U4VSBDO5.js} +88 -0
  126. package/{chunk-PPJYZRSQ.js → chunk-U5LOKQ2R.js} +30 -14
  127. package/{chunk-KDAGMRDA.js → chunk-UAHUJ4HH.js} +100 -32
  128. package/{chunk-BGGHA5DV.js → chunk-UAOFSUG7.js} +1 -1
  129. package/{chunk-CKT6QUE2.js → chunk-UHW6SCVK.js} +1 -1
  130. package/chunk-UKSKCDBG.js +62 -0
  131. package/{chunk-KEN3N2TN.js → chunk-VMJVAJ6W.js} +13 -10
  132. package/{chunk-SOF4OWDM.js → chunk-VS276URX.js} +0 -2
  133. package/chunk-WDWZPASX.js +29 -0
  134. package/chunk-WFGNWWJI.js +326 -0
  135. package/{chunk-UYOICCYG.js → chunk-WHO3LYDW.js} +64 -89
  136. package/{chunk-UJKTI5PG.js → chunk-WRKMXMU7.js} +2 -1
  137. package/{chunk-FIYSMXHY.js → chunk-WWTSEBDF.js} +1 -1
  138. package/{chunk-QLFCTYRH.js → chunk-X37RQEA3.js} +17 -10
  139. package/{chunk-E2BESSAW.js → chunk-X4O7FJF5.js} +2 -0
  140. package/chunk-X7IA2B7R.js +166 -0
  141. package/{chunk-GIABSSWQ.js → chunk-XAFOLWLU.js} +4 -4
  142. package/{chunk-45LZIYXB.js → chunk-XNEDFWT4.js} +2 -2
  143. package/{chunk-EOJZGQAE.js → chunk-Y5RN44VH.js} +103 -100
  144. package/{chunk-OB6DVWPF.js → chunk-YFRJAE3R.js} +319 -95
  145. package/{chunk-L5I543VB.js → chunk-YGDYYFRX.js} +20 -24
  146. package/{chunk-3KNEE64G.js → chunk-YMCSR7PA.js} +14 -14
  147. package/chunk-YUZ2DAIH.js +34 -0
  148. package/chunk-Z6YTCDU4.js +24 -0
  149. package/{chunk-XQBIZRGW.js → chunk-ZBQ5UGYY.js} +3 -3
  150. package/{chunk-VREDDN25.js → chunk-ZQUCJBS4.js} +14 -9
  151. package/{chunk-UEKXWO7A.js → chunk-ZT3DYK5T.js} +15 -4
  152. package/{chunk-LM2PS3YS.js → chunk-ZTLTDUV6.js} +24 -11
  153. package/{chunk-KN3HEZIQ.js → chunk-ZVOL2MAJ.js} +1 -1
  154. package/{cliAgentConfigHelpers-KICKKNYQ.js → cliAgentConfigHelpers-RFR7ZCSK.js} +12 -12
  155. package/{cliAuthorityBrokerClient-XHH7MH2P.js → cliAuthorityBrokerClient-SFPC3WVK.js} +1 -1
  156. package/{cliEnvHelpers-VPSJ4XWC.js → cliEnvHelpers-CNMP3RDX.js} +1 -1
  157. package/{cliExecutor-4MAX3PZL.js → cliExecutor-K6FDZTQ2.js} +3 -1
  158. package/{cliLocalAgentRecordReader-6FXGFBI3.js → cliLocalAgentRecordReader-AJ4UKHKT.js} +51 -45
  159. package/{commandRegistry-HJDPQSQ4.js → commandRegistry-IHWZVV4G.js} +98 -94
  160. package/{contentThunks-I6OR5ENG.js → contentThunks-YQRCBDKF.js} +38 -35
  161. package/{cooldownCommands-X7P5M2V5.js → cooldownCommands-W67DE765.js} +4 -4
  162. package/{createAgentAutomationAction-7BCCTWO5.js → createAgentAutomationAction-ERSDNR4R.js} +38 -35
  163. package/{createDialogAction-CU27KSCJ.js → createDialogAction-QXC7JZPE.js} +39 -37
  164. package/{createPageAction-CWRTEYVA.js → createPageAction-RLZ7776F.js} +40 -37
  165. package/{db-CS4ZJQKV.js → db-6NRZLEW2.js} +10 -7
  166. package/{dbSlice-ZJPDIFER.js → dbSlice-7M2ESEUO.js} +13 -12
  167. package/{deleteFile-Q3YDB4ML.js → deleteFile-WO6WSSNK.js} +10 -7
  168. package/{dialogCommands-OPTRZWTE.js → dialogCommands-UIRO4QNN.js} +62 -56
  169. package/dialogMessageRecord-OAV77LT7.js +7 -0
  170. package/{dialogNotifyCommand-77B57PL6.js → dialogNotifyCommand-VDUFYBZV.js} +14 -14
  171. package/{dialogSlice-XODSLDHY.js → dialogSlice-A4U3C76D.js} +36 -33
  172. package/{dialogUsageCommand-HTVPR2CX.js → dialogUsageCommand-SEC6UZWM.js} +3 -3
  173. package/{docCreateCommands-36WS33BK.js → docCreateCommands-MHPYTJWR.js} +56 -49
  174. package/{docDeleteCommands-C4CS4XLF.js → docDeleteCommands-VYULMBAQ.js} +58 -51
  175. package/{docReadCommands-QZMSFMPN.js → docReadCommands-FV3GGZ7V.js} +56 -49
  176. package/{docStore-TVN4SNVE.js → docStore-AWWI72FA.js} +15 -14
  177. package/{docUpdateCommands-BYI64HVV.js → docUpdateCommands-JNS3HX7F.js} +56 -49
  178. package/fetchMessages-TQEUZD7H.js +2 -2
  179. package/{getPricing-VNGFM4PN.js → getPricing-U5AR7ZHS.js} +5 -5
  180. package/{handleSendMessageAction-NSEMVHWX.js → handleSendMessageAction-WDJOUDNV.js} +68 -63
  181. package/{hostCredentialCreate-WBZY7DZB.js → hostCredentialCreate-H3FF2SAO.js} +123 -111
  182. package/index.js +56 -18
  183. package/keys-RWF7UCB4.js +2 -2
  184. package/{lib-OT5OTXRU.js → lib-62SWPXNF.js} +3 -7
  185. package/{localDialogRead-SVTPA5GY.js → localDialogRead-3T2KMCRC.js} +1 -1
  186. package/{localRuntimeAdapter-OAIWERFA.js → localRuntimeAdapter-JAQQXZJP.js} +126 -113
  187. package/{localRuntimeAuthority-IBJAT62G.js → localRuntimeAuthority-7DKIT7UH.js} +4 -2
  188. package/{localRuntimeDb-N7KHDXS2.js → localRuntimeDb-5WZ4RJJO.js} +1 -1
  189. package/{machineCommands-OI37ZUQ4.js → machineCommands-WYOFNB5I.js} +146 -120
  190. package/{machineWsRunDispatch-73HKPV6D.js → machineWsRunDispatch-Y7UIAZNM.js} +118 -107
  191. package/markdownToSlate-KIYM7B3P.js +8 -0
  192. package/mcpLocalAuthorizeCommand-SCYEFLRK.js +106 -0
  193. package/{memberThunks-JRYNONYV.js → memberThunks-DIITWU4M.js} +22 -17
  194. package/{memoryCommands-5WC3T66U.js → memoryCommands-BC6REPQB.js} +4 -4
  195. package/{models-H5NNZRLH.js → models-CINY5UZR.js} +2 -2
  196. package/{overlay-THLKYIWY.js → overlay-JA3SPVUS.js} +7 -3
  197. package/package.json +1 -1
  198. package/{projectArchive-GVEARCOG.js → projectArchive-IZJXBW5N.js} +43 -40
  199. package/{providerPresetApply-J3WMRPD2.js → providerPresetApply-2QWXPJXZ.js} +6 -6
  200. package/{providerRegistry-KJGB5XWS.js → providerRegistry-W4LCKK6V.js} +6 -6
  201. package/{read-Q7GOHGNP.js → read-OBLJNMA2.js} +9 -8
  202. package/{readDocTool-Z5OQ6422.js → readDocTool-QQZ4DAER.js} +1 -1
  203. package/{readlineWorkspace-5DWUGNSU.js → readlineWorkspace-WF3SWZGR.js} +7055 -5248
  204. package/rememberExplicit-CPAPONSI.js +15 -0
  205. package/{removeDialogAgentAction-U3F2MNAY.js → removeDialogAgentAction-HC3SOY3G.js} +17 -16
  206. package/{runAgentClientLoop-RDXIPF34.js → runAgentClientLoop-Z7V6TA3O.js} +97 -72
  207. package/{runtimeDoctorCommands-UXKXYBW6.js → runtimeDoctorCommands-KX6YLPWV.js} +17 -17
  208. package/{secretCommands-LJXOOYA7.js → secretCommands-STRAX275.js} +4 -4
  209. package/{setDialogExtraReferencesAction-G3WSJ7EM.js → setDialogExtraReferencesAction-DDZUQPY6.js} +16 -15
  210. package/{setPrimaryDialogAgentAction-6FHAHZBB.js → setPrimaryDialogAgentAction-EB67OMAJ.js} +17 -16
  211. package/{settingThunks-AXTBX3Q5.js → settingThunks-TN6GFASU.js} +181 -62
  212. package/{skillDiscovery-B5V23AXP.js → skillDiscovery-MDDKPTW3.js} +4 -3
  213. package/{spaceCommands-GUKMDRWN.js → spaceCommands-HBYQUVJI.js} +61 -54
  214. package/{store-JRVN62NM.js → store-Z53ICFL3.js} +3 -1
  215. package/{streamAgentChatTurn-XEYQZPDJ.js → streamAgentChatTurn-CM7QQXOS.js} +178 -173
  216. package/{switchDialogAgentAction-UOFIAGPL.js → switchDialogAgentAction-XY5TKQQE.js} +15 -14
  217. package/{tableCommands-HITDSLHS.js → tableCommands-MXFL3JIT.js} +13 -10
  218. package/{toolApiClient-OGQEBQVX.js → toolApiClient-53YMJ2G6.js} +8 -6
  219. package/{tools-6DFTHCFX.js → tools-AT6H73LD.js} +66 -62
  220. package/tuiRestart-272SAYSK.js +41 -0
  221. package/{tuiSummaryLlmCaller-7WLUKNP2.js → tuiSummaryLlmCaller-K2OVRVHG.js} +20 -19
  222. package/{updateCommands-RJVCRSBP.js → updateCommands-O3BOVVVN.js} +8 -6
  223. package/{updateDialogTitleAction-AMSBV2H7.js → updateDialogTitleAction-PGY4UPLH.js} +38 -35
  224. package/{usageCommand-YPJ2ZI2F.js → usageCommand-SCF3ROV2.js} +4 -4
  225. package/{usageRebuildCommand-FERQO74C.js → usageRebuildCommand-K5WPIBA5.js} +5 -5
  226. package/webapi-24RZDIIQ.js +2488 -0
  227. package/{windowsSelfUpdate-KERHIAB4.js → windowsSelfUpdate-WJDUZLEO.js} +2 -2
  228. package/workContext-Y3ADAPZU.js +14 -0
  229. package/workContextAccess-UZHDLBUR.js +11 -0
  230. package/workContextWriteNotice-YCSSMHN4.js +7 -0
  231. package/agentRecordCommands-KLYKI4Z7.js +0 -177
  232. package/chunk-2THCNKE4.js +0 -147
  233. package/chunk-2WZXXAQD.js +0 -57
  234. package/chunk-5ZMIIR23.js +0 -265
  235. package/chunk-652XYZGP.js +0 -352
  236. package/chunk-BJF2MHJ3.js +0 -118
  237. package/chunk-KEPOVMF4.js +0 -91
  238. package/chunk-QZI44GWV.js +0 -776
  239. package/{accountResolver-EK2S4PWF.js → accountResolver-QETKNC7T.js} +3 -3
  240. package/{chunk-BLVSFYQ3.js → chunk-LISC7BD4.js} +3 -3
  241. package/{chunk-SNBZZPYH.js → chunk-OQHIVPG4.js} +3 -3
  242. package/{chunk-47ITIXO7.js → chunk-USGHJSGO.js} +3 -3
  243. package/{chunk-FJ23FZXF.js → chunk-VIYVRPMJ.js} +0 -0
  244. package/{offlineMarxistsAgentCommand-4IC3Y4C6.js → offlineMarxistsAgentCommand-XVXUE6G5.js} +3 -3
  245. package/{workloadLifecycle-O2I3NZ2Q.js → workloadLifecycle-HFJIN5IZ.js} +8 -8
@@ -1,12 +1,9 @@
1
1
  import {
2
+ AGENT_PROMPT_IN_MESSAGES,
2
3
  DEVIN_CONNECT_URL,
3
4
  parseSseDataLineJson,
4
5
  parseSseDataLineObject
5
- } from "./chunk-VFBVA3U2.js";
6
- import {
7
- evaluateFileWritePolicy,
8
- summarizeToolArguments
9
- } from "./chunk-CHOZJMJS.js";
6
+ } from "./chunk-5TJE4QCL.js";
10
7
  import {
11
8
  EXECUTION_BACKEND_KINDS
12
9
  } from "./chunk-PWTNI4N7.js";
@@ -22,27 +19,19 @@ import {
22
19
  flushChatCompletionStream,
23
20
  providerHttpFailure,
24
21
  throwIfChatCompletionStreamFailed
25
- } from "./chunk-VV7TXWOC.js";
22
+ } from "./chunk-OYHJ4TW7.js";
26
23
  import {
27
24
  readSseFrames
28
25
  } from "./chunk-HNUWUO75.js";
29
26
  import {
30
- resolveToolExecutionContract
31
- } from "./chunk-LKA64WH4.js";
27
+ evaluateFileWritePolicy,
28
+ summarizeToolArguments
29
+ } from "./chunk-CHOZJMJS.js";
32
30
  import {
33
31
  evaluateRequestBudget,
34
32
  hasImageInRuntimeMessages,
35
33
  stripImagePartsFromMessages
36
- } from "./chunk-UEKXWO7A.js";
37
- import {
38
- clipToolText,
39
- resolveHistoricalToolContentCap,
40
- resolveToolOutputProfile
41
- } from "./chunk-2WZXXAQD.js";
42
- import {
43
- resolveAgentImageInputSupport,
44
- resolveToolImagePolicy
45
- } from "./chunk-KNIIRXHF.js";
34
+ } from "./chunk-ZT3DYK5T.js";
46
35
  import {
47
36
  applyShapingCounts,
48
37
  attachProjectionFacts,
@@ -53,7 +42,7 @@ import {
53
42
  projectUserPartForModel,
54
43
  resolveOutboundDiagnosticSink,
55
44
  writeThinkingFacts
56
- } from "./chunk-SOG7OEXX.js";
45
+ } from "./chunk-DWWUVRB5.js";
57
46
  import {
58
47
  createThinkParserState,
59
48
  createToolCallAccumulator,
@@ -62,16 +51,9 @@ import {
62
51
  finalizeAccumulatedToolCalls
63
52
  } from "./chunk-56GBUMO5.js";
64
53
  import {
65
- CREDENTIAL_HYGIENE_RULE,
66
- DELETE_SAFETY_RED_LINE,
67
- DISPATCH_BACKEND_POLICY,
68
- DISPATCH_CANDIDATE_POLICY,
69
- PARALLEL_DISPATCH_DEFAULT_RULE,
70
- PLATFORM_RISK_CONTROL_RULE,
71
54
  TOOL_GUIDED_SECTION_ORDER,
72
- VERIFY_BEFORE_CONCLUDING_RULE,
73
- buildConsultationModeBlock,
74
55
  buildIdentityBlock,
56
+ buildPlatformStaticScopedBlocks,
75
57
  buildRuntimeGuidanceBlocks,
76
58
  detectDispatchIntent,
77
59
  detectDispatchIntentFromMessages,
@@ -79,7 +61,7 @@ import {
79
61
  hashStablePrefixContent,
80
62
  resolveResponseGuidelines,
81
63
  resolveToolGuidedSections
82
- } from "./chunk-2TIQO6TC.js";
64
+ } from "./chunk-GCVFX6ZL.js";
83
65
  import {
84
66
  BRIDGE_STREAM_MAX_CHARS,
85
67
  CLI_NOLO_WORKSPACE_TOOL_NAMES,
@@ -94,10 +76,10 @@ import {
94
76
  parseNoloWorkspaceToolArguments,
95
77
  readTextStreamUpToChars,
96
78
  resolveNoloDialogInput
97
- } from "./chunk-C4VAR65S.js";
79
+ } from "./chunk-IUXBKS5L.js";
98
80
  import {
99
81
  applyToolSurfaceConstraints
100
- } from "./chunk-SOF4OWDM.js";
82
+ } from "./chunk-VS276URX.js";
101
83
  import {
102
84
  classifyUnparsableToolArgs,
103
85
  collectStablePromptPrefix,
@@ -121,7 +103,7 @@ import {
121
103
  toOpenAiCompatibleMessages,
122
104
  toResponsesTools,
123
105
  transferDowngradedToolTurnOrigin
124
- } from "./chunk-JM5C4EUA.js";
106
+ } from "./chunk-NQQL2DKF.js";
125
107
  import {
126
108
  TOOL_HAD_IMAGES,
127
109
  TOOL_IMAGES,
@@ -134,13 +116,35 @@ import {
134
116
  toolImageDelivery,
135
117
  toolImages,
136
118
  withoutToolImages
137
- } from "./chunk-E2BESSAW.js";
119
+ } from "./chunk-X4O7FJF5.js";
120
+ import {
121
+ resolveToolExecutionContract
122
+ } from "./chunk-LKA64WH4.js";
123
+ import {
124
+ resolveAgentImageInputSupport,
125
+ resolveToolImagePolicy
126
+ } from "./chunk-IPRPYKBP.js";
138
127
  import {
128
+ isContextOverflowText,
139
129
  isQuotaExhaustedError
140
130
  } from "./chunk-TLE77UJ5.js";
131
+ import {
132
+ PROJECT_INSTRUCTION_MAX_BYTES,
133
+ PROJECT_INSTRUCTION_MAX_CHARS,
134
+ SECRET_PATTERNS,
135
+ clipToolText,
136
+ hasPotentialSecrets,
137
+ isCompleteInstructionOutput,
138
+ resolveHistoricalToolContentCap,
139
+ resolveToolOutputProfile,
140
+ sanitizeToolOutputContent,
141
+ sanitizeToolOutputText,
142
+ scrubObjectSecrets,
143
+ scrubSecrets
144
+ } from "./chunk-WFGNWWJI.js";
141
145
  import {
142
146
  isAgentSkillDisabled
143
- } from "./chunk-EOWLBDY6.js";
147
+ } from "./chunk-MM73SP4K.js";
144
148
  import {
145
149
  buildDialogFallbackTitleFromUserInput
146
150
  } from "./chunk-2MBTWINN.js";
@@ -152,15 +156,18 @@ import {
152
156
  resolveEmptyAssistantFallbackMessage,
153
157
  resolveEmptyAssistantOutcome,
154
158
  resolveTruncatedReasoningTailLog
155
- } from "./chunk-LM2PS3YS.js";
159
+ } from "./chunk-ZTLTDUV6.js";
156
160
  import {
157
161
  COMPACTION_SUMMARY_SCHEMA_VERSION,
158
162
  COMPACTION_SUMMARY_SYSTEM_PROMPT,
159
163
  buildBoundedCompactionRequest,
160
164
  buildCompactionMetricsFromPlan,
165
+ buildSummarySourceDiagnostics,
166
+ buildSummarySourceSegments,
161
167
  classifySummaryError,
162
168
  computeSummarySourceMetadata,
163
169
  createSummaryBudget,
170
+ diffSummarySourceSegments,
164
171
  formatCompactionMetricsLog,
165
172
  getMessageTokenCount,
166
173
  getModelContextWindow,
@@ -172,10 +179,9 @@ import {
172
179
  resolveCompressionTriggerRatio,
173
180
  resolveEffectiveCompactionBudgets,
174
181
  runSummaryWithContract,
175
- sha256Hex,
176
182
  summaryCompletionTokens,
177
183
  truncateToolOutputForContext
178
- } from "./chunk-IZIN2UNJ.js";
184
+ } from "./chunk-6X3CS6NJ.js";
179
185
  import {
180
186
  createProviderCallTimingTracker,
181
187
  finalizeProviderCallTiming,
@@ -183,15 +189,15 @@ import {
183
189
  observeMeaningfulProviderResponse,
184
190
  withProviderCallTimingFields
185
191
  } from "./chunk-H57T64RA.js";
192
+ import {
193
+ sha256Hex
194
+ } from "./chunk-SR4FE5VD.js";
186
195
  import {
187
196
  clipCompactText
188
197
  } from "./chunk-5MMAK75Q.js";
189
198
  import {
190
199
  asRecordOrEmpty
191
200
  } from "./chunk-KX6YBIHG.js";
192
- import {
193
- assertCredentialRef
194
- } from "./chunk-SNBZZPYH.js";
195
201
  import {
196
202
  isLevelNotFoundError
197
203
  } from "./chunk-OW765XBU.js";
@@ -199,31 +205,14 @@ import {
199
205
  isAbortError
200
206
  } from "./chunk-7DPNBQSV.js";
201
207
  import {
202
- WORKTREE_ISOLATION_PRELUDE
203
- } from "./chunk-GNHMRBYZ.js";
204
- import {
205
- canonicalizeToolName,
206
- canonicalizeToolNames
207
- } from "./chunk-6OVNSQHN.js";
208
- import {
209
- dialogMessageKey,
210
- dialogMessageRange
211
- } from "./chunk-OJKUU3LP.js";
212
- import {
213
- asTrimmedNonEmptyStringArray
214
- } from "./chunk-I42VC5KR.js";
215
- import {
216
- buildDialogSummaryLayer
217
- } from "./chunk-JWXITTQB.js";
218
- import {
219
- buildUserResponseLanguageContext
220
- } from "./chunk-L5I543VB.js";
221
- import {
208
+ TOOL_OUTPUT_SPILL_BYTES,
209
+ TOOL_OUTPUT_SPILL_LINES,
222
210
  buildInteractiveCommandBlockedResult,
223
211
  buildProcessTaskResultCapsule,
224
212
  buildWorkspaceShellCommand,
225
213
  buildWorkspaceShellEscapeBlockedResult,
226
214
  buildWorkspaceShellPlan,
215
+ countLines,
227
216
  createGlob,
228
217
  deriveLabel,
229
218
  extractActivity,
@@ -242,14 +231,44 @@ import {
242
231
  spillToolOutput,
243
232
  toProcessTaskView,
244
233
  truncateToolOutput
245
- } from "./chunk-KEN3N2TN.js";
234
+ } from "./chunk-VMJVAJ6W.js";
246
235
  import {
247
236
  estimateTokenCount
248
237
  } from "./chunk-PSCNXBYA.js";
238
+ import {
239
+ resolveNoloStateDir
240
+ } from "./chunk-6UBGXX2W.js";
241
+ import {
242
+ dialogMessageRecordToAgentRuntimeMessage
243
+ } from "./chunk-4ZCTKB27.js";
244
+ import {
245
+ canonicalizeToolName,
246
+ canonicalizeToolNames
247
+ } from "./chunk-6OVNSQHN.js";
248
+ import {
249
+ dialogMessageKey,
250
+ dialogMessageRange
251
+ } from "./chunk-OJKUU3LP.js";
252
+ import {
253
+ asTrimmedNonEmptyStringArray
254
+ } from "./chunk-I42VC5KR.js";
255
+ import {
256
+ asOptionalPositiveFiniteNumber
257
+ } from "./chunk-U6VC4MU4.js";
258
+ import {
259
+ buildAgentsMdLayer,
260
+ buildAgentsMdLayerHeader,
261
+ buildDialogSummaryLayer,
262
+ hasMemoryTools
263
+ } from "./chunk-5HUO7SEX.js";
264
+ import {
265
+ MEMORY_USE_GUIDANCE,
266
+ buildUserResponseLanguageContext
267
+ } from "./chunk-YGDYYFRX.js";
249
268
  import {
250
269
  buildProviderAuthHeaders,
251
270
  buildProviderExecutionPlan
252
- } from "./chunk-4NA3YTBC.js";
271
+ } from "./chunk-LMFMV5UC.js";
253
272
  import {
254
273
  toErrorMessage
255
274
  } from "./chunk-HNMXYYJR.js";
@@ -259,15 +278,6 @@ import {
259
278
  import {
260
279
  isRecord
261
280
  } from "./chunk-KUG52IAP.js";
262
- import {
263
- PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL
264
- } from "./chunk-OBSEKCVK.js";
265
- import {
266
- asTrimmedLowercaseString
267
- } from "./chunk-QSJ3HFEF.js";
268
- import {
269
- asOptionalPositiveFiniteNumber
270
- } from "./chunk-U6VC4MU4.js";
271
281
  import {
272
282
  asOptionalTrimmedString
273
283
  } from "./chunk-G3SUCT4W.js";
@@ -275,8 +285,11 @@ import {
275
285
  normalizeServerOrigin
276
286
  } from "./chunk-CF7PE763.js";
277
287
  import {
278
- resolveNoloStateDir
279
- } from "./chunk-6UBGXX2W.js";
288
+ PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL
289
+ } from "./chunk-U4VSBDO5.js";
290
+ import {
291
+ asTrimmedLowercaseString
292
+ } from "./chunk-QSJ3HFEF.js";
280
293
  import {
281
294
  __export
282
295
  } from "./chunk-U67V476Y.js";
@@ -323,6 +336,36 @@ function readTitleParams(value) {
323
336
  return Object.fromEntries(entries);
324
337
  }
325
338
 
339
+ // packages/agent-runtime/dialogHistoryOrder.ts
340
+ import { decodeTime } from "ulid";
341
+ function orderDialogHistory(messages) {
342
+ const time = (message) => {
343
+ if (Number.isFinite(message.cliHistoryOrder)) return message.cliHistoryOrder;
344
+ const id = message.id ?? message.cliMessageId;
345
+ if (!id) return Infinity;
346
+ const timestamp = /^(\d+)-/.exec(id);
347
+ if (timestamp) return Number(timestamp[1]);
348
+ if (/^[0-9A-HJKMNP-TV-Z]{26}$/.test(id)) {
349
+ try {
350
+ return decodeTime(id);
351
+ } catch {
352
+ }
353
+ }
354
+ return Number.isFinite(message.createdAt) ? message.createdAt : -Infinity;
355
+ };
356
+ const identity2 = (message) => message.id ?? message.cliMessageId;
357
+ return messages.map((message, index) => ({ message, index, time: time(message) })).sort((a, b) => {
358
+ if (a.time !== b.time) return a.time < b.time ? -1 : 1;
359
+ const left = identity2(a.message), right = identity2(b.message);
360
+ if (left && right && left !== right) return left < right ? -1 : 1;
361
+ return a.index - b.index;
362
+ }).map(({ message }) => message);
363
+ }
364
+ function dialogTurnUserMessageId(turnId, index) {
365
+ if (typeof turnId !== "string" || !/^turn-[0-9A-HJKMNP-TV-Z]{26}$/.test(turnId)) return void 0;
366
+ return `${decodeTime(turnId.slice(5))}-${String(index + 1).padStart(3, "0")}-${turnId}`;
367
+ }
368
+
326
369
  // packages/agent-runtime/contextRefusal.ts
327
370
  var machineIdentifier = (value) => value && /^[A-Z][A-Z0-9_]{0,63}$/.test(value) ? value : void 0;
328
371
  function classifyContextRefusal(args2) {
@@ -5548,8 +5591,8 @@ var runPromiseExitWith = (context3) => {
5548
5591
  const runFork3 = runForkWith(context3);
5549
5592
  return (effect, options) => {
5550
5593
  const fiber3 = runFork3(effect, options);
5551
- return new Promise((resolve6) => {
5552
- fiber3.addObserver((exit3) => resolve6(exit3));
5594
+ return new Promise((resolve7) => {
5595
+ fiber3.addObserver((exit3) => resolve7(exit3));
5553
5596
  });
5554
5597
  };
5555
5598
  };
@@ -12772,8 +12815,8 @@ var toReadableStreamWith = /* @__PURE__ */ dual((args2) => isStream(args2[0]), (
12772
12815
  }
12773
12816
  },
12774
12817
  pull() {
12775
- return new Promise((resolve6) => {
12776
- currentResolve = resolve6;
12818
+ return new Promise((resolve7) => {
12819
+ currentResolve = resolve7;
12777
12820
  latch.openUnsafe();
12778
12821
  });
12779
12822
  },
@@ -13307,255 +13350,6 @@ function sanitizeToolCallPairing(messages) {
13307
13350
  return output;
13308
13351
  }
13309
13352
 
13310
- // packages/agent-runtime/secretScrubber.ts
13311
- var SECRET_PATTERNS = [
13312
- // 1. PEM 私钥块(高危硬拦截)
13313
- {
13314
- kind: "PRIVATE_KEY",
13315
- placeholder: "[REDACTED:PRIVATE_KEY]",
13316
- regex: /-----BEGIN (?:[A-Z0-9 ]+)?PRIVATE KEY-----[\s\S]+?-----END (?:[A-Z0-9 ]+)?PRIVATE KEY-----/g
13317
- },
13318
- // 2. Anthropic API Key (sk-ant-...)
13319
- {
13320
- kind: "ANTHROPIC_KEY",
13321
- placeholder: "[REDACTED:ANTHROPIC_KEY]",
13322
- regex: /\bsk-ant-[a-zA-Z0-9_\-]{20,}\b/g
13323
- },
13324
- // 3. OpenAI / DeepSeek / 通用 API Key (sk-...)
13325
- {
13326
- kind: "API_KEY",
13327
- placeholder: "[REDACTED:API_KEY]",
13328
- regex: /\bsk-[a-zA-Z0-9_\-]{24,}\b/g
13329
- },
13330
- // 3b. BigModel / 智谱(GLM)API Key:32 位 hex + "." + 16 位字母数字
13331
- // (2026-11 实证:这类 key 没有任何可辨识前缀,此前漏在清洗与入路隔离之外,
13332
- // 用户贴进对话后明文直接进了 prompt / 历史 / 工具日志。)
13333
- {
13334
- kind: "BIGMODEL_KEY",
13335
- placeholder: "[REDACTED:BIGMODEL_KEY]",
13336
- regex: /\b[0-9a-fA-F]{32}\.[A-Za-z0-9]{16}\b/g
13337
- },
13338
- // 4. GitHub 访问令牌 (ghp_..., gho_..., github_pat_...)
13339
- {
13340
- kind: "GITHUB_TOKEN",
13341
- placeholder: "[REDACTED:GITHUB_TOKEN]",
13342
- regex: /\b(?:gh[pousr]_[a-zA-Z0-9]{30,}|github_pat_[a-zA-Z0-9_]{40,})\b/g
13343
- },
13344
- // 5. Bearer Token (JWT / Authorization Bearer)
13345
- {
13346
- kind: "BEARER_TOKEN",
13347
- placeholder: "Bearer [REDACTED:BEARER_TOKEN]",
13348
- regex: /\bBearer\s+[a-zA-Z0-9_\-\.]{25,}\b/gi
13349
- },
13350
- // 6. 常见环境变量或配置中的密码赋值 (PASSWORD=..., PASSWD=...)
13351
- {
13352
- kind: "PASSWORD",
13353
- placeholder: "$1=[REDACTED:PASSWORD]",
13354
- regex: /\b((?:DB_|DATABASE_|ADMIN_|ROOT_|MYSQL_|POSTGRES_)?(?:PASSWORD|PASSWD|SECRET_KEY))\s*=\s*['"]?([^\s'"]{4,})['"]?/gi
13355
- }
13356
- ];
13357
- var QUICK_PROBE_SUBSTRINGS = [
13358
- "sk-",
13359
- "ghp_",
13360
- "gho_",
13361
- "ghu_",
13362
- "ghs_",
13363
- "ghr_",
13364
- "github_pat_",
13365
- "PRIVATE KEY",
13366
- "Bearer ",
13367
- "bearer ",
13368
- "PASSWORD",
13369
- "password",
13370
- "PASSWD",
13371
- "SECRET_KEY"
13372
- ];
13373
- var UNPREFIXED_PROBE_REGEX = /\b[0-9a-fA-F]{32}\.[A-Za-z0-9]{16}\b/;
13374
- function hasPotentialSecrets(text2) {
13375
- if (typeof text2 !== "string" || text2.length === 0) return false;
13376
- if (QUICK_PROBE_SUBSTRINGS.some((probe) => text2.includes(probe))) return true;
13377
- return UNPREFIXED_PROBE_REGEX.test(text2);
13378
- }
13379
- function scrubSecrets(text2) {
13380
- if (typeof text2 !== "string" || text2.length === 0) {
13381
- return { cleaned: text2, redactedCount: 0, matchedKinds: [] };
13382
- }
13383
- if (!hasPotentialSecrets(text2)) {
13384
- return { cleaned: text2, redactedCount: 0, matchedKinds: [] };
13385
- }
13386
- let cleaned = text2;
13387
- let redactedCount = 0;
13388
- const matchedKinds = [];
13389
- for (const pattern of SECRET_PATTERNS) {
13390
- pattern.regex.lastIndex = 0;
13391
- const matches = cleaned.match(pattern.regex);
13392
- if (matches && matches.length > 0) {
13393
- redactedCount += matches.length;
13394
- if (!matchedKinds.includes(pattern.kind)) {
13395
- matchedKinds.push(pattern.kind);
13396
- }
13397
- cleaned = cleaned.replace(pattern.regex, pattern.placeholder);
13398
- }
13399
- }
13400
- return { cleaned, redactedCount, matchedKinds };
13401
- }
13402
- function scrubObjectSecrets(val) {
13403
- if (val === null || val === void 0) return val;
13404
- if (typeof val === "string") {
13405
- return scrubSecrets(val).cleaned;
13406
- }
13407
- if (Array.isArray(val)) {
13408
- return val.map((item) => scrubObjectSecrets(item));
13409
- }
13410
- if (typeof val === "object") {
13411
- if (val instanceof Date || val instanceof RegExp) return val;
13412
- const result4 = {};
13413
- for (const [k, v] of Object.entries(val)) {
13414
- result4[k] = scrubObjectSecrets(v);
13415
- }
13416
- return result4;
13417
- }
13418
- return val;
13419
- }
13420
-
13421
- // packages/agent-runtime/toolOutputSanitizer.ts
13422
- var SANITIZE_REPLACEMENT_CHAR = "\uFFFD";
13423
- var MAX_CONTROL_SEQUENCE_CHARS = 256;
13424
- var ESC = 27;
13425
- var BEL = 7;
13426
- var LINE_FEED = 10;
13427
- var TAB = 9;
13428
- var DEL = 127;
13429
- var C1_DCS = 144;
13430
- var C1_SOS = 152;
13431
- var C1_CSI = 155;
13432
- var C1_ST = 156;
13433
- var C1_OSC = 157;
13434
- var C1_PM = 158;
13435
- var C1_APC = 159;
13436
- var HIGH_SURROGATE_MIN = 55296;
13437
- var HIGH_SURROGATE_MAX = 56319;
13438
- var LOW_SURROGATE_MIN = 56320;
13439
- var LOW_SURROGATE_MAX = 57343;
13440
- var NEEDS_SANITIZE_RE = new RegExp("[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f]|\\p{Cs}", "u");
13441
- function isC1Introducer(code) {
13442
- return code === C1_CSI || code === C1_OSC || code === C1_DCS || code === C1_SOS || code === C1_PM || code === C1_APC;
13443
- }
13444
- var UNTERMINATED_SEQUENCE = -1;
13445
- function skipCsiBody(text2, start, limit) {
13446
- let i = start;
13447
- while (i < limit) {
13448
- const code = text2.charCodeAt(i);
13449
- if (code >= 64 && code <= 126) return i + 1;
13450
- if (code >= 32 && code <= 63) {
13451
- i += 1;
13452
- continue;
13453
- }
13454
- return i;
13455
- }
13456
- return UNTERMINATED_SEQUENCE;
13457
- }
13458
- function skipControlStringBody(text2, start, limit) {
13459
- const length = text2.length;
13460
- let i = start;
13461
- while (i < limit) {
13462
- const code = text2.charCodeAt(i);
13463
- if (code === BEL || code === C1_ST) return i + 1;
13464
- if (code === ESC && i + 1 < length && text2.charCodeAt(i + 1) === 92) {
13465
- return Math.min(i + 2, limit);
13466
- }
13467
- i += 1;
13468
- }
13469
- return UNTERMINATED_SEQUENCE;
13470
- }
13471
- function skipEscapeSequence(text2, escIndex) {
13472
- const length = text2.length;
13473
- const limit = Math.min(length, escIndex + MAX_CONTROL_SEQUENCE_CHARS);
13474
- const leadIndex = escIndex + 1;
13475
- if (leadIndex >= length) return leadIndex;
13476
- const lead = text2.charCodeAt(leadIndex);
13477
- if (lead === 91) {
13478
- const csiEnd = skipCsiBody(text2, leadIndex + 1, limit);
13479
- return csiEnd === UNTERMINATED_SEQUENCE ? escIndex + 1 : csiEnd;
13480
- }
13481
- if (lead === 93 || lead === 80 || lead === 88 || lead === 94 || lead === 95) {
13482
- const stringEnd = skipControlStringBody(text2, leadIndex + 1, limit);
13483
- return stringEnd === UNTERMINATED_SEQUENCE ? escIndex + 1 : stringEnd;
13484
- }
13485
- let j = leadIndex;
13486
- while (j < limit && text2.charCodeAt(j) >= 32 && text2.charCodeAt(j) <= 47) {
13487
- j += 1;
13488
- }
13489
- if (j < limit) {
13490
- const final = text2.charCodeAt(j);
13491
- if (final >= 48 && final <= 126) return j + 1;
13492
- }
13493
- return escIndex + 1;
13494
- }
13495
- function skipC1Sequence(text2, index) {
13496
- const limit = Math.min(text2.length, index + MAX_CONTROL_SEQUENCE_CHARS);
13497
- const code = text2.charCodeAt(index);
13498
- const bodyEnd = code === C1_CSI ? skipCsiBody(text2, index + 1, limit) : skipControlStringBody(text2, index + 1, limit);
13499
- return bodyEnd === UNTERMINATED_SEQUENCE ? index + 1 : bodyEnd;
13500
- }
13501
- function sanitizeToolOutputText(text2) {
13502
- if (typeof text2 !== "string" || text2.length === 0) return text2;
13503
- if (!NEEDS_SANITIZE_RE.test(text2)) return text2;
13504
- const out = [];
13505
- const length = text2.length;
13506
- let plainStart = 0;
13507
- let i = 0;
13508
- const dropRange = (end3) => {
13509
- if (plainStart < i) out.push(text2.slice(plainStart, i));
13510
- i = end3;
13511
- plainStart = end3;
13512
- };
13513
- while (i < length) {
13514
- const code = text2.charCodeAt(i);
13515
- if (code === LINE_FEED || code === TAB) {
13516
- i += 1;
13517
- continue;
13518
- }
13519
- if (code === ESC) {
13520
- dropRange(skipEscapeSequence(text2, i));
13521
- continue;
13522
- }
13523
- if (isC1Introducer(code)) {
13524
- dropRange(skipC1Sequence(text2, i));
13525
- continue;
13526
- }
13527
- if (code < 32 || code === DEL || code >= 128 && code <= 159) {
13528
- dropRange(i + 1);
13529
- continue;
13530
- }
13531
- if (code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX) {
13532
- const low = text2.charCodeAt(i + 1);
13533
- if (low >= LOW_SURROGATE_MIN && low <= LOW_SURROGATE_MAX) {
13534
- i += 2;
13535
- continue;
13536
- }
13537
- if (plainStart < i) out.push(text2.slice(plainStart, i));
13538
- out.push(SANITIZE_REPLACEMENT_CHAR);
13539
- i += 1;
13540
- plainStart = i;
13541
- continue;
13542
- }
13543
- if (code >= LOW_SURROGATE_MIN && code <= LOW_SURROGATE_MAX) {
13544
- if (plainStart < i) out.push(text2.slice(plainStart, i));
13545
- out.push(SANITIZE_REPLACEMENT_CHAR);
13546
- i += 1;
13547
- plainStart = i;
13548
- continue;
13549
- }
13550
- i += 1;
13551
- }
13552
- if (plainStart < length) out.push(text2.slice(plainStart));
13553
- return out.join("");
13554
- }
13555
- function sanitizeToolOutputContent(content) {
13556
- return typeof content === "string" ? sanitizeToolOutputText(content) : content;
13557
- }
13558
-
13559
13353
  // packages/agent-runtime/providerMessageProjection.ts
13560
13354
  var TOOL_DURATION_METADATA_KEY = "toolExecMs";
13561
13355
  var OBSERVATION_ONLY_METADATA_KEYS = /* @__PURE__ */ new Set([
@@ -13702,6 +13496,7 @@ function projectToolContentForProvider(args2) {
13702
13496
  const content = typeof rawContent === "string" ? sanitizeToolOutputText(rawContent) : rawContent;
13703
13497
  if (typeof content !== "string") return content;
13704
13498
  if (isSpilledToolOutput(content)) return content;
13499
+ if (isCompleteInstructionOutput(args2.toolName, args2.metadata, content)) return content;
13705
13500
  const metadataText = compactToolMetadata(args2.metadata);
13706
13501
  const embeddedMetadataIndex = metadataText ? content.indexOf("\n\n[tool metadata]\n") : -1;
13707
13502
  const contentForProjection = embeddedMetadataIndex >= 0 ? content.slice(0, embeddedMetadataIndex) : content;
@@ -13900,7 +13695,8 @@ ${args2.input}` : [
13900
13695
  const prefix2 = stableContent ? [{
13901
13696
  role: "system",
13902
13697
  content: stableContent,
13903
- stable_prefix_chars: stableContent.length
13698
+ stable_prefix_chars: stableContent.length,
13699
+ ...args2.prompt?.trim() ? { [AGENT_PROMPT_IN_MESSAGES]: true } : {}
13904
13700
  }] : [];
13905
13701
  const composed2 = composeProviderMessages({
13906
13702
  prefix: prefix2,
@@ -13923,7 +13719,11 @@ ${args2.input}` : [
13923
13719
  }
13924
13720
  const blocks = (args2.contextBlocks ?? []).map((block) => block.trim()).filter(Boolean);
13925
13721
  const systemContent = [args2.prompt?.trim(), ...blocks].filter(Boolean).join("\n\n");
13926
- const prefix = systemContent ? [{ role: "system", content: systemContent }] : [];
13722
+ const prefix = systemContent ? [{
13723
+ role: "system",
13724
+ content: systemContent,
13725
+ ...args2.prompt?.trim() ? { [AGENT_PROMPT_IN_MESSAGES]: true } : {}
13726
+ }] : [];
13927
13727
  const composed = composeProviderMessages({
13928
13728
  prefix,
13929
13729
  history: args2.history,
@@ -15033,12 +14833,255 @@ async function invokeCapability(capabilityOrName, input, ctx = {}) {
15033
14833
  }
15034
14834
 
15035
14835
  // packages/agent-runtime/localWorkspaceTools.ts
15036
- import { existsSync as existsSync2 } from "node:fs";
14836
+ import { existsSync as existsSync3 } from "node:fs";
15037
14837
  import { createHash as createHash3 } from "node:crypto";
15038
14838
 
14839
+ // packages/agent-runtime/agentsMd.ts
14840
+ import { existsSync, readFileSync } from "node:fs";
14841
+ import { resolve } from "node:path";
14842
+ var AGENTS_MD_MAX_BYTES = 8192;
14843
+ var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
14844
+ var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
14845
+ function truncateAgentsMdContent(content, maxBytes = AGENTS_MD_MAX_BYTES) {
14846
+ const buf = Buffer.from(content, "utf8");
14847
+ if (buf.byteLength <= maxBytes) {
14848
+ return content;
14849
+ }
14850
+ let boundary = Math.min(maxBytes, buf.byteLength);
14851
+ while (boundary > 0 && boundary < buf.byteLength && (buf[boundary] & 192) === 128) {
14852
+ boundary--;
14853
+ }
14854
+ const boundarySlice = buf.subarray(0, boundary).toString("utf8");
14855
+ const slice = buf.subarray(0, maxBytes);
14856
+ const lastNewline = slice.lastIndexOf(10);
14857
+ if (lastNewline > 0) {
14858
+ const lineCandidate = slice.subarray(0, lastNewline).toString("utf8");
14859
+ const lineBytes = Buffer.byteLength(lineCandidate, "utf8");
14860
+ const boundaryBytes = Buffer.byteLength(boundarySlice, "utf8");
14861
+ if (lineCandidate.trim().length > 0 && lineBytes * 2 >= boundaryBytes) {
14862
+ return lineCandidate.replace(/\r$/, "");
14863
+ }
14864
+ }
14865
+ return boundarySlice.replace(/\r$/, "");
14866
+ }
14867
+ var AGENTS_MD_SUMMARY_MAX_BYTES = 3072;
14868
+ var AGENTS_MD_SUMMARY_ITEM_MAX_CHARS = 120;
14869
+ var AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS = [
14870
+ "review",
14871
+ "\u8BC4\u5BA1",
14872
+ "commit",
14873
+ "\u63D0\u4EA4",
14874
+ "worktree",
14875
+ "\u6D4B\u8BD5",
14876
+ "typecheck",
14877
+ "\u7C7B\u578B\u68C0\u67E5",
14878
+ "push",
14879
+ "\u53D1\u5E03",
14880
+ "\u6587\u6863\u843D\u4F4D",
14881
+ "\u5220\u9664",
14882
+ "\u6D3E\u53D1"
14883
+ ];
14884
+ var AGENTS_MD_SUMMARY_POINTER_INSTRUCTION = "\u7528 readFile \u8BFB\u5168\u6587\uFF1A%REL%\uFF08cwd\uFF09/ %PATH%\n\u4EC5\u7D22\u5F15\uFF1A\u63D0\u4EA4/\u8BC4\u5BA1\u95E8\u7981\u3001worktree \u9694\u79BB\u3001\u6D4B\u8BD5/typecheck\u3001\u6587\u6863\u843D\u4F4D\u3001\u5220\u9664\u3001push/\u53D1\u5E03\u524D\uFF0C**\u5FC5\u987B\u5148 readFile \u8BFB\u5168\u6587\u518D\u6267\u884C**\u3002\n\u8DEF\u5F84\uFF1A%REL% \u76F8\u5BF9 cwd\uFF1Bmachine:<id>/\u6C99\u76D2\u6267\u884C\u9762 cwd \u7531\u5176\u51B3\u5B9A\uFF0C\u8BFB\u4E0D\u5230\u8BA9\u5BBF\u4E3B\u6CE8\u5165\u6216\u7528\u7EDD\u5BF9\u8DEF\u5F84\u3002";
14885
+ var AGENTS_MD_SUMMARY_DELETE_REFERENCE = "- \u5220\u9664/\u4E0D\u53EF\u9006\u64CD\u4F5C\uFF1A\u9075\u5B88\u7CFB\u7EDF\u63D0\u793A\u7684\u5220\u9664\u7EA2\u7EBF\uFF08\u5148\u5448\u73B0\u5B8C\u6574\u5F85\u5220\u6E05\u5355\u5E76\u83B7\u7528\u6237\u660E\u786E\u786E\u8BA4\uFF0C\u7981\u6B62\u5148\u5220\u540E\u62A5\u3001\u7981\u6B62\u6A21\u7CCA\u5B9A\u4F4D\uFF09\uFF0C\u4ED3\u5E93\u82E5\u6709\u9644\u52A0\u5220\u9664\u89C4\u5219\u89C1\u5B8C\u6574\u6587\u4EF6\u3002";
14886
+ var clipToChars = (text2, maxChars) => text2.length <= maxChars ? text2 : `${text2.slice(0, maxChars).trimEnd()}\u2026`;
14887
+ var parseAgentsMdItem = (body) => {
14888
+ const bold = /^\*\*(.+?)\*\*/.exec(body);
14889
+ if (bold) {
14890
+ return {
14891
+ label: bold[1].trim().replace(/[::]$/, ""),
14892
+ rest: body.slice(bold[0].length).replace(/^[::\s]+/, "")
14893
+ };
14894
+ }
14895
+ const firstClause = body.split(/[::]/)[0];
14896
+ return {
14897
+ label: clipToChars(firstClause.trim(), 40),
14898
+ rest: body.slice(firstClause.length).replace(/^[::\s]+/, "")
14899
+ };
14900
+ };
14901
+ var AGENTS_MD_COMMAND_TOKEN_PREFIX = /^(bunx?|npx|node|npm|pnpm|yarn|git|gh|tsc|deno)\b\s/;
14902
+ var extractAgentsMdCommandTokens = (body) => {
14903
+ const tokens = [];
14904
+ const seen = /* @__PURE__ */ new Set();
14905
+ for (const match7 of body.matchAll(/`([^`\n]+)`/g)) {
14906
+ const raw = match7[1];
14907
+ if (!AGENTS_MD_COMMAND_TOKEN_PREFIX.test(raw)) continue;
14908
+ if (seen.has(raw)) continue;
14909
+ seen.add(raw);
14910
+ tokens.push(raw);
14911
+ }
14912
+ return tokens;
14913
+ };
14914
+ var buildAgentsMdItemGist = (firstSentence, bulletBody) => {
14915
+ const max4 = AGENTS_MD_SUMMARY_ITEM_MAX_CHARS;
14916
+ const clipped = clipToChars(firstSentence, max4);
14917
+ const missing = extractAgentsMdCommandTokens(bulletBody).filter(
14918
+ (token) => !clipped.includes(token)
14919
+ );
14920
+ if (missing.length === 0) return clipped;
14921
+ let tail = "";
14922
+ for (const token of missing) {
14923
+ const candidate = tail ? `${tail} \`${token}\`` : `\`${token}\``;
14924
+ if (candidate.length > max4) continue;
14925
+ tail = candidate;
14926
+ }
14927
+ if (!tail) return clipped;
14928
+ const room = max4 - tail.length - 2;
14929
+ const head3 = room > 0 ? clipToChars(firstSentence, room) : "";
14930
+ return head3 ? `${head3} ${tail}` : tail;
14931
+ };
14932
+ var priorityOf = (label) => {
14933
+ const lowered = label.toLowerCase();
14934
+ for (let i = 0; i < AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS.length; i += 1) {
14935
+ if (lowered.includes(AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS[i].toLowerCase())) {
14936
+ return i;
14937
+ }
14938
+ }
14939
+ return -1;
14940
+ };
14941
+ var collectAgentsMdSummaryItems = (content) => {
14942
+ const items = [];
14943
+ const seen = /* @__PURE__ */ new Set();
14944
+ let section = null;
14945
+ for (const rawLine of content.split(/\r?\n/)) {
14946
+ const line = rawLine.trim();
14947
+ if (!line) continue;
14948
+ const heading = /^#{2,3}\s+(.+)$/.exec(line);
14949
+ if (heading) {
14950
+ section = heading[1].trim();
14951
+ continue;
14952
+ }
14953
+ if (line.startsWith("#") || line.startsWith("<") || line.startsWith("<!--")) {
14954
+ continue;
14955
+ }
14956
+ const bullet = /^[-*]\s+(.+)$/.exec(line);
14957
+ if (!bullet) continue;
14958
+ const { label, rest } = parseAgentsMdItem(bullet[1]);
14959
+ if (!label || seen.has(label)) continue;
14960
+ seen.add(label);
14961
+ const firstSentence = rest.split("\u3002")[0].trim();
14962
+ items.push({
14963
+ section,
14964
+ label,
14965
+ gist: buildAgentsMdItemGist(firstSentence, bullet[1]),
14966
+ priority: priorityOf(label)
14967
+ });
14968
+ }
14969
+ return items;
14970
+ };
14971
+ function buildAgentsMdSummaryBody(content, filePath, options = {}) {
14972
+ const budgetBytes = options.budgetBytes ?? AGENTS_MD_SUMMARY_MAX_BYTES;
14973
+ const items = collectAgentsMdSummaryItems(content);
14974
+ if (items.length === 0) return null;
14975
+ const relativePath = options.fileName ?? "AGENTS.md";
14976
+ const pointer = AGENTS_MD_SUMMARY_POINTER_INSTRUCTION.replaceAll(
14977
+ "%REL%",
14978
+ relativePath
14979
+ ).replaceAll("%PATH%", filePath);
14980
+ const head3 = `${pointer}
14981
+ ${AGENTS_MD_SUMMARY_DELETE_REFERENCE}
14982
+ `;
14983
+ if (Buffer.byteLength(head3, "utf8") > budgetBytes) return null;
14984
+ const candidates = [
14985
+ ...items.filter((item) => item.priority >= 0).sort((a, b) => a.priority - b.priority),
14986
+ ...items.filter((item) => item.priority < 0)
14987
+ ];
14988
+ const noteBlock = `
14989
+ \u2026\uFF08\u7D22\u5F15\u5DF2\u622A\u65AD\uFF0C\u5176\u4F59\u951A\u70B9\u89C1\u5B8C\u6574\u6587\u4EF6\uFF09`;
14990
+ const noteBytes = Buffer.byteLength(noteBlock, "utf8");
14991
+ let used = Buffer.byteLength(head3, "utf8");
14992
+ const admitted = [];
14993
+ const seenSections = /* @__PURE__ */ new Set();
14994
+ let truncated = false;
14995
+ for (const item of candidates) {
14996
+ const line = item.gist ? `- ${item.label}\uFF1A${item.gist}` : `- ${item.label}`;
14997
+ const headingCost = item.section && !seenSections.has(item.section) ? Buffer.byteLength(`
14998
+ ## ${item.section}`, "utf8") : 0;
14999
+ const cost = headingCost + Buffer.byteLength(`
15000
+ ${line}`, "utf8");
15001
+ if (used + cost + noteBytes > budgetBytes) {
15002
+ truncated = true;
15003
+ continue;
15004
+ }
15005
+ used += cost;
15006
+ if (item.section) seenSections.add(item.section);
15007
+ admitted.push(item);
15008
+ }
15009
+ const groupOrder = [];
15010
+ for (const item of admitted) {
15011
+ if (!groupOrder.includes(item.section)) groupOrder.push(item.section);
15012
+ }
15013
+ const frozen = [];
15014
+ for (const section of groupOrder) {
15015
+ for (const item of admitted) {
15016
+ if (item.section !== section) continue;
15017
+ frozen.push({
15018
+ section,
15019
+ line: item.gist ? `- ${item.label}\uFF1A${item.gist}` : `- ${item.label}`
15020
+ });
15021
+ }
15022
+ }
15023
+ if (admitted.length === 0) return null;
15024
+ return `${head3}${renderSummarySections(frozen)}${truncated ? noteBlock : ""}`;
15025
+ }
15026
+ var renderSummarySections = (entries) => {
15027
+ let rendered = "";
15028
+ let currentSection = null;
15029
+ for (const entry of entries) {
15030
+ if (entry.section && entry.section !== currentSection) {
15031
+ rendered += `
15032
+ ## ${entry.section}`;
15033
+ currentSection = entry.section;
15034
+ }
15035
+ rendered += `
15036
+ ${entry.line}`;
15037
+ }
15038
+ return rendered;
15039
+ };
15040
+ function readAgentsMdLayerFromDisk(cwd) {
15041
+ for (const name of AGENTS_MD_CANDIDATES) {
15042
+ const filePath = resolve(cwd, name);
15043
+ if (!existsSync(filePath)) continue;
15044
+ try {
15045
+ const raw = readFileSync(filePath, "utf8");
15046
+ const content = raw.trim();
15047
+ if (!content) continue;
15048
+ const totalBytes = Buffer.byteLength(raw, "utf8");
15049
+ const trimmedBytes = Buffer.byteLength(content, "utf8");
15050
+ const headerBytes = Buffer.byteLength(buildAgentsMdLayerHeader(name), "utf8");
15051
+ if (headerBytes + trimmedBytes <= AGENTS_MD_MAX_BYTES) {
15052
+ return buildAgentsMdLayer(content, name);
15053
+ }
15054
+ const summaryBody = buildAgentsMdSummaryBody(content, filePath, {
15055
+ // 正文预算 = 摘要上限 − 块头部:buildAgentsMdLayer 会再拼一次头部,
15056
+ // 因此「头部 + 正文」才等于最终注入字节,不得超过摘要上限。
15057
+ budgetBytes: AGENTS_MD_SUMMARY_MAX_BYTES - headerBytes,
15058
+ fileName: name
15059
+ });
15060
+ if (summaryBody) return buildAgentsMdLayer(summaryBody, name);
15061
+ const buildMarker = (omitted2, withPath) => {
15062
+ const pathPart = withPath ? `\u5B8C\u6574\u6587\u4EF6\uFF1A${filePath}` : `\u5B8C\u6574\u6587\u4EF6\uFF1A\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u7684 ${name}`;
15063
+ return `<!-- AGENTS.md truncated: \u539F\u6587\u4EF6 ${totalBytes} \u5B57\u8282\uFF0C\u6CE8\u5165\u9884\u7B97 ${AGENTS_MD_MAX_BYTES} \u5B57\u8282\uFF0C\u5DF2\u7701\u7565 ${omitted2} \u5B57\u8282\uFF08\u4E0A\u6587\u53EF\u80FD\u7F3A\u5C11\u6587\u4EF6\u672B\u5C3E\u7684 commit/review \u95E8\u7981\u7EC6\u5219\uFF0C\u63D0\u4EA4/\u8BC4\u5BA1\u524D\u8BF7\u8BFB\u5B8C\u6574\u6587\u4EF6\uFF09\u3002${pathPart} -->`;
15064
+ };
15065
+ const bodyBudget = AGENTS_MD_MAX_BYTES - AGENTS_MD_MARKER_RESERVE_BYTES - 2 - headerBytes;
15066
+ const body = truncateAgentsMdContent(content, bodyBudget);
15067
+ const bodyBytes = Buffer.byteLength(body, "utf8");
15068
+ const omitted = Math.max(0, totalBytes - bodyBytes);
15069
+ let marker = buildMarker(omitted, true);
15070
+ if (Buffer.byteLength(marker, "utf8") > AGENTS_MD_MARKER_RESERVE_BYTES) {
15071
+ marker = buildMarker(omitted, false);
15072
+ }
15073
+ return buildAgentsMdLayer(`${body}
15074
+
15075
+ ${marker}`, name);
15076
+ } catch {
15077
+ }
15078
+ }
15079
+ return null;
15080
+ }
15081
+
15039
15082
  // packages/agent-runtime/visualRenderer.node.ts
15040
15083
  import { createRequire } from "node:module";
15041
- import { existsSync } from "node:fs";
15084
+ import { existsSync as existsSync2 } from "node:fs";
15042
15085
  import { realpath, stat, readFile } from "node:fs/promises";
15043
15086
  import { isAbsolute, relative, win32 } from "node:path";
15044
15087
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -15091,7 +15134,7 @@ var VisualRenderSemaphore = class {
15091
15134
  active = 0;
15092
15135
  queue = [];
15093
15136
  async run(task) {
15094
- if (this.active >= this.limit) await new Promise((resolve6) => this.queue.push(resolve6));
15137
+ if (this.active >= this.limit) await new Promise((resolve7) => this.queue.push(resolve7));
15095
15138
  else this.active++;
15096
15139
  try {
15097
15140
  return await task();
@@ -15109,7 +15152,7 @@ function visualRendererCapability() {
15109
15152
  if (process.env.NOLO_VISUAL_RENDERER_DISABLED === "1") return { available: false, reasonCode: "disabled", reason: "Platform renderer disabled by NOLO_VISUAL_RENDERER_DISABLED=1 on this runtime host." };
15110
15153
  try {
15111
15154
  const { chromium } = require2("playwright");
15112
- const executablePath = [chromium.executablePath(), resolveExecutableOnPath("google-chrome"), resolveExecutableOnPath("chromium"), resolveExecutableOnPath("chromium-browser")].find((path) => !!path && existsSync(path));
15155
+ const executablePath = [chromium.executablePath(), resolveExecutableOnPath("google-chrome"), resolveExecutableOnPath("chromium"), resolveExecutableOnPath("chromium-browser")].find((path) => !!path && existsSync2(path));
15113
15156
  if (!executablePath) return { available: false, reasonCode: "missing-browser", reason: "No Chromium renderer installed. Install Playwright Chromium (playwright install chromium) or system Chromium/Google Chrome on the runtime host." };
15114
15157
  return { available: true, chromium, executablePath };
15115
15158
  } catch {
@@ -15285,7 +15328,7 @@ finally:
15285
15328
  pass
15286
15329
  bus.signal_unsubscribe(subscription)
15287
15330
  `;
15288
- var capturePortalScreenshot = (signal) => new Promise((resolve6, reject) => {
15331
+ var capturePortalScreenshot = (signal) => new Promise((resolve7, reject) => {
15289
15332
  const child = spawn("/usr/bin/python3", ["-c", PORTAL_SCRIPT], { stdio: ["ignore", "pipe", "pipe"] });
15290
15333
  let stdout = "";
15291
15334
  let stderr = "";
@@ -15306,7 +15349,7 @@ var capturePortalScreenshot = (signal) => new Promise((resolve6, reject) => {
15306
15349
  if (signal.aborted) return reject(new Error("portal capture timeout"));
15307
15350
  if (code !== 0) return reject(new Error(stderr.trim() || `portal helper exited ${code}`));
15308
15351
  try {
15309
- resolve6(JSON.parse(stdout));
15352
+ resolve7(JSON.parse(stdout));
15310
15353
  } catch {
15311
15354
  reject(new Error("invalid portal response"));
15312
15355
  }
@@ -15318,7 +15361,7 @@ function createHostWindowCapture(options = {}) {
15318
15361
  let active = 0;
15319
15362
  const waiters = [];
15320
15363
  function acquire(signal) {
15321
- return new Promise((resolve6, reject) => {
15364
+ return new Promise((resolve7, reject) => {
15322
15365
  const abort = () => {
15323
15366
  const index = waiters.indexOf(start);
15324
15367
  if (index >= 0) waiters.splice(index, 1);
@@ -15327,7 +15370,7 @@ function createHostWindowCapture(options = {}) {
15327
15370
  const start = () => {
15328
15371
  signal.removeEventListener("abort", abort);
15329
15372
  active++;
15330
- resolve6();
15373
+ resolve7();
15331
15374
  };
15332
15375
  if (signal.aborted) return abort();
15333
15376
  if (active < concurrency) start();
@@ -15385,7 +15428,7 @@ var captureHostWindow = createHostWindowCapture();
15385
15428
  // packages/agent-runtime/localWorkspaceTools.ts
15386
15429
  import { lstat as lstat2, readdir as readdir2, readFile as readFile4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
15387
15430
  import { homedir } from "node:os";
15388
- import { dirname as dirname2, relative as relative4, resolve as resolve4, sep as sep2 } from "node:path";
15431
+ import { dirname as dirname2, relative as relative4, resolve as resolve5, sep as sep2 } from "node:path";
15389
15432
  import { spawn as spawnChildProcess2 } from "node:child_process";
15390
15433
 
15391
15434
  // packages/agent-runtime/runResultReadProjection.ts
@@ -15468,12 +15511,12 @@ function isLineRangeCovered(request3, covered) {
15468
15511
 
15469
15512
  // packages/agent-runtime/fileTextSearch.ts
15470
15513
  import { readdir, readFile as readFile3, stat as stat3 } from "node:fs/promises";
15471
- import { basename as basename2, relative as relative2, resolve as resolve2 } from "node:path";
15514
+ import { basename as basename2, relative as relative2, resolve as resolve3 } from "node:path";
15472
15515
  import { spawn as spawnChildProcess } from "node:child_process";
15473
15516
 
15474
15517
  // packages/agent-runtime/gitignore.ts
15475
15518
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
15476
- import { resolve } from "node:path";
15519
+ import { resolve as resolve2 } from "node:path";
15477
15520
  function isIgnorableFsError(err) {
15478
15521
  if (err && typeof err === "object" && "code" in err) {
15479
15522
  const code = err.code;
@@ -15484,7 +15527,7 @@ function isIgnorableFsError(err) {
15484
15527
  async function readRootGitignorePatterns(workspaceRoot) {
15485
15528
  let content;
15486
15529
  try {
15487
- content = await readFile2(resolve(workspaceRoot, ".gitignore"), "utf8");
15530
+ content = await readFile2(resolve2(workspaceRoot, ".gitignore"), "utf8");
15488
15531
  } catch (err) {
15489
15532
  if (isIgnorableFsError(err)) return [];
15490
15533
  throw err;
@@ -15498,7 +15541,7 @@ async function readRootGitignorePatterns(workspaceRoot) {
15498
15541
  }
15499
15542
  async function hasRootGitignore(workspaceRoot) {
15500
15543
  try {
15501
- await stat2(resolve(workspaceRoot, ".gitignore"));
15544
+ await stat2(resolve2(workspaceRoot, ".gitignore"));
15502
15545
  return true;
15503
15546
  } catch (err) {
15504
15547
  if (isIgnorableFsError(err)) return false;
@@ -15569,7 +15612,7 @@ function parseMatches(root, output) {
15569
15612
  const records = [];
15570
15613
  const pattern = /(?:^|\n)([^\0\n]+)\0(\d+):(.*?)(?=\n[^\0\n]+\0|$)/gs;
15571
15614
  for (const match7 of output.matchAll(pattern)) {
15572
- records.push({ file: resolve2(root, match7[1] ?? ""), line: Number(match7[2]), text: (match7[3] ?? "").replace(/\n$/, "") });
15615
+ records.push({ file: resolve3(root, match7[1] ?? ""), line: Number(match7[2]), text: (match7[3] ?? "").replace(/\n$/, "") });
15573
15616
  }
15574
15617
  return records;
15575
15618
  }
@@ -15627,7 +15670,7 @@ async function jsSearch(o, targetPath) {
15627
15670
  } else {
15628
15671
  const walk = async (dir) => {
15629
15672
  for (const e of await readdir(dir, { withFileTypes: true })) {
15630
- const f = resolve2(dir, e.name), rel = pathFor(o.root, f);
15673
+ const f = resolve3(dir, e.name), rel = pathFor(o.root, f);
15631
15674
  if (e.isDirectory()) {
15632
15675
  if (!excludes.some((p) => globMatch(p, rel))) await walk(f);
15633
15676
  } else if (e.isFile() && !excludes.some((p) => globMatch(p, rel)) && !isIgnored(rel) && (!o.include || globMatch(o.include, rel))) {
@@ -15676,7 +15719,7 @@ var COMMAND_ENGINES = [
15676
15719
  { engine: "grep", binaryOption: "resolveGrepBinary", binaryName: "grep", argsKey: "grep" }
15677
15720
  ];
15678
15721
  async function searchFileTextMatches(o) {
15679
- const targetPath = resolve2(o.root, o.target || ".");
15722
+ const targetPath = resolve3(o.root, o.target || ".");
15680
15723
  const targetStat = await stat3(targetPath).catch(() => null);
15681
15724
  if (!targetStat) return { matches: [], totalMatches: 0, truncated: false, engine: "js" };
15682
15725
  if (targetStat.isFile()) return jsSearch(o, targetPath);
@@ -15745,7 +15788,7 @@ function resolveCleanupReport(evidence, previousStatus) {
15745
15788
  }
15746
15789
  var TERMINAL_EVENT_TYPES = /* @__PURE__ */ new Set(["exited", "killed"]);
15747
15790
  function defaultSleep(ms) {
15748
- return new Promise((resolve6) => setTimeout(resolve6, ms));
15791
+ return new Promise((resolve7) => setTimeout(resolve7, ms));
15749
15792
  }
15750
15793
  function defaultSignalSender(pid, signal) {
15751
15794
  process.kill(pid, signal);
@@ -16020,13 +16063,13 @@ function buildWorkspacePathProperty() {
16020
16063
  };
16021
16064
  }
16022
16065
  function buildReadWorkspaceDescription() {
16023
- return "Read a UTF-8 text file inside the workspace. Absolute paths and ~/ are also accepted (runtime spill files can be read directly). Use lines for focused range reads after search to save tokens. A range already delivered earlier for an unchanged file answers with a short notice instead of resending (force:true refetches).";
16066
+ return "Read a UTF-8 text file inside the workspace. For multiple files, call readFile concurrently in the same turn. Absolute paths and ~/ are also accepted (runtime spill files can be read directly). Use lines for focused range reads after search to save tokens. A range already delivered earlier for an unchanged file answers with a short notice instead of resending (force:true refetches).";
16024
16067
  }
16025
16068
  function buildReadWorkspaceParameters() {
16026
16069
  const path = buildWorkspacePathProperty();
16027
16070
  const lines = {
16028
16071
  type: "string",
16029
- description: 'Line slice: "40-120" (range, 1-based, inclusive), "120-" (from line to end), "-50" (tail N lines), "50" (head N lines). Omit to read full file.'
16072
+ description: 'Line slice: "40-120" (range, 1-based, inclusive), "120-" (from line to end), "-50" (tail N lines), "50" (head N lines). Omit to read from the start; large results return a bounded window. Continue from metadata endLine + 1.'
16030
16073
  };
16031
16074
  const force = {
16032
16075
  type: "boolean",
@@ -16366,9 +16409,9 @@ function filterDeclaredWorkspaceToolNames(args2) {
16366
16409
  // packages/agent-runtime/workspacePathGuard.ts
16367
16410
  import { constants as fsConstants } from "node:fs";
16368
16411
  import { lstat, mkdir, open, readlink, realpath as realpath2 } from "node:fs/promises";
16369
- import { basename as basename3, dirname, isAbsolute as isAbsolute2, join as join2, relative as relative3, resolve as resolve3, sep } from "node:path";
16412
+ import { basename as basename3, dirname, isAbsolute as isAbsolute2, join as join2, relative as relative3, resolve as resolve4, sep } from "node:path";
16370
16413
  function isPathInsideRoot(root, targetPath) {
16371
- const rel = relative3(resolve3(root), resolve3(targetPath));
16414
+ const rel = relative3(resolve4(root), resolve4(targetPath));
16372
16415
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute2(rel);
16373
16416
  }
16374
16417
  function isNotFoundError(error) {
@@ -16377,7 +16420,7 @@ function isNotFoundError(error) {
16377
16420
  }
16378
16421
  async function realpathAllowMissing(targetPath) {
16379
16422
  const tail = [];
16380
- let current = resolve3(targetPath);
16423
+ let current = resolve4(targetPath);
16381
16424
  for (; ; ) {
16382
16425
  try {
16383
16426
  const real = await realpath2(current);
@@ -16396,8 +16439,8 @@ async function realpathAllowMissing(targetPath) {
16396
16439
  }
16397
16440
  async function resolveWorkspaceSafePath(args2) {
16398
16441
  const requested = args2.requestedPath ?? args2.targetPath;
16399
- const lexicalRoot = resolve3(args2.workspaceRoot);
16400
- const targetPath = resolve3(args2.targetPath);
16442
+ const lexicalRoot = resolve4(args2.workspaceRoot);
16443
+ const targetPath = resolve4(args2.targetPath);
16401
16444
  const lexicalInside = args2.lexicalInside ?? isPathInsideRoot(lexicalRoot, targetPath);
16402
16445
  const [physicalRoot, resolved] = await Promise.all([
16403
16446
  realpath2(lexicalRoot).catch(() => null),
@@ -16553,7 +16596,7 @@ async function openPinnedDirectory(dirPath, guard) {
16553
16596
  }
16554
16597
  async function createMissingDirectoryChain(guard) {
16555
16598
  const missing = [];
16556
- let existing = resolve3(guard.path);
16599
+ let existing = resolve4(guard.path);
16557
16600
  for (; ; ) {
16558
16601
  try {
16559
16602
  await lstat(existing);
@@ -16815,7 +16858,6 @@ function readExpectedReplacementCount(args2) {
16815
16858
  }
16816
16859
  return value;
16817
16860
  }
16818
- var READ_FILE_SLICE_FALLBACK_LINES = 200;
16819
16861
  function isAbsentArg(value) {
16820
16862
  return value === void 0 || value === null;
16821
16863
  }
@@ -16887,17 +16929,9 @@ function parseLinesArg(value) {
16887
16929
  return { slice: { startLine, endLine } };
16888
16930
  }
16889
16931
  function readFileSliceArgs(args2) {
16890
- const warnings = [];
16891
- const withFallback = (slice2, invalidLines) => {
16892
- warnings.push(
16893
- `No usable line range remained; returned the first ${READ_FILE_SLICE_FALLBACK_LINES} lines instead of the whole file.`
16894
- );
16895
- return { ...slice2, maxLines: READ_FILE_SLICE_FALLBACK_LINES, warnings, invalidLines };
16896
- };
16897
- if (isAbsentArg(args2.lines)) return { warnings, invalidLines: void 0 };
16932
+ if (isAbsentArg(args2.lines) || args2.lines === "") return {};
16898
16933
  const { slice, warning } = parseLinesArg(args2.lines);
16899
- if (warning) warnings.push(warning);
16900
- return slice ? { ...slice, warnings, invalidLines: void 0 } : withFallback({}, describeRejectedArgValue(args2.lines));
16934
+ return slice ? { slice } : { error: clipMarkerValue(warning ?? "Invalid line range", 240) };
16901
16935
  }
16902
16936
  function buildReadFileSliceHint(totalLines) {
16903
16937
  return `File has ${totalLines} lines. Use lines: ${LINES_ARG_SYNTAX}, or omit it for the whole file.`;
@@ -17040,7 +17074,7 @@ function resolveRipgrepBinary(env = process.env) {
17040
17074
  const fromEnv = asOptionalTrimmedString(env.NOLO_BUNDLED_RG);
17041
17075
  if (fromEnv) {
17042
17076
  try {
17043
- if (existsSync2(fromEnv)) return fromEnv;
17077
+ if (existsSync3(fromEnv)) return fromEnv;
17044
17078
  } catch {
17045
17079
  }
17046
17080
  }
@@ -17061,14 +17095,14 @@ async function resolveRuntimeOwnedSpillPath(targetPath) {
17061
17095
  }
17062
17096
  function expandHomePath(requestedPath) {
17063
17097
  if (requestedPath === "~") return homedir();
17064
- if (requestedPath.startsWith("~/")) return resolve4(homedir(), requestedPath.slice(2));
17098
+ if (requestedPath.startsWith("~/")) return resolve5(homedir(), requestedPath.slice(2));
17065
17099
  return requestedPath;
17066
17100
  }
17067
17101
  function resolveRequestedWorkspacePath(workspaceRoot, requestedPath) {
17068
- return resolve4(resolve4(workspaceRoot), expandHomePath(requestedPath));
17102
+ return resolve5(resolve5(workspaceRoot), expandHomePath(requestedPath));
17069
17103
  }
17070
17104
  async function resolveLocalWorkspaceToolApproval(args2) {
17071
- const workspaceRoot = resolve4(args2.workspaceRoot);
17105
+ const workspaceRoot = resolve5(args2.workspaceRoot);
17072
17106
  const targetPath = resolveRequestedWorkspacePath(workspaceRoot, args2.requestedPath);
17073
17107
  const insideWorkspace = isPathInsideWorkspace({ workspaceRoot, targetPath });
17074
17108
  const guard = await resolveWorkspaceSafePath({
@@ -17165,8 +17199,63 @@ var READ_FILE_LEDGER_MAX_RECORDS = 64;
17165
17199
  var READ_FILE_LEDGER_MAX_KEYS = 256;
17166
17200
  async function readFileTool(args2) {
17167
17201
  const parsed = parseWorkspaceToolArguments(args2.call.arguments);
17202
+ if (parsed.files !== void 0 && !args2.batchItem) {
17203
+ if (!Array.isArray(parsed.files) || parsed.files.length < 1 || parsed.files.length > 8 || pickFirstAlias(parsed, PATH_FIELD_ALIASES) !== void 0) {
17204
+ return { content: "[readFile] Supply either path or files (1\u20138 items), not both.", metadata: { status: "invalid-arguments" } };
17205
+ }
17206
+ if (parsed.files.some((file) => !file || typeof file !== "object" || typeof file.path !== "string" || !file.path || file.path.length > 512 || file.lines !== void 0 && typeof file.lines !== "string")) {
17207
+ return { content: "[readFile] Each batch item requires a path (maximum 512 characters) and optional string lines.", metadata: { status: "invalid-arguments" } };
17208
+ }
17209
+ const items = parsed.files.map((item) => ({ path: item.path, status: "not-delivered" }));
17210
+ const budget = resolveHistoricalToolContentCap("readFile", 0);
17211
+ const batchStartLedger = args2.readLedger ? new Map([...args2.readLedger].map(([key, entry2]) => [key, { ...entry2, records: [...entry2.records] }])) : void 0;
17212
+ for (let i = 0; i < parsed.files.length; i++) {
17213
+ const file = parsed.files[i];
17214
+ if (!file || typeof file !== "object" || typeof file.path !== "string" || !file.path || file.lines !== void 0 && typeof file.lines !== "string") {
17215
+ items[i] = { ...items[i], status: "invalid-arguments" };
17216
+ continue;
17217
+ }
17218
+ const trialLedger = args2.readLedger ? new Map([...args2.readLedger].map(([key, entry2]) => [key, { ...entry2, records: [...entry2.records] }])) : void 0;
17219
+ try {
17220
+ const result4 = await readFileTool({ ...args2, batchItem: true, readLedger: trialLedger, call: { ...args2.call, arguments: JSON.stringify(file) } });
17221
+ const metadata2 = result4.metadata ?? {};
17222
+ const candidate = { path: file.path, status: metadata2.deduped ? "already-delivered" : metadata2.status === "invalid-arguments" ? "invalid-arguments" : metadata2.truncatedByCharLimit || metadata2.partialLine ? "partial" : "complete", content: result4.content, ...metadata2 };
17223
+ const previous = items[i];
17224
+ items[i] = candidate;
17225
+ const formatted = formatToolMessageContent({ toolName: "readFile", content: JSON.stringify(items), metadata: { batch: true, items: items.map(({ path, status, startLine, endLine }) => ({ path, status, startLine, endLine })) } });
17226
+ if (formatted.length > budget) {
17227
+ items[i] = previous;
17228
+ continue;
17229
+ }
17230
+ if (args2.readLedger && trialLedger) {
17231
+ args2.readLedger.clear();
17232
+ for (const [key, value] of trialLedger) args2.readLedger.set(key, value);
17233
+ }
17234
+ } catch {
17235
+ items[i] = { path: file.path, status: "error" };
17236
+ }
17237
+ }
17238
+ const batchContent = JSON.stringify(items);
17239
+ const batchMetadata = { batch: true, items: items.map(({ path, status, startLine, endLine }) => ({ path, status, startLine, endLine })) };
17240
+ if (formatToolMessageContent({ toolName: "readFile", content: batchContent, metadata: batchMetadata }).length > budget) {
17241
+ if (args2.readLedger && batchStartLedger) {
17242
+ args2.readLedger.clear();
17243
+ for (const [key, value] of batchStartLedger) args2.readLedger.set(key, value);
17244
+ }
17245
+ return { content: "[readFile] Batch request exceeds the shared delivery budget; no content delivered. Use fewer or shorter paths.", metadata: { status: "batch-limit-exceeded" } };
17246
+ }
17247
+ return { content: batchContent, metadata: batchMetadata };
17248
+ }
17168
17249
  const requestedPath = requireWorkspaceToolPath(parsed);
17169
- const { warnings, invalidLines, ...sliceArgs } = readFileSliceArgs(parsed);
17250
+ const parsedSlice = readFileSliceArgs(parsed);
17251
+ if (parsedSlice.error) {
17252
+ return {
17253
+ content: `[readFile] Invalid lines: ${parsedSlice.error} No file content was read. Use lines: ${LINES_ARG_SYNTAX}, or omit lines.`,
17254
+ metadata: { status: "invalid-arguments", tool: "readFile" }
17255
+ };
17256
+ }
17257
+ const sliceArgs = parsedSlice.slice ?? {};
17258
+ const warnings = [];
17170
17259
  const approval = await resolveLocalWorkspaceToolApproval({
17171
17260
  workspaceRoot: args2.workspaceRoot,
17172
17261
  requestedPath,
@@ -17182,45 +17271,101 @@ async function readFileTool(args2) {
17182
17271
  content,
17183
17272
  ...sliceArgs
17184
17273
  });
17185
- const truncatedRead = defensivelyTruncateReadFile({
17186
- content: sliced.content,
17187
- totalLines: sliced.totalLines
17188
- });
17189
- const invalidLinesMarker = invalidLines !== void 0 ? `[readFile] lines=${clipMarkerValue(invalidLines)} was rejected (only ONE range: ${LINES_ARG_SYNTAX}); returned lines ${sliced.startLine}-${sliced.endLine} instead. Fix the argument before relying on this window.
17190
- ` : "";
17191
- const finalRead = invalidLinesMarker.length > 0 ? defensivelyTruncateReadFile({
17192
- content: truncatedRead.content,
17193
- totalLines: sliced.totalLines,
17194
- limit: Math.max(1, READ_FILE_MAX_CHAR_LIMIT - invalidLinesMarker.length)
17195
- }) : truncatedRead;
17196
- const finalContent = invalidLinesMarker + finalRead.content;
17197
- const truncatedByCharLimit = truncatedRead.truncatedByCharLimit || finalRead.truncatedByCharLimit;
17198
- const isTruncated = sliced.truncated || truncatedByCharLimit;
17199
17274
  const relativePath = normalizeWorkspaceRelativePath({
17200
- workspaceRoot: resolve4(args2.workspaceRoot),
17275
+ workspaceRoot: resolve5(args2.workspaceRoot),
17201
17276
  targetPath: absolutePath
17202
17277
  });
17278
+ const instructionPath = AGENTS_MD_CANDIDATES.some((name) => absolutePath === resolve5(args2.workspaceRoot, name));
17279
+ const instructionLimit = PROJECT_INSTRUCTION_MAX_BYTES;
17280
+ const instructionOversized = Buffer.byteLength(content) > instructionLimit || countLines(content) > TOOL_OUTPUT_SPILL_LINES;
17281
+ const instruction = !args2.batchItem && instructionPath && !instructionOversized;
17282
+ if (!args2.batchItem && instructionPath && instructionOversized && Object.keys(sliceArgs).length === 0) {
17283
+ return {
17284
+ content: `[readFile] Project instruction exceeds the delivery limit (${instructionLimit} bytes or ${TOOL_OUTPUT_SPILL_LINES} lines); no content delivered. Continue with lines="1-" to inspect the first bounded range.`,
17285
+ metadata: { path: relativePath, status: "instruction-limit-exceeded", truncated: true, totalBytes: Buffer.byteLength(originalContent) }
17286
+ };
17287
+ }
17288
+ const cap = instruction ? PROJECT_INSTRUCTION_MAX_CHARS : resolveHistoricalToolContentCap("readFile", 0);
17289
+ const selectedLines = splitTextLines(sliced.content);
17290
+ const makeMetadata = (body, endLine, windowed2, partialLine) => ({
17291
+ path: relativePath,
17292
+ ...instruction ? { projectInstruction: true } : {},
17293
+ bytes: Buffer.byteLength(body),
17294
+ totalBytes: Buffer.byteLength(originalContent),
17295
+ ...projection.projected ? {
17296
+ projection: "run-result-observations",
17297
+ projectedTotalBytes: Buffer.byteLength(content),
17298
+ rawReadHint: "readFile raw:true reads original evidence; line numbers are unchanged."
17299
+ } : {},
17300
+ startLine: sliced.startLine,
17301
+ ...partialLine ? { partialLine: true } : { endLine },
17302
+ totalLines: sliced.totalLines,
17303
+ truncated: sliced.truncated || windowed2,
17304
+ ...scrubSecrets(sanitizeToolOutputText(body)).cleaned !== body ? { contentSanitized: true } : {},
17305
+ ...windowed2 ? { truncatedByByteLimit: true, truncatedByCharLimit: true } : {},
17306
+ ...sliceArgs.maxLines ? { maxLines: sliceArgs.maxLines } : {},
17307
+ ...sliceArgs.tailLines ? { tailLines: sliceArgs.tailLines } : {},
17308
+ ...activity ? { activity } : {}
17309
+ });
17310
+ const fits = (body, endLine, windowed2) => {
17311
+ if (Buffer.byteLength(body) > TOOL_OUTPUT_SPILL_BYTES || countLines(body) > TOOL_OUTPUT_SPILL_LINES) return false;
17312
+ const metadata2 = makeMetadata(body, endLine, windowed2, false);
17313
+ return formatToolMessageContent({ toolName: "readFile", content: body, metadata: metadata2 }).length <= cap;
17314
+ };
17315
+ let deliveredCount = selectedLines.length;
17316
+ let finalContent = sliced.content;
17317
+ let windowed = false;
17318
+ if (!fits(finalContent, sliced.endLine, false)) {
17319
+ let low = 0;
17320
+ let high = selectedLines.length;
17321
+ while (low < high) {
17322
+ const mid = Math.ceil((low + high) / 2);
17323
+ const candidate = selectedLines.slice(0, mid).join("\n");
17324
+ if (fits(candidate, sliced.startLine + mid - 1, true)) low = mid;
17325
+ else high = mid - 1;
17326
+ }
17327
+ deliveredCount = low;
17328
+ windowed = true;
17329
+ finalContent = selectedLines.slice(0, deliveredCount).join("\n");
17330
+ }
17331
+ const oversizedLine = windowed && deliveredCount === 0;
17332
+ if (oversizedLine) {
17333
+ let low = 0;
17334
+ let high = Math.min(sliced.content.length, cap);
17335
+ while (low < high) {
17336
+ const mid = Math.ceil((low + high) / 2);
17337
+ const candidate = defensivelyTruncateReadFile({ content: sliced.content, totalLines: sliced.totalLines, limit: mid }).content;
17338
+ const metadata2 = makeMetadata(candidate, sliced.startLine, true, true);
17339
+ const fitsPreview = Buffer.byteLength(candidate) <= TOOL_OUTPUT_SPILL_BYTES && countLines(candidate) <= TOOL_OUTPUT_SPILL_LINES && formatToolMessageContent({ toolName: "readFile", content: candidate, metadata: metadata2 }).length <= cap;
17340
+ if (fitsPreview) low = mid;
17341
+ else high = mid - 1;
17342
+ }
17343
+ finalContent = low > 0 ? defensivelyTruncateReadFile({ content: sliced.content, totalLines: sliced.totalLines, limit: low }).content : "[readFile] Line exceeds the delivery budget; use codeSearch or another tool to inspect it.";
17344
+ }
17345
+ const deliveredEndLine = windowed && !oversizedLine ? sliced.startLine + deliveredCount - 1 : sliced.endLine;
17346
+ const metadata = makeMetadata(finalContent, deliveredEndLine, windowed, oversizedLine);
17203
17347
  const force = parsed.force === true;
17204
17348
  const ledger = args2.readLedger;
17205
- const requestRange = { startLine: sliced.startLine, endLine: sliced.endLine };
17349
+ const deliveredRange = { startLine: sliced.startLine, endLine: deliveredEndLine };
17206
17350
  const fingerprint = createHash3("sha1").update(originalContent).update(parsed.raw === true ? "\0raw" : "\0default").digest("hex").slice(0, 20);
17207
17351
  let entry = ledger?.get(relativePath);
17208
17352
  if (entry && entry.fingerprint !== fingerprint) {
17209
17353
  entry = void 0;
17210
17354
  ledger?.delete(relativePath);
17211
17355
  }
17212
- if (!force && entry && ledger) {
17213
- const retainedCap = resolveHistoricalToolContentCap("readFile", 0);
17356
+ if (!force && entry && ledger && !oversizedLine) {
17357
+ const retainedCap = instructionPath && !instructionOversized ? PROJECT_INSTRUCTION_MAX_CHARS : resolveHistoricalToolContentCap("readFile", 0);
17214
17358
  const retained = filterRetainedLedgerRecords(entry.records, retainedCap);
17215
- if (retained.length > 0 && isLineRangeCovered(requestRange, retained)) {
17359
+ if (retained.length > 0 && isLineRangeCovered(deliveredRange, retained)) {
17216
17360
  ledger.delete(relativePath);
17217
17361
  ledger.set(relativePath, entry);
17218
17362
  return {
17219
- content: `[readFile] ${relativePath} lines ${requestRange.startLine}-${requestRange.endLine} were already delivered earlier and the file is unchanged; not resending. Pass force:true to refetch.`,
17363
+ content: `[readFile] ${relativePath} lines ${deliveredRange.startLine}-${deliveredRange.endLine} were already delivered earlier and the file is unchanged; not resending. Pass force:true to refetch.` + (windowed ? ` Continue with lines=${deliveredEndLine + 1}-.` : ""),
17220
17364
  metadata: {
17221
17365
  path: relativePath,
17222
- startLine: requestRange.startLine,
17223
- endLine: requestRange.endLine,
17366
+ startLine: deliveredRange.startLine,
17367
+ endLine: deliveredRange.endLine,
17368
+ ...windowed ? { truncated: true } : {},
17224
17369
  totalLines: sliced.totalLines,
17225
17370
  deduped: true,
17226
17371
  ...warnings.length ? { warnings: [...warnings, buildReadFileSliceHint(sliced.totalLines)] } : {},
@@ -17229,29 +17374,10 @@ async function readFileTool(args2) {
17229
17374
  };
17230
17375
  }
17231
17376
  }
17232
- const metadata = {
17233
- path: relativePath,
17234
- bytes: Buffer.byteLength(finalContent),
17235
- totalBytes: Buffer.byteLength(originalContent),
17236
- ...projection.projected ? {
17237
- projection: "run-result-observations",
17238
- projectedTotalBytes: Buffer.byteLength(content),
17239
- rawReadHint: "readFile raw:true reads original evidence; line numbers are unchanged."
17240
- } : {},
17241
- startLine: sliced.startLine,
17242
- endLine: sliced.endLine,
17243
- totalLines: sliced.totalLines,
17244
- truncated: isTruncated,
17245
- ...truncatedByCharLimit ? { truncatedByByteLimit: true, truncatedByCharLimit: true } : {},
17246
- ...sliceArgs.maxLines ? { maxLines: sliceArgs.maxLines } : {},
17247
- ...sliceArgs.tailLines ? { tailLines: sliceArgs.tailLines } : {},
17248
- ...warnings.length ? { warnings: [...warnings, buildReadFileSliceHint(sliced.totalLines)] } : {},
17249
- ...activity ? { activity } : {}
17250
- };
17251
- if (!isTruncated && ledger) {
17252
- const persistedChars = finalContent.length + "\n\n[tool metadata]\n".length + JSON.stringify(metadata).length;
17377
+ if (!oversizedLine && ledger) {
17378
+ const persistedChars = formatToolMessageContent({ toolName: "readFile", content: finalContent, metadata }).length;
17253
17379
  const records = entry?.records ?? [];
17254
- records.push({ ...requestRange, chars: persistedChars });
17380
+ records.push({ ...deliveredRange, chars: persistedChars });
17255
17381
  ledger.delete(relativePath);
17256
17382
  ledger.set(relativePath, {
17257
17383
  fingerprint,
@@ -17287,7 +17413,7 @@ async function writeFileTool(args2) {
17287
17413
  await ensureGuardedParentDirectory({ workspaceRoot: args2.workspaceRoot, fileApproval: approval });
17288
17414
  await writeGuardApprovedFile(approval, content);
17289
17415
  const relativePath = normalizeWorkspaceRelativePath({
17290
- workspaceRoot: resolve4(args2.workspaceRoot),
17416
+ workspaceRoot: resolve5(args2.workspaceRoot),
17291
17417
  targetPath: absolutePath
17292
17418
  });
17293
17419
  const activity = extractActivity(parsed);
@@ -17410,7 +17536,7 @@ ${hint}` : "")
17410
17536
  }
17411
17537
  await writeGuardApprovedFile(approval, nextContent);
17412
17538
  const relativePath = normalizeWorkspaceRelativePath({
17413
- workspaceRoot: resolve4(args2.workspaceRoot),
17539
+ workspaceRoot: resolve5(args2.workspaceRoot),
17414
17540
  targetPath: absolutePath
17415
17541
  });
17416
17542
  const activity = extractActivity(parsed);
@@ -17450,7 +17576,7 @@ async function listWorkspaceEntries(args2) {
17450
17576
  const names = (await readdir2(dirPath)).sort((left, right) => left.localeCompare(right));
17451
17577
  for (const name of names) {
17452
17578
  if (truncated) break;
17453
- const absolutePath = resolve4(dirPath, name);
17579
+ const absolutePath = resolve5(dirPath, name);
17454
17580
  const info = await stat4(absolutePath);
17455
17581
  const relativePath = relative4(args2.dirPath, absolutePath) || ".";
17456
17582
  const isDirectory = info.isDirectory();
@@ -17479,7 +17605,7 @@ async function internalSearchWorkspace(args2) {
17479
17605
  allowRuntimeOwnedSpill: true,
17480
17606
  ...args2.confirmExternalFileAccess ? { confirmExternalFileAccess: args2.confirmExternalFileAccess } : {}
17481
17607
  });
17482
- const workspaceRoot = resolve4(args2.workspaceRoot);
17608
+ const workspaceRoot = resolve5(args2.workspaceRoot);
17483
17609
  const inside = isPathInsideWorkspace({ workspaceRoot, targetPath: searchPath });
17484
17610
  const result4 = await searchFileTextMatches({
17485
17611
  root: inside ? workspaceRoot : searchPath,
@@ -17559,7 +17685,7 @@ async function globFilesTool(args2) {
17559
17685
  ...args2.confirmExternalFileAccess ? { confirmExternalFileAccess: args2.confirmExternalFileAccess } : {}
17560
17686
  });
17561
17687
  const relativeSearchPath = normalizeWorkspaceRelativePath({
17562
- workspaceRoot: resolve4(args2.workspaceRoot),
17688
+ workspaceRoot: resolve5(args2.workspaceRoot),
17563
17689
  targetPath: searchPath
17564
17690
  });
17565
17691
  const pathPrefix = relativeSearchPath === "." ? "" : `${relativeSearchPath.replace(/\/+$/, "")}/`;
@@ -17856,7 +17982,7 @@ async function launchProcessTool(args2) {
17856
17982
  ];
17857
17983
  const detached = process.platform !== "win32";
17858
17984
  const proc = spawnChildProcess2(cmdArgs[0] ?? "", cmdArgs.slice(1), {
17859
- cwd: resolve4(args2.workspaceRoot),
17985
+ cwd: resolve5(args2.workspaceRoot),
17860
17986
  stdio: ["ignore", "pipe", "pipe"],
17861
17987
  detached,
17862
17988
  windowsHide: true
@@ -18180,12 +18306,12 @@ function createLocalWorkspaceToolExecutors(args2) {
18180
18306
  images: results2.flatMap((result4) => result4.images ?? [])
18181
18307
  };
18182
18308
  },
18183
- readFile: (call) => readFileTool({
18309
+ readFile: Object.assign((call) => readFileTool({
18184
18310
  call,
18185
18311
  workspaceRoot: args2.workspaceRoot,
18186
18312
  ...readFileLedger ? { readLedger: readFileLedger } : {},
18187
18313
  ...fileAccess
18188
- }),
18314
+ }), { resetReadLedger: () => readFileLedger?.clear() }),
18189
18315
  writeFile: (call) => writeFileTool({
18190
18316
  call,
18191
18317
  workspaceRoot: args2.workspaceRoot,
@@ -19184,43 +19310,139 @@ function createTurnUsageLedger(args2) {
19184
19310
  };
19185
19311
  }
19186
19312
 
19187
- // packages/agent-runtime/leafFinalHandoff.ts
19188
- var LEAF_FINAL_HANDOFF_INSTRUCTIONS = `Leaf subtask final: return only the result, blockers/findings, and minimal evidence the parent needs. Do not narrate your process or restate the task. Keep success minimal (a one-line result is enough); on failure include the blocker, severity when relevant, and an evidence reference (file:line, test command, commit, artifact, or run/dialog). If the task explicitly requires a long-form deliverable (document, translation, dataset, code, or other artifact), provide that deliverable in full and keep only the handoff around it concise. During execution, follow the brief as given: report only results incremental to the brief, new evidence, overturned assumptions, and remaining questions; only when new evidence would materially change the goal, risk, irreversibility, or DoD should you surface it as a blocker/finding \u2014 do not silently expand scope or re-litigate the settled direction. Own investigation, implementation, related checks and failure fixes within the brief\u2019s scope and budget; leave goals and critical decisions to the parent. For required DoD checks, include the worktree, checked version (including uncommitted change scope), command, check scope, pass/fail and original-output reference; explicitly mark checks not run or evidence unavailable. Reuse valid same-version evidence; additional checks are warranted for version changes, missing/conflicting evidence or integration risk. Do not invent version metadata or treat a completion summary as independent review approval. Keep success concise without omitting required evidence.`;
19313
+ // packages/agent-runtime/agentRunIsolation.ts
19314
+ var ORCHESTRATION_TOOL_NAMES = /* @__PURE__ */ new Set([
19315
+ "startAgentRun",
19316
+ "controlAgentRun",
19317
+ "listAgents",
19318
+ "readAgent",
19319
+ "runStreamingAgent"
19320
+ ]);
19321
+ var INTERACTION_REQUIRED_TOOL_NAMES = /* @__PURE__ */ new Set([
19322
+ "ask_user",
19323
+ // 凭据请求:需要宿主交互面板(Block 1a);desktop 无通道时同 ask_user 剥离。
19324
+ "secret-request"
19325
+ ]);
19326
+ var SELF_MUTATION_TOOL_NAMES = /* @__PURE__ */ new Set([
19327
+ "updateSelf",
19328
+ "updateAgent"
19329
+ ]);
19330
+ var SUBTASK_REMOVED_TOOL_NAMES = /* @__PURE__ */ new Set([
19331
+ ...ORCHESTRATION_TOOL_NAMES,
19332
+ ...INTERACTION_REQUIRED_TOOL_NAMES,
19333
+ ...SELF_MUTATION_TOOL_NAMES
19334
+ ]);
19335
+ function isSubtaskRun(env) {
19336
+ if (!env) return false;
19337
+ const value = env.NOLO_AGENT_RUN_CHILD;
19338
+ return typeof value === "string" && value.length > 0 && value !== "0";
19339
+ }
19340
+ var RUN_WAKE_CHANNEL_ENV = "NOLO_RUN_WAKE";
19341
+ function hasRunWakeChannel(env) {
19342
+ if (!env) return false;
19343
+ const value = env[RUN_WAKE_CHANNEL_ENV];
19344
+ return typeof value === "string" && value.length > 0 && value !== "0";
19345
+ }
19346
+ function filterToolNamesForRunKind(toolNames, isSubtask) {
19347
+ if (!isSubtask) return [...toolNames];
19348
+ return toolNames.filter((name) => !SUBTASK_REMOVED_TOOL_NAMES.has(name));
19349
+ }
19189
19350
 
19190
- // packages/agent-runtime/taskExecutionContract.ts
19191
- var present = (value) => typeof value === "string" && value.trim().length > 0;
19192
- function evaluateTaskExecutionContract(contract, outcome = {}) {
19193
- if (!contract) return void 0;
19194
- const result4 = (status, ...reasons) => ({ taskId: contract.taskId, status, reasons });
19195
- if (outcome.stopped) return result4("blocked", "stopped");
19196
- if (!present(contract.taskId) || !["owner", "implementation-leaf"].includes(contract.role) || !["active", "paused", "revoked"].includes(contract.authorization) || !["pending", "waived", "accepted", "unknown"].includes(contract.acceptance) || !["complete", "incomplete", "unknown"].includes(contract.implementation) || !["changed", "unchanged", "unknown"].includes(contract.changes)) {
19197
- return result4("blocked", "invalid_contract");
19198
- }
19199
- if (contract.authorization === "revoked") return result4("blocked", "authorization_revoked");
19200
- if (contract.authorization === "paused") return result4("blocked", "authorization_paused");
19201
- if (outcome.executionFailed) return result4("blocked", "execution_failed");
19202
- if (outcome.budgetExhausted) return result4("incomplete", "budget_exhausted");
19203
- if (contract.implementation !== "complete") return result4("incomplete", "implementation_incomplete");
19204
- if (contract.acceptance === "pending") return result4("waiting", "acceptance_pending");
19205
- if (contract.acceptance === "unknown") return result4("blocked", "acceptance_unknown");
19206
- if (contract.changes === "unknown") return result4("incomplete", "changes_unknown");
19207
- if (contract.role === "implementation-leaf" || contract.changes === "unchanged") return result4("completed");
19208
- if (!present(contract.revision)) return result4("incomplete", "revision_missing");
19209
- const review = contract.review;
19210
- if (!review || !present(review.evidenceRef)) return result4("incomplete", "review_missing");
19211
- if (review.revision !== contract.revision) return result4("incomplete", "review_stale");
19212
- if (!present(contract.authorInstanceId) || !present(review.reviewerInstanceId) || review.reviewerInstanceId === contract.authorInstanceId) return result4("blocked", "review_not_independent");
19213
- if (review.verdict !== "APPROVE" || review.hasCriticalOrHigh !== false) return result4("blocked", "review_rejected");
19214
- const commit = contract.commit;
19215
- if (!commit || !present(commit.commitId) || !present(commit.evidenceRef)) return result4("incomplete", "commit_missing");
19216
- if (commit.revision !== contract.revision) return result4("incomplete", "commit_stale");
19217
- const merge4 = contract.localMerge;
19218
- if (!merge4 || !present(merge4.targetBranch) || !present(merge4.mergeCommitId) || !present(merge4.evidenceRef)) {
19219
- return result4("incomplete", "local_merge_missing");
19220
- }
19221
- if (merge4.sourceCommitId !== commit.commitId) return result4("incomplete", "local_merge_mismatch");
19222
- return result4("completed");
19351
+ // packages/agent-runtime/subtaskBudget.ts
19352
+ var DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_1_TOOL_CALLS = 40;
19353
+ var DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_2_TOOL_CALLS = 80;
19354
+ var SUBTASK_SOFT_BUDGET_MILESTONE_1_PREFIX = "[\u7CFB\u7EDF\u63D0\u793A \xB7 \u5B50\u4EFB\u52A1\u8F6F\u9884\u7B97\u63D0\u9192]";
19355
+ var SUBTASK_SOFT_BUDGET_MILESTONE_2_PREFIX = "[\u7CFB\u7EDF\u63D0\u793A \xB7 \u5B50\u4EFB\u52A1\u5F3A\u6536\u655B\u63D0\u9192]";
19356
+ function buildSubtaskSoftBudgetMilestone1Prompt(toolCallCount) {
19357
+ return `${SUBTASK_SOFT_BUDGET_MILESTONE_1_PREFIX} \u5F53\u524D\u5B50\u4EFB\u52A1\u5DF2\u7D2F\u8BA1\u6267\u884C ${toolCallCount} \u6B21\u5DE5\u5177\u8C03\u7528\uFF0C\u8BF7\u505A\u4E00\u6B21\u6536\u655B\u81EA\u68C0\uFF1A\u82E5\u6838\u5FC3\u76EE\u6807\u4E0E\u5FC5\u9700\u9A8C\u8BC1\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u5C3D\u5FEB\u6574\u7406\u7ED3\u679C\u5E76\u6536\u655B\u4EA4\u4ED8\uFF1B\u82E5\u540C\u4E00\u62A5\u9519\u5DF2\u8FDE\u7EED\u91CD\u8BD5\u4E14\u65E0\u65B0\u8BC1\u636E\uFF0C\u8BF7\u505C\u6B62\u76F2\u8BD5\u5E76\u5728\u7ED3\u679C\u4E2D\u5982\u5B9E\u62A5\u544A\u6839\u56E0\u4E0E\u963B\u788D\uFF1B\u82E5\u786E\u7CFB\u6B63\u5E38\u7684\u591A\u6587\u4EF6\u4FEE\u6539\u6216\u9A8C\u8BC1\u5DE5\u4F5C\uFF0C\u53EF\u7EE7\u7EED\u7A33\u6B65\u5B8C\u6210\u3002`;
19358
+ }
19359
+ function buildSubtaskSoftBudgetMilestone2Prompt(toolCallCount) {
19360
+ return `${SUBTASK_SOFT_BUDGET_MILESTONE_2_PREFIX} \u5F53\u524D\u5B50\u4EFB\u52A1\u5DF2\u7D2F\u8BA1\u6267\u884C ${toolCallCount} \u6B21\u5DE5\u5177\u8C03\u7528\u3002\u5EFA\u8BAE\u5728\u5B8C\u6210\u5F53\u524D\u624B\u5934\u6700\u540E\u4E00\u6B65\u5FC5\u8981\u9A8C\u8BC1\u540E\uFF0C\u7ACB\u5373\u6574\u7406\u5DF2\u6709\u6210\u679C\u3001\u672A\u5B8C\u6210\u9879\u4E0E\u5EFA\u8BAE\u7684\u4E0B\u4E00\u6B65\u76F4\u63A5\u4EA4\u4ED8\u7236\u5BF9\u8BDD\uFF0C\u907F\u514D\u5355\u6B21\u5B50\u4EFB\u52A1\u8FC7\u5EA6\u6D88\u8017\u914D\u989D\u4E0E\u4E0A\u4E0B\u6587\u3002`;
19361
+ }
19362
+ function resolveSoftBudgetEnv(explicitEnv) {
19363
+ if (explicitEnv !== void 0) return explicitEnv;
19364
+ if (typeof process !== "undefined" && process.env) return process.env;
19365
+ return void 0;
19366
+ }
19367
+ function isEnvSoftBudgetDisabled(env) {
19368
+ const raw = env?.NOLO_SUBTASK_SOFT_BUDGET?.trim().toLowerCase();
19369
+ return raw === "0" || raw === "false";
19223
19370
  }
19371
+ function hasParentDialogEnvSignal(env) {
19372
+ const raw = env?.NOLO_PARENT_DIALOG_ID;
19373
+ return typeof raw === "string" && raw.trim().length > 0;
19374
+ }
19375
+ function normalizeThreshold(value) {
19376
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
19377
+ return void 0;
19378
+ }
19379
+ return Math.floor(value);
19380
+ }
19381
+ function createSubtaskSoftBudgetAdvisor(options) {
19382
+ const env = resolveSoftBudgetEnv(options?.env);
19383
+ const envDisabled = isEnvSoftBudgetDisabled(env);
19384
+ const configDisabled = options?.softBudget === false || typeof options?.softBudget === "object" && options.softBudget !== null && options.softBudget.enabled === false;
19385
+ const configEnabled = options?.softBudget === true || typeof options?.softBudget === "object" && options.softBudget !== null && options.softBudget.enabled !== false;
19386
+ const hasSubtaskContext = options?.isSubtask === true || options?.runKind === "subtask" || hasParentDialogEnvSignal(env) || isSubtaskRun(env);
19387
+ const enabled = !envDisabled && !configDisabled && (configEnabled || hasSubtaskContext);
19388
+ const rawConfig = typeof options?.softBudget === "object" && options.softBudget !== null ? options.softBudget : void 0;
19389
+ const milestone1ToolCalls = normalizeThreshold(rawConfig?.milestone1ToolCalls) ?? DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_1_TOOL_CALLS;
19390
+ const explicitMilestone2 = normalizeThreshold(rawConfig?.milestone2ToolCalls);
19391
+ const milestone2ToolCalls = explicitMilestone2 !== void 0 ? Math.max(milestone1ToolCalls + 1, explicitMilestone2) : Math.max(
19392
+ DEFAULT_SUBTASK_SOFT_BUDGET_MILESTONE_2_TOOL_CALLS,
19393
+ milestone1ToolCalls * 2
19394
+ );
19395
+ let milestone1Triggered = false;
19396
+ let milestone2Triggered = false;
19397
+ let lastObservedToolCallCount = 0;
19398
+ function observeToolCalls(toolCallCount) {
19399
+ const normalized = typeof toolCallCount === "number" && Number.isFinite(toolCallCount) && toolCallCount > 0 ? Math.floor(toolCallCount) : 0;
19400
+ if (normalized > lastObservedToolCallCount) {
19401
+ lastObservedToolCallCount = normalized;
19402
+ }
19403
+ if (!enabled) return null;
19404
+ if (!milestone2Triggered && normalized >= milestone2ToolCalls) {
19405
+ milestone1Triggered = true;
19406
+ milestone2Triggered = true;
19407
+ return {
19408
+ milestone: 2,
19409
+ threshold: milestone2ToolCalls,
19410
+ toolCallCount: normalized,
19411
+ message: buildSubtaskSoftBudgetMilestone2Prompt(normalized)
19412
+ };
19413
+ }
19414
+ if (!milestone1Triggered && normalized >= milestone1ToolCalls) {
19415
+ milestone1Triggered = true;
19416
+ return {
19417
+ milestone: 1,
19418
+ threshold: milestone1ToolCalls,
19419
+ toolCallCount: normalized,
19420
+ message: buildSubtaskSoftBudgetMilestone1Prompt(normalized)
19421
+ };
19422
+ }
19423
+ return null;
19424
+ }
19425
+ function getState2() {
19426
+ return {
19427
+ enabled,
19428
+ milestone1ToolCalls,
19429
+ milestone2ToolCalls,
19430
+ milestone1Triggered,
19431
+ milestone2Triggered,
19432
+ lastObservedToolCallCount
19433
+ };
19434
+ }
19435
+ return {
19436
+ enabled,
19437
+ milestone1ToolCalls,
19438
+ milestone2ToolCalls,
19439
+ observeToolCalls,
19440
+ getState: getState2
19441
+ };
19442
+ }
19443
+
19444
+ // packages/agent-runtime/leafFinalHandoff.ts
19445
+ var LEAF_FINAL_HANDOFF_INSTRUCTIONS = `Leaf subtask final: return only the result, blockers/findings, and minimal evidence the parent needs. Do not narrate your process or restate the task. Keep success concise without dropping the current delivery scope, unresolved blockers or evidence references; on failure include the blocker, severity when relevant, and an evidence reference (file:line, test command, commit, artifact, or run/dialog). If the task explicitly requires a long-form deliverable (document, translation, dataset, code, or other artifact), provide that deliverable in full and keep only the handoff around it concise. During execution, follow the brief as given: keep progress updates incremental to the brief; the final report must stand alone with the complete current delivery scope, unresolved blockers and evidence references, including on continuation; only when new evidence would materially change the goal, risk, irreversibility, or DoD should you surface it as a blocker/finding \u2014 do not silently expand scope or re-litigate the settled direction. Own investigation, implementation, related checks and failure fixes within the brief\u2019s scope and budget; leave goals and critical decisions to the parent. For required DoD checks, include the worktree, checked version (including uncommitted change scope), command, check scope, pass/fail and original-output reference; explicitly mark checks not run or evidence unavailable. Reuse valid same-version evidence; additional checks are warranted for version changes, missing/conflicting evidence or integration risk. Do not invent version metadata. Process done/exit 0 and assistant claims do not establish passing tests, user acceptance, independent review approval, integration or release; runtime acceptance is observations only and unknown remains unknown. Preserve a requested reviewer JSON/checkVerdict format; do not wrap it in another report. Keep success concise without omitting required evidence.`;
19224
19446
 
19225
19447
  // packages/agent-runtime/contextBlockScope.ts
19226
19448
  var isContextBlockScope = (value) => {
@@ -19283,6 +19505,25 @@ function findSummaryAnchorIndex(bridged, anchorId) {
19283
19505
  const index = Number(legacy[1]);
19284
19506
  return Number.isSafeInteger(index) && index < bridged.length ? index : -1;
19285
19507
  }
19508
+ function logSummarySourceDiagnostics(phase, dialogId, history, anchor, segmentDiff) {
19509
+ const sourceHash = hashSummarySourceSlice(history, anchor)?.slice(0, 16);
19510
+ if (phase === "invalidated" && segmentDiff) {
19511
+ console.log(`[compaction-source] ${JSON.stringify({
19512
+ phase,
19513
+ dialogId,
19514
+ sourceHash,
19515
+ kind: "segment-diff",
19516
+ ...segmentDiff
19517
+ })}`);
19518
+ }
19519
+ const rows = buildSummarySourceDiagnostics(toPlanCompressionMessages(history), anchor);
19520
+ for (const row of rows) console.log(`[compaction-source] ${JSON.stringify({
19521
+ phase,
19522
+ dialogId,
19523
+ sourceHash,
19524
+ ...row
19525
+ })}`);
19526
+ }
19286
19527
  function hashSummarySourceSlice(history, summarizedBeforeId) {
19287
19528
  if (!summarizedBeforeId) return void 0;
19288
19529
  const bridged = toPlanCompressionMessages(history);
@@ -19472,13 +19713,15 @@ async function maybeAutoCompactLocalHistory(args2) {
19472
19713
  let reason;
19473
19714
  if (invalidStored?.schemaVersion !== void 0 && invalidStored.schemaVersion !== COMPACTION_SUMMARY_SCHEMA_VERSION) {
19474
19715
  reason = "schema-version-mismatch";
19475
- } else if (typeof invalidStored?.summarizedBeforeId !== "string" || !bridged.some((m) => m.id === invalidStored.summarizedBeforeId)) {
19716
+ } else if (typeof invalidStored?.summarizedBeforeId !== "string" || findSummaryAnchorIndex(bridged, invalidStored.summarizedBeforeId) === -1) {
19476
19717
  reason = "anchor-not-found";
19477
19718
  } else if (typeof invalidStored?.sourceCount === "number" && history.length < invalidStored.sourceCount) {
19478
19719
  reason = "history-trimmed";
19479
19720
  } else {
19480
19721
  reason = "hash-mismatch";
19481
19722
  }
19723
+ const currentSegments = buildSummarySourceSegments(bridged, invalidStored?.summarizedBeforeId);
19724
+ const segmentDiff = reason === "hash-mismatch" ? diffSummarySourceSegments(invalidStored?.sourceSegments, currentSegments) : void 0;
19482
19725
  console.warn(
19483
19726
  `[localLoop] invalidated dialog summary for ${dialogId} (${reason}); discarding and re-compressing`,
19484
19727
  // 诊断分项(**仅加日志,不改任何哈希/校验/重锚语义**):区分「历史真被改写」
@@ -19491,9 +19734,17 @@ async function maybeAutoCompactLocalHistory(args2) {
19491
19734
  storedSourceCount: typeof invalidStored?.sourceCount === "number" ? invalidStored.sourceCount : null,
19492
19735
  summarizedBeforeId: typeof invalidStored?.summarizedBeforeId === "string" ? invalidStored.summarizedBeforeId : null,
19493
19736
  recomputedHashPrefix: hashSummarySourceSlice(history, invalidStored?.summarizedBeforeId)?.slice(0, 8) ?? null,
19494
- storedHashPrefix: typeof invalidStored?.sourceHash === "string" && invalidStored.sourceHash ? invalidStored.sourceHash.slice(0, 8) : null
19737
+ storedHashPrefix: typeof invalidStored?.sourceHash === "string" && invalidStored.sourceHash ? invalidStored.sourceHash.slice(0, 8) : null,
19738
+ ...segmentDiff ? { segmentDiff } : {}
19495
19739
  }
19496
19740
  );
19741
+ logSummarySourceDiagnostics(
19742
+ "invalidated",
19743
+ dialogId,
19744
+ history,
19745
+ invalidStored?.summarizedBeforeId,
19746
+ segmentDiff
19747
+ );
19497
19748
  stored = null;
19498
19749
  }
19499
19750
  const existingSummary = typeof stored?.summary === "string" ? stored.summary : "";
@@ -19503,7 +19754,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19503
19754
  const contextWindow = typeof args2.contextWindow === "number" && Number.isFinite(args2.contextWindow) && args2.contextWindow > 0 ? args2.contextWindow : getModelContextWindow(args2.model ?? "");
19504
19755
  const allMsgs = toPlanCompressionMessages(prepareHistoryForNextTurn(history, args2.contextReferenceResolver));
19505
19756
  const maxInputItems = resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint });
19506
- const force = args2.force === true || args2.requestOverBudget?.(
19757
+ const force = args2.force === true || invalidSummary || args2.requestOverBudget?.(
19507
19758
  existingSummary ? projectHistoryWithSummary({ history, summary: existingSummary, summarizedBeforeId }) : history
19508
19759
  ) === true;
19509
19760
  const plan = planCompression({
@@ -19781,7 +20032,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19781
20032
  primaryElapsedMs = Date.now() - compactionT0;
19782
20033
  logCompactionTiming("provider-error", {});
19783
20034
  emitPhase({ kind: "compaction-retry", attempt: attempt + 1, maxAttempts });
19784
- await new Promise((resolve6, reject) => {
20035
+ await new Promise((resolve7, reject) => {
19785
20036
  const signal = requestController.signal;
19786
20037
  const cancel = () => {
19787
20038
  clearTimeout(timer);
@@ -19790,7 +20041,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19790
20041
  };
19791
20042
  const timer = setTimeout(() => {
19792
20043
  signal.removeEventListener("abort", cancel);
19793
- resolve6();
20044
+ resolve7();
19794
20045
  }, delayMs);
19795
20046
  signal.addEventListener("abort", cancel, { once: true });
19796
20047
  if (signal.aborted) cancel();
@@ -19804,16 +20055,16 @@ async function maybeAutoCompactLocalHistory(args2) {
19804
20055
  (error) => ({ kind: "provider-error", error })
19805
20056
  );
19806
20057
  const guards = [];
19807
- if (timeoutMs) guards.push(new Promise((resolve6) => {
20058
+ if (timeoutMs) guards.push(new Promise((resolve7) => {
19808
20059
  timeoutHandle = setTimeout(() => {
19809
20060
  requestController.abort(new DOMException("Summary deadline exceeded", "TimeoutError"));
19810
- resolve6({ kind: "timeout" });
20061
+ resolve7({ kind: "timeout" });
19811
20062
  }, timeoutMs);
19812
20063
  }));
19813
- if (args2.abortSignal) guards.push(new Promise((resolve6) => {
20064
+ if (args2.abortSignal) guards.push(new Promise((resolve7) => {
19814
20065
  abortListener = () => {
19815
20066
  requestController.abort(args2.abortSignal?.reason);
19816
- resolve6({ kind: "aborted" });
20067
+ resolve7({ kind: "aborted" });
19817
20068
  };
19818
20069
  args2.abortSignal?.addEventListener("abort", abortListener, { once: true });
19819
20070
  if (args2.abortSignal?.aborted) abortListener();
@@ -19927,8 +20178,13 @@ async function maybeAutoCompactLocalHistory(args2) {
19927
20178
  }
19928
20179
  };
19929
20180
  }
20181
+ const bridgedHistory = toPlanCompressionMessages(history);
19930
20182
  const sourceMeta = await computeSummarySourceMetadata(
19931
- toPlanCompressionMessages(history),
20183
+ bridgedHistory,
20184
+ bounded3.summarizedBeforeId
20185
+ );
20186
+ const sourceSegments = buildSummarySourceSegments(
20187
+ bridgedHistory,
19932
20188
  bounded3.summarizedBeforeId
19933
20189
  );
19934
20190
  if (Date.now() >= summaryDeadlineMs) throw Object.assign(new Error("Summary deadline exceeded"), { compactionReason: "timeout" });
@@ -19936,7 +20192,7 @@ async function maybeAutoCompactLocalHistory(args2) {
19936
20192
  throw Object.assign(new Error("auto-compaction aborted"), { compactionReason: "aborted" });
19937
20193
  }
19938
20194
  const saveT0 = Date.now();
19939
- await adapter.saveDialogSummary({
20195
+ const summarySavePayload = {
19940
20196
  dialogId,
19941
20197
  summary: newSummary,
19942
20198
  summarizedBeforeId: bounded3.summarizedBeforeId,
@@ -19944,13 +20200,16 @@ async function maybeAutoCompactLocalHistory(args2) {
19944
20200
  sourceHash: sourceMeta?.sourceHash,
19945
20201
  sourceCount: sourceMeta?.sourceCount ?? 0,
19946
20202
  schemaVersion: COMPACTION_SUMMARY_SCHEMA_VERSION,
20203
+ ...sourceSegments.length > 0 ? { sourceSegments } : {},
19947
20204
  referenceKeys: Array.from(
19948
20205
  new Set(
19949
20206
  history.slice(0, sourceMeta?.sourceCount ?? 0).flatMap((message) => extractReferenceKeysFromMessage(message))
19950
20207
  )
19951
20208
  )
19952
- });
20209
+ };
20210
+ await adapter.saveDialogSummary(summarySavePayload);
19953
20211
  saveElapsedMs = Date.now() - saveT0;
20212
+ logSummarySourceDiagnostics("saved", dialogId, history, bounded3.summarizedBeforeId);
19954
20213
  console.log(formatCompactionMetricsLog(metrics));
19955
20214
  logCompactionTiming("success", {
19956
20215
  model: result4?.model ?? args2.model ?? null,
@@ -20131,7 +20390,7 @@ function createTurnCompactionController(args2) {
20131
20390
  return { history: result4.history, applied: result4.history !== history, usage: result4.usage };
20132
20391
  };
20133
20392
  let lastCompactionOutcome;
20134
- const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens) => {
20393
+ const prepareRequest = async (requestOverBudget, initial = false, availableHistoryTokens, force = false) => {
20135
20394
  lastCompactionOutcome = void 0;
20136
20395
  const contextUsage = args2.getContextUsage();
20137
20396
  let inputTokens = contextUsage ? normalizeUsage(contextUsage).input_tokens : 0;
@@ -20143,8 +20402,8 @@ function createTurnCompactionController(args2) {
20143
20402
  }
20144
20403
  }
20145
20404
  const ratio = inputTokens > 0 ? Math.min(1, inputTokens / args2.contextWindow) : void 0;
20146
- if (!requestOverBudget && ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85 && resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint }) === void 0) {
20147
- return;
20405
+ if (!force && !requestOverBudget && ratio !== void 0 && ratio < args2.compressionTriggerRatio * 0.85 && resolveProviderInputItemLimit({ provider: args2.provider, endpoint: args2.providerEndpoint }) === void 0) {
20406
+ return false;
20148
20407
  }
20149
20408
  try {
20150
20409
  const compacted = await maybeAutoCompactLocalHistory({
@@ -20164,6 +20423,7 @@ function createTurnCompactionController(args2) {
20164
20423
  providerEndpoint: args2.providerEndpoint,
20165
20424
  resolveProvider: args2.resolveProvider,
20166
20425
  contextWindow: args2.contextWindow,
20426
+ ...force ? { force: true } : {},
20167
20427
  ...ratio !== void 0 ? { realContextUsagePercent: ratio } : {},
20168
20428
  abortSignal: args2.abortSignal,
20169
20429
  timeoutMs: args2.timeoutMs,
@@ -20190,12 +20450,16 @@ function createTurnCompactionController(args2) {
20190
20450
  args2.onSelectedSummary?.(compacted.selectedSummary ?? { outcome: initial ? "absent" : "unknown" });
20191
20451
  }
20192
20452
  emitObservation(compacted);
20453
+ return Boolean(compacted.compressed && compacted.summaryGenerated);
20193
20454
  } catch (error) {
20194
20455
  lastCompactionOutcome = { ...lastCompactionOutcome, error: classifySummaryError(error) };
20195
20456
  console.warn("[localLoop] in-loop auto-compaction failed:", error);
20457
+ return false;
20196
20458
  }
20197
20459
  };
20198
- return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: () => prepareRequest(), forceCompact, prepareRequest };
20460
+ return { getLastCompactionOutcome: () => lastCompactionOutcome, runInitial, maybeCompactInLoop: async () => {
20461
+ await prepareRequest();
20462
+ }, forceCompact, prepareRequest };
20199
20463
  }
20200
20464
 
20201
20465
  // packages/agent-runtime/providerCallTelemetry.ts
@@ -20517,10 +20781,6 @@ function attachUsageRecordsToError(error, usageRecords) {
20517
20781
  }
20518
20782
  async function persistFailedLocalTurn(args2) {
20519
20783
  const errorMessage = toErrorMessage(args2.error);
20520
- const businessCompletion = evaluateTaskExecutionContract(args2.input.taskExecutionContract, {
20521
- stopped: args2.input.abortSignal?.aborted || args2.error instanceof Error && args2.error.code === LOCAL_TURN_ABORTED_CODE,
20522
- executionFailed: true
20523
- });
20524
20784
  try {
20525
20785
  const saved = await args2.adapter.saveTurn({
20526
20786
  agentKey: args2.agentKey,
@@ -20531,7 +20791,6 @@ async function persistFailedLocalTurn(args2) {
20531
20791
  toolCallCount: args2.toolCallCount ?? 0,
20532
20792
  error: true,
20533
20793
  errorMessage,
20534
- ...businessCompletion ? { businessCompletion } : {},
20535
20794
  ...args2.usage ? { usage: args2.usage } : {}
20536
20795
  },
20537
20796
  ...args2.accountingUsage ? { accountingUsage: args2.accountingUsage } : {},
@@ -20578,6 +20837,7 @@ function combineRollbackError(primary, rollbackError) {
20578
20837
  return combined;
20579
20838
  }
20580
20839
  async function runLocalAgentTurn(input) {
20840
+ input = { ...input, runtimeContext: input.runtimeContext ? { ...input.runtimeContext } : void 0 };
20581
20841
  const legacyCallbacks = {
20582
20842
  onLoopEvent: input.onLoopEvent,
20583
20843
  onToolEvent: input.onToolEvent,
@@ -20720,8 +20980,16 @@ async function runLocalAgentTurn(input) {
20720
20980
  // 防止 session-scope 的 agentCollaboration 段逐轮翻转击穿前缀缓存。
20721
20981
  dispatchIntent: detectDispatchIntentFromMessages(history) || detectDispatchIntent(
20722
20982
  typeof input.input === "string" ? input.input : void 0
20723
- )
20983
+ ),
20984
+ runKind: input.runKind
20724
20985
  });
20986
+ const callerScopes = normalizeContextBlockScopes(
20987
+ input.contextBlocks,
20988
+ input.contextBlockScopes
20989
+ );
20990
+ const callerHasMemoryGuidance = callerScopes.some(
20991
+ (scope3) => scope3.content.includes(MEMORY_USE_GUIDANCE)
20992
+ );
20725
20993
  const guidanceScopes = [
20726
20994
  ...input.userLanguage?.trim() ? [buildUserResponseLanguageContext({ language: input.userLanguage })] : [],
20727
20995
  guidanceBlocks.startupProtocol,
@@ -20730,12 +20998,14 @@ async function runLocalAgentTurn(input) {
20730
20998
  // 注入顺序遵循 TOOL_GUIDED_SECTION_ORDER(与 buildSystemPrompt 的显式
20731
20999
  // layer 列表同源),禁止用 Object.values 自行定序。
20732
21000
  ...TOOL_GUIDED_SECTION_ORDER.map((id) => toolGuidedSections[id] ?? ""),
21001
+ // 记忆使用指引(session-scope,进稳定前缀):判定真值是 turnContext 的
21002
+ // `hasMemoryTools`(有效工具面),与 web/server 的 buildSystemPrompt 同一条
21003
+ // 规则。放在这里而不是各宿主:CLI/TUI/desktop 都经 runLocalAgentTurn 进入本
21004
+ // 函数,一处即可覆盖三端,并补齐「空库 + 有记忆工具」这一档——此前本地宿主
21005
+ // 只按记忆 overlay 是否为空门控,空库时模型永远不知道该怎么用记忆工具。
21006
+ ...hasMemoryTools(agentTools) && !callerHasMemoryGuidance ? [MEMORY_USE_GUIDANCE] : [],
20733
21007
  ...input.runKind === "subtask" ? [LEAF_FINAL_HANDOFF_INSTRUCTIONS] : []
20734
21008
  ].map((content) => content.trim()).filter((content) => content.length > 0).map((content) => ({ content, cacheScope: "session" }));
20735
- const callerScopes = normalizeContextBlockScopes(
20736
- input.contextBlocks,
20737
- input.contextBlockScopes
20738
- );
20739
21009
  const responseGuidelines = resolveResponseGuidelines(
20740
21010
  input.responseViewport ?? "unknown"
20741
21011
  );
@@ -20749,24 +21019,8 @@ async function runLocalAgentTurn(input) {
20749
21019
  ] : []
20750
21020
  ];
20751
21021
  const mergedContextBlockScopes = [
20752
- // 删除安全红线:系统层最高优先级约束,位于所有块之前(含身份信息块),
20753
- // owner 要求常驻「根本提示词」的最顶部(2026-09-26 批量误删事故)。
20754
- { content: DELETE_SAFETY_RED_LINE, cacheScope: "session" },
20755
- // 凭据纪律:与红线同为系统层固定块,紧随其后(四条装配线同源)。
20756
- { content: CREDENTIAL_HYGIENE_RULE, cacheScope: "session" },
20757
- // 并行是默认:系统层固定块,紧随红线(localLoop 无 static 作用域,用 session 占位,
20758
- // 「最顶」由数组首位保证——与红线同一约定)。
20759
- { content: VERIFY_BEFORE_CONCLUDING_RULE, cacheScope: "session" },
20760
- { content: PARALLEL_DISPATCH_DEFAULT_RULE, cacheScope: "session" },
20761
- // 派发落点:并行派发纪律的下一层(派到哪个执行后端),沿用 session 占位约定。
20762
- { content: DISPATCH_BACKEND_POLICY, cacheScope: "session" },
20763
- { content: DISPATCH_CANDIDATE_POLICY, cacheScope: "session" },
20764
- // 平台风控纪律:无条件系统层块,沿用 session 占位约定。
20765
- { content: PLATFORM_RISK_CONTROL_RULE, cacheScope: "session" },
20766
- { content: buildConsultationModeBlock(), cacheScope: "session" },
20767
- // Git 任务隔离:系统层固定前置,四条装配线同序(请教模式之后、身份信息之前;
20768
- // skill 配置 disabled 也注入)。
20769
- { content: WORKTREE_ISOLATION_PRELUDE, cacheScope: "session" },
21022
+ // 顶部固定平台层(唯一真源见 platformStaticPromptLayers.ts;localLoop 无 static 作用域,session 占位)。
21023
+ ...buildPlatformStaticScopedBlocks(),
20770
21024
  { content: identityBlock, cacheScope: "session" },
20771
21025
  ...guidanceScopes,
20772
21026
  // 回复行为准则:local 线(CLI 非交互 / 桌面 / TUI)的唯一注入边界。
@@ -20821,19 +21075,23 @@ async function runLocalAgentTurn(input) {
20821
21075
  summaryFallback: input.compactionSummaryFallback ?? readHostCompactionSummaryFallback(input.adapter),
20822
21076
  boundary: observationBoundary,
20823
21077
  getContextUsage: () => usageLedger.lastContextUsage(),
20824
- getCanonicalCompactionHistory: () => [
21078
+ getCanonicalCompactionHistory: () => orderDialogHistory([
20825
21079
  ...canonicalHistory,
20826
21080
  ...transcript.persisted(
20827
21081
  sanitizedPersistedInput,
20828
21082
  input.persistedInputReference
20829
- )
20830
- ],
21083
+ ).map((message) => {
21084
+ const receipt = message.cliMessageId;
21085
+ return receipt ? { ...message, id: receipt } : message;
21086
+ })
21087
+ ]),
20831
21088
  getWorkingPrefix: () => transcript.working().slice(0, prefixCount),
20832
21089
  onSelectedSummary: (summary) => {
20833
21090
  selectedSummary = summary;
20834
21091
  },
20835
21092
  replaceWorkingView: (next) => {
20836
21093
  transcript.replaceWorkingHistory(next);
21094
+ input.adapter.onWorkingHistoryReplaced?.();
20837
21095
  summaryProjectedPhase = contextPhase("summary-projected", next);
20838
21096
  },
20839
21097
  contextReferenceResolver: input.adapter.host === "cli" ? input.contextReferenceResolver : void 0,
@@ -20880,6 +21138,11 @@ async function runLocalAgentTurn(input) {
20880
21138
  })));
20881
21139
  messages.splice(currentInputStart, messages.length - currentInputStart, ...sanitizedUsers);
20882
21140
  }
21141
+ if (!input.userMessages?.length && input.adapter.host === "cli") {
21142
+ const userIndex = builtMessages.prefixCount + history.length;
21143
+ const id = dialogTurnUserMessageId(input.runtimeContext?.turnId, 0);
21144
+ if (id && messages[userIndex]?.role === "user") messages[userIndex] = { ...messages[userIndex], id };
21145
+ }
20883
21146
  const acceptToolImages = createToolImageLedger();
20884
21147
  const transcript = createTurnTranscript({
20885
21148
  initialWorking: messages,
@@ -20909,6 +21172,12 @@ async function runLocalAgentTurn(input) {
20909
21172
  let skipFinalAppend = false;
20910
21173
  let partialContent = "";
20911
21174
  const progressGuard = createLocalLoopProgressGuard(input.progressGuardConfig);
21175
+ const softBudgetAdvisor = createSubtaskSoftBudgetAdvisor({
21176
+ softBudget: input.softBudget,
21177
+ isSubtask: input.isSubtask,
21178
+ runKind: input.runKind,
21179
+ ...input.softBudgetEnv ? { env: input.softBudgetEnv } : {}
21180
+ });
20912
21181
  let pendingInjectionCommits = [];
20913
21182
  let inFlightTransactions = [];
20914
21183
  let rollbackInjectionCommits = async () => {
@@ -20929,7 +21198,8 @@ async function runLocalAgentTurn(input) {
20929
21198
  transcript.push({
20930
21199
  role: "user",
20931
21200
  content,
20932
- ...message.cliMessageId ? { cliMessageId: message.cliMessageId } : {}
21201
+ ...message.cliMessageId ? { cliMessageId: message.cliMessageId } : {},
21202
+ ...Number.isFinite(message.cliHistoryOrder) ? { cliHistoryOrder: message.cliHistoryOrder } : {}
20933
21203
  });
20934
21204
  }
20935
21205
  pendingInjectionCommits.push({ commit: entry.commit, rollback: entry.rollback, messages: entry.messages });
@@ -21029,7 +21299,7 @@ async function runLocalAgentTurn(input) {
21029
21299
  });
21030
21300
  imageDowngradeEmitted = true;
21031
21301
  }
21032
- const requestMessages = projectRequest(transcript.working());
21302
+ let requestMessages = projectRequest(transcript.working());
21033
21303
  if (requestOverBudget(requestMessages)) {
21034
21304
  const budget = evaluateLocalRequestBudget({
21035
21305
  messages: requestMessages,
@@ -21050,7 +21320,7 @@ async function runLocalAgentTurn(input) {
21050
21320
  }));
21051
21321
  }
21052
21322
  budgetTrimPhase = contextPhase("budget-trim", requestMessages, { droppedCount: 0 });
21053
- const contextMetrics = {
21323
+ let contextMetrics = {
21054
21324
  ...preparedMessages.metrics,
21055
21325
  messageCount: requestMessages.length,
21056
21326
  contentChars: requestMessages.reduce(
@@ -21072,8 +21342,8 @@ async function runLocalAgentTurn(input) {
21072
21342
  input.onToolEvent || input.onObservationEvent || input.observationBoundary
21073
21343
  );
21074
21344
  let llmStreamActivity = 0;
21075
- const callStartedAt = Date.now();
21076
- const requestTelemetry = buildRequestTelemetry({
21345
+ let callStartedAt = Date.now();
21346
+ let requestTelemetry = buildRequestTelemetry({
21077
21347
  // 无 dialogId 的新对话用本 turn 唯一键,避免不同新对话共用一个槽误报漂移。
21078
21348
  dialogKey: input.continueDialogId || newDialogTelemetryKey,
21079
21349
  messages: requestMessages,
@@ -21090,6 +21360,16 @@ async function runLocalAgentTurn(input) {
21090
21360
  inFlightTransactions = pendingInjectionCommits.splice(0);
21091
21361
  try {
21092
21362
  for (const transaction of inFlightTransactions) await transaction.commit();
21363
+ input.runtimeContext = { ...input.runtimeContext };
21364
+ delete input.runtimeContext.userMessageId;
21365
+ const admittedMessages = inFlightTransactions.flatMap((transaction) => transaction.messages);
21366
+ if (admittedMessages.length === 1 && admittedMessages[0]?.cliMessageId) {
21367
+ try {
21368
+ const id = await input.resolveInjectedUserMessageId?.(admittedMessages);
21369
+ if (id === admittedMessages[0].cliMessageId) input.runtimeContext.userMessageId = id;
21370
+ } catch {
21371
+ }
21372
+ }
21093
21373
  if (input.abortSignal?.aborted) throw buildAbortedError();
21094
21374
  } catch (error) {
21095
21375
  const toRollback = inFlightTransactions;
@@ -21102,83 +21382,148 @@ async function runLocalAgentTurn(input) {
21102
21382
  throw error;
21103
21383
  }
21104
21384
  }
21105
- let providerInvoked = false;
21106
- try {
21107
- result4 = await runCompleteWithTimeout({
21108
- provider: { complete: (messages2, options) => {
21109
- providerInvoked = true;
21110
- inFlightTransactions = [];
21111
- return provider.complete(messages2, options);
21112
- } },
21385
+ const tryOverflowRescueCompaction = async () => {
21386
+ const beforeTokens = estimateLocalRequestInput(requestMessages);
21387
+ const compacted = await compaction.prepareRequest((source) => {
21388
+ const projected = composeProviderMessages({
21389
+ prefix: transcript.working().slice(0, prefixCount),
21390
+ history: source,
21391
+ contextReferenceResolver: input.adapter.host === "cli" ? input.contextReferenceResolver : void 0
21392
+ });
21393
+ return requestOverBudget(projectRequest(projected.messages));
21394
+ }, false, availableHistoryTokens, true);
21395
+ if (!compacted) return false;
21396
+ const nextPrepared = prepareMessagesForProviderCall(transcript.working());
21397
+ const nextRequestMessages = projectRequest(transcript.working());
21398
+ const afterTokens = estimateLocalRequestInput(nextRequestMessages);
21399
+ if (afterTokens >= beforeTokens || requestOverBudget(nextRequestMessages)) return false;
21400
+ requestMessages = nextRequestMessages;
21401
+ contextMetrics = {
21402
+ ...nextPrepared.metrics,
21403
+ messageCount: requestMessages.length,
21404
+ contentChars: requestMessages.reduce(
21405
+ (total, message) => total + contentCharCount(message.content),
21406
+ 0
21407
+ ),
21408
+ stableContextChars: builtMessages.stableContextChars,
21409
+ dynamicContextChars: builtMessages.dynamicContextChars
21410
+ };
21411
+ callStartedAt = Date.now();
21412
+ requestTelemetry = buildRequestTelemetry({
21413
+ dialogKey: input.continueDialogId || newDialogTelemetryKey,
21113
21414
  messages: requestMessages,
21114
- options: {
21115
- timeoutMs: resolveLlmRequestTimeoutMs(input),
21116
- // 用户取消信号穿进 provider options:providerStreamRetry 据此在
21117
- // 取消后跳过重试,provider 分支(如 antigravity/openai-compatible)
21118
- // 也可把 fetch 绑定到同一信号,实现真正的传输层取消。
21119
- ...input.abortSignal ? { signal: input.abortSignal } : {},
21120
- // 计费归因:续聊轮次带上 dialogId,platform proxy 才能把 token 记录
21121
- // 归到具体对话而不是 chat-proxy 兜底桶。新对话首轮 id 尚未分配。
21122
- ...input.continueDialogId ? { dialogId: input.continueDialogId } : {},
21123
- ...shouldStreamDeltas ? { onTextDelta: (chunk) => {
21124
- llmStreamActivity += 1;
21125
- partialContent += chunk;
21126
- observationBoundary.emit({
21127
- kind: "text-delta",
21128
- chunk,
21129
- round,
21130
- atMs: Date.now()
21131
- });
21132
- } } : {},
21133
- ...shouldStreamReasoning ? { onReasoningDelta: (chunk) => {
21134
- llmStreamActivity += 1;
21135
- observationBoundary.emit({
21136
- kind: "reasoning-delta",
21137
- chunk,
21138
- round,
21139
- atMs: Date.now()
21140
- });
21141
- } } : {},
21142
- ...shouldPassToolEvents ? { onToolEvent: (event) => {
21143
- llmStreamActivity += 1;
21144
- observationBoundary.emit({
21145
- kind: "tool-event",
21146
- event,
21147
- round,
21148
- atMs: Date.now()
21149
- });
21150
- } } : {},
21151
- ...shouldPassToolEvents ? { toolEventRound: round } : {}
21415
+ provenance: {
21416
+ schemaVersion: 1,
21417
+ transport: provider.transport ?? "unknown",
21418
+ phases: [historyLoadedPhase, summaryProjectedPhase, budgetTrimPhase, contextPhase("final-request", requestMessages)],
21419
+ summary: selectedSummary
21152
21420
  },
21153
- timeoutMs: resolveLlmRequestTimeoutMs(input),
21154
- activityVersion: () => llmStreamActivity,
21155
- round,
21156
- input,
21157
- boundary: observationBoundary,
21158
- context: contextMetrics,
21159
- providerName: agentConfig.provider,
21160
- model: provider.model
21421
+ toolsHash: safeToolNamesHash(agentTools)
21161
21422
  });
21162
- } catch (error) {
21163
- if (!providerInvoked && inFlightTransactions.length > 0) {
21164
- const toRollback = inFlightTransactions;
21165
- inFlightTransactions = [];
21166
- try {
21167
- await rollbackInjectionCommits(toRollback);
21168
- } catch (rbErr) {
21169
- error = combineRollbackError(error, rbErr);
21423
+ resetToolImageDelivery(requestMessages.flatMap(toolImages));
21424
+ return true;
21425
+ };
21426
+ let overflowRescueAttempted = false;
21427
+ while (true) {
21428
+ llmStreamActivity = 0;
21429
+ partialContent = "";
21430
+ let providerInvoked = false;
21431
+ try {
21432
+ result4 = await runCompleteWithTimeout({
21433
+ provider: { complete: (messages2, options) => {
21434
+ providerInvoked = true;
21435
+ inFlightTransactions = [];
21436
+ return provider.complete(messages2, options);
21437
+ } },
21438
+ messages: requestMessages,
21439
+ options: {
21440
+ timeoutMs: resolveLlmRequestTimeoutMs(input),
21441
+ // 用户取消信号穿进 provider options:providerStreamRetry 据此在
21442
+ // 取消后跳过重试,provider 分支(如 antigravity/openai-compatible)
21443
+ // 也可把 fetch 绑定到同一信号,实现真正的传输层取消。
21444
+ ...input.abortSignal ? { signal: input.abortSignal } : {},
21445
+ // 计费归因:续聊轮次带上 dialogId,platform proxy 才能把 token 记录
21446
+ // 归到具体对话而不是 chat-proxy 兜底桶。新对话首轮 id 尚未分配。
21447
+ ...input.continueDialogId ? { dialogId: input.continueDialogId } : {},
21448
+ ...shouldStreamDeltas ? { onTextDelta: (chunk) => {
21449
+ llmStreamActivity += 1;
21450
+ partialContent += chunk;
21451
+ observationBoundary.emit({
21452
+ kind: "text-delta",
21453
+ chunk,
21454
+ round,
21455
+ atMs: Date.now()
21456
+ });
21457
+ } } : {},
21458
+ ...shouldStreamReasoning ? { onReasoningDelta: (chunk) => {
21459
+ llmStreamActivity += 1;
21460
+ observationBoundary.emit({
21461
+ kind: "reasoning-delta",
21462
+ chunk,
21463
+ round,
21464
+ atMs: Date.now()
21465
+ });
21466
+ } } : {},
21467
+ ...shouldPassToolEvents ? { onToolEvent: (event) => {
21468
+ llmStreamActivity += 1;
21469
+ observationBoundary.emit({
21470
+ kind: "tool-event",
21471
+ event,
21472
+ round,
21473
+ atMs: Date.now()
21474
+ });
21475
+ } } : {},
21476
+ ...shouldPassToolEvents ? { toolEventRound: round } : {}
21477
+ },
21478
+ timeoutMs: resolveLlmRequestTimeoutMs(input),
21479
+ activityVersion: () => llmStreamActivity,
21480
+ round,
21481
+ input,
21482
+ boundary: observationBoundary,
21483
+ context: contextMetrics,
21484
+ providerName: agentConfig.provider,
21485
+ model: provider.model
21486
+ });
21487
+ } catch (error) {
21488
+ if (!providerInvoked && inFlightTransactions.length > 0) {
21489
+ const toRollback = inFlightTransactions;
21490
+ inFlightTransactions = [];
21491
+ try {
21492
+ await rollbackInjectionCommits(toRollback);
21493
+ } catch (rbErr) {
21494
+ error = combineRollbackError(error, rbErr);
21495
+ }
21496
+ }
21497
+ if (providerInvoked) usageLedger.recordProviderCall({
21498
+ model: agentConfig.model,
21499
+ telemetry: {
21500
+ ...requestTelemetry,
21501
+ round,
21502
+ endTs: Date.now(),
21503
+ requestState: input.abortSignal?.aborted ? "cancelled" : "failed"
21504
+ }
21505
+ });
21506
+ if (providerInvoked && !overflowRescueAttempted && llmStreamActivity === 0 && !input.abortSignal?.aborted && isContextOverflowText(toErrorMessage(error))) {
21507
+ overflowRescueAttempted = true;
21508
+ if (await tryOverflowRescueCompaction()) {
21509
+ continue;
21510
+ }
21170
21511
  }
21512
+ throw error;
21171
21513
  }
21172
- if (providerInvoked) usageLedger.recordProviderCall({
21173
- model: agentConfig.model,
21174
- telemetry: {
21175
- ...requestTelemetry,
21176
- round,
21177
- endTs: Date.now(),
21178
- requestState: input.abortSignal?.aborted ? "cancelled" : "failed"
21514
+ if ((result4.error || result4.runtimeProviderFailure) && !overflowRescueAttempted && llmStreamActivity === 0 && !input.abortSignal?.aborted && isContextOverflowText(result4.runtimeProviderFailure?.message ?? result4.errorMessage ?? "")) {
21515
+ overflowRescueAttempted = true;
21516
+ usageLedger.recordProviderCall({
21517
+ usage: result4.usage,
21518
+ model: result4.model ?? agentConfig.model,
21519
+ provider: result4.provider,
21520
+ telemetry: { ...finalizeCallTelemetry(requestTelemetry, result4, round, callStartedAt), requestState: "failed" }
21521
+ });
21522
+ if (await tryOverflowRescueCompaction()) {
21523
+ continue;
21179
21524
  }
21180
- });
21181
- throw error;
21525
+ }
21526
+ break;
21182
21527
  }
21183
21528
  acceptToolImages.discard(requestMessages.flatMap(toolImages).filter((image) => toolImageDelivery(image) === "impossible"));
21184
21529
  acceptToolImages.commit(
@@ -21474,6 +21819,15 @@ ${reasoningTailLog}
21474
21819
  };
21475
21820
  break;
21476
21821
  }
21822
+ if (!input.abortSignal?.aborted) {
21823
+ const softBudgetAdvisory = softBudgetAdvisor.observeToolCalls(toolCallCount);
21824
+ if (softBudgetAdvisory) {
21825
+ transcript.push({
21826
+ role: "user",
21827
+ content: softBudgetAdvisory.message
21828
+ });
21829
+ }
21830
+ }
21477
21831
  loopTiming.mark("roundEnd", round);
21478
21832
  round += 1;
21479
21833
  }
@@ -21525,12 +21879,6 @@ ${reasoningTailLog}
21525
21879
  ...result4,
21526
21880
  stopReason: input.abortSignal?.aborted ? "aborted" : result4.error || result4.runtimeProviderFailure || result4.emptyAssistantFallbackReason ? "error" : stopReason
21527
21881
  };
21528
- delete result4.businessCompletion;
21529
- const businessCompletion = evaluateTaskExecutionContract(input.taskExecutionContract, {
21530
- stopped: input.abortSignal?.aborted,
21531
- executionFailed: result4.error === true || !!result4.runtimeProviderFailure || !!result4.emptyAssistantFallbackReason
21532
- });
21533
- if (businessCompletion) result4.businessCompletion = businessCompletion;
21534
21882
  if (!skipFinalAppend) {
21535
21883
  const truncatedReasoningTailLog = resolveTruncatedReasoningTailLog(
21536
21884
  result4.emptyAssistantFallbackReason,
@@ -22535,756 +22883,6 @@ async function resolveOpenAiCompatibleProviderConfig(args2) {
22535
22883
  };
22536
22884
  }
22537
22885
 
22538
- // packages/agent-runtime/macOsKeychainCredentialBroker.ts
22539
- import { spawn as spawn2 } from "node:child_process";
22540
- var MACOS_KEYCHAIN_SERVICE_PREFIX = "nolo.credentials.keys";
22541
- var MACOS_KEYCHAIN_ACCOUNT = "api-key";
22542
- var SECURITY_ITEM_NOT_FOUND_EXIT = 44;
22543
- var DEFAULT_SECURITY_BIN = "/usr/bin/security";
22544
- function safeCredentialRef(ref) {
22545
- try {
22546
- return assertCredentialRef(ref);
22547
- } catch {
22548
- throw new Error("invalid_ref");
22549
- }
22550
- }
22551
- function credentialRefToMacOsKeychainService(ref, servicePrefix = MACOS_KEYCHAIN_SERVICE_PREFIX) {
22552
- const safe = safeCredentialRef(ref);
22553
- const hex = Buffer.from(safe, "utf8").toString("hex");
22554
- if (!hex) {
22555
- throw new Error("invalid_ref");
22556
- }
22557
- return `${servicePrefix}.${hex}`;
22558
- }
22559
- function rethrowBrokerError(op, _error) {
22560
- throw new Error(`credential_broker_${op}_failed`);
22561
- }
22562
- function createDefaultSecurityRunner(securityBin = DEFAULT_SECURITY_BIN) {
22563
- return function defaultSecurityRunner(input) {
22564
- return new Promise((resolve6) => {
22565
- let settled = false;
22566
- const finish = (result4) => {
22567
- if (settled) return;
22568
- settled = true;
22569
- resolve6(result4);
22570
- };
22571
- let child;
22572
- try {
22573
- child = spawn2(securityBin, input.args, {
22574
- stdio: ["pipe", "pipe", "pipe"]
22575
- });
22576
- } catch {
22577
- finish({ exitCode: -1, stdout: "", stderr: "" });
22578
- return;
22579
- }
22580
- let stdout = "";
22581
- let stderr = "";
22582
- child.stdout?.setEncoding("utf8");
22583
- child.stderr?.setEncoding("utf8");
22584
- child.stdout?.on("data", (chunk) => {
22585
- stdout += chunk;
22586
- });
22587
- child.stderr?.on("data", (chunk) => {
22588
- stderr += chunk;
22589
- });
22590
- child.on("error", () => {
22591
- finish({ exitCode: -1, stdout: "", stderr: "" });
22592
- });
22593
- child.on("close", (code) => {
22594
- finish({
22595
- exitCode: typeof code === "number" ? code : -1,
22596
- stdout,
22597
- stderr
22598
- });
22599
- });
22600
- if (input.stdin !== void 0) {
22601
- child.stdin?.write(input.stdin);
22602
- }
22603
- child.stdin?.end();
22604
- });
22605
- };
22606
- }
22607
- function createMacOsKeychainCredentialBroker(options = {}) {
22608
- const runner = options.runner ?? createDefaultSecurityRunner(options.securityBin);
22609
- const servicePrefix = options.servicePrefix ?? MACOS_KEYCHAIN_SERVICE_PREFIX;
22610
- const account = options.account ?? MACOS_KEYCHAIN_ACCOUNT;
22611
- const serviceFor = (ref) => credentialRefToMacOsKeychainService(ref, servicePrefix);
22612
- return {
22613
- async get(ref) {
22614
- const safeRef = safeCredentialRef(ref);
22615
- const service4 = serviceFor(safeRef);
22616
- let result4;
22617
- try {
22618
- result4 = await runner({
22619
- args: [
22620
- "find-generic-password",
22621
- "-a",
22622
- account,
22623
- "-s",
22624
- service4,
22625
- "-w"
22626
- ]
22627
- });
22628
- } catch (error) {
22629
- rethrowBrokerError("get", error);
22630
- }
22631
- if (result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22632
- return null;
22633
- }
22634
- if (result4.exitCode !== 0) {
22635
- rethrowBrokerError("get");
22636
- }
22637
- const secret = result4.stdout.replace(/\n$/, "");
22638
- return secret.length > 0 ? secret : null;
22639
- },
22640
- async put(ref, secret) {
22641
- const safeRef = safeCredentialRef(ref);
22642
- const value = asTrimmedString(secret);
22643
- if (!value) {
22644
- throw new Error("Cannot store an empty credential secret.");
22645
- }
22646
- const service4 = serviceFor(safeRef);
22647
- const stdin = `${value}
22648
- ${value}
22649
- `;
22650
- let result4;
22651
- try {
22652
- result4 = await runner({
22653
- args: [
22654
- "add-generic-password",
22655
- "-a",
22656
- account,
22657
- "-s",
22658
- service4,
22659
- "-U",
22660
- "-w"
22661
- ],
22662
- stdin
22663
- });
22664
- } catch (error) {
22665
- rethrowBrokerError("put", error);
22666
- }
22667
- if (result4.exitCode !== 0) {
22668
- rethrowBrokerError("put");
22669
- }
22670
- },
22671
- async delete(ref) {
22672
- const safeRef = safeCredentialRef(ref);
22673
- const service4 = serviceFor(safeRef);
22674
- let result4;
22675
- try {
22676
- result4 = await runner({
22677
- args: [
22678
- "delete-generic-password",
22679
- "-a",
22680
- account,
22681
- "-s",
22682
- service4
22683
- ]
22684
- });
22685
- } catch (error) {
22686
- rethrowBrokerError("delete", error);
22687
- }
22688
- if (result4.exitCode === 0 || result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22689
- return;
22690
- }
22691
- rethrowBrokerError("delete");
22692
- },
22693
- async has(ref) {
22694
- const safeRef = safeCredentialRef(ref);
22695
- const service4 = serviceFor(safeRef);
22696
- let result4;
22697
- try {
22698
- result4 = await runner({
22699
- args: [
22700
- "find-generic-password",
22701
- "-a",
22702
- account,
22703
- "-s",
22704
- service4
22705
- ]
22706
- });
22707
- } catch (error) {
22708
- rethrowBrokerError("has", error);
22709
- }
22710
- if (result4.exitCode === SECURITY_ITEM_NOT_FOUND_EXIT) {
22711
- return false;
22712
- }
22713
- if (result4.exitCode !== 0) {
22714
- rethrowBrokerError("has");
22715
- }
22716
- return true;
22717
- }
22718
- };
22719
- }
22720
-
22721
- // packages/agent-runtime/windowsCredentialManagerBroker.ts
22722
- import { spawn as spawn3 } from "node:child_process";
22723
- var WINDOWS_CREDENTIAL_TARGET_PREFIX = "nolo.credentials.keys";
22724
- var WIN_ERROR_NOT_FOUND = 1168;
22725
- var WINDOWS_CREDENTIAL_MANAGER_SCRIPT = `
22726
- $ErrorActionPreference = 'Stop'
22727
- try {
22728
- $raw = [Console]::In.ReadToEnd()
22729
- if ([string]::IsNullOrWhiteSpace($raw)) { exit 1 }
22730
- $req = $raw | ConvertFrom-Json
22731
- $op = [string]$req.op
22732
- $target = [string]$req.target
22733
- if ([string]::IsNullOrWhiteSpace($op) -or [string]::IsNullOrWhiteSpace($target)) { exit 1 }
22734
-
22735
- Add-Type @"
22736
- using System;
22737
- using System.Runtime.InteropServices;
22738
- using System.Text;
22739
-
22740
- public class NoloCredNative {
22741
- public const int CRED_TYPE_GENERIC = 1;
22742
- public const int CRED_PERSIST_LOCAL_MACHINE = 2;
22743
- public const int ERROR_NOT_FOUND = 1168;
22744
-
22745
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
22746
- public struct CREDENTIAL {
22747
- public int Flags;
22748
- public int Type;
22749
- public string TargetName;
22750
- public string Comment;
22751
- public long LastWritten;
22752
- public int CredentialBlobSize;
22753
- public IntPtr CredentialBlob;
22754
- public int Persist;
22755
- public int AttributeCount;
22756
- public IntPtr Attributes;
22757
- public string TargetAlias;
22758
- public string UserName;
22759
- }
22760
-
22761
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22762
- public static extern bool CredWriteW(ref CREDENTIAL userCredential, uint flags);
22763
-
22764
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22765
- public static extern bool CredReadW(string target, int type, int reservedFlag, out IntPtr credentialPtr);
22766
-
22767
- [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
22768
- public static extern bool CredDeleteW(string target, int type, int flags);
22769
-
22770
- [DllImport("advapi32.dll", SetLastError = true)]
22771
- public static extern void CredFree(IntPtr buffer);
22772
- }
22773
- "@
22774
-
22775
- if ($op -eq 'get') {
22776
- $ptr = [IntPtr]::Zero
22777
- $ok = [NoloCredNative]::CredReadW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0, [ref]$ptr)
22778
- if (-not $ok) {
22779
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22780
- }
22781
- try {
22782
- $cred = [Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [type][NoloCredNative+CREDENTIAL])
22783
- if ($cred.CredentialBlobSize -le 0 -or $cred.CredentialBlob -eq [IntPtr]::Zero) {
22784
- $payload = @{ secret = '' } | ConvertTo-Json -Compress
22785
- [Console]::Out.Write($payload)
22786
- exit 0
22787
- }
22788
- $bytes = New-Object byte[] $cred.CredentialBlobSize
22789
- [Runtime.InteropServices.Marshal]::Copy($cred.CredentialBlob, $bytes, 0, $cred.CredentialBlobSize)
22790
- $secret = [Text.Encoding]::UTF8.GetString($bytes)
22791
- $payload = @{ secret = $secret } | ConvertTo-Json -Compress
22792
- [Console]::Out.Write($payload)
22793
- exit 0
22794
- } finally {
22795
- [NoloCredNative]::CredFree($ptr)
22796
- }
22797
- }
22798
-
22799
- if ($op -eq 'has') {
22800
- $ptr = [IntPtr]::Zero
22801
- $ok = [NoloCredNative]::CredReadW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0, [ref]$ptr)
22802
- if (-not $ok) {
22803
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22804
- }
22805
- [NoloCredNative]::CredFree($ptr)
22806
- exit 0
22807
- }
22808
-
22809
- if ($op -eq 'put') {
22810
- $secret = [string]$req.secret
22811
- if ([string]::IsNullOrEmpty($secret)) { exit 1 }
22812
- $blob = [Text.Encoding]::UTF8.GetBytes($secret)
22813
- $cred = New-Object NoloCredNative+CREDENTIAL
22814
- $cred.Type = [NoloCredNative]::CRED_TYPE_GENERIC
22815
- $cred.TargetName = $target
22816
- $cred.UserName = 'api-key'
22817
- $cred.Persist = [NoloCredNative]::CRED_PERSIST_LOCAL_MACHINE
22818
- $cred.CredentialBlobSize = $blob.Length
22819
- $cred.CredentialBlob = [Runtime.InteropServices.Marshal]::AllocHGlobal($blob.Length)
22820
- try {
22821
- if ($blob.Length -gt 0) {
22822
- [Runtime.InteropServices.Marshal]::Copy($blob, 0, $cred.CredentialBlob, $blob.Length)
22823
- }
22824
- $ok = [NoloCredNative]::CredWriteW([ref]$cred, 0)
22825
- if (-not $ok) {
22826
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22827
- }
22828
- exit 0
22829
- } finally {
22830
- [Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
22831
- }
22832
- }
22833
-
22834
- if ($op -eq 'delete') {
22835
- $ok = [NoloCredNative]::CredDeleteW($target, [NoloCredNative]::CRED_TYPE_GENERIC, 0)
22836
- if (-not $ok) {
22837
- exit [Runtime.InteropServices.Marshal]::GetLastWin32Error()
22838
- }
22839
- exit 0
22840
- }
22841
-
22842
- exit 1
22843
- } catch {
22844
- exit 1
22845
- }
22846
- `.trim();
22847
- function safeCredentialRef2(ref) {
22848
- try {
22849
- return assertCredentialRef(ref);
22850
- } catch {
22851
- throw new Error("invalid_ref");
22852
- }
22853
- }
22854
- function credentialRefToWindowsCredentialTarget(ref, targetPrefix = WINDOWS_CREDENTIAL_TARGET_PREFIX) {
22855
- const safe = safeCredentialRef2(ref);
22856
- const hex = Buffer.from(safe, "utf8").toString("hex");
22857
- if (!hex) {
22858
- throw new Error("invalid_ref");
22859
- }
22860
- return `${targetPrefix}.${hex}`;
22861
- }
22862
- function rethrowBrokerError2(op, _error) {
22863
- throw new Error(`credential_broker_${op}_failed`);
22864
- }
22865
- function buildWindowsCredentialPowerShellArgs(script = WINDOWS_CREDENTIAL_MANAGER_SCRIPT) {
22866
- const encoded = Buffer.from(script, "utf16le").toString("base64");
22867
- return [
22868
- "-NoProfile",
22869
- "-NonInteractive",
22870
- "-ExecutionPolicy",
22871
- "Bypass",
22872
- "-EncodedCommand",
22873
- encoded
22874
- ];
22875
- }
22876
- function requestStdin(payload) {
22877
- return JSON.stringify(payload);
22878
- }
22879
- function parseGetSecretFromStdout(stdout) {
22880
- const trimmed = asTrimmedString(stdout);
22881
- if (!trimmed) {
22882
- rethrowBrokerError2("get");
22883
- }
22884
- let parsed;
22885
- try {
22886
- parsed = JSON.parse(trimmed);
22887
- } catch {
22888
- rethrowBrokerError2("get");
22889
- }
22890
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || typeof parsed.secret !== "string") {
22891
- rethrowBrokerError2("get");
22892
- }
22893
- return parsed.secret;
22894
- }
22895
- function spawnShell(bin, args2, stdin) {
22896
- return new Promise((resolve6) => {
22897
- let settled = false;
22898
- const finish = (result4) => {
22899
- if (settled) return;
22900
- settled = true;
22901
- resolve6(result4);
22902
- };
22903
- let child;
22904
- try {
22905
- child = spawn3(bin, args2, {
22906
- stdio: ["pipe", "pipe", "pipe"],
22907
- windowsHide: true
22908
- });
22909
- } catch {
22910
- finish({ exitCode: -1, stdout: "", stderr: "" });
22911
- return;
22912
- }
22913
- let stdout = "";
22914
- let stderr = "";
22915
- child.stdout?.setEncoding("utf8");
22916
- child.stderr?.setEncoding("utf8");
22917
- child.stdout?.on("data", (chunk) => {
22918
- stdout += chunk;
22919
- });
22920
- child.stderr?.on("data", (chunk) => {
22921
- stderr += chunk;
22922
- });
22923
- child.on("error", () => {
22924
- finish({ exitCode: -1, stdout: "", stderr: "" });
22925
- });
22926
- child.on("close", (code) => {
22927
- finish({
22928
- exitCode: typeof code === "number" ? code : -1,
22929
- stdout,
22930
- stderr
22931
- });
22932
- });
22933
- if (stdin !== void 0) {
22934
- child.stdin?.write(stdin);
22935
- }
22936
- child.stdin?.end();
22937
- });
22938
- }
22939
- function createDefaultWindowsCredentialRunner(shellBin) {
22940
- let resolvedBin = shellBin ?? null;
22941
- return async function defaultWindowsCredentialRunner(input) {
22942
- if (resolvedBin) {
22943
- return spawnShell(resolvedBin, input.args, input.stdin);
22944
- }
22945
- const first = await spawnShell("powershell.exe", input.args, input.stdin);
22946
- if (first.exitCode !== -1) {
22947
- resolvedBin = "powershell.exe";
22948
- return first;
22949
- }
22950
- const second = await spawnShell("pwsh", input.args, input.stdin);
22951
- if (second.exitCode !== -1) {
22952
- resolvedBin = "pwsh";
22953
- }
22954
- return second;
22955
- };
22956
- }
22957
- function createWindowsCredentialManagerBroker(options = {}) {
22958
- const runner = options.runner ?? createDefaultWindowsCredentialRunner(options.shellBin);
22959
- const targetPrefix = options.targetPrefix ?? WINDOWS_CREDENTIAL_TARGET_PREFIX;
22960
- const targetFor = (ref) => credentialRefToWindowsCredentialTarget(ref, targetPrefix);
22961
- const staticArgs = buildWindowsCredentialPowerShellArgs();
22962
- return {
22963
- async get(ref) {
22964
- const safeRef = safeCredentialRef2(ref);
22965
- const target = targetFor(safeRef);
22966
- let result4;
22967
- try {
22968
- result4 = await runner({
22969
- args: staticArgs,
22970
- stdin: requestStdin({ op: "get", target })
22971
- });
22972
- } catch (error) {
22973
- rethrowBrokerError2("get", error);
22974
- }
22975
- if (result4.exitCode === WIN_ERROR_NOT_FOUND) {
22976
- return null;
22977
- }
22978
- if (result4.exitCode !== 0) {
22979
- rethrowBrokerError2("get");
22980
- }
22981
- const secret = parseGetSecretFromStdout(result4.stdout);
22982
- return secret.length > 0 ? secret : null;
22983
- },
22984
- async put(ref, secret) {
22985
- const safeRef = safeCredentialRef2(ref);
22986
- const value = asTrimmedString(secret);
22987
- if (!value) {
22988
- throw new Error("Cannot store an empty credential secret.");
22989
- }
22990
- const target = targetFor(safeRef);
22991
- let result4;
22992
- try {
22993
- result4 = await runner({
22994
- args: staticArgs,
22995
- stdin: requestStdin({ op: "put", target, secret: value })
22996
- });
22997
- } catch (error) {
22998
- rethrowBrokerError2("put", error);
22999
- }
23000
- if (result4.exitCode !== 0) {
23001
- rethrowBrokerError2("put");
23002
- }
23003
- },
23004
- async delete(ref) {
23005
- const safeRef = safeCredentialRef2(ref);
23006
- const target = targetFor(safeRef);
23007
- let result4;
23008
- try {
23009
- result4 = await runner({
23010
- args: staticArgs,
23011
- stdin: requestStdin({ op: "delete", target })
23012
- });
23013
- } catch (error) {
23014
- rethrowBrokerError2("delete", error);
23015
- }
23016
- if (result4.exitCode === 0 || result4.exitCode === WIN_ERROR_NOT_FOUND) {
23017
- return;
23018
- }
23019
- rethrowBrokerError2("delete");
23020
- },
23021
- async has(ref) {
23022
- const safeRef = safeCredentialRef2(ref);
23023
- const target = targetFor(safeRef);
23024
- let result4;
23025
- try {
23026
- result4 = await runner({
23027
- args: staticArgs,
23028
- stdin: requestStdin({ op: "has", target })
23029
- });
23030
- } catch (error) {
23031
- rethrowBrokerError2("has", error);
23032
- }
23033
- if (result4.exitCode === WIN_ERROR_NOT_FOUND) {
23034
- return false;
23035
- }
23036
- if (result4.exitCode !== 0) {
23037
- rethrowBrokerError2("has");
23038
- }
23039
- return true;
23040
- }
23041
- };
23042
- }
23043
-
23044
- // packages/agent-runtime/linuxSecretServiceCredentialBroker.ts
23045
- import { spawn as spawn4 } from "node:child_process";
23046
- var LINUX_SECRET_SERVICE_ATTRIBUTE = "nolo-credential";
23047
- var SECRET_TOOL_NO_MATCH_EXIT = 1;
23048
- var DEFAULT_SECRET_TOOL_BIN = "secret-tool";
23049
- function safeCredentialRef3(ref) {
23050
- try {
23051
- return assertCredentialRef(ref);
23052
- } catch {
23053
- throw new Error("invalid_ref");
23054
- }
23055
- }
23056
- function brokerFailure(op) {
23057
- throw new Error(`credential_broker_${op}_failed`);
23058
- }
23059
- function createDefaultSecretToolRunner(secretToolBin = DEFAULT_SECRET_TOOL_BIN) {
23060
- return (input) => new Promise((resolve6) => {
23061
- let stdout = "";
23062
- let stderr = "";
23063
- let settled = false;
23064
- const finish = (result4) => {
23065
- if (settled) return;
23066
- settled = true;
23067
- resolve6(result4);
23068
- };
23069
- let child;
23070
- try {
23071
- child = spawn4(secretToolBin, input.args, {
23072
- stdio: ["pipe", "pipe", "pipe"]
23073
- });
23074
- } catch {
23075
- finish({ exitCode: -1, stdout: "", stderr: "" });
23076
- return;
23077
- }
23078
- child.stdout?.on("data", (chunk) => {
23079
- stdout += chunk;
23080
- });
23081
- child.stderr?.on("data", (chunk) => {
23082
- stderr += chunk;
23083
- });
23084
- child.on("error", () => {
23085
- finish({ exitCode: -1, stdout: "", stderr: "" });
23086
- });
23087
- child.on("close", (code) => {
23088
- finish({
23089
- exitCode: typeof code === "number" ? code : -1,
23090
- stdout,
23091
- stderr
23092
- });
23093
- });
23094
- if (input.stdin !== void 0) {
23095
- child.stdin?.write(input.stdin);
23096
- }
23097
- child.stdin?.end();
23098
- });
23099
- }
23100
- function createLinuxSecretServiceCredentialBroker(options = {}) {
23101
- const runner = options.runner ?? createDefaultSecretToolRunner(options.secretToolBin);
23102
- const attribute = options.attribute ?? LINUX_SECRET_SERVICE_ATTRIBUTE;
23103
- const attrArgs = (ref) => [attribute, ref];
23104
- const lookup3 = async (ref) => {
23105
- try {
23106
- return await runner({ args: ["lookup", ...attrArgs(ref)] });
23107
- } catch {
23108
- brokerFailure("get");
23109
- }
23110
- };
23111
- return {
23112
- async get(ref) {
23113
- const safeRef = safeCredentialRef3(ref);
23114
- const result4 = await lookup3(safeRef);
23115
- if (result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) return null;
23116
- if (result4.exitCode !== 0) brokerFailure("get");
23117
- const secret = result4.stdout.replace(/\n$/, "");
23118
- return secret.length > 0 ? secret : null;
23119
- },
23120
- async put(ref, secret) {
23121
- const safeRef = safeCredentialRef3(ref);
23122
- const value = asTrimmedString(secret);
23123
- if (!value) {
23124
- throw new Error("Cannot store an empty credential secret.");
23125
- }
23126
- const args2 = [
23127
- "store",
23128
- `--label=nolo-credential:${safeRef}`,
23129
- ...attrArgs(safeRef)
23130
- ];
23131
- if (value.includes("\n") || args2.some((arg) => arg.includes(value))) {
23132
- brokerFailure("put");
23133
- }
23134
- let result4;
23135
- try {
23136
- result4 = await runner({ args: args2, stdin: value });
23137
- } catch {
23138
- brokerFailure("put");
23139
- }
23140
- if (result4.exitCode !== 0) brokerFailure("put");
23141
- },
23142
- async delete(ref) {
23143
- const safeRef = safeCredentialRef3(ref);
23144
- let result4;
23145
- try {
23146
- result4 = await runner({ args: ["clear", ...attrArgs(safeRef)] });
23147
- } catch {
23148
- brokerFailure("delete");
23149
- }
23150
- if (result4.exitCode === 0 || result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) {
23151
- return;
23152
- }
23153
- brokerFailure("delete");
23154
- },
23155
- async has(ref) {
23156
- const safeRef = safeCredentialRef3(ref);
23157
- const result4 = await lookup3(safeRef);
23158
- if (result4.exitCode === SECRET_TOOL_NO_MATCH_EXIT) return false;
23159
- if (result4.exitCode !== 0) brokerFailure("has");
23160
- return true;
23161
- }
23162
- };
23163
- }
23164
-
23165
- // packages/agent-runtime/desktopHostCredentialBroker.ts
23166
- function createClosedCredentialBroker(code = "credential_store_unavailable") {
23167
- const fail9 = () => {
23168
- throw new Error(code);
23169
- };
23170
- return {
23171
- get: fail9,
23172
- put: fail9,
23173
- delete: fail9,
23174
- has: () => false
23175
- };
23176
- }
23177
- function createHostCredentialBrokerChain(args2) {
23178
- const { strict, session, legacy, notifySessionFallback, notifyLegacyHit } = args2;
23179
- const legacyNoticed = /* @__PURE__ */ new Set();
23180
- let sessionNotified = false;
23181
- const noticeSession = () => {
23182
- if (sessionNotified || !notifySessionFallback) return;
23183
- sessionNotified = true;
23184
- try {
23185
- notifySessionFallback();
23186
- } catch {
23187
- }
23188
- };
23189
- return {
23190
- async get(ref) {
23191
- try {
23192
- const strictValue = await strict.get(ref);
23193
- if (strictValue !== null && strictValue !== void 0) return strictValue;
23194
- } catch {
23195
- }
23196
- const sessionValue = await session.get(ref);
23197
- if (sessionValue !== null && sessionValue !== void 0) return sessionValue;
23198
- if (!legacy) return null;
23199
- const legacyValue = await legacy.get(ref);
23200
- if (legacyValue !== null && legacyValue !== void 0) {
23201
- if (notifyLegacyHit && !legacyNoticed.has(ref)) {
23202
- legacyNoticed.add(ref);
23203
- try {
23204
- notifyLegacyHit(ref);
23205
- } catch {
23206
- }
23207
- }
23208
- return legacyValue;
23209
- }
23210
- return null;
23211
- },
23212
- async put(ref, secret) {
23213
- try {
23214
- await strict.put(ref, secret);
23215
- if (await strict.has(ref)) return;
23216
- } catch {
23217
- }
23218
- await session.put(ref, secret);
23219
- noticeSession();
23220
- },
23221
- async delete(ref) {
23222
- try {
23223
- await strict.delete(ref);
23224
- } catch {
23225
- }
23226
- try {
23227
- await session.delete(ref);
23228
- } catch {
23229
- }
23230
- if (legacy) await legacy.delete(ref);
23231
- },
23232
- async has(ref) {
23233
- try {
23234
- if (await strict.has(ref)) return true;
23235
- } catch {
23236
- }
23237
- if (await session.has(ref)) return true;
23238
- return legacy ? await legacy.has(ref) : false;
23239
- }
23240
- };
23241
- }
23242
- function createStrictHostCredentialBroker(options = {}) {
23243
- const platform = options.platform ?? process.platform;
23244
- const env = options.env ?? process.env;
23245
- const override = String(env.NOLO_DESKTOP_CREDENTIAL_STORE ?? "").trim().toLowerCase();
23246
- if (override === "file") {
23247
- return createClosedCredentialBroker("credential_store_file_not_allowed");
23248
- }
23249
- if (platform === "darwin" || override === "keychain") {
23250
- return options.keychainBroker ?? (options.createKeychainBroker ?? (() => createMacOsKeychainCredentialBroker()))();
23251
- }
23252
- if (platform === "win32" || override === "credman") {
23253
- return options.windowsCredentialBroker ?? (options.createWindowsCredentialBroker ?? (() => createWindowsCredentialManagerBroker()))();
23254
- }
23255
- if (platform === "linux" || override === "secret-service") {
23256
- return options.linuxSecretServiceBroker ?? (options.createLinuxSecretServiceBroker ?? (() => createLinuxSecretServiceCredentialBroker()))();
23257
- }
23258
- return createClosedCredentialBroker("credential_store_unsupported");
23259
- }
23260
-
23261
- // packages/agent-runtime/dialogMessageRecord.ts
23262
- function dialogMessageRecordToAgentRuntimeMessage(record2) {
23263
- if (!record2 || typeof record2 !== "object") return null;
23264
- if (record2.role !== "user" && record2.role !== "assistant" && record2.role !== "tool") return null;
23265
- return {
23266
- ...typeof record2.id === "string" ? { id: record2.id } : {},
23267
- role: record2.role,
23268
- content: record2.content ?? "",
23269
- ...record2.contextReference !== void 0 ? { context_reference: record2.contextReference } : {},
23270
- ...typeof record2.reasoning_content === "string" ? { reasoning_content: record2.reasoning_content } : {},
23271
- ...typeof record2.toolCallId === "string" ? { tool_call_id: record2.toolCallId } : {},
23272
- ...Array.isArray(record2.tool_calls) ? { tool_calls: record2.tool_calls } : {},
23273
- ...record2.toolPayload !== void 0 ? { toolPayload: record2.toolPayload } : {},
23274
- ...typeof record2.toolName === "string" ? { toolName: record2.toolName } : {},
23275
- // 写侧(dialogWritePlan)把 tool_result_metadata 以 `metadata` 字段落库;
23276
- // 回读必须还原,否则跨 turn 投影丢失 metadata 后缀,同一 tool 消息的字节
23277
- // 在 turn 边界漂移 → provider 前缀缓存断裂(stable projection 契约,
23278
- // 见 docs/plans/2026-09-05-tool-output-cache-stability.md)。
23279
- ...record2.metadata && typeof record2.metadata === "object" ? { tool_result_metadata: record2.metadata } : {},
23280
- ...(() => {
23281
- const raw = record2.createdAt;
23282
- const ms = typeof raw === "number" ? raw : typeof raw === "string" ? Date.parse(raw) : NaN;
23283
- return Number.isFinite(ms) ? { createdAt: ms } : {};
23284
- })()
23285
- };
23286
- }
23287
-
23288
22886
  // packages/agent-runtime/dialogWritePlan.ts
23289
22887
  function extractLastUserText(messages) {
23290
22888
  const lastUser = [...messages].reverse().find((message) => message.role === "user");
@@ -23710,11 +23308,11 @@ var E_ALREADY_LOCKED = new Error("mutex already locked");
23710
23308
  var E_CANCELED = new Error("request for lock canceled");
23711
23309
  var __awaiter$2 = function(thisArg, _arguments, P, generator) {
23712
23310
  function adopt(value) {
23713
- return value instanceof P ? value : new P(function(resolve6) {
23714
- resolve6(value);
23311
+ return value instanceof P ? value : new P(function(resolve7) {
23312
+ resolve7(value);
23715
23313
  });
23716
23314
  }
23717
- return new (P || (P = Promise))(function(resolve6, reject) {
23315
+ return new (P || (P = Promise))(function(resolve7, reject) {
23718
23316
  function fulfilled(value) {
23719
23317
  try {
23720
23318
  step(generator.next(value));
@@ -23730,7 +23328,7 @@ var __awaiter$2 = function(thisArg, _arguments, P, generator) {
23730
23328
  }
23731
23329
  }
23732
23330
  function step(result4) {
23733
- result4.done ? resolve6(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23331
+ result4.done ? resolve7(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23734
23332
  }
23735
23333
  step((generator = generator.apply(thisArg, _arguments || [])).next());
23736
23334
  });
@@ -23745,8 +23343,8 @@ var Semaphore = class {
23745
23343
  acquire(weight = 1, priority = 0) {
23746
23344
  if (weight <= 0)
23747
23345
  throw new Error(`invalid weight ${weight}: must be positive`);
23748
- return new Promise((resolve6, reject) => {
23749
- const task = { resolve: resolve6, reject, weight, priority };
23346
+ return new Promise((resolve7, reject) => {
23347
+ const task = { resolve: resolve7, reject, weight, priority };
23750
23348
  const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
23751
23349
  if (i === -1 && weight <= this._value) {
23752
23350
  this._dispatchItem(task);
@@ -23771,10 +23369,10 @@ var Semaphore = class {
23771
23369
  if (this._couldLockImmediately(weight, priority)) {
23772
23370
  return Promise.resolve();
23773
23371
  } else {
23774
- return new Promise((resolve6) => {
23372
+ return new Promise((resolve7) => {
23775
23373
  if (!this._weightedWaiters[weight - 1])
23776
23374
  this._weightedWaiters[weight - 1] = [];
23777
- insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve6, priority });
23375
+ insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve7, priority });
23778
23376
  });
23779
23377
  }
23780
23378
  }
@@ -23857,11 +23455,11 @@ function findIndexFromEnd(a, predicate) {
23857
23455
  }
23858
23456
  var __awaiter$1 = function(thisArg, _arguments, P, generator) {
23859
23457
  function adopt(value) {
23860
- return value instanceof P ? value : new P(function(resolve6) {
23861
- resolve6(value);
23458
+ return value instanceof P ? value : new P(function(resolve7) {
23459
+ resolve7(value);
23862
23460
  });
23863
23461
  }
23864
- return new (P || (P = Promise))(function(resolve6, reject) {
23462
+ return new (P || (P = Promise))(function(resolve7, reject) {
23865
23463
  function fulfilled(value) {
23866
23464
  try {
23867
23465
  step(generator.next(value));
@@ -23877,7 +23475,7 @@ var __awaiter$1 = function(thisArg, _arguments, P, generator) {
23877
23475
  }
23878
23476
  }
23879
23477
  function step(result4) {
23880
- result4.done ? resolve6(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23478
+ result4.done ? resolve7(result4.value) : adopt(result4.value).then(fulfilled, rejected);
23881
23479
  }
23882
23480
  step((generator = generator.apply(thisArg, _arguments || [])).next());
23883
23481
  });
@@ -23968,7 +23566,7 @@ async function registerDialogOwner(args2) {
23968
23566
  // packages/cli/client/localDialogRecords.ts
23969
23567
  var localDialogMessageRecordToRuntimeMessage = dialogMessageRecordToAgentRuntimeMessage;
23970
23568
  function buildLocalDialogWritePlan(args2) {
23971
- return buildAgentRuntimeDialogWritePlan({
23569
+ const plan = buildAgentRuntimeDialogWritePlan({
23972
23570
  input: args2.input,
23973
23571
  userId: args2.userId,
23974
23572
  now: args2.now,
@@ -23980,6 +23578,21 @@ function buildLocalDialogWritePlan(args2) {
23980
23578
  },
23981
23579
  ...args2.titleOverride ? { titleOverride: args2.titleOverride } : {}
23982
23580
  });
23581
+ const turnId = args2.input.runtimeContext?.turnId;
23582
+ const captureUserMessageIds = [];
23583
+ if (typeof turnId === "string" && /^turn-[0-9A-HJKMNP-TV-Z]{26}$/.test(turnId)) {
23584
+ const messages = args2.input.messages.filter((message) => message.role !== "system");
23585
+ for (const [index, message] of messages.entries()) {
23586
+ if (message.role !== "user" || message.cliMessageId) continue;
23587
+ const op = plan.ops[index + 1];
23588
+ const id = dialogTurnUserMessageId(turnId, index);
23589
+ const key = `dialog-${plan.dialogId}-msg-${id}`;
23590
+ op.key = key;
23591
+ op.value = { ...op.value, id, dbKey: key };
23592
+ captureUserMessageIds.push(id);
23593
+ }
23594
+ }
23595
+ return { ...plan, captureUserMessageIds };
23983
23596
  }
23984
23597
  async function saveCliPendingUserMessages(args2) {
23985
23598
  const dialogKey = `dialog-${args2.userId}-${args2.dialogId}`;
@@ -24026,7 +23639,7 @@ async function saveCliPendingUserMessages(args2) {
24026
23639
  if (ops.length) await args2.store.batch(ops);
24027
23640
  }
24028
23641
  async function readCliPendingUserMessages(store, dialogId) {
24029
- const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-6FXGFBI3.js");
23642
+ const { readDialogMessageRecords } = await import("./cliLocalAgentRecordReader-AJ4UKHKT.js");
24030
23643
  const rows = await readDialogMessageRecords({ store, dialogId });
24031
23644
  const uncertain = rows.filter(({ record: record2 }) => record2.metadata?.cliBatchPhase === "requested" && !record2.metadata?.cliBatchResolution);
24032
23645
  const recovery = uncertain.length ? {
@@ -24075,6 +23688,8 @@ async function markCliUserBatchPhase(store, dialogId, messageId, phase, messageI
24075
23688
  metadata: {
24076
23689
  ...message.metadata,
24077
23690
  queueState: "accepted",
23691
+ cliBatchId: messageId,
23692
+ ...Number.isFinite(prepared?.cliHistoryOrder) ? { cliHistoryOrder: prepared.cliHistoryOrder } : {},
24078
23693
  ...id === messageId ? { cliBatchPhase: phase, acceptedUserMessageIds: [...messageIds] } : {}
24079
23694
  }
24080
23695
  } });
@@ -24089,6 +23704,8 @@ async function rollbackCliUserBatchPhase(store, dialogId, batchId, messageIds) {
24089
23704
  if (!record2) continue;
24090
23705
  const metadata = { ...record2.metadata };
24091
23706
  delete metadata.cliBatchPhase;
23707
+ delete metadata.cliBatchId;
23708
+ delete metadata.acceptedUserMessageIds;
24092
23709
  metadata.queueState = "pending";
24093
23710
  ops.push({ type: "put", key, value: { ...record2, metadata } });
24094
23711
  }
@@ -24121,15 +23738,15 @@ async function readNoloProcessStream(readable) {
24121
23738
  async function runNoloWorkspaceCliTool(call, args2) {
24122
23739
  const cliArgs = buildNoloWorkspaceCommandArgs(call);
24123
23740
  const bunSpawn = globalThis.Bun?.spawn;
24124
- const spawn5 = args2.spawn ?? (typeof bunSpawn === "function" ? bunSpawn : nodeSpawnFallback);
23741
+ const spawn2 = args2.spawn ?? (typeof bunSpawn === "function" ? bunSpawn : nodeSpawnFallback);
24125
23742
  const execPath = args2.processExecPath ?? process.execPath;
24126
23743
  const entrypoint = args2.cliEntrypoint;
24127
23744
  const cmd = entrypoint && entrypoint !== execPath ? [execPath, entrypoint, ...cliArgs] : [execPath, ...cliArgs];
24128
- const proc = spawn5({
23745
+ const proc = spawn2({
24129
23746
  cmd,
24130
23747
  stdout: "pipe",
24131
23748
  stderr: "pipe",
24132
- env: args2.env
23749
+ env: call.name === "listAgents" ? { ...process.env, ...args2.env, NOLO_PLANNING_CALLER: JSON.stringify(args2.planningCaller ?? {}) } : args2.env
24133
23750
  });
24134
23751
  const [stdout, stderr, exitCode] = await Promise.all([
24135
23752
  readNoloProcessStream(proc.stdout),
@@ -24237,10 +23854,10 @@ function buildLoadSkillExecutor(args2) {
24237
23854
  metadata: { loadSkill: true, resolved: false }
24238
23855
  };
24239
23856
  }
24240
- const { resolveSkillByName } = await import("./skillDiscovery-B5V23AXP.js");
23857
+ const { resolveSkillByName } = await import("./skillDiscovery-MDDKPTW3.js");
24241
23858
  const resolved = resolveSkillByName(args2.cwd, name);
24242
23859
  if (!resolved) {
24243
- const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-PXH7EGQB.js");
23860
+ const { resolveBuiltinSkillByName } = await import("./builtinSkillRegistry-AYWYQVA4.js");
24244
23861
  const builtin = resolveBuiltinSkillByName(name);
24245
23862
  if (builtin) {
24246
23863
  const denied = await rejectDisabledBuiltin(args2.agentSkillSource, builtin.slug, name, args2.resolveAgentSkillSource);
@@ -24267,8 +23884,8 @@ ${builtin.content}`,
24267
23884
  };
24268
23885
  }
24269
23886
  try {
24270
- const { readFileSync } = await import("node:fs");
24271
- const body = readFileSync(resolved, "utf8");
23887
+ const { readFileSync: readFileSync2 } = await import("node:fs");
23888
+ const body = readFileSync2(resolved, "utf8");
24272
23889
  return {
24273
23890
  content: `Skill "${name}" loaded inline. Follow its instructions.
24274
23891
 
@@ -24319,7 +23936,7 @@ async function loadPreciseSkill(cwd, parsed, agentSkillSource, resolveAgentSkill
24319
23936
  if (!nonEmpty(parsed.slug) || has2("projectBinding") || has2("relativePath")) {
24320
23937
  return reject("builtin requires only an exact slug.");
24321
23938
  }
24322
- const { listBuiltinSkills } = await import("./builtinSkillRegistry-PXH7EGQB.js");
23939
+ const { listBuiltinSkills } = await import("./builtinSkillRegistry-AYWYQVA4.js");
24323
23940
  const builtin = listBuiltinSkills().find((entry) => entry.slug === parsed.slug);
24324
23941
  if (!builtin) return reject("builtin slug not found.");
24325
23942
  const denied = await rejectDisabledBuiltin(agentSkillSource, builtin.slug, builtin.slug, resolveAgentSkillSource);
@@ -24344,8 +23961,8 @@ ${builtin.content}`,
24344
23961
  return reject("project requires projectBinding and relativePath only.");
24345
23962
  }
24346
23963
  try {
24347
- const { realpathSync, statSync, readFileSync } = await import("node:fs");
24348
- const { resolve: resolve6, relative: relative6, isAbsolute: isAbsolute5, basename: basename4, sep: sep3 } = await import("node:path");
23964
+ const { realpathSync, statSync, readFileSync: readFileSync2 } = await import("node:fs");
23965
+ const { resolve: resolve7, relative: relative6, isAbsolute: isAbsolute5, basename: basename4, sep: sep3 } = await import("node:path");
24349
23966
  const inside = (root, target) => {
24350
23967
  const rel = relative6(root, target);
24351
23968
  return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute5(rel);
@@ -24357,8 +23974,8 @@ ${builtin.content}`,
24357
23974
  if (isAbsolute5(parsed.relativePath) || basename4(parsed.relativePath) !== "SKILL.md") {
24358
23975
  return reject("relativePath must reference a project SKILL.md.");
24359
23976
  }
24360
- const skillsRoot = resolve6(realCwd, ".agents", "skills");
24361
- const candidate = resolve6(realCwd, parsed.relativePath);
23977
+ const skillsRoot = resolve7(realCwd, ".agents", "skills");
23978
+ const candidate = resolve7(realCwd, parsed.relativePath);
24362
23979
  if (!inside(skillsRoot, candidate)) return reject("path is outside cwd/.agents/skills/.");
24363
23980
  const realRoot = realpathSync(skillsRoot);
24364
23981
  const realPath = realpathSync(candidate);
@@ -24366,7 +23983,7 @@ ${builtin.content}`,
24366
23983
  return reject("skill path escapes cwd/.agents/skills/ or is not SKILL.md.");
24367
23984
  }
24368
23985
  if (!statSync(realPath).isFile()) return reject("SKILL.md is not a file.");
24369
- const body = readFileSync(realPath, "utf8");
23986
+ const body = readFileSync2(realPath, "utf8");
24370
23987
  return {
24371
23988
  content: `Skill "${parsed.relativePath}" loaded inline. Follow its instructions.
24372
23989
 
@@ -24385,7 +24002,7 @@ ${body}`,
24385
24002
  }
24386
24003
  }
24387
24004
  async function formatUnknownSkillMessage(cwd, requestedName) {
24388
- const { discoverSkills } = await import("./skillDiscovery-B5V23AXP.js");
24005
+ const { discoverSkills } = await import("./skillDiscovery-MDDKPTW3.js");
24389
24006
  let available = [];
24390
24007
  try {
24391
24008
  available = discoverSkills(cwd).map((s) => s.name);
@@ -24957,11 +24574,11 @@ function createDevinProvider(options) {
24957
24574
  }
24958
24575
 
24959
24576
  // packages/agent-runtime/executionLeaseValidation.ts
24960
- import { isAbsolute as isAbsolute4, relative as relative5, resolve as resolve5 } from "node:path";
24577
+ import { isAbsolute as isAbsolute4, relative as relative5, resolve as resolve6 } from "node:path";
24961
24578
  function withinRoot(root, child) {
24962
24579
  if (!isAbsolute4(root) || !isAbsolute4(child)) return false;
24963
- const canonicalRoot = resolve5(root);
24964
- const canonicalChild = resolve5(child);
24580
+ const canonicalRoot = resolve6(root);
24581
+ const canonicalChild = resolve6(child);
24965
24582
  const suffix = relative5(canonicalRoot, canonicalChild);
24966
24583
  return suffix === "" || suffix !== ".." && !suffix.startsWith("../") && !suffix.startsWith("..\\") && !isAbsolute4(suffix);
24967
24584
  }
@@ -25024,17 +24641,16 @@ function verifyOwnerRouteAck(headers, expectedRequestId) {
25024
24641
  }
25025
24642
 
25026
24643
  export {
25027
- createHostCredentialBrokerChain,
25028
- createStrictHostCredentialBroker,
25029
24644
  readCommandActionGatePayload,
25030
24645
  readActionGate,
24646
+ orderDialogHistory,
25031
24647
  Option_exports,
25032
24648
  Duration_exports,
25033
24649
  Exit_exports,
25034
24650
  Effect_exports,
25035
- scrubSecrets,
25036
24651
  isDestructiveShellCommand,
25037
24652
  evaluateShellCommandPolicy,
24653
+ readAgentsMdLayerFromDisk,
25038
24654
  filterRetainedLedgerRecords,
25039
24655
  isLineRangeCovered,
25040
24656
  runTaskStop,
@@ -25058,7 +24674,12 @@ export {
25058
24674
  runExecShellGates,
25059
24675
  executeLocalToolWithPolicy,
25060
24676
  LOCAL_TURN_ABORTED_CODE,
25061
- evaluateTaskExecutionContract,
24677
+ isSubtaskRun,
24678
+ RUN_WAKE_CHANNEL_ENV,
24679
+ hasRunWakeChannel,
24680
+ filterToolNamesForRunKind,
24681
+ findSummaryAnchorIndex,
24682
+ validateStoredSummary,
25062
24683
  projectContextProvenance,
25063
24684
  hashToolDefinitions,
25064
24685
  LOCAL_AGENT_CONFIG_MISSING_CODE,
@@ -25073,7 +24694,6 @@ export {
25073
24694
  executeOpenAiCompatibleChatCompletion,
25074
24695
  describeOpenAiCompatibleRequestBudget,
25075
24696
  resolveOpenAiCompatibleProviderConfig,
25076
- dialogMessageRecordToAgentRuntimeMessage,
25077
24697
  buildAgentRuntimeDialogWritePlan,
25078
24698
  shouldCacheHybridRemoteRecord,
25079
24699
  parseSyncServersEnv,