nolo-cli 0.228.0 → 0.228.1

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 (212) hide show
  1. package/{_executeModel-GIFVXKDT.js → _executeModel-AKCTHGMP.js} +62 -61
  2. package/{action-WZTKEF5H.js → action-C6IQAKN4.js} +6 -6
  3. package/{addContentAction-MLI6GOBV.js → addContentAction-53364YDW.js} +10 -10
  4. package/{addDialogAgentAction-ARGQM22H.js → addDialogAgentAction-U5DD5EN5.js} +9 -9
  5. package/{agentDeleteCommand-UF7XVELS.js → agentDeleteCommand-2E5FAGUO.js} +99 -93
  6. package/{agentEmailCommands-SFHRPQYC.js → agentEmailCommands-UGZZAH7E.js} +99 -93
  7. package/{agentListCommands-IXKBP3W5.js → agentListCommands-JCTW3J2K.js} +240 -52
  8. package/{agentMachineCommands-7NX6PWQ6.js → agentMachineCommands-QPG5ZXF4.js} +45 -41
  9. package/{agentProviderCommands-C5T7C5KZ.js → agentProviderCommands-QLTABYR7.js} +2 -2
  10. package/{agentPullCommand-4EQZYHU4.js → agentPullCommand-2EYJ5ENC.js} +1 -1
  11. package/{agentRecordCommands-IUNX6XD6.js → agentRecordCommands-4NTVR6MZ.js} +98 -92
  12. package/{agentRunCommand-LCR4XADM.js → agentRunCommand-VHF34PYC.js} +103 -94
  13. package/{agentRunControl-RN2P6AOD.js → agentRunControl-QYTXUQGY.js} +10 -7
  14. package/{agentRuntimeLocal-LVXPQ7QA.js → agentRuntimeLocal-U54AKHXH.js} +38 -36
  15. package/{agentSlice-ZGMOH6TE.js → agentSlice-4JGDEXWK.js} +10 -10
  16. package/{appDeleteCommands-BESCJOQM.js → appDeleteCommands-XBE5QJ6P.js} +46 -42
  17. package/{appDeployCommands-LPTR6IOX.js → appDeployCommands-QIYLXXGA.js} +46 -42
  18. package/{appDeployStatusCommands-BZ7KZ5RD.js → appDeployStatusCommands-JXS6ZQZZ.js} +46 -42
  19. package/{appGetCommands-EDWGJV4S.js → appGetCommands-SZS7SJPK.js} +46 -42
  20. package/{appListCommands-OPRWYPM6.js → appListCommands-B3GBJSNV.js} +46 -42
  21. package/{authCommand-3C3RN4OU.js → authCommand-V6EOMZX6.js} +15 -15
  22. package/{authCommands-ZMVEDCQD.js → authCommands-T5FODCEG.js} +2 -2
  23. package/{builtinSkillRegistry-VRCMQ77Q.js → builtinSkillRegistry-ZQC3IIO2.js} +4 -3
  24. package/{chromeOpsCommands-NZITLHWO.js → chromeOpsCommands-OFX7ZGKP.js} +2 -2
  25. package/{chunk-MZVCFV3T.js → chunk-223KZUJ6.js} +4 -4
  26. package/{chunk-UF6J7NXV.js → chunk-2C5VN7NH.js} +1 -1
  27. package/{chunk-MAA42MMV.js → chunk-2FZVXOFX.js} +4 -4
  28. package/{chunk-ESN4WNWU.js → chunk-2JHGUL5K.js} +2 -2
  29. package/chunk-3A5NNQCN.js +64 -0
  30. package/chunk-3F2FRLIO.js +372 -0
  31. package/{chunk-V4IYI3SB.js → chunk-46FETNLF.js} +2 -2
  32. package/{chunk-RR3MB26M.js → chunk-4GYVS4PM.js} +8 -6
  33. package/{chunk-ZQ6K57FJ.js → chunk-4YPH5KRA.js} +1 -1
  34. package/{chunk-Y4NPF2UN.js → chunk-5AYP5QBB.js} +5 -5
  35. package/{chunk-4OXPN3WC.js → chunk-5ISNPTQH.js} +4 -4
  36. package/{chunk-CO6E7YK6.js → chunk-5P3PPQVP.js} +1 -1
  37. package/{chunk-6TVYUQRM.js → chunk-6BMTKYAO.js} +2 -2
  38. package/{chunk-KLAMJNKQ.js → chunk-6PAHSSD2.js} +15 -8
  39. package/{chunk-CTWCZKNS.js → chunk-6SOWMEAY.js} +4 -4
  40. package/{chunk-ARFCL53U.js → chunk-6VEO7Z3Y.js} +5 -5
  41. package/{chunk-ZM5AZTQG.js → chunk-7BIJFGKS.js} +20 -8
  42. package/{chunk-BAH3BAUZ.js → chunk-7OVOZRZF.js} +5 -5
  43. package/{chunk-N74XL3NI.js → chunk-7PON4LBY.js} +42 -24
  44. package/{chunk-LTVEOOZL.js → chunk-7WHCIA5V.js} +16 -3
  45. package/{chunk-HZDK56EK.js → chunk-ADYWV732.js} +34 -12
  46. package/{chunk-2FK2KZSL.js → chunk-AIFQKNPP.js} +1 -1
  47. package/{chunk-VTHWBTRE.js → chunk-BPB3T5EU.js} +5 -8
  48. package/{chunk-SX6AWTNK.js → chunk-BZLGPM5B.js} +3 -3
  49. package/{chunk-MTM4LRVG.js → chunk-BZMDWGQQ.js} +2 -2
  50. package/{chunk-JP2BH4NC.js → chunk-CEKRIR22.js} +1 -1
  51. package/{chunk-5HUO7SEX.js → chunk-D634SL2Y.js} +1 -1
  52. package/{chunk-SCMYAGQE.js → chunk-DHRPLRIR.js} +294 -159
  53. package/{chunk-VUHKG4KS.js → chunk-DNNPARJK.js} +9 -5
  54. package/{chunk-X22AUZKL.js → chunk-E3LSO6EI.js} +189 -88
  55. package/{chunk-LHCGKAFO.js → chunk-EHFBP6IK.js} +100 -48
  56. package/{chunk-6ASGEP5D.js → chunk-EJQE5HB7.js} +1 -1
  57. package/{chunk-2BKNICGK.js → chunk-EL5NRJHI.js} +1 -1
  58. package/chunk-EUGTFFO6.js +42 -0
  59. package/{chunk-YFW4H6DL.js → chunk-EVHTYVD2.js} +821 -131
  60. package/{chunk-6XRPBZRS.js → chunk-EYLGAEB4.js} +0 -134
  61. package/{chunk-E5RYFR7E.js → chunk-FEIVARWR.js} +49 -15
  62. package/{chunk-3DJJ4CFG.js → chunk-FLBJ7IJI.js} +9 -9
  63. package/{chunk-W3HSD32M.js → chunk-FXEPZKNJ.js} +2 -2
  64. package/{chunk-VKCPKCSS.js → chunk-FYAMUU55.js} +625 -62
  65. package/{chunk-JEWMQR6J.js → chunk-FZANZZ63.js} +1 -1
  66. package/{chunk-WWTSEBDF.js → chunk-GIXWVN2W.js} +1 -1
  67. package/{chunk-YHNUDTU4.js → chunk-HDKMVYNJ.js} +4 -4
  68. package/chunk-HEVRQGGH.js +106 -0
  69. package/{chunk-PBPXXMWZ.js → chunk-HFHJPHFK.js} +1 -1
  70. package/{chunk-WQDTSK5U.js → chunk-HPDLPEUG.js} +11 -5
  71. package/{chunk-SPU3L3OR.js → chunk-HQUGB2HM.js} +3 -3
  72. package/chunk-IVK2KT3H.js +209 -0
  73. package/{chunk-73PZD7JZ.js → chunk-IYLUK67R.js} +2 -2
  74. package/{chunk-BFKJ2RS3.js → chunk-J55F3IEZ.js} +1 -1
  75. package/{chunk-ADOOL3PG.js → chunk-J7JRCOIW.js} +1 -1
  76. package/{chunk-AEZBAFC6.js → chunk-JAKRY74O.js} +138 -8
  77. package/{chunk-NEG5LYK5.js → chunk-JCQ3WCQ3.js} +3 -1
  78. package/{chunk-W6T4FNZP.js → chunk-JLZJL3WC.js} +219 -351
  79. package/{chunk-PQ63BDV3.js → chunk-JPXACKSW.js} +9 -1
  80. package/{chunk-IIOSZAJX.js → chunk-KDBDOXOM.js} +137 -53
  81. package/{chunk-CIGCTSBF.js → chunk-KDDHQMSH.js} +1 -1
  82. package/{chunk-OAZP4TSA.js → chunk-KG27JIG4.js} +2 -2
  83. package/{chunk-RHBD22LV.js → chunk-KHYSFS3W.js} +80 -4
  84. package/{chunk-7UVVLYKC.js → chunk-KKIQAVDR.js} +5 -5
  85. package/{chunk-HS7MLR74.js → chunk-KZ4A7EIV.js} +3 -5
  86. package/{chunk-OLGFIQN2.js → chunk-LLUBUHNT.js} +1 -1
  87. package/{chunk-QJTZ76CP.js → chunk-LS5KAVFQ.js} +1 -0
  88. package/{chunk-K26XPZRB.js → chunk-LVZVSLKO.js} +29 -9
  89. package/{chunk-XJSEST7D.js → chunk-MNFUKRRU.js} +3 -3
  90. package/{chunk-R5NRFXGD.js → chunk-O3A2CHAL.js} +5 -5
  91. package/{chunk-4IQN6FWY.js → chunk-OB4FBZXJ.js} +4 -4
  92. package/{chunk-J2VIGDJN.js → chunk-OJSJJKHF.js} +3 -3
  93. package/{chunk-OHUYN3YU.js → chunk-OKAXQFON.js} +1 -1
  94. package/{chunk-CD2DK5JA.js → chunk-OKH74FML.js} +2 -1
  95. package/{chunk-MYYNZG2M.js → chunk-OOV5JN25.js} +4 -4
  96. package/{chunk-TMRJGSK2.js → chunk-OOVOAG4Q.js} +1 -1
  97. package/chunk-OQFOE4SJ.js +405 -0
  98. package/{chunk-AS6L5KSD.js → chunk-P4R5KXU7.js} +2 -2
  99. package/{chunk-VIYVRPMJ.js → chunk-PHREU2KZ.js} +5 -3
  100. package/{chunk-EDT65EUE.js → chunk-PIVTQRX6.js} +45 -15
  101. package/{chunk-QMNVV3YM.js → chunk-PJL7OJRC.js} +12 -11
  102. package/{chunk-XCA4WHX5.js → chunk-PNLDLUMO.js} +315 -360
  103. package/{chunk-UPOW5HTG.js → chunk-QGFLVQ6E.js} +3 -3
  104. package/{chunk-JU7VN4LF.js → chunk-QONAOHVW.js} +6 -6
  105. package/{chunk-UOUMPHS5.js → chunk-R3FZHW4Q.js} +13 -13
  106. package/{chunk-K7VIXYTZ.js → chunk-R3MV2GII.js} +1 -45
  107. package/{chunk-FE7G6DSP.js → chunk-R72QWIFO.js} +14 -4
  108. package/{chunk-KZAT2M2V.js → chunk-RIWKZT7E.js} +22 -0
  109. package/{chunk-RMWDKLBE.js → chunk-S7H4KTMB.js} +1099 -71
  110. package/{chunk-IJZC2KIJ.js → chunk-SA356NGW.js} +1 -1
  111. package/{chunk-BVEDT6DM.js → chunk-SCAC3NM5.js} +3 -3
  112. package/{chunk-EQZQUQ33.js → chunk-SLUN7W6S.js} +5 -5
  113. package/{chunk-KK3FCYZM.js → chunk-SQL7YNED.js} +7 -4
  114. package/{chunk-LMGFVH65.js → chunk-SSOR2EDT.js} +10 -10
  115. package/chunk-TRRXYFTR.js +46 -0
  116. package/{chunk-XNTZD4AE.js → chunk-TUOHSUK5.js} +19367 -17503
  117. package/chunk-TYJCIA2O.js +835 -0
  118. package/{chunk-FTWAOKFU.js → chunk-U3BUWDUP.js} +415 -1962
  119. package/{chunk-CD64YXRB.js → chunk-U6QNVOR5.js} +1 -1
  120. package/chunk-UAF5VQCE.js +77 -0
  121. package/{chunk-CIUZXD5D.js → chunk-UFGUJ2IH.js} +5 -5
  122. package/{chunk-CTIEJRTP.js → chunk-UP7KBWLE.js} +81 -29
  123. package/{chunk-GX6DITLQ.js → chunk-UUCYUN6Y.js} +1 -1
  124. package/{chunk-UHW6SCVK.js → chunk-UZKBVQUX.js} +1 -1
  125. package/{chunk-XSRSAU3O.js → chunk-V5TI7HJH.js} +3 -3
  126. package/{chunk-WFGNWWJI.js → chunk-VH7UO6E5.js} +252 -114
  127. package/{chunk-ITBX27W6.js → chunk-VJFDG3ZG.js} +30 -122
  128. package/{chunk-6MTVACLN.js → chunk-WC3J5SL2.js} +277 -293
  129. package/{chunk-HCCQEMTK.js → chunk-WD5547ZF.js} +15 -12
  130. package/{chunk-X3OZ655T.js → chunk-WS36XPJD.js} +2 -2
  131. package/{chunk-JFRJEPFI.js → chunk-WSLL7VV4.js} +2 -2
  132. package/chunk-XRGBJHZX.js +136 -0
  133. package/{chunk-KZ5OD2MO.js → chunk-Y2KWJTOZ.js} +3 -3
  134. package/{dialogUsageCommand-6RW2FY6K.js → chunk-Y2TCTNUD.js} +24 -17
  135. package/{chunk-FFFKAOJN.js → chunk-YN23INFZ.js} +1 -1
  136. package/{chunk-ODBYGVO2.js → chunk-YXK3GJF5.js} +5 -5
  137. package/{chunk-6CXQ3YNJ.js → chunk-Z2OWAYMI.js} +53 -31
  138. package/{chunk-6XVPMGXK.js → chunk-ZTHAJU3O.js} +10 -4
  139. package/{chunk-D25ONVOH.js → chunk-ZYPXOQS2.js} +1 -1
  140. package/{cliAgentConfigHelpers-37ZNEY5Y.js → cliAgentConfigHelpers-BXHQ3PXP.js} +8 -8
  141. package/{cliAuthorityBrokerClient-SFPC3WVK.js → cliAuthorityBrokerClient-TFNXJLXL.js} +1 -1
  142. package/cliAuthorityBrokerProcess-5ZFBTHLB.js +22 -0
  143. package/{cliLocalAgentRecordReader-MCQVRWBR.js → cliLocalAgentRecordReader-47PXMHPH.js} +43 -41
  144. package/{commandRegistry-NTH5IAN5.js → commandRegistry-CTMPAQH2.js} +93 -156
  145. package/{contentThunks-SPXTX5U2.js → contentThunks-CAHIIZO5.js} +25 -25
  146. package/{cooldownCommands-TIFCHCUN.js → cooldownCommands-WDOI5VD7.js} +3 -3
  147. package/{createAgentAutomationAction-KUQKCOXB.js → createAgentAutomationAction-M25XZSPD.js} +25 -25
  148. package/{createDialogAction-HJN5U3XS.js → createDialogAction-4SN7FKI7.js} +26 -26
  149. package/{createPageAction-ZAHRDOAU.js → createPageAction-N7QPDN3M.js} +28 -28
  150. package/{db-CMUTP3W5.js → db-VR74ADGC.js} +7 -2
  151. package/{dbSlice-656PMWR2.js → dbSlice-RWPSVHBC.js} +9 -9
  152. package/{deleteFile-ZCQESEEQ.js → deleteFile-ECU6FU5C.js} +12 -7
  153. package/{dialogCommands-KZTZLWPZ.js → dialogCommands-BBHWCKDP.js} +57 -47
  154. package/{dialogNotifyCommand-PST75COP.js → dialogNotifyCommand-IASQGEMW.js} +9 -9
  155. package/{dialogSlice-BXIERQHO.js → dialogSlice-JI3J22RV.js} +23 -23
  156. package/dialogTraceCommand-EW2KK6A4.js +961 -0
  157. package/dialogUsageCommand-WJ3U6KZU.js +27 -0
  158. package/{docCreateCommands-26HJ5NAY.js → docCreateCommands-QSX3X5U4.js} +45 -41
  159. package/{docDeleteCommands-UAOHH5XK.js → docDeleteCommands-63JBG2HQ.js} +46 -42
  160. package/{docReadCommands-4ADG7YE6.js → docReadCommands-CQFKRQUI.js} +45 -41
  161. package/{docStore-FZ75HWP2.js → docStore-XLBKGGNM.js} +10 -10
  162. package/{docUpdateCommands-OGFJZENF.js → docUpdateCommands-534LUK25.js} +45 -41
  163. package/ebookDownloaderAgentCommand-DYSKF5ZY.js +677 -0
  164. package/{getPricing-FCHYVRJU.js → getPricing-5BLZRPTM.js} +3 -3
  165. package/{handleSendMessageAction-KP6GGBFY.js → handleSendMessageAction-Q2VMEVOR.js} +90 -48
  166. package/{hostCredentialCreate-23TX56G7.js → hostCredentialCreate-C57T7YPE.js} +99 -93
  167. package/index.js +23 -11
  168. package/{localDialogRead-CIOTQM5T.js → localDialogRead-BJJT3TF5.js} +1 -1
  169. package/{localRuntimeAdapter-MTUWOYPN.js → localRuntimeAdapter-OALZPFZU.js} +96 -90
  170. package/{localRuntimeAuthority-TYHQCTZN.js → localRuntimeAuthority-UF2DAQ3F.js} +13 -3
  171. package/{localRuntimeDb-BO7IVWAZ.js → localRuntimeDb-ZJFGNHML.js} +1 -1
  172. package/{machineCommands-4WJUJQHW.js → machineCommands-N6IVWRZT.js} +109 -92
  173. package/{machineWsRunDispatch-V3U4JM67.js → machineWsRunDispatch-PDWYB33B.js} +97 -91
  174. package/{markdownToSlate-KIYM7B3P.js → markdownToSlate-PXYAIBVL.js} +1 -1
  175. package/{mcpLocalAuthorizeCommand-TI656UWC.js → mcpLocalAuthorizeCommand-KYI4EGF5.js} +17 -13
  176. package/{memberThunks-JFYC4Z5L.js → memberThunks-43B7UYC5.js} +11 -11
  177. package/{models-EP7VG6N2.js → models-ZX2BYIMB.js} +2 -2
  178. package/package.json +2 -1
  179. package/{projectArchive-NU2Z5HOR.js → projectArchive-TJNW5DLM.js} +28 -28
  180. package/{providerPresetApply-4H7YP5D7.js → providerPresetApply-NTJUINI6.js} +35 -16
  181. package/{providerRegistry-F3UPOTIY.js → providerRegistry-W45SLUV6.js} +5 -5
  182. package/{read-BRZHXUJ6.js → read-KG6INYUT.js} +12 -7
  183. package/{readDocTool-N7RVFQEE.js → readDocTool-N3GA52JR.js} +1 -1
  184. package/{readlineWorkspace-T56MRMS5.js → readlineWorkspace-PJZJVGA5.js} +1296 -1056
  185. package/{removeDialogAgentAction-J7XU7OUX.js → removeDialogAgentAction-EEVSOQOJ.js} +11 -11
  186. package/{runAgentClientLoop-O2GRCGRZ.js → runAgentClientLoop-3VC5TCDW.js} +69 -58
  187. package/{runtimeDoctorCommands-RDRJXMXC.js → runtimeDoctorCommands-V3M3JTUV.js} +14 -11
  188. package/{secretCommands-2FEMRUFM.js → secretCommands-KVVZS7A6.js} +2 -2
  189. package/{setDialogExtraReferencesAction-Q4V2ZZW2.js → setDialogExtraReferencesAction-DNO5POHA.js} +10 -10
  190. package/{setPrimaryDialogAgentAction-742H5S6T.js → setPrimaryDialogAgentAction-QABBEO4C.js} +11 -11
  191. package/{settingThunks-T4FXSV6M.js → settingThunks-DVKG4X4S.js} +13 -17
  192. package/{skillDiscovery-MDDKPTW3.js → skillDiscovery-ZMJH36AK.js} +3 -3
  193. package/{spaceCommands-W5TAVFDT.js → spaceCommands-AGGZXPY3.js} +218 -77
  194. package/{streamAgentChatTurn-OWDJMU5E.js → streamAgentChatTurn-4GTLL2OF.js} +111 -95
  195. package/{switchDialogAgentAction-HLDLHRRA.js → switchDialogAgentAction-KYWJSGOO.js} +9 -9
  196. package/{tableCommands-44GC4N6J.js → tableCommands-EFA754RE.js} +3 -3
  197. package/{tools-O7SGGVA3.js → tools-5AGPOPLW.js} +48 -47
  198. package/{tuiRestart-EOGC2BYY.js → tuiRestart-77E7PL4R.js} +9 -8
  199. package/{tuiSummaryLlmCaller-TM5BU73J.js → tuiSummaryLlmCaller-HROLGN4F.js} +12 -12
  200. package/{updateCommands-FBYA5WVG.js → updateCommands-GJGRS6JK.js} +3 -3
  201. package/{updateDialogTitleAction-EXSZGTLL.js → updateDialogTitleAction-5OSEDGRK.js} +25 -25
  202. package/{usageCommand-L4OFWXEU.js → usageCommand-WI6SQOPB.js} +2 -2
  203. package/{usageRebuildCommand-7JR33UHS.js → usageRebuildCommand-WQRLLZAT.js} +3 -3
  204. package/{windowsSelfUpdate-M4V77OUB.js → windowsSelfUpdate-C7LGVWYX.js} +2 -2
  205. package/{workloadLifecycle-ZCSQCHG3.js → workloadLifecycle-P2SJVV3S.js} +2 -2
  206. package/chunk-FGHEF6WI.js +0 -34
  207. package/chunk-U5LOKQ2R.js +0 -176
  208. package/chunk-YDRRGVT5.js +0 -142
  209. package/chunk-YGDYYFRX.js +0 -86
  210. package/chunk-Z7KE4K3H.js +0 -758
  211. package/lib-62SWPXNF.js +0 -21042
  212. /package/{chunk-ANUP75N2.js → chunk-2E4BYAUE.js} +0 -0
@@ -1,10 +1,6 @@
1
- import {
2
- fetchCiStatus,
3
- summarizeLatest
4
- } from "./chunk-U5LOKQ2R.js";
5
1
  import {
6
2
  resolveAuthGuidanceState
7
- } from "./chunk-ZQ6K57FJ.js";
3
+ } from "./chunk-4YPH5KRA.js";
8
4
  import {
9
5
  runAnthropicOAuthLogin,
10
6
  runCursorOAuthLogin,
@@ -12,7 +8,7 @@ import {
12
8
  runXaiOAuthDeviceCode,
13
9
  runXaiOAuthLogin,
14
10
  syncCredentialToServer
15
- } from "./chunk-BAH3BAUZ.js";
11
+ } from "./chunk-7OVOZRZF.js";
16
12
  import {
17
13
  createAccountSessionCore,
18
14
  createDeviceAuthorizationProtocol,
@@ -20,19 +16,13 @@ import {
20
16
  parseStoredTokenEntries,
21
17
  parseUserToken,
22
18
  saveTokenLogin
23
- } from "./chunk-SPU3L3OR.js";
24
- import {
25
- listFavoriteAgentIdsAcrossServers,
26
- listLocalCachedAgents,
27
- listRemoteAgents,
28
- listRemoteAgentsAcrossServers,
29
- normalizeListedAgent
30
- } from "./chunk-Y4NPF2UN.js";
19
+ } from "./chunk-HQUGB2HM.js";
31
20
  import {
32
21
  runCloudflareOAuthLogin
33
- } from "./chunk-UF6J7NXV.js";
22
+ } from "./chunk-2C5VN7NH.js";
34
23
  import {
35
24
  COLLAPSED_PASTE_PLACEHOLDER_RE,
25
+ DEFAULT_TUI_AGENT_KEY,
36
26
  MAX_URL_LENGTH,
37
27
  OWNER_OAUTH_UNAVAILABLE_HINT,
38
28
  THEME_PALETTES,
@@ -53,28 +43,37 @@ import {
53
43
  emitTerminalProgramStatus,
54
44
  expandCollapsedPastes,
55
45
  expandRangeToCollapsedPasteChips,
46
+ findAgentCatalogEntry,
56
47
  findCollapsedPasteSpanAt,
48
+ formatAgentSourceLabel,
57
49
  formatAssistantDisplay,
58
50
  formatCreditsChip,
59
51
  formatTokenCount,
52
+ formatUnavailableFavoritesNotice,
60
53
  getActiveThemeMode,
61
54
  getActiveThemeName,
62
55
  getTopReservedRows,
56
+ hasWarmAgentCatalogCache,
63
57
  isAuthFailureError,
64
58
  isBalanceExhaustedError,
65
59
  isInvalidGrantError,
66
60
  isLocalContextCoverageFailure,
67
61
  isOwnerOAuthUnavailableError,
68
62
  isRunResultStalledOrTruncated,
63
+ loadAgentCatalog,
64
+ loadAgentCatalogWithNotices,
65
+ lookupCachedAgentName,
69
66
  normalizeHttpUrl,
70
67
  openExternalUrl,
71
68
  platformCreditsFromUsage,
72
69
  polishBreathInsertsBlankBetween,
73
70
  preferredTopTaskEntries,
71
+ prefetchAgentCatalog,
74
72
  preserveContextUsageWithoutReceipt,
75
73
  redactSecrets,
76
74
  releaseCollapsedPaste,
77
75
  releaseCollapsedPasteReferences,
76
+ renderAgentCatalogList,
78
77
  renderSurfaceLine,
79
78
  renderTokenStatus,
80
79
  replaceCollapsedPastesWithReferences,
@@ -82,6 +81,7 @@ import {
82
81
  resolveAgentContextWindow,
83
82
  resolveAgentModelIdentity,
84
83
  resolveAuthorityTurnCount,
84
+ resolveCatalogPlatformAgents,
85
85
  resolveCliColorEnabled,
86
86
  resolveCliHyperlinkEnabled,
87
87
  resolveCliMemory,
@@ -108,19 +108,21 @@ import {
108
108
  themeColorSequence,
109
109
  themeText,
110
110
  toolRowDetailLine,
111
- tuiRenderThemeFingerprint
112
- } from "./chunk-RMWDKLBE.js";
111
+ tuiRenderThemeFingerprint,
112
+ userBubbleSurfaceBackgroundSequence
113
+ } from "./chunk-S7H4KTMB.js";
113
114
  import "./chunk-6QDYSCPW.js";
114
115
  import "./chunk-GAHJLSDO.js";
116
+ import "./chunk-5AYP5QBB.js";
117
+ import "./chunk-P27E22MA.js";
118
+ import "./chunk-ZYPXOQS2.js";
115
119
  import {
116
- refreshSubscriptionQuotas
117
- } from "./chunk-P27E22MA.js";
118
- import {
119
- getReadableCliDb
120
- } from "./chunk-D25ONVOH.js";
121
- import {
120
+ INSTABOX_SCHEMA_EXPOSURE_ENV,
121
+ MCP_EXPOSURE_ENV,
122
122
  buildCliNoticeText,
123
+ buildLocalPolicyToolNames,
123
124
  buildNoticeTasksFromRuns,
125
+ buildOpenAiTools,
124
126
  clearCliLocalRuntimePreparedAgentCache,
125
127
  createCliHybridRecordStore,
126
128
  createCliLocalRuntimeAdapter,
@@ -131,15 +133,16 @@ import {
131
133
  readTimestamp,
132
134
  renderCliNotice,
133
135
  renderNoticeElements,
136
+ resolveCliRequestedToolNames,
134
137
  resolveNoticeTitle,
135
138
  setTurnNoticeMeta
136
- } from "./chunk-SCMYAGQE.js";
139
+ } from "./chunk-DHRPLRIR.js";
137
140
  import {
138
141
  createHostApprovalCardQueue,
139
142
  formatApprovalRemaining,
140
143
  registerHostApprovalRenderer
141
- } from "./chunk-KLAMJNKQ.js";
142
- import "./chunk-FE7G6DSP.js";
144
+ } from "./chunk-6PAHSSD2.js";
145
+ import "./chunk-R72QWIFO.js";
143
146
  import {
144
147
  ANSI_ESCAPE_REGEX,
145
148
  anthropicGrantRemainingMs,
@@ -165,15 +168,15 @@ import {
165
168
  wrapTextToLines,
166
169
  wrapTranscriptLine,
167
170
  wrapTranscriptLineWithLayout
168
- } from "./chunk-6TVYUQRM.js";
169
- import "./chunk-WWTSEBDF.js";
170
- import "./chunk-VTHWBTRE.js";
171
+ } from "./chunk-6BMTKYAO.js";
172
+ import "./chunk-GIXWVN2W.js";
173
+ import "./chunk-BPB3T5EU.js";
171
174
  import "./chunk-U6RD332P.js";
172
175
  import "./chunk-WOAZVUSN.js";
173
176
  import {
174
177
  getRestartBlocker,
175
178
  hasRestartBlockingRuns
176
- } from "./chunk-PBPXXMWZ.js";
179
+ } from "./chunk-HFHJPHFK.js";
177
180
  import "./chunk-4D4QD7FT.js";
178
181
  import "./chunk-PVFYPUIM.js";
179
182
  import "./chunk-53W5BXLN.js";
@@ -193,48 +196,46 @@ import {
193
196
  resolveDialogNotifyRoot,
194
197
  writeAck,
195
198
  writeLease
196
- } from "./chunk-OHUYN3YU.js";
199
+ } from "./chunk-OKAXQFON.js";
197
200
  import {
198
201
  defaultPromptReader,
199
202
  setSecret
200
- } from "./chunk-ADOOL3PG.js";
203
+ } from "./chunk-J7JRCOIW.js";
201
204
  import {
202
205
  createTuiSummaryLlmCaller
203
- } from "./chunk-4IQN6FWY.js";
206
+ } from "./chunk-OB4FBZXJ.js";
204
207
  import "./chunk-OYUMJMC5.js";
205
208
  import "./chunk-R7XWZDOH.js";
206
209
  import "./chunk-S73EPYNC.js";
207
210
  import "./chunk-ZEZC7IIM.js";
208
211
  import "./chunk-VIWDGTDA.js";
209
- import "./chunk-ATNTHIZI.js";
210
- import "./chunk-JEXVIMYZ.js";
211
- import {
212
- prepareTools
213
- } from "./chunk-IIOSZAJX.js";
214
- import "./chunk-HS7MLR74.js";
215
- import "./chunk-FTWAOKFU.js";
216
- import "./chunk-XCA4WHX5.js";
217
- import "./chunk-AMWMV56B.js";
218
- import "./chunk-MVOZ22RZ.js";
219
- import "./chunk-WDWZPASX.js";
220
- import "./chunk-OAZP4TSA.js";
221
- import "./chunk-JFRJEPFI.js";
222
212
  import {
223
213
  formatSkillSlashReference,
224
214
  parseSkillSlashReference,
225
215
  resolveSkillSlashUserPrompt
226
216
  } from "./chunk-PRJ473FK.js";
227
217
  import "./chunk-BMQ2MJUK.js";
228
- import "./chunk-XSRSAU3O.js";
229
- import "./chunk-LMGFVH65.js";
218
+ import "./chunk-ATNTHIZI.js";
219
+ import "./chunk-V5TI7HJH.js";
220
+ import "./chunk-JEXVIMYZ.js";
221
+ import "./chunk-KDBDOXOM.js";
222
+ import "./chunk-KZ4A7EIV.js";
223
+ import "./chunk-U3BUWDUP.js";
224
+ import "./chunk-3F2FRLIO.js";
225
+ import "./chunk-MVOZ22RZ.js";
226
+ import "./chunk-KG27JIG4.js";
227
+ import "./chunk-SSOR2EDT.js";
230
228
  import "./chunk-NF64D32W.js";
231
- import "./chunk-UOUMPHS5.js";
232
- import "./chunk-J2VIGDJN.js";
229
+ import "./chunk-R3FZHW4Q.js";
230
+ import "./chunk-WDWZPASX.js";
231
+ import "./chunk-OJSJJKHF.js";
232
+ import "./chunk-WSLL7VV4.js";
233
233
  import "./chunk-VF4K2QE6.js";
234
- import "./chunk-OLGFIQN2.js";
235
- import "./chunk-CD64YXRB.js";
236
- import "./chunk-ODBYGVO2.js";
237
- import "./chunk-HCCQEMTK.js";
234
+ import "./chunk-LLUBUHNT.js";
235
+ import "./chunk-U6QNVOR5.js";
236
+ import "./chunk-MNFUKRRU.js";
237
+ import "./chunk-YXK3GJF5.js";
238
+ import "./chunk-WD5547ZF.js";
238
239
  import {
239
240
  createChatQueueRuntime,
240
241
  createTurnRequest,
@@ -242,50 +243,53 @@ import {
242
243
  historyTokensBeforeLatestAssistant,
243
244
  initialChatQueueState,
244
245
  normalizeRunCompletionShape
245
- } from "./chunk-YFW4H6DL.js";
246
- import "./chunk-TZXPT53C.js";
246
+ } from "./chunk-EVHTYVD2.js";
247
247
  import "./chunk-BUDVRYES.js";
248
+ import "./chunk-TZXPT53C.js";
248
249
  import {
249
250
  BUILTIN_DIALOG_LLM_FALLBACK_MODEL,
250
251
  BUILTIN_SUMMARY_LLM_CONFIG
251
252
  } from "./chunk-523DITKR.js";
252
- import "./chunk-N74XL3NI.js";
253
- import "./chunk-FFFKAOJN.js";
253
+ import "./chunk-7PON4LBY.js";
254
+ import "./chunk-YN23INFZ.js";
254
255
  import "./chunk-BYXBJQAS.js";
255
- import "./chunk-ARFCL53U.js";
256
+ import "./chunk-6VEO7Z3Y.js";
256
257
  import {
257
258
  getActiveDialogAgentId
258
259
  } from "./chunk-5RGU3J7P.js";
259
260
  import "./chunk-UVLYNWIE.js";
260
261
  import "./chunk-YNIYE47Z.js";
261
- import "./chunk-V4IYI3SB.js";
262
+ import "./chunk-BZMDWGQQ.js";
263
+ import "./chunk-46FETNLF.js";
262
264
  import "./chunk-UAD2WT54.js";
263
- import "./chunk-HZDK56EK.js";
265
+ import "./chunk-ADYWV732.js";
264
266
  import "./chunk-3PVYUPXK.js";
265
- import "./chunk-X3OZ655T.js";
267
+ import "./chunk-WS36XPJD.js";
268
+ import {
269
+ getDefaultCliLocalRuntimeDb
270
+ } from "./chunk-J55F3IEZ.js";
266
271
  import "./chunk-HXER7YJF.js";
267
272
  import {
268
273
  isHiddenFromDialogList,
269
274
  normalizeDialogRecord,
270
275
  readDialogSnapshot,
271
276
  sortDialogs
272
- } from "./chunk-QMNVV3YM.js";
277
+ } from "./chunk-PJL7OJRC.js";
273
278
  import "./chunk-ID4G2MAR.js";
274
- import {
275
- listUserRecordsFromServers,
276
- readLiveDbRecordAfterTombstoneMerge
277
- } from "./chunk-JEWMQR6J.js";
278
279
  import "./chunk-Y5GCAMGP.js";
280
+ import {
281
+ listUserRecordsFromServers
282
+ } from "./chunk-FZANZZ63.js";
279
283
  import {
280
284
  loadLocalRunChildDialogIds
281
- } from "./chunk-CIGCTSBF.js";
285
+ } from "./chunk-KDDHQMSH.js";
282
286
  import "./chunk-LKZPX6YH.js";
283
287
  import {
284
288
  deleteDbRecord,
285
- queryUserRecords,
286
289
  readDbRecord
287
- } from "./chunk-CIUZXD5D.js";
288
- import "./chunk-FGHEF6WI.js";
290
+ } from "./chunk-UFGUJ2IH.js";
291
+ import "./chunk-PNLDLUMO.js";
292
+ import "./chunk-AMWMV56B.js";
289
293
  import "./chunk-DXWGFL2Z.js";
290
294
  import "./chunk-3L2WKC3W.js";
291
295
  import {
@@ -297,8 +301,9 @@ import {
297
301
  listRunRecords,
298
302
  listRunRecordsAsync,
299
303
  readRunRecord,
304
+ resolveRunsDir,
300
305
  runAgentStopCommand
301
- } from "./chunk-AEZBAFC6.js";
306
+ } from "./chunk-JAKRY74O.js";
302
307
  import {
303
308
  clipText,
304
309
  formatDuration,
@@ -314,43 +319,39 @@ import "./chunk-KQHEGELM.js";
314
319
  import "./chunk-QYPE3TS3.js";
315
320
  import "./chunk-U35UUM5K.js";
316
321
  import "./chunk-RD3QLZQV.js";
317
- import "./chunk-ZM5AZTQG.js";
318
- import "./chunk-WQDTSK5U.js";
319
- import "./chunk-UEILX4EV.js";
320
- import "./chunk-XJSEST7D.js";
321
- import "./chunk-MTM4LRVG.js";
322
- import "./chunk-6XVPMGXK.js";
323
- import "./chunk-YHNUDTU4.js";
322
+ import "./chunk-7BIJFGKS.js";
323
+ import "./chunk-HPDLPEUG.js";
324
+ import "./chunk-ZTHAJU3O.js";
325
+ import "./chunk-HDKMVYNJ.js";
324
326
  import {
325
327
  isExternalSessionKind
326
328
  } from "./chunk-YJPK35HB.js";
329
+ import "./chunk-UEILX4EV.js";
327
330
  import "./chunk-QQ56R7KS.js";
328
331
  import "./chunk-PXYBUFDB.js";
329
332
  import {
330
333
  buildSkillDiscoveryContextBlock,
331
334
  buildSkillDiscoveryContextLayer,
332
335
  discoverSkills
333
- } from "./chunk-UHW6SCVK.js";
336
+ } from "./chunk-UZKBVQUX.js";
334
337
  import "./chunk-GBWGPTA7.js";
335
- import "./chunk-W6T4FNZP.js";
336
- import "./chunk-K7VIXYTZ.js";
337
- import "./chunk-KK3FCYZM.js";
338
+ import "./chunk-OQFOE4SJ.js";
339
+ import "./chunk-TRRXYFTR.js";
340
+ import "./chunk-JLZJL3WC.js";
341
+ import "./chunk-3A5NNQCN.js";
342
+ import "./chunk-R3MV2GII.js";
343
+ import "./chunk-SQL7YNED.js";
338
344
  import "./chunk-CVMMWN6P.js";
339
- import {
340
- getDefaultCliLocalRuntimeDb
341
- } from "./chunk-BFKJ2RS3.js";
342
345
  import "./chunk-GLKOYSRU.js";
343
346
  import {
344
347
  readDialogMessageRecords
345
- } from "./chunk-7UVVLYKC.js";
346
- import "./chunk-MZVCFV3T.js";
347
- import "./chunk-JP2BH4NC.js";
348
- import "./chunk-IJZC2KIJ.js";
348
+ } from "./chunk-KKIQAVDR.js";
349
+ import "./chunk-223KZUJ6.js";
350
+ import "./chunk-CEKRIR22.js";
351
+ import "./chunk-SA356NGW.js";
349
352
  import {
350
353
  RUN_WAKE_CHANNEL_ENV,
351
354
  buildLoadSkillExecutor,
352
- buildLocalWorkspaceOpenAiTools,
353
- buildLocalWorkspaceToolset,
354
355
  findSummaryAnchorIndex,
355
356
  markCliUserBatchPhase,
356
357
  orderDialogHistory,
@@ -363,17 +364,20 @@ import {
363
364
  runTaskStop,
364
365
  saveCliPendingUserMessages,
365
366
  validateStoredSummary
366
- } from "./chunk-XNTZD4AE.js";
367
- import "./chunk-LHCGKAFO.js";
367
+ } from "./chunk-TUOHSUK5.js";
368
368
  import "./chunk-ZNFJWEN4.js";
369
- import "./chunk-MYYNZG2M.js";
370
- import "./chunk-ANUP75N2.js";
369
+ import "./chunk-EHFBP6IK.js";
370
+ import "./chunk-OOV5JN25.js";
371
+ import "./chunk-2E4BYAUE.js";
371
372
  import "./chunk-AL3TYDIF.js";
372
- import "./chunk-EDT65EUE.js";
373
+ import "./chunk-PIVTQRX6.js";
373
374
  import "./chunk-HNUWUO75.js";
374
375
  import "./chunk-CHOZJMJS.js";
375
- import "./chunk-4OXPN3WC.js";
376
- import "./chunk-2FK2KZSL.js";
376
+ import "./chunk-DMPZMYH4.js";
377
+ import "./chunk-5ISNPTQH.js";
378
+ import "./chunk-BYXBJQAS.js";
379
+ import "./chunk-BZLGPM5B.js";
380
+ import "./chunk-AIFQKNPP.js";
377
381
  import "./chunk-56GBUMO5.js";
378
382
  import {
379
383
  TOOL_GUIDED_SECTION_ORDER,
@@ -382,28 +386,25 @@ import {
382
386
  buildRuntimeGuidanceBlocks,
383
387
  resolveResponseGuidelines,
384
388
  resolveToolGuidedSections
385
- } from "./chunk-Z7KE4K3H.js";
386
- import "./chunk-ITBX27W6.js";
387
- import "./chunk-KXOPLLFP.js";
389
+ } from "./chunk-TYJCIA2O.js";
390
+ import "./chunk-VJFDG3ZG.js";
388
391
  import {
389
392
  classifyFailureSubclass,
390
393
  formatQuotaSummary
391
- } from "./chunk-QJTZ76CP.js";
392
- import "./chunk-W3HSD32M.js";
394
+ } from "./chunk-LS5KAVFQ.js";
395
+ import "./chunk-FXEPZKNJ.js";
393
396
  import "./chunk-X4O7FJF5.js";
394
- import "./chunk-DMPZMYH4.js";
395
- import "./chunk-BYXBJQAS.js";
396
- import "./chunk-SX6AWTNK.js";
397
397
  import "./chunk-TLE77UJ5.js";
398
398
  import {
399
+ sanitizeToolOutputText,
399
400
  scrubSecrets
400
- } from "./chunk-WFGNWWJI.js";
401
- import "./chunk-VUHKG4KS.js";
402
- import "./chunk-YDRRGVT5.js";
401
+ } from "./chunk-VH7UO6E5.js";
402
+ import "./chunk-KXOPLLFP.js";
403
+ import "./chunk-DNNPARJK.js";
403
404
  import "./chunk-2MBTWINN.js";
404
405
  import {
405
406
  extractReferenceKeysFromMessage
406
- } from "./chunk-LTVEOOZL.js";
407
+ } from "./chunk-7WHCIA5V.js";
407
408
  import "./chunk-5ZUL4CUO.js";
408
409
  import {
409
410
  COMPACTION_SUMMARY_SYSTEM_PROMPT,
@@ -420,7 +421,7 @@ import {
420
421
  planCompression,
421
422
  runSummaryWithContract,
422
423
  serializeMessageContent
423
- } from "./chunk-MAA42MMV.js";
424
+ } from "./chunk-2FZVXOFX.js";
424
425
  import "./chunk-H57T64RA.js";
425
426
  import "./chunk-UKZX3NHN.js";
426
427
  import "./chunk-SR4FE5VD.js";
@@ -433,29 +434,31 @@ import "./chunk-KX6YBIHG.js";
433
434
  import {
434
435
  formatToolOverflowMarker,
435
436
  getProcessRegistry
436
- } from "./chunk-CTIEJRTP.js";
437
+ } from "./chunk-UP7KBWLE.js";
438
+ import "./chunk-HEVRQGGH.js";
437
439
  import {
438
440
  isQuotaExhaustedError
439
441
  } from "./chunk-EWQ3HGNZ.js";
440
442
  import {
441
443
  estimateTokenCount
442
444
  } from "./chunk-PSCNXBYA.js";
445
+ import "./chunk-IVK2KT3H.js";
443
446
  import {
444
447
  compactWhitespace
445
448
  } from "./chunk-DWLEOOGR.js";
446
- import "./chunk-OW765XBU.js";
447
449
  import {
448
450
  isAbortError
449
451
  } from "./chunk-7DPNBQSV.js";
452
+ import "./chunk-OW765XBU.js";
450
453
  import {
451
454
  buildMemoryOverlayLayer,
452
455
  buildMemoryUseGuidanceLayer,
453
456
  partitionScopedBlocks,
454
457
  renderTurnContextBlocksWithScope
455
- } from "./chunk-5HUO7SEX.js";
458
+ } from "./chunk-D634SL2Y.js";
456
459
  import {
457
460
  buildUserResponseLanguageContext
458
- } from "./chunk-YGDYYFRX.js";
461
+ } from "./chunk-UAF5VQCE.js";
459
462
  import "./chunk-2SXN7LAY.js";
460
463
  import {
461
464
  createOAuthTokenStore,
@@ -467,57 +470,54 @@ import {
467
470
  dialogMessageRecordToAgentRuntimeMessage
468
471
  } from "./chunk-4ZCTKB27.js";
469
472
  import {
470
- expandEnabledPacks,
471
473
  listBuiltinSkills
472
- } from "./chunk-6MTVACLN.js";
474
+ } from "./chunk-WC3J5SL2.js";
475
+ import "./chunk-EUGTFFO6.js";
473
476
  import {
474
477
  parseExternalSkillMarkdown
475
478
  } from "./chunk-AETZ7AD6.js";
476
- import "./chunk-CO6E7YK6.js";
479
+ import "./chunk-5P3PPQVP.js";
477
480
  import "./chunk-KHCLMKZZ.js";
478
481
  import "./chunk-SYTHYBMI.js";
479
482
  import "./chunk-OJKUU3LP.js";
480
483
  import "./chunk-YZMNK53S.js";
481
484
  import {
482
485
  resolveLocalUserId
483
- } from "./chunk-UPOW5HTG.js";
486
+ } from "./chunk-QGFLVQ6E.js";
484
487
  import {
485
488
  CURRENT_OPERATOR_USER_ID,
486
- NOLO_DEFAULT_AGENT_KEY,
487
489
  resolveCliAgentKeyInput
488
490
  } from "./chunk-BR3GT6MR.js";
489
- import "./chunk-NEG5LYK5.js";
490
- import "./chunk-GX6DITLQ.js";
491
+ import "./chunk-JCQ3WCQ3.js";
492
+ import "./chunk-UUCYUN6Y.js";
491
493
  import {
492
494
  canonicalizeToolNames
493
495
  } from "./chunk-YLAHYLDQ.js";
494
496
  import {
495
497
  BUILTIN_NOLO_AGENT_KEY,
496
498
  BUILTIN_NOLO_AGENT_MODEL,
497
- BUILTIN_NOLO_AGENT_NAME,
498
- builtinAgentCatalogEntryById,
499
- parseBuiltinPlatformAgentId
500
- } from "./chunk-KZAT2M2V.js";
499
+ BUILTIN_NOLO_AGENT_NAME
500
+ } from "./chunk-RIWKZT7E.js";
501
501
  import {
502
- extractCustomId,
503
- parsePublicAgentId
502
+ extractCustomId
504
503
  } from "./chunk-M2EJHDJP.js";
505
504
  import "./chunk-I42VC5KR.js";
506
- import "./chunk-AS6L5KSD.js";
505
+ import "./chunk-P4R5KXU7.js";
507
506
  import "./chunk-VIDPVFP3.js";
508
507
  import "./chunk-4JH2UMJR.js";
509
508
  import "./chunk-U6VC4MU4.js";
509
+ import "./chunk-XRGBJHZX.js";
510
510
  import {
511
511
  getDiagnostics,
512
512
  getProcessRingBuffer,
513
513
  resolveDefaultLogPath
514
- } from "./chunk-6XRPBZRS.js";
514
+ } from "./chunk-EYLGAEB4.js";
515
515
  import {
516
516
  checkForCliUpdate,
517
517
  getCliInstallChannel,
518
518
  probeCliUpdate,
519
519
  runSelfUpdateDetailed
520
- } from "./chunk-73PZD7JZ.js";
520
+ } from "./chunk-IYLUK67R.js";
521
521
  import {
522
522
  parseUserIdFromAuthToken,
523
523
  resolveAuthToken,
@@ -546,7 +546,7 @@ import {
546
546
  resolveDefaultSpawn,
547
547
  spawnProcess
548
548
  } from "./chunk-4O22PGNQ.js";
549
- import "./chunk-TMRJGSK2.js";
549
+ import "./chunk-OOVOAG4Q.js";
550
550
  import {
551
551
  dailyWelcomeTip,
552
552
  getCliLocale,
@@ -556,19 +556,19 @@ import {
556
556
  t,
557
557
  toolFamilyOf,
558
558
  toolLabelVariants
559
- } from "./chunk-E5RYFR7E.js";
560
- import "./chunk-6ASGEP5D.js";
561
- import "./chunk-CTWCZKNS.js";
559
+ } from "./chunk-FEIVARWR.js";
560
+ import "./chunk-EJQE5HB7.js";
561
+ import "./chunk-6SOWMEAY.js";
562
562
  import {
563
563
  toErrorMessage
564
564
  } from "./chunk-HNMXYYJR.js";
565
565
  import {
566
566
  resolvePlatformAuthToken
567
- } from "./chunk-K26XPZRB.js";
568
- import "./chunk-ESN4WNWU.js";
567
+ } from "./chunk-LVZVSLKO.js";
568
+ import "./chunk-2JHGUL5K.js";
569
569
  import "./chunk-3EUW3WEO.js";
570
570
  import "./chunk-WWC7I6TA.js";
571
- import "./chunk-CD2DK5JA.js";
571
+ import "./chunk-OKH74FML.js";
572
572
  import "./chunk-JRTNUU5Z.js";
573
573
  import {
574
574
  isRecord
@@ -582,601 +582,12 @@ import {
582
582
  } from "./chunk-CF7PE763.js";
583
583
  import {
584
584
  PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL
585
- } from "./chunk-PQ63BDV3.js";
585
+ } from "./chunk-JPXACKSW.js";
586
586
  import {
587
587
  asTrimmedLowercaseString
588
588
  } from "./chunk-QSJ3HFEF.js";
589
589
  import "./chunk-U67V476Y.js";
590
590
 
591
- // packages/ai/agent/utils/sortUtils.ts
592
- function sortAgentsFavoriteOwnedPublic(items) {
593
- const map = /* @__PURE__ */ new Map();
594
- for (const item of items) {
595
- const existing = map.get(item.key);
596
- if (!existing) {
597
- map.set(item.key, { ...item });
598
- continue;
599
- }
600
- map.set(item.key, {
601
- ...existing,
602
- ...item,
603
- key: existing.key,
604
- favoritedAt: Math.max(existing.favoritedAt ?? 0, item.favoritedAt ?? 0) || void 0,
605
- isOwned: Boolean(existing.isOwned || item.isOwned),
606
- isPublic: Boolean(existing.isPublic || item.isPublic),
607
- updatedAt: Math.max(existing.updatedAt ?? 0, item.updatedAt ?? 0),
608
- order: existing.order ?? item.order
609
- });
610
- }
611
- const arr = Array.from(map.values());
612
- arr.sort((a, b) => {
613
- const aFav = a.favoritedAt != null && a.favoritedAt > 0;
614
- const bFav = b.favoritedAt != null && b.favoritedAt > 0;
615
- if (aFav !== bFav) return aFav ? -1 : 1;
616
- if (aFav && bFav) {
617
- const diff = (b.favoritedAt ?? 0) - (a.favoritedAt ?? 0);
618
- if (diff !== 0) return diff;
619
- }
620
- const aOwned = Boolean(a.isOwned);
621
- const bOwned = Boolean(b.isOwned);
622
- if (aOwned !== bOwned) return aOwned ? -1 : 1;
623
- const aPublic = Boolean(a.isPublic);
624
- const bPublic = Boolean(b.isPublic);
625
- if (aPublic !== bPublic) return aPublic ? -1 : 1;
626
- const tsDiff = (b.updatedAt ?? 0) - (a.updatedAt ?? 0);
627
- if (tsDiff !== 0) return tsDiff;
628
- const aOrder = a.order ?? Number.POSITIVE_INFINITY;
629
- const bOrder = b.order ?? Number.POSITIVE_INFINITY;
630
- if (aOrder !== bOrder) return aOrder - bOrder;
631
- return a.key.localeCompare(b.key);
632
- });
633
- return arr;
634
- }
635
-
636
- // packages/cli/tui/agentCatalog.ts
637
- var DEFAULT_TUI_AGENT_KEY = NOLO_DEFAULT_AGENT_KEY;
638
- function formatAgentSourceLabel(entry) {
639
- if (entry.kind === "platform" || entry.apiSource === "platform") return t("agentSourcePlatform");
640
- if (entry.apiSource === "cli") {
641
- return entry.cliProvider ? `${t("agentSourceSubscription")}(${entry.cliProvider})` : t("agentSourceSubscription");
642
- }
643
- if (entry.apiSource === "custom") return t("agentSourceApi");
644
- return t("agentSourcePlatform");
645
- }
646
- var PLATFORM_AGENTS = [
647
- {
648
- // 名称与模型都从 builtinAgentCatalog 派生:`/switch` 里的 nolo 项直接显示
649
- // 它实际指向的模型(当前 deepseek-flash),换代自动跟随。
650
- name: BUILTIN_NOLO_AGENT_NAME,
651
- key: DEFAULT_TUI_AGENT_KEY,
652
- model: BUILTIN_NOLO_AGENT_MODEL,
653
- kind: "platform",
654
- description: "one assistant that routes work across your agents and data"
655
- }
656
- ];
657
- function resolveCatalogPlatformAgents(_env = process.env) {
658
- return PLATFORM_AGENTS;
659
- }
660
- function toUpdatedAt(value) {
661
- if (value == null) return 0;
662
- const parsed = new Date(value).getTime();
663
- return Number.isFinite(parsed) ? parsed : 0;
664
- }
665
- function listedAgentToCatalogEntry(agent) {
666
- return {
667
- name: agent.name,
668
- key: agent.privateKey,
669
- model: agent.model,
670
- kind: "private",
671
- updatedAt: toUpdatedAt(agent.updatedAt),
672
- ...agent.apiSource ? { apiSource: agent.apiSource } : {},
673
- ...agent.cliProvider ? { cliProvider: agent.cliProvider } : {},
674
- ...agent.quota ? { quota: agent.quota } : {}
675
- };
676
- }
677
- function mergeCatalogEntries(currentKey, platformAgents, privateAgents, favoritedAtByKey = {}) {
678
- const seen = /* @__PURE__ */ new Set();
679
- const merged = [];
680
- const push = (entry) => {
681
- if (seen.has(entry.key)) return;
682
- seen.add(entry.key);
683
- const favoritedAt = favoritedAtByKey[entry.key];
684
- merged.push(favoritedAt ? { ...entry, favoritedAt } : entry);
685
- };
686
- const current = [...platformAgents, ...privateAgents].find((entry) => entry.key === currentKey) ?? null;
687
- if (current) push(current);
688
- for (const entry of platformAgents) {
689
- if (entry.key !== currentKey) push(entry);
690
- }
691
- const sortablePrivate = privateAgents.map((entry) => ({
692
- key: entry.key,
693
- ...favoritedAtByKey[entry.key] !== void 0 ? { favoritedAt: favoritedAtByKey[entry.key] } : {},
694
- isOwned: true,
695
- updatedAt: entry.updatedAt ?? 0
696
- }));
697
- const sortedKeys = sortAgentsFavoriteOwnedPublic(sortablePrivate);
698
- const sortedKeyOrder = new Map(sortedKeys.map((item, i) => [item.key, i]));
699
- const sortedPrivate = [...privateAgents].sort(
700
- (a, b) => (sortedKeyOrder.get(a.key) ?? 0) - (sortedKeyOrder.get(b.key) ?? 0)
701
- );
702
- for (const entry of sortedPrivate) {
703
- if (entry.key !== currentKey) push(entry);
704
- }
705
- return merged;
706
- }
707
- function formatUnavailableFavoritesNotice(unavailableFavoriteCount) {
708
- if (!Number.isFinite(unavailableFavoriteCount) || unavailableFavoriteCount <= 0) {
709
- return null;
710
- }
711
- return t(
712
- "agentCatalogUnavailableFavorites",
713
- String(Math.floor(unavailableFavoriteCount))
714
- );
715
- }
716
- var agentCatalogCache = null;
717
- var lastRefresh = null;
718
- function getAgentCatalogRefreshStatus(args = {}) {
719
- const env = args.env ?? process.env;
720
- const token = resolveAuthToken([], env);
721
- const key = `${token ? parseUserIdFromAuthToken(token) ?? "anon" : "anon"}|${resolveServerUrl(env)}`;
722
- return lastRefresh?.cacheKey === key ? lastRefresh.status : null;
723
- }
724
- var agentCatalogRefreshInFlight = null;
725
- var agentCatalogGeneration = 0;
726
- var agentCatalogRawLoadInFlight = /* @__PURE__ */ new Map();
727
- var AGENT_CATALOG_FRESH_MS = 15e3;
728
- var AGENT_CATALOG_MAX_STALE_MS = 5 * 6e4;
729
- var AGENT_CATALOG_FOREGROUND_DEADLINE_MS = 2500;
730
- var AGENT_CATALOG_BACKGROUND_DEADLINE_MS = 8e3;
731
- function resolveCatalogDeadlineMs(kind, env) {
732
- const override = Number.parseInt(env.NOLO_TUI_CATALOG_DEADLINE_MS ?? "", 10);
733
- if (Number.isFinite(override) && override > 0) return override;
734
- return kind === "foreground" ? AGENT_CATALOG_FOREGROUND_DEADLINE_MS : AGENT_CATALOG_BACKGROUND_DEADLINE_MS;
735
- }
736
- var SERVER_TRIP_AFTER_CONSECUTIVE_FAILURES = 1;
737
- var SERVER_COOLDOWN_MS = 5 * 6e4;
738
- var serverHealth = /* @__PURE__ */ new Map();
739
- var serverHealthNow = () => Date.now();
740
- function filterHealthyServers(serverUrls) {
741
- const now = serverHealthNow();
742
- const healthy = serverUrls.filter((url) => {
743
- const state = serverHealth.get(url);
744
- if (!state) return true;
745
- return !(state.consecutiveFailures >= SERVER_TRIP_AFTER_CONSECUTIVE_FAILURES && now - state.trippedAt < SERVER_COOLDOWN_MS);
746
- });
747
- return healthy.length > 0 ? healthy : serverUrls;
748
- }
749
- function keepPrimaryServer(serverUrls, primary) {
750
- return serverUrls.includes(primary) ? serverUrls : [primary, ...serverUrls];
751
- }
752
- function recordServerFailures(failures) {
753
- const now = serverHealthNow();
754
- for (const failure of failures) {
755
- const state = serverHealth.get(failure.serverUrl) ?? {
756
- consecutiveFailures: 0,
757
- trippedAt: 0
758
- };
759
- state.consecutiveFailures += 1;
760
- if (state.consecutiveFailures >= SERVER_TRIP_AFTER_CONSECUTIVE_FAILURES) {
761
- state.trippedAt = now;
762
- }
763
- serverHealth.set(failure.serverUrl, state);
764
- }
765
- }
766
- function recordServerSuccesses(serverUrls) {
767
- for (const url of serverUrls) serverHealth.delete(url);
768
- }
769
- function withFetchDeadline(fetchImpl, deadlineMs) {
770
- return async (input, init) => {
771
- let timer;
772
- const deadline = new Promise((_, reject) => {
773
- timer = setTimeout(
774
- () => reject(new Error(`catalog fetch deadline exceeded (${deadlineMs}ms)`)),
775
- deadlineMs
776
- );
777
- });
778
- const signal = init?.signal;
779
- let onAbort;
780
- let aborted = null;
781
- if (signal) {
782
- if (signal.aborted) {
783
- throw signal.reason ?? new Error("catalog fetch aborted");
784
- }
785
- aborted = new Promise((_, reject) => {
786
- onAbort = () => reject(signal.reason ?? new Error("catalog fetch aborted"));
787
- signal.addEventListener("abort", onAbort, { once: true });
788
- });
789
- }
790
- try {
791
- const response = await Promise.race([
792
- fetchImpl(input, init),
793
- deadline,
794
- ...aborted ? [aborted] : []
795
- ]);
796
- const text = await Promise.race([
797
- response.text(),
798
- deadline,
799
- ...aborted ? [aborted] : []
800
- ]);
801
- return new Response(text, {
802
- status: response.status,
803
- statusText: response.statusText,
804
- headers: response.headers
805
- });
806
- } finally {
807
- if (timer) clearTimeout(timer);
808
- if (signal && onAbort) signal.removeEventListener("abort", onAbort);
809
- }
810
- };
811
- }
812
- function hasWarmAgentCatalogCache(args = {}) {
813
- const env = args.env ?? process.env;
814
- const authToken = resolveAuthToken([], env);
815
- const userId = authToken ? parseUserIdFromAuthToken(authToken) : null;
816
- const cacheKey = `${userId ?? "anon"}|${resolveServerUrl(env)}`;
817
- return agentCatalogCache?.cacheKey === cacheKey && Date.now() - agentCatalogCache.at < AGENT_CATALOG_MAX_STALE_MS;
818
- }
819
- async function loadAgentCatalog(args) {
820
- return (await loadAgentCatalogWithNotices(args)).entries;
821
- }
822
- async function loadAgentCatalogWithNotices(args) {
823
- const env = args.env ?? process.env;
824
- const authToken = resolveAuthToken([], env);
825
- const userId = authToken ? parseUserIdFromAuthToken(authToken) : null;
826
- const cacheKey = `${userId ?? "anon"}|${resolveServerUrl(env)}`;
827
- const cached = agentCatalogCache?.cacheKey === cacheKey ? agentCatalogCache : null;
828
- if (cached && !args.fresh && Date.now() - cached.at < AGENT_CATALOG_MAX_STALE_MS) {
829
- const refreshStatus = getAgentCatalogRefreshStatus({ env });
830
- if (args.revalidateInBackground || Date.now() - cached.at >= AGENT_CATALOG_FRESH_MS) {
831
- refreshAgentCatalogInBackground(args, env, cacheKey);
832
- }
833
- if (args.currentKey && cached.entries.length > 1 && cached.entries[0]?.key !== args.currentKey) {
834
- const idx = cached.entries.findIndex((entry) => entry.key === args.currentKey);
835
- if (idx > 0) {
836
- return {
837
- entries: [
838
- cached.entries[idx],
839
- ...cached.entries.slice(0, idx),
840
- ...cached.entries.slice(idx + 1)
841
- ],
842
- refreshStatus,
843
- unavailableFavoriteCount: cached.unavailableFavoriteCount
844
- };
845
- }
846
- }
847
- return {
848
- entries: cached.entries,
849
- refreshStatus,
850
- unavailableFavoriteCount: cached.unavailableFavoriteCount
851
- };
852
- }
853
- let rawData;
854
- const generation = args.fresh ? ++agentCatalogGeneration : agentCatalogGeneration;
855
- const deadlineKind = args.fresh ? "foreground" : args.deadlineKind ?? "foreground";
856
- const inFlight = agentCatalogRawLoadInFlight.get(deadlineKind);
857
- if (inFlight) {
858
- rawData = await inFlight;
859
- } else {
860
- const promise = fetchRawCatalogData({ ...args, deadlineKind }, env);
861
- agentCatalogRawLoadInFlight.set(deadlineKind, promise);
862
- try {
863
- rawData = await promise;
864
- } finally {
865
- if (agentCatalogRawLoadInFlight.get(deadlineKind) === promise) {
866
- agentCatalogRawLoadInFlight.delete(deadlineKind);
867
- }
868
- }
869
- }
870
- const entries = mergeCatalogEntries(
871
- args.currentKey,
872
- resolveCatalogPlatformAgents(env),
873
- rawData.privateAgents,
874
- rawData.favoritedAtByKey
875
- );
876
- if (generation === agentCatalogGeneration) {
877
- lastRefresh = { cacheKey, status: rawData.status };
878
- }
879
- if (generation === agentCatalogGeneration && rawData.status === "success") {
880
- agentCatalogCache = {
881
- cacheKey,
882
- at: Date.now(),
883
- entries,
884
- unavailableFavoriteCount: rawData.unavailableFavoriteCount
885
- };
886
- }
887
- void mergeCatalogQuotas(entries, { env, fetchImpl: args.fetchImpl }).catch(() => {
888
- });
889
- return { entries, unavailableFavoriteCount: rawData.unavailableFavoriteCount, refreshStatus: rawData.status };
890
- }
891
- async function mergeCatalogQuotas(entries, args) {
892
- const fresh = await refreshSubscriptionQuotas({
893
- entries: entries.map((entry) => ({
894
- key: entry.key,
895
- ...entry.quota ? { quota: entry.quota } : {},
896
- probeable: entry.kind === "private"
897
- })),
898
- ...args.env ? { env: args.env } : {},
899
- ...args.fetchImpl ? { fetchImpl: args.fetchImpl } : {}
900
- });
901
- for (const entry of entries) {
902
- const quota = fresh[entry.key];
903
- if (quota) entry.quota = quota;
904
- }
905
- }
906
- function refreshAgentCatalogInBackground(args, env, cacheKey) {
907
- if (agentCatalogRefreshInFlight) return;
908
- const generation = agentCatalogGeneration;
909
- agentCatalogRefreshInFlight = fetchRawCatalogData(
910
- { ...args, deadlineKind: "background" },
911
- env
912
- ).then(async (rawData) => {
913
- if (generation !== agentCatalogGeneration) return;
914
- lastRefresh = { cacheKey, status: rawData.status };
915
- if (rawData.status !== "success") return;
916
- const entries = mergeCatalogEntries(
917
- args.currentKey,
918
- resolveCatalogPlatformAgents(env),
919
- rawData.privateAgents,
920
- rawData.favoritedAtByKey
921
- );
922
- await mergeCatalogQuotas(entries, { env, fetchImpl: args.fetchImpl });
923
- if (generation === agentCatalogGeneration) {
924
- agentCatalogCache = {
925
- cacheKey,
926
- at: Date.now(),
927
- entries,
928
- unavailableFavoriteCount: rawData.unavailableFavoriteCount
929
- };
930
- }
931
- }).catch(() => {
932
- if (generation === agentCatalogGeneration) lastRefresh = { cacheKey, status: "failed" };
933
- }).finally(() => {
934
- agentCatalogRefreshInFlight = null;
935
- });
936
- }
937
- async function prefillCatalogFromLocalDb(_args) {
938
- }
939
- function prefetchAgentCatalog(args) {
940
- void (async () => {
941
- await prefillCatalogFromLocalDb({ env: args.env, getDb: args.getDb }).catch(() => {
942
- });
943
- void loadAgentCatalog({ ...args, currentKey: "", deadlineKind: "background" }).catch(() => {
944
- });
945
- })();
946
- }
947
- async function fetchRawCatalogData(args, env) {
948
- const deadlineMs = resolveCatalogDeadlineMs(args.deadlineKind ?? "foreground", env);
949
- const fetchImpl = withFetchDeadline(args.fetchImpl ?? fetch, deadlineMs);
950
- const fallbackFetchImpl = args.fallbackFetchImpl ? withFetchDeadline(args.fallbackFetchImpl, deadlineMs) : void 0;
951
- const authToken = resolveAuthToken([], env);
952
- const userId = authToken ? parseUserIdFromAuthToken(authToken) : null;
953
- if (!authToken || !userId) {
954
- return { privateAgents: [], favoritedAtByKey: {}, unavailableFavoriteCount: 0, status: "success" };
955
- }
956
- const serverUrl = resolveServerUrl(env);
957
- const allServerUrls = resolveServerCandidates([], env, serverUrl);
958
- const serverUrls = (args.deadlineKind ?? "foreground") === "foreground" ? keepPrimaryServer(filterHealthyServers(allServerUrls), serverUrl) : allServerUrls;
959
- const fetchStartedAt = performance.now();
960
- let listedAgents = [];
961
- let catalogAuthoritative = false;
962
- let catalogAvailable = false;
963
- let favoritesFailed = false;
964
- const favoritesPromise = listFavoriteAgentIdsAcrossServers({
965
- authToken,
966
- fetchImpl,
967
- serverUrls,
968
- onFailure: () => {
969
- favoritesFailed = true;
970
- }
971
- }).catch(() => {
972
- favoritesFailed = true;
973
- return {};
974
- });
975
- try {
976
- const remoteResult = await listRemoteAgentsAcrossServers({
977
- authToken,
978
- fallbackFetchImpl,
979
- fetchImpl,
980
- serverUrls,
981
- userId
982
- });
983
- listedAgents = remoteResult.agents;
984
- catalogAvailable = true;
985
- catalogAuthoritative = remoteResult.failures.length === 0 && serverUrls.length === allServerUrls.length;
986
- recordServerSuccesses(serverUrls.filter(
987
- (url) => !remoteResult.failures.some((f) => f.serverUrl === url)
988
- ));
989
- recordServerFailures(remoteResult.failures);
990
- } catch {
991
- try {
992
- const localBudgetMs = Math.max(
993
- 500,
994
- deadlineMs - (performance.now() - fetchStartedAt)
995
- );
996
- let localTimer;
997
- try {
998
- listedAgents = await Promise.race([
999
- (async () => {
1000
- const db = args.getDb ? await args.getDb() : await getReadableCliDb({ write: () => {
1001
- } });
1002
- return listLocalCachedAgents({ db, userId });
1003
- })(),
1004
- new Promise((_, reject) => {
1005
- localTimer = setTimeout(
1006
- () => reject(new Error("local catalog deadline exceeded")),
1007
- localBudgetMs
1008
- );
1009
- })
1010
- ]);
1011
- catalogAvailable = true;
1012
- } finally {
1013
- if (localTimer) clearTimeout(localTimer);
1014
- }
1015
- } catch {
1016
- try {
1017
- listedAgents = await listRemoteAgents({
1018
- authToken,
1019
- fallbackFetchImpl,
1020
- fetchImpl,
1021
- serverUrl,
1022
- userId,
1023
- queryUserRecords,
1024
- readDbRecord
1025
- });
1026
- catalogAvailable = true;
1027
- } catch {
1028
- listedAgents = [];
1029
- }
1030
- }
1031
- }
1032
- const privateAgents = listedAgents.map(listedAgentToCatalogEntry);
1033
- const favoritedAtByKey = await favoritesPromise;
1034
- for (const agent of listedAgents) {
1035
- const favoritedAt = [agent.privateKey, agent.publicKey, agent.id].map((key) => favoritedAtByKey[key]).find((value) => value !== void 0);
1036
- if (favoritedAt !== void 0) favoritedAtByKey[agent.privateKey] = favoritedAt;
1037
- }
1038
- const existingKeys = /* @__PURE__ */ new Set();
1039
- for (const agent of listedAgents) {
1040
- existingKeys.add(agent.privateKey);
1041
- existingKeys.add(agent.publicKey);
1042
- existingKeys.add(agent.id);
1043
- }
1044
- let unavailableFavoriteCount = 0;
1045
- let orphanSkipped = false;
1046
- await Promise.all(
1047
- Object.keys(favoritedAtByKey).map(async (favKey) => {
1048
- if (existingKeys.has(favKey)) return;
1049
- const remainingMs = deadlineMs - (performance.now() - fetchStartedAt);
1050
- if (remainingMs <= 0) {
1051
- orphanSkipped = true;
1052
- return;
1053
- }
1054
- try {
1055
- let orphanTimer;
1056
- const orphanDeadline = new Promise((_, reject) => {
1057
- orphanTimer = setTimeout(
1058
- () => reject(new Error("orphan hydrate deadline")),
1059
- remainingMs
1060
- );
1061
- });
1062
- try {
1063
- const favRead = await Promise.race([
1064
- readLiveDbRecordAfterTombstoneMerge({
1065
- authToken,
1066
- dbKey: favKey,
1067
- fallbackFetchImpl,
1068
- fetchImpl,
1069
- serverUrls
1070
- }),
1071
- orphanDeadline
1072
- ]);
1073
- const record = favRead.record;
1074
- if (!record || record.type && record.type !== "agent") return;
1075
- const norm = normalizeListedAgent(record);
1076
- if (!norm) return;
1077
- if (existingKeys.has(norm.privateKey) || existingKeys.has(norm.publicKey) || existingKeys.has(norm.id)) {
1078
- return;
1079
- }
1080
- existingKeys.add(norm.privateKey);
1081
- existingKeys.add(norm.publicKey);
1082
- existingKeys.add(norm.id);
1083
- privateAgents.push(listedAgentToCatalogEntry(norm));
1084
- } finally {
1085
- if (orphanTimer) clearTimeout(orphanTimer);
1086
- }
1087
- } catch {
1088
- unavailableFavoriteCount += 1;
1089
- }
1090
- })
1091
- );
1092
- const status = !catalogAvailable && favoritesFailed ? "failed" : catalogAuthoritative && !favoritesFailed && unavailableFavoriteCount === 0 && !orphanSkipped ? "success" : "degraded";
1093
- return { privateAgents, favoritedAtByKey, unavailableFavoriteCount, status };
1094
- }
1095
- function renderAgentCatalogList(entries, currentKey, options) {
1096
- const lines = ["Agents:"];
1097
- entries.forEach((entry, index) => {
1098
- const current = entry.key === currentKey ? " (current)" : "";
1099
- const favorite = entry.favoritedAt ? " \u2605" : "";
1100
- const detail = entry.description ? ` \u2014 ${entry.description}` : "";
1101
- const quota = formatQuotaSummary(entry.quota, Date.now(), { model: entry.model });
1102
- const trailing = quota ? ` [${quota}]` : detail;
1103
- lines.push(
1104
- ` ${String(index + 1).padStart(2)} ${entry.name.padEnd(18)} ${entry.model.padEnd(14)} ${formatAgentSourceLabel(entry)}${favorite}${trailing}${current}`
1105
- );
1106
- });
1107
- lines.push("");
1108
- const notice = formatUnavailableFavoritesNotice(
1109
- options?.unavailableFavoriteCount ?? 0
1110
- );
1111
- if (notice) lines.push(notice);
1112
- lines.push("Tip: run /switch in an interactive terminal to pick with \u2191\u2193.");
1113
- return lines.join("\n");
1114
- }
1115
- function resolveEntryApiSource(entry) {
1116
- if (entry.apiSource) return entry.apiSource;
1117
- return entry.kind === "platform" ? "platform" : void 0;
1118
- }
1119
- function toSwitchTarget(entry) {
1120
- const apiSource = resolveEntryApiSource(entry);
1121
- return {
1122
- name: entry.name,
1123
- key: entry.key,
1124
- model: entry.model,
1125
- ...apiSource ? { apiSource } : {}
1126
- };
1127
- }
1128
- function findAgentCatalogEntry(entries, rawTarget) {
1129
- const target = rawTarget.trim();
1130
- if (!target) return null;
1131
- if (/^\d+$/.test(target)) {
1132
- const entry = entries[Number(target) - 1];
1133
- return entry ? toSwitchTarget(entry) : null;
1134
- }
1135
- const lower = target.toLowerCase();
1136
- const byName = entries.find(
1137
- (entry) => entry.name.toLowerCase() === lower || entry.key.toLowerCase() === lower || entry.key.toLowerCase().endsWith(`-${lower}`)
1138
- );
1139
- if (byName) return toSwitchTarget(byName);
1140
- if (target.startsWith("agent-") || target.startsWith("agent-pub-")) {
1141
- const builtin = builtinAgentCatalogEntryById(
1142
- parseBuiltinPlatformAgentId(target) ?? parsePublicAgentId(target)
1143
- );
1144
- if (builtin) {
1145
- return {
1146
- name: builtin.name,
1147
- key: target,
1148
- model: builtin.model,
1149
- apiSource: builtin.apiSource ?? "platform"
1150
- };
1151
- }
1152
- return { name: target, key: target };
1153
- }
1154
- return null;
1155
- }
1156
- function lookupCachedAgentName(agentKey) {
1157
- const trimmed = agentKey.trim();
1158
- if (!trimmed) return void 0;
1159
- const platform = PLATFORM_AGENTS.find(
1160
- (p) => p.key === trimmed || p.key.toLowerCase() === trimmed.toLowerCase()
1161
- );
1162
- if (platform?.name) return platform.name;
1163
- const builtin = builtinAgentCatalogEntryById(
1164
- parseBuiltinPlatformAgentId(trimmed) ?? parsePublicAgentId(trimmed)
1165
- );
1166
- if (builtin?.name) return builtin.name;
1167
- if (agentCatalogCache?.entries) {
1168
- const direct = agentCatalogCache.entries.find(
1169
- (entry) => entry.key === trimmed || entry.key.toLowerCase() === trimmed.toLowerCase()
1170
- );
1171
- if (direct?.name) return direct.name;
1172
- const suffix = agentCatalogCache.entries.find(
1173
- (entry) => entry.key.toLowerCase().endsWith(`-${trimmed.toLowerCase()}`) || trimmed.toLowerCase().endsWith(`-${entry.key.toLowerCase()}`)
1174
- );
1175
- if (suffix?.name) return suffix.name;
1176
- }
1177
- return void 0;
1178
- }
1179
-
1180
591
  // packages/cli/tui/runSnapshotDisplay.ts
1181
592
  function runStatusTone(status) {
1182
593
  if (!isAgentRunTerminalStatus(status)) return "warning";
@@ -1911,19 +1322,48 @@ function autoScrollStepForTicks(ticks) {
1911
1322
  if (ticks >= 8) return 3;
1912
1323
  return 1;
1913
1324
  }
1914
- function renderScrollbarRow(rowIndex, visibleHeight, totalLines, scrollTop) {
1915
- if (totalLines <= visibleHeight) return " ";
1325
+ function computeScrollbarGeometry(visibleHeight, totalLines, scrollTop) {
1326
+ if (visibleHeight <= 0 || totalLines <= visibleHeight) return null;
1916
1327
  const trackHeight = visibleHeight;
1917
1328
  const thumbSize = Math.max(
1918
1329
  1,
1919
1330
  Math.floor(visibleHeight * visibleHeight / totalLines)
1920
1331
  );
1921
1332
  const maxScrollTop = totalLines - visibleHeight;
1333
+ const clampedScrollTop = Math.max(0, Math.min(maxScrollTop, scrollTop));
1922
1334
  const thumbTop = Math.floor(
1923
- scrollTop / maxScrollTop * (trackHeight - thumbSize)
1335
+ clampedScrollTop / maxScrollTop * (trackHeight - thumbSize)
1336
+ );
1337
+ return {
1338
+ trackHeight,
1339
+ thumbSize,
1340
+ thumbTop,
1341
+ thumbBottom: thumbTop + thumbSize,
1342
+ maxScrollTop
1343
+ };
1344
+ }
1345
+ function isScrollbarColumnHit(screenCol, columns, marginRight = 0) {
1346
+ if (columns <= 0) return false;
1347
+ const firstHitCol = Math.max(0, columns - 1 - Math.max(0, marginRight));
1348
+ return screenCol >= firstHitCol && screenCol < columns;
1349
+ }
1350
+ function scrollTopFromScrollbarDrag(rowIndex, grabOffset, visibleHeight, totalLines) {
1351
+ const geom = computeScrollbarGeometry(visibleHeight, totalLines, 0);
1352
+ if (!geom) return 0;
1353
+ const movableTrack = geom.trackHeight - geom.thumbSize;
1354
+ if (movableTrack <= 0) {
1355
+ return rowIndex <= 0 ? 0 : geom.maxScrollTop;
1356
+ }
1357
+ const desiredThumbTop = Math.max(
1358
+ 0,
1359
+ Math.min(movableTrack, rowIndex - grabOffset)
1924
1360
  );
1925
- const thumbBottom = thumbTop + thumbSize;
1926
- if (rowIndex >= thumbTop && rowIndex < thumbBottom) {
1361
+ return Math.round(desiredThumbTop / movableTrack * geom.maxScrollTop);
1362
+ }
1363
+ function renderScrollbarRow(rowIndex, visibleHeight, totalLines, scrollTop) {
1364
+ const geom = computeScrollbarGeometry(visibleHeight, totalLines, scrollTop);
1365
+ if (!geom) return " ";
1366
+ if (rowIndex >= geom.thumbTop && rowIndex < geom.thumbBottom) {
1927
1367
  return "\u2588";
1928
1368
  }
1929
1369
  return "\u2502";
@@ -2538,10 +1978,16 @@ function createTurnHistory() {
2538
1978
  followBottom: true
2539
1979
  };
2540
1980
  }
2541
- function startTurn(history, role) {
1981
+ function formatToolDetails(history, last) {
1982
+ return (last ? history.toolDetails?.slice(history.lastTurnToolDetailStart ?? 0) : history.toolDetails)?.join("") ?? "";
1983
+ }
1984
+ function startTurn(history, role, options) {
2542
1985
  if (history.currentRole !== null && history.currentContent) {
2543
1986
  finalizeCurrentTurn(history);
2544
1987
  }
1988
+ if (role === "assistant" && !options?.continueAssistantTurn) {
1989
+ history.lastTurnToolDetailStart = history.toolDetails?.length ?? 0;
1990
+ }
2545
1991
  history.currentRole = role;
2546
1992
  history.currentContent = "";
2547
1993
  history.currentBlocks = [];
@@ -2554,7 +2000,7 @@ function appendToCurrentTurn(history, chunk) {
2554
2000
  function appendCurrentBlock(history, kind, chunk) {
2555
2001
  if (!chunk) return;
2556
2002
  const last = history.currentBlocks.at(-1);
2557
- if (last?.kind === kind) {
2003
+ if (last?.kind === kind && !last.runWindow) {
2558
2004
  last.content = applyTerminalOutputToText(last.content, chunk);
2559
2005
  } else {
2560
2006
  history.currentBlocks.push({
@@ -2565,11 +2011,27 @@ function appendCurrentBlock(history, kind, chunk) {
2565
2011
  }
2566
2012
  function finalizeCurrentTurn(history) {
2567
2013
  if (history.currentRole !== null) {
2014
+ let content = history.currentContent;
2015
+ const blocks = [];
2016
+ for (let index = history.currentBlocks.length - 1; index >= 0; index--) {
2017
+ const block = history.currentBlocks[index];
2018
+ const window = block.runWindow;
2019
+ const end = window ? window.start + block.content.length : 0;
2020
+ if (window && content.slice(window.start, end) === block.content) {
2021
+ const summary = `${window.finalizedSummary}
2022
+ `;
2023
+ content = content.slice(0, window.start) + summary + content.slice(end);
2024
+ blocks.push({ kind: block.kind, content: summary });
2025
+ } else {
2026
+ blocks.push({ kind: block.kind, content: block.content });
2027
+ }
2028
+ }
2029
+ blocks.reverse();
2568
2030
  history.turns.push({
2569
2031
  role: history.currentRole,
2570
- content: compactTurnContent(history.currentContent),
2032
+ content: compactTurnContent(content),
2571
2033
  ...history.currentRole === "assistant" && history.currentBlocks.length > 0 ? {
2572
- blocks: history.currentBlocks.map((block) => ({
2034
+ blocks: blocks.map((block) => ({
2573
2035
  ...block,
2574
2036
  content: compactTurnContent(block.content)
2575
2037
  })).filter((block) => block.content.length > 0)
@@ -2595,9 +2057,18 @@ function appendLocalTurn(history, command, output) {
2595
2057
  function readTreePayload(chunk) {
2596
2058
  return JSON.parse(chunk.slice(TUI_TREE_MARKER.length).replace(/\u0002\n?$/, ""));
2597
2059
  }
2598
- function applyTreeRewrite(text, chunk) {
2599
- if (!chunk.startsWith(TUI_TREE_MARKER)) return null;
2600
- const payload = readTreePayload(chunk);
2060
+ function applyTreeRewrite(text, payload) {
2061
+ if (payload.previousLines && payload.lines) {
2062
+ let end = text.length - Number(text.endsWith("\n"));
2063
+ for (let i = payload.previousLines.length - 1; i >= 0; i--) {
2064
+ if (end < 0) return null;
2065
+ const start = end === 0 ? 0 : text.lastIndexOf("\n", end - 1) + 1;
2066
+ if (stripAnsi(text.slice(start, end)) !== stripAnsi(payload.previousLines[i])) return null;
2067
+ end = start - 1;
2068
+ }
2069
+ return `${text.slice(0, end + 1)}${payload.lines.join("\n")}
2070
+ `;
2071
+ }
2601
2072
  const tree = `\u25B8 ${payload.summary}`;
2602
2073
  const hadTrailingNewline = text.endsWith("\n");
2603
2074
  const body = hadTrailingNewline ? text.slice(0, -1) : text;
@@ -2620,36 +2091,52 @@ function applyTreeRewrite(text, chunk) {
2620
2091
  }
2621
2092
  function applyOutputChunkToCurrentTurn(history, chunk, kind = "assistant") {
2622
2093
  if (kind === "tool") {
2094
+ const payload = chunk.startsWith(TUI_TREE_MARKER) ? readTreePayload(chunk) : null;
2623
2095
  const details = history.toolDetails ??= [];
2624
- details.push(
2625
- chunk.startsWith(TUI_TREE_MARKER) ? readTreePayload(chunk).details ?? readTreePayload(chunk).fallback : (
2626
- // 详情里把行首图标还原成双语族名(Read/读取…):/tools 永远读得懂。
2627
- toolRowDetailLine(chunk)
2628
- )
2629
- );
2630
- while (details.length > MAX_TUI_HISTORY_TURNS * 10) details.shift();
2631
- if (chunk.startsWith(TUI_TREE_MARKER)) {
2632
- const payload = readTreePayload(chunk);
2633
- if (payload.appendOnly) {
2096
+ details.push(payload ? payload.details ?? payload.fallback : toolRowDetailLine(chunk));
2097
+ while (details.length > MAX_TUI_HISTORY_TURNS * 10) {
2098
+ details.shift();
2099
+ history.lastTurnToolDetailStart = Math.max(0, (history.lastTurnToolDetailStart ?? 0) - 1);
2100
+ }
2101
+ if (payload) {
2102
+ const appendFallback = () => {
2634
2103
  history.currentContent = applyTerminalOutputToText(history.currentContent, payload.fallback);
2635
2104
  appendCurrentBlock(history, kind, payload.fallback);
2105
+ };
2106
+ if (payload.appendOnly) {
2107
+ appendFallback();
2636
2108
  return true;
2637
2109
  }
2638
- const rewrittenTree = applyTreeRewrite(history.currentContent, chunk);
2639
- if (rewrittenTree === null) {
2640
- const safe = readTreePayload(chunk).fallback;
2641
- history.currentContent = applyTerminalOutputToText(history.currentContent, safe);
2642
- appendCurrentBlock(history, kind, safe);
2643
- return false;
2644
- }
2645
- const treeContent = rewrittenTree;
2646
- history.currentContent = treeContent;
2647
2110
  const lastBlock = history.currentBlocks.at(-1);
2648
- const treeBlock = `\u25B8 ${readTreePayload(chunk).summary}
2111
+ const rewrittenTree = applyTreeRewrite(history.currentContent, payload);
2112
+ if (payload.previousLines && payload.lines) {
2113
+ const rewrittenBlock = lastBlock?.kind === "tool" ? applyTreeRewrite(lastBlock.content, payload) : null;
2114
+ if (rewrittenTree !== null && rewrittenBlock !== null && lastBlock) {
2115
+ const window = `${payload.lines.join("\n")}
2649
2116
  `;
2650
- if (lastBlock?.kind === "tool") lastBlock.content = applyTreeRewrite(lastBlock.content, chunk) ?? `${lastBlock.content}${treeBlock}`;
2651
- else history.currentBlocks.push({ kind: "tool", content: treeBlock });
2652
- return true;
2117
+ const prefix = rewrittenBlock.slice(0, -window.length);
2118
+ history.currentBlocks.pop();
2119
+ if (prefix) history.currentBlocks.push({ kind: "tool", content: prefix });
2120
+ history.currentBlocks.push({
2121
+ kind: "tool",
2122
+ content: window,
2123
+ ...payload.finalizedSummary !== void 0 && {
2124
+ runWindow: { start: rewrittenTree.length - window.length, finalizedSummary: payload.finalizedSummary }
2125
+ }
2126
+ });
2127
+ history.currentContent = rewrittenTree;
2128
+ return true;
2129
+ }
2130
+ } else if (rewrittenTree !== null) {
2131
+ history.currentContent = rewrittenTree;
2132
+ const treeBlock = `\u25B8 ${payload.summary}
2133
+ `;
2134
+ if (lastBlock?.kind === "tool") lastBlock.content = applyTreeRewrite(lastBlock.content, payload) ?? `${lastBlock.content}${treeBlock}`;
2135
+ else history.currentBlocks.push({ kind: "tool", content: treeBlock });
2136
+ return true;
2137
+ }
2138
+ appendFallback();
2139
+ return false;
2653
2140
  }
2654
2141
  }
2655
2142
  const next = applyTerminalOutputToText(history.currentContent, chunk);
@@ -2683,10 +2170,11 @@ function styleAssistantTurn(content, colorEnabled, state = assistantLayoutState(
2683
2170
  Object.assign(state, { anchored, inToolBlock });
2684
2171
  return styledLines.join("\n");
2685
2172
  }
2173
+ var USER_BUBBLE_RIGHT_PAD = 2;
2686
2174
  function gutterForRole(role, colorEnabled) {
2687
2175
  if (role === "user") {
2688
2176
  const accentSeq = colorEnabled ? themeColorSequence("accent") : "";
2689
- const prefix = colorEnabled ? `${accentSeq}\x1B[1m\u2503 \x1B[0m` : "\u2503 ";
2177
+ const prefix = colorEnabled ? `${accentSeq}\x1B[1m\u258C \x1B[0m` : "\u258C ";
2690
2178
  return { prefix, prefixWidth: 3 };
2691
2179
  }
2692
2180
  if (role === "local") {
@@ -2727,9 +2215,10 @@ function layoutTextRows(role, content, contentWidth, colorEnabled, command, stat
2727
2215
  if (role === "user") {
2728
2216
  const logicalLines = content.split("\n");
2729
2217
  const accentSeq = colorEnabled ? themeColorSequence("accent") : "";
2730
- const firstPrefix = colorEnabled ? `${accentSeq}\x1B[1m\u2503 \x1B[0m` : "\u2503 ";
2731
- const multilinePrefix = colorEnabled ? `${accentSeq}\x1B[1m\u2503 \x1B[0m` : "\u2503 ";
2732
- const hangingIndent = colorEnabled ? `${accentSeq}\x1B[1m\u2503 \x1B[0m` : "\u2503 ";
2218
+ const surfaceSeq = colorEnabled ? userBubbleSurfaceBackgroundSequence() : "";
2219
+ const firstPrefix = colorEnabled ? `${accentSeq}\x1B[1m\u258C \x1B[0m` : "\u258C ";
2220
+ const multilinePrefix = colorEnabled ? `${accentSeq}\x1B[1m\u258C \x1B[0m` : "\u258C ";
2221
+ const hangingIndent = colorEnabled ? `${accentSeq}\x1B[1m\u258C \x1B[0m` : "\u258C ";
2733
2222
  const boldOn = colorEnabled ? "\x1B[1m" : "";
2734
2223
  const boldOff = colorEnabled ? "\x1B[22m" : "";
2735
2224
  const fgOff = colorEnabled ? "\x1B[39m" : "";
@@ -2762,7 +2251,23 @@ function layoutTextRows(role, content, contentWidth, colorEnabled, command, stat
2762
2251
  }
2763
2252
  lineSourceStart += line.length + 1;
2764
2253
  }
2765
- return rows2.length > 0 ? rows2 : [{ rendered: firstPrefix, sourceStart: 0, sourceEnd: 0, prefixWidth: 3 }];
2254
+ const baseRows = rows2.length > 0 ? rows2 : [{ rendered: firstPrefix, sourceStart: 0, sourceEnd: 0, prefixWidth: 3 }];
2255
+ if (!surfaceSeq) return baseRows;
2256
+ let maxRowWidth = 0;
2257
+ for (const row of baseRows) {
2258
+ const width = visibleWidth(row.rendered);
2259
+ if (width > maxRowWidth) maxRowWidth = width;
2260
+ }
2261
+ const bubbleWidth = Math.min(contentWidth, maxRowWidth + USER_BUBBLE_RIGHT_PAD);
2262
+ return baseRows.map((row) => ({
2263
+ ...row,
2264
+ rendered: renderSurfaceLine({
2265
+ text: row.rendered,
2266
+ surface: surfaceSeq,
2267
+ padTo: bubbleWidth
2268
+ }),
2269
+ compactSurface: true
2270
+ }));
2766
2271
  }
2767
2272
  if (role === "local") {
2768
2273
  const dimSeq = colorEnabled ? "\x1B[2m" : "";
@@ -2914,6 +2419,7 @@ function layoutLayoutRowEqual(a, b) {
2914
2419
  if (a.prefixWidth !== b.prefixWidth) return false;
2915
2420
  if ((a.softWrapped ?? false) !== (b.softWrapped ?? false)) return false;
2916
2421
  if ((a.softWrapJoiner ?? "") !== (b.softWrapJoiner ?? "")) return false;
2422
+ if ((a.compactSurface ?? false) !== (b.compactSurface ?? false)) return false;
2917
2423
  const ma = a.sourceMapping;
2918
2424
  const mb = b.sourceMapping;
2919
2425
  if (ma || mb) {
@@ -3111,7 +2617,8 @@ function countTurnLines(role, content, contentWidth, command, options) {
3111
2617
  }
3112
2618
  function turnSeparatorRows(prevRole, role) {
3113
2619
  if (prevRole === null) return 0;
3114
- if (role === "user" || role === "local") return 1;
2620
+ if (role === "user") return 2;
2621
+ if (role === "local") return 1;
3115
2622
  if (role === "assistant") {
3116
2623
  return prevRole === "user" || prevRole === "local" ? 1 : 0;
3117
2624
  }
@@ -3168,12 +2675,12 @@ function getAllTurnEntries(history, contentWidth) {
3168
2675
  colorEnabled,
3169
2676
  themeFingerprint
3170
2677
  );
3171
- const sep = currentTurnSeparator(history);
3172
- const startRow = finalizedLines + sep;
2678
+ const sep2 = currentTurnSeparator(history);
2679
+ const startRow = finalizedLines + sep2;
3173
2680
  entries.push({
3174
2681
  startRow,
3175
2682
  lineCount: streamingLines.length,
3176
- separatorAbove: sep
2683
+ separatorAbove: sep2
3177
2684
  });
3178
2685
  turns.push({
3179
2686
  role: history.currentRole,
@@ -3313,18 +2820,20 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3313
2820
  const themeFingerprint = tuiRenderThemeFingerprint(colorEnabled);
3314
2821
  const graphicsEnabled = history.graphicsEnabled === true;
3315
2822
  const { entries, totalLines: finalizedLines } = buildTurnOffsets(history, contentWidth);
2823
+ let currentLayoutRows = [];
3316
2824
  let currentLines = [];
3317
2825
  let currentStart = -1;
3318
2826
  if (history.currentRole !== null && history.currentContent) {
3319
- currentLines = getStreamingTurnLines(
2827
+ currentLayoutRows = computeStreamingTurnLayoutRows(
3320
2828
  history.currentRole,
3321
2829
  history.currentContent,
3322
2830
  contentWidth,
3323
2831
  colorEnabled,
3324
2832
  themeFingerprint
3325
2833
  );
3326
- const sep = currentTurnSeparator(history);
3327
- currentStart = finalizedLines + sep;
2834
+ currentLines = currentLayoutRows.map((r) => r.rendered);
2835
+ const sep2 = currentTurnSeparator(history);
2836
+ currentStart = finalizedLines + sep2;
3328
2837
  }
3329
2838
  const totalLines = currentStart >= 0 ? currentStart + currentLines.length : finalizedLines;
3330
2839
  if (history.followBottom) {
@@ -3340,6 +2849,7 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3340
2849
  const winStart = history.scrollTop;
3341
2850
  const winEnd = Math.min(totalLines, winStart + visibleHeight);
3342
2851
  let visibleLines = new Array(visibleHeight).fill("");
2852
+ const visibleCompactSurface = new Array(visibleHeight).fill(false);
3343
2853
  const visibleImages = [];
3344
2854
  for (let i = 0; i < entries.length; i++) {
3345
2855
  const entry = entries[i];
@@ -3347,6 +2857,7 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3347
2857
  const sepRow = entry.startRow - s;
3348
2858
  if (sepRow >= winStart && sepRow < winEnd) {
3349
2859
  visibleLines[sepRow - winStart] = "";
2860
+ visibleCompactSurface[sepRow - winStart] = false;
3350
2861
  }
3351
2862
  }
3352
2863
  const turnStart = entry.startRow;
@@ -3372,6 +2883,7 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3372
2883
  const interEnd = Math.min(turnEnd, winEnd);
3373
2884
  for (let r = interStart; r < interEnd; r++) {
3374
2885
  visibleLines[r - winStart] = lines[r - turnStart] ?? "";
2886
+ visibleCompactSurface[r - winStart] = layoutRows[r - turnStart]?.compactSurface === true;
3375
2887
  }
3376
2888
  if (options?.onVisibleImages) {
3377
2889
  collectVisibleImageRows(layoutRows, i, turnStart, winStart, winEnd, visibleImages);
@@ -3383,6 +2895,7 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3383
2895
  const sepRow = currentStart - s;
3384
2896
  if (sepRow >= winStart && sepRow < winEnd) {
3385
2897
  visibleLines[sepRow - winStart] = "";
2898
+ visibleCompactSurface[sepRow - winStart] = false;
3386
2899
  }
3387
2900
  }
3388
2901
  const currentEnd = currentStart + currentLines.length;
@@ -3391,6 +2904,7 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3391
2904
  const interEnd = Math.min(currentEnd, winEnd);
3392
2905
  for (let r = interStart; r < interEnd; r++) {
3393
2906
  visibleLines[r - winStart] = currentLines[r - currentStart] ?? "";
2907
+ visibleCompactSurface[r - winStart] = currentLayoutRows[r - currentStart]?.compactSurface === true;
3394
2908
  }
3395
2909
  }
3396
2910
  }
@@ -3407,30 +2921,49 @@ function renderHistory(output, history, inputLines, selection, reservedRows = 0,
3407
2921
  const isGeometryCompatible = prevBuffer !== void 0 && prevBuffer.rows === rows && prevBuffer.columns === columns && prevBuffer.inputLines === inputLines && (prevBuffer.topReservedRows ?? 0) === getTopReservedRows(output) && (prevBuffer.reservedRows ?? 0) === reservedRows && prevBuffer.lines.length === visibleHeight;
3408
2922
  const prevLines = isGeometryCompatible ? prevBuffer.lines : void 0;
3409
2923
  const outsideRows = /* @__PURE__ */ new Map();
3410
- const transcriptRow = (row) => {
3411
- if (row >= winStart && row < winEnd) return visibleLines[row - winStart] ?? "";
3412
- if (currentStart >= 0 && row >= currentStart) return currentLines[row - currentStart] ?? "";
2924
+ const transcriptRowInfo = (row) => {
2925
+ if (row >= winStart && row < winEnd) {
2926
+ return {
2927
+ line: visibleLines[row - winStart] ?? "",
2928
+ compactSurface: visibleCompactSurface[row - winStart] === true
2929
+ };
2930
+ }
2931
+ if (currentStart >= 0 && row >= currentStart) {
2932
+ const layoutRow2 = currentLayoutRows[row - currentStart];
2933
+ return {
2934
+ line: currentLines[row - currentStart] ?? "",
2935
+ compactSurface: layoutRow2?.compactSurface === true
2936
+ };
2937
+ }
3413
2938
  const index = entries.findIndex((entry) => row >= entry.startRow && row < entry.startRow + entry.lineCount);
3414
- if (index < 0) return "";
3415
- let lines = outsideRows.get(index);
3416
- if (!lines) {
3417
- lines = getTurnLayoutRows(history.turns[index], contentWidth, colorEnabled, themeFingerprint, graphicsEnabled).map((line) => line.rendered);
3418
- outsideRows.set(index, lines);
2939
+ if (index < 0) return { line: "", compactSurface: false };
2940
+ let layoutRows = outsideRows.get(index);
2941
+ if (!layoutRows) {
2942
+ layoutRows = getTurnLayoutRows(history.turns[index], contentWidth, colorEnabled, themeFingerprint, graphicsEnabled);
2943
+ outsideRows.set(index, layoutRows);
3419
2944
  }
3420
- return lines[row - entries[index].startRow] ?? "";
2945
+ const layoutRow = layoutRows[row - entries[index].startRow];
2946
+ return {
2947
+ line: layoutRow?.rendered ?? "",
2948
+ compactSurface: layoutRow?.compactSurface === true
2949
+ };
3421
2950
  };
3422
- const surfaceOf = (line) => colorEnabled ? line.match(/\x1b\[(?:48;2;[0-9;]+|100)m/)?.[0] ?? "" : "";
3423
- const rowSurfaces = visibleLines.map(surfaceOf);
2951
+ const surfaceOf = (line, compactSurface) => colorEnabled && !compactSurface ? line.match(/\x1b\[(?:48;2;[0-9;]+|100)m/)?.[0] ?? "" : "";
2952
+ const rowSurfaces = visibleLines.map(
2953
+ (line, i) => surfaceOf(line, visibleCompactSurface[i] === true)
2954
+ );
3424
2955
  for (let start = 0; colorEnabled && start < winEnd - winStart; start++) {
3425
2956
  if (stripAnsi(visibleLines[start] ?? "").trim()) continue;
3426
2957
  let end = start;
3427
2958
  while (end < winEnd - winStart && !stripAnsi(visibleLines[end] ?? "").trim()) end++;
3428
2959
  let before = winStart + start - 1;
3429
- while (before >= 0 && !stripAnsi(transcriptRow(before)).trim()) before--;
2960
+ while (before >= 0 && !stripAnsi(transcriptRowInfo(before).line).trim()) before--;
3430
2961
  let after = winStart + end;
3431
- while (after < totalLines && !stripAnsi(transcriptRow(after)).trim()) after++;
3432
- const preceding = before >= 0 ? surfaceOf(transcriptRow(before)) : "";
3433
- const following = after < totalLines ? surfaceOf(transcriptRow(after)) : "";
2962
+ while (after < totalLines && !stripAnsi(transcriptRowInfo(after).line).trim()) after++;
2963
+ const beforeInfo = before >= 0 ? transcriptRowInfo(before) : null;
2964
+ const afterInfo = after < totalLines ? transcriptRowInfo(after) : null;
2965
+ const preceding = beforeInfo ? surfaceOf(beforeInfo.line, beforeInfo.compactSurface) : "";
2966
+ const following = afterInfo ? surfaceOf(afterInfo.line, afterInfo.compactSurface) : "";
3434
2967
  if (preceding && following) rowSurfaces.fill(preceding, start, end);
3435
2968
  start = end - 1;
3436
2969
  }
@@ -3635,13 +3168,13 @@ function createDialogHost(args) {
3635
3168
  };
3636
3169
  let operationRunning = false;
3637
3170
  const operations = [];
3638
- const exclusive = (body, cancellation) => new Promise((resolve4, reject) => {
3171
+ const exclusive = (body, cancellation) => new Promise((resolve5, reject) => {
3639
3172
  const abortQueued = () => {
3640
3173
  const index = operations.indexOf(start);
3641
3174
  if (index < 0) return;
3642
3175
  operations.splice(index, 1);
3643
3176
  cancellation?.signal.removeEventListener("abort", abortQueued);
3644
- resolve4(cancellation.cancelled());
3177
+ resolve5(cancellation.cancelled());
3645
3178
  };
3646
3179
  const start = () => {
3647
3180
  cancellation?.signal.removeEventListener("abort", abortQueued);
@@ -3662,7 +3195,7 @@ function createDialogHost(args) {
3662
3195
  void Promise.resolve(result).then(
3663
3196
  (value) => {
3664
3197
  release();
3665
- resolve4(value);
3198
+ resolve5(value);
3666
3199
  },
3667
3200
  (error) => {
3668
3201
  release();
@@ -3671,7 +3204,7 @@ function createDialogHost(args) {
3671
3204
  );
3672
3205
  };
3673
3206
  if (cancellation?.signal.aborted) {
3674
- resolve4(cancellation.cancelled());
3207
+ resolve5(cancellation.cancelled());
3675
3208
  return;
3676
3209
  }
3677
3210
  if (operationRunning) {
@@ -4048,9 +3581,9 @@ function createRawKeyReader(input, options) {
4048
3581
  };
4049
3582
  const resolveWaiter = (value) => {
4050
3583
  if (!waiter) return;
4051
- const resolve4 = waiter;
3584
+ const resolve5 = waiter;
4052
3585
  waiter = null;
4053
- resolve4(value);
3586
+ resolve5(value);
4054
3587
  };
4055
3588
  const tryDeliver = () => {
4056
3589
  if (!waiter) return;
@@ -4109,12 +3642,12 @@ function createRawKeyReader(input, options) {
4109
3642
  input.on("close", onClose);
4110
3643
  input.on("end", onClose);
4111
3644
  input.resume?.();
4112
- const reader = () => new Promise((resolve4) => {
3645
+ const reader = () => new Promise((resolve5) => {
4113
3646
  if (closed) {
4114
- resolve4(drainClosed());
3647
+ resolve5(drainClosed());
4115
3648
  return;
4116
3649
  }
4117
- waiter = resolve4;
3650
+ waiter = resolve5;
4118
3651
  tryDeliver();
4119
3652
  });
4120
3653
  reader.dispose = () => {
@@ -4149,8 +3682,8 @@ async function runSelectDialog(args) {
4149
3682
  const input = args.input ?? process.stdin;
4150
3683
  const readKey = args.readKey ?? createRawKeyReader(input, hotkeys ? { preserveBracketedPaste: true } : void 0);
4151
3684
  let cancelRead;
4152
- const cancelled = new Promise((resolve4) => {
4153
- cancelRead = () => resolve4(STREAM_CLOSED);
3685
+ const cancelled = new Promise((resolve5) => {
3686
+ cancelRead = () => resolve5(STREAM_CLOSED);
4154
3687
  });
4155
3688
  args.signal?.addEventListener("abort", cancelRead, { once: true });
4156
3689
  if (args.signal?.aborted) cancelRead();
@@ -4585,7 +4118,7 @@ function createShellApprovalSession(confirm, isAutoConfirm = () => false) {
4585
4118
 
4586
4119
  // packages/cli/tui/readlineWorkspace.ts
4587
4120
  import { createInterface } from "node:readline";
4588
- import { basename } from "node:path";
4121
+ import { basename as basename2 } from "node:path";
4589
4122
  import { PassThrough } from "node:stream";
4590
4123
  import { stdin as defaultInput, stdout as defaultOutput } from "node:process";
4591
4124
 
@@ -6059,11 +5592,11 @@ function createSecretInputCoordinator() {
6059
5592
  };
6060
5593
  return {
6061
5594
  enqueue(start, options) {
6062
- return new Promise((resolve4) => {
6063
- const entry = { start, settle: resolve4, cancelled: options.cancelled, controller: new AbortController(), detach: () => options.signal?.removeEventListener("abort", abort) };
5595
+ return new Promise((resolve5) => {
5596
+ const entry = { start, settle: resolve5, cancelled: options.cancelled, controller: new AbortController(), detach: () => options.signal?.removeEventListener("abort", abort) };
6064
5597
  const abort = () => cancel(entry);
6065
5598
  if (closed || options.signal?.aborted) {
6066
- resolve4(options.cancelled());
5599
+ resolve5(options.cancelled());
6067
5600
  return;
6068
5601
  }
6069
5602
  queue.push(entry);
@@ -6075,9 +5608,9 @@ function createSecretInputCoordinator() {
6075
5608
  if (active) {
6076
5609
  if (!active.controller.signal.aborted) {
6077
5610
  if (waiter) {
6078
- const resolve4 = waiter;
5611
+ const resolve5 = waiter;
6079
5612
  waiter = null;
6080
- resolve4(token);
5613
+ resolve5(token);
6081
5614
  } else inbox.push(token);
6082
5615
  }
6083
5616
  return true;
@@ -6086,10 +5619,10 @@ function createSecretInputCoordinator() {
6086
5619
  const entry = queue[0];
6087
5620
  active = entry;
6088
5621
  inbox = [];
6089
- const readKey = () => new Promise((resolve4) => {
6090
- if (entry.controller.signal.aborted) resolve4(STREAM_CLOSED);
6091
- else if (inbox.length) resolve4(inbox.shift());
6092
- else waiter = resolve4;
5622
+ const readKey = () => new Promise((resolve5) => {
5623
+ if (entry.controller.signal.aborted) resolve5(STREAM_CLOSED);
5624
+ else if (inbox.length) resolve5(inbox.shift());
5625
+ else waiter = resolve5;
6093
5626
  });
6094
5627
  readKey.dispose = closeInbox;
6095
5628
  let operation;
@@ -6166,8 +5699,8 @@ async function runSecretInputDialog(args) {
6166
5699
  wakeAbort?.();
6167
5700
  readKey?.dispose?.();
6168
5701
  };
6169
- const aborted = new Promise((resolve4) => {
6170
- wakeAbort = () => resolve4(STREAM_CLOSED);
5702
+ const aborted = new Promise((resolve5) => {
5703
+ wakeAbort = () => resolve5(STREAM_CLOSED);
6171
5704
  });
6172
5705
  try {
6173
5706
  readKey = args.readKey ?? createRawKeyReader(input, { preserveBracketedPaste: true });
@@ -6255,7 +5788,6 @@ async function runSecretInputDialog(args) {
6255
5788
 
6256
5789
  // packages/cli/client/browserApprovalCopy.ts
6257
5790
  var actions = /* @__PURE__ */ new Map([
6258
- ["click", "Click a control"],
6259
5791
  ["type", "Enter text"],
6260
5792
  ["press", "Press a key"],
6261
5793
  ["set_select_value", "Select an option"],
@@ -6266,7 +5798,7 @@ function describeBrowserApproval(action, target) {
6266
5798
  const isScript = action === "eval_script";
6267
5799
  const label = actions.get(action);
6268
5800
  return {
6269
- action: label ? `${label} (${action})` : "Unknown browser action",
5801
+ action: action === "click" ? "Allow Nolo to click this control?" : label ? `${label} (${action})` : "Unknown browser action",
6270
5802
  target: isScript ? "Script in the target tab" : target || "Unknown control",
6271
5803
  impact: isScript ? "May read or modify the page and cause changes outside the page." : "May modify the page or cause changes outside the page.",
6272
5804
  detailLabel: isScript ? "Script preview" : "Details"
@@ -6276,8 +5808,9 @@ function describeBrowserApproval(action, target) {
6276
5808
  // packages/cli/tui/hostApprovalCard.ts
6277
5809
  var SELECT_ALLOW = /* @__PURE__ */ new Set(["\x1B[C", "\x1BOC"]);
6278
5810
  var SELECT_CANCEL = /* @__PURE__ */ new Set(["\x1B[D", "\x1BOD"]);
6279
- var ENTER = /* @__PURE__ */ new Set(["\r", "\n"]);
6280
5811
  var ESCAPE_KEYS = /* @__PURE__ */ new Set(["\x1B", "\x1B\x1B", "\x1B[27~"]);
5812
+ var PAGE_UP = "\x1B[5~";
5813
+ var PAGE_DOWN = "\x1B[6~";
6281
5814
  var FALLBACK_COLUMNS = 80;
6282
5815
  var LABEL_COLUMN = 9;
6283
5816
  var CONTENT_INDENT = LABEL_COLUMN + 1;
@@ -6400,38 +5933,52 @@ function renderHostApprovalCardLines(card, opts) {
6400
5933
  const isMcp = card.actionLabel === "callMcpTool";
6401
5934
  const copy = describeBrowserApproval(card.actionLabel, safeApprovalSingleLineText(card.target));
6402
5935
  const detail = safeApprovalMultilineText(card.summary);
6403
- const heading = isMcp ? "Call a read tool (callMcpTool)" : copy.action;
6404
- const impact = isMcp ? "A connected service will receive the shown arguments." : copy.impact;
5936
+ const heading = isMcp ? t("hostApprovalMcpHeading") : copy.action;
5937
+ const impact = isMcp ? t("hostApprovalMcpImpact") : copy.impact;
6405
5938
  const browserParts = !isMcp ? [
6406
5939
  safeApprovalSingleLineText(card.browser),
6407
5940
  safeApprovalSingleLineText(card.tabId) ? `tab ${safeApprovalSingleLineText(card.tabId)}` : ""
6408
5941
  ].filter(Boolean) : [];
6409
- const actionBar = " \u276F Cancel (Enter) Allow once (\u2192 then Enter)";
6410
- const actionRows = displayWidth(actionBar) <= columns - 1 ? [actionBar] : [
6411
- ...wrapProseLine("\u276F Cancel (Enter)", columns - 2).map((line) => ` ${line}`),
6412
- ...wrapProseLine("Allow once (\u2192 then Enter)", columns - 4).map((line) => ` ${line}`)
6413
- ];
6414
- const lines = [
6415
- renderDialogRule(columns, false),
5942
+ const body = [
6416
5943
  ...wrapProseLine(heading, columns - 2).map((line) => ` ${line}`),
6417
5944
  "",
6418
- ...fieldRows("target", isMcp ? safeApprovalSingleLineText(card.target) || "Unknown tool" : copy.target, contentWidth),
6419
- ...fieldRows(isMcp ? "scope" : "site", safeApprovalSingleLineText(card.origin) || (isMcp ? "Unknown scope" : "Unknown site"), contentWidth),
5945
+ ...fieldRows("target", isMcp ? safeApprovalSingleLineText(card.target) || t("hostApprovalUnknownTool") : copy.target, contentWidth),
5946
+ ...fieldRows(isMcp ? "scope" : "site", safeApprovalSingleLineText(card.origin) || (isMcp ? t("hostApprovalUnknownScope") : "Unknown site"), contentWidth),
6420
5947
  ...browserParts.length ? fieldRows("browser", browserParts.join(" \xB7 "), contentWidth) : [],
6421
5948
  ...wrapProseLine(impact, contentWidth).map((row, index) => `${index === 0 ? ` ${"impact".padEnd(LABEL_COLUMN, " ")}` : " ".repeat(CONTENT_INDENT)}${row}`),
6422
- ...detail ? ["", ...detailRows(detail, contentWidth)] : [],
6423
- "",
6424
- ...expired ? [
6425
- ...fieldRows("expired", "This action was not run and will not be retried.", contentWidth),
6426
- ...fieldRows("keys", "disabled", contentWidth)
6427
- ] : [
6428
- ...fieldRows("expires", `${formatApprovalRemaining(card.expiresAt, opts.now)} left`, contentWidth),
6429
- ...wrapProseLine("With an empty input line:", columns - 2).map((line) => ` ${line}`),
6430
- ...actionRows
6431
- ],
6432
- renderDialogRule(columns, false)
5949
+ ...detail ? ["", ...detailRows(detail, contentWidth)] : []
5950
+ ];
5951
+ const footer = expired ? [
5952
+ ...fieldRows("expired", "This action was not run and will not be retried.", contentWidth),
5953
+ ...fieldRows("keys", "disabled", contentWidth)
5954
+ ] : [
5955
+ ...fieldRows("expires", `${formatApprovalRemaining(card.expiresAt, opts.now)} left`, contentWidth),
5956
+ ...wrapProseLine(t("hostApprovalKeys"), columns - 2).map((line) => ` ${line}`)
5957
+ ];
5958
+ const rule = renderDialogRule(columns, false);
5959
+ const bodyBudget = (opts.rows ?? Infinity) - footer.length - (expired ? 0 : 2) - 2;
5960
+ let visibleBody = body;
5961
+ if (body.length > bodyBudget) {
5962
+ const pageSize = bodyBudget - 1;
5963
+ if (pageSize < 1) throw new Error("approval frame does not fit");
5964
+ const start = Math.min(opts.scroll ?? 0, body.length - pageSize);
5965
+ const end = start + pageSize;
5966
+ opts.onScroll?.(start);
5967
+ visibleBody = [
5968
+ ...body.slice(start, end),
5969
+ ` PgUp/PgDn ${start + 1}\u2013${end}/${body.length}`
5970
+ ];
5971
+ } else {
5972
+ opts.onScroll?.(0);
5973
+ }
5974
+ return [
5975
+ ...[rule, ...visibleBody].map((line) => clipCardLine(line, columns)),
5976
+ ...!expired ? [
5977
+ renderDialogRow({ label: `[1] ${t("hostApprovalCancel")}`, focused: !opts.allowFocused }, opts.colorEnabled ?? false),
5978
+ renderDialogRow({ label: `[2] ${t("hostApprovalAllowOnce")}`, focused: !!opts.allowFocused }, opts.colorEnabled ?? false)
5979
+ ] : [],
5980
+ ...[...footer, rule].map((line) => clipCardLine(line, columns))
6433
5981
  ];
6434
- return lines.map((line) => clipCardLine(line, columns));
6435
5982
  }
6436
5983
  function createInlineHostApprovalPrompt(args) {
6437
5984
  const now = args.now ?? Date.now;
@@ -6446,84 +5993,148 @@ function createInlineHostApprovalPrompt(args) {
6446
5993
  if (!active) return;
6447
5994
  const finishing = active;
6448
5995
  active = null;
5996
+ finishing.finish(decision);
6449
5997
  try {
6450
5998
  args.write(`${note}
6451
5999
  `);
6452
6000
  } catch {
6453
- } finally {
6454
- finishing.finish(decision);
6455
6001
  }
6456
6002
  };
6457
- const presentOne = (card, context = {}) => new Promise((resolve4) => {
6003
+ const presentOne = (card, context, anchor) => new Promise((resolve5) => {
6458
6004
  if (disposed || context.signal?.aborted) {
6459
- resolve4(disposed ? "deny" : "cancelled");
6005
+ resolve5(disposed ? "deny" : "cancelled");
6006
+ return;
6007
+ }
6008
+ const expiresAt = Math.min(card.expiresAt, context.expiresAt ?? Infinity);
6009
+ if (expiresAt <= now()) {
6010
+ resolve5("expired");
6460
6011
  return;
6461
6012
  }
6462
6013
  const abort = () => settle(context.signal?.reason === "expired" ? "expired" : "cancelled", "\u2716 approval ended \u2014 the action was not run");
6463
- active = { card, allowSelected: false, finish: (result) => {
6464
- context.signal?.removeEventListener("abort", abort);
6465
- resolve4(result);
6466
- } };
6014
+ let scroll = 0;
6015
+ const render = (rows) => {
6016
+ const lines = renderHostApprovalCardLines({ ...card, expiresAt }, {
6017
+ now: now(),
6018
+ columns: columns(),
6019
+ allowFocused: current.allowSelected,
6020
+ colorEnabled: rows !== void 0 && args.colorEnabled,
6021
+ rows,
6022
+ scroll,
6023
+ onScroll: (start) => {
6024
+ scroll = start;
6025
+ }
6026
+ });
6027
+ return lines.join("\n");
6028
+ };
6029
+ const output = args.output;
6030
+ const availableRows = () => anchor.bottomRow() - getTopReservedRows(output);
6031
+ const painter = anchor && output && outputIsTty(output) ? createDialogFramePainter({
6032
+ output,
6033
+ render: () => render(availableRows()),
6034
+ bottomAnchored: anchor.bottomAnchored,
6035
+ resolveBottomRow: anchor.bottomRow,
6036
+ session: anchor.session
6037
+ }) : void 0;
6038
+ const failPaint = () => settle("unavailable", "\u2716 approval could not be shown (terminal too short or repaint failed) \u2014 the action was not run");
6039
+ const repaint = () => {
6040
+ if (active !== current) return;
6041
+ if (expiresAt <= now()) {
6042
+ settle("expired", "\u231B approval expired \u2014 the action was not run");
6043
+ return;
6044
+ }
6045
+ try {
6046
+ painter?.paint();
6047
+ } catch {
6048
+ failPaint();
6049
+ }
6050
+ };
6051
+ const current = {
6052
+ expiresAt,
6053
+ allowSelected: false,
6054
+ repaint,
6055
+ interactive: Boolean(painter),
6056
+ page(delta) {
6057
+ if (!painter) return false;
6058
+ scroll = Math.max(0, scroll + delta * Math.max(1, Math.floor(availableRows() / 3)));
6059
+ repaint();
6060
+ return true;
6061
+ },
6062
+ finish(result) {
6063
+ context.signal?.removeEventListener("abort", abort);
6064
+ try {
6065
+ painter?.clear();
6066
+ } catch {
6067
+ } finally {
6068
+ resolve5(result);
6069
+ }
6070
+ }
6071
+ };
6072
+ active = current;
6467
6073
  context.signal?.addEventListener("abort", abort, { once: true });
6468
- try {
6469
- const lines = renderHostApprovalCardLines(card, { now: now(), columns: columns() });
6470
- args.write(`${lines.join("\n")}
6074
+ anchor?.registerForegroundRepaint?.(repaint);
6075
+ if (painter) repaint();
6076
+ else {
6077
+ try {
6078
+ args.write(`${render()}
6471
6079
  `);
6472
- } catch {
6473
- settle("deny", "\u231B approval could not be shown \u2014 the action was not run");
6474
- return;
6080
+ } catch {
6081
+ failPaint();
6082
+ }
6475
6083
  }
6476
6084
  });
6477
6085
  return {
6478
6086
  awaitHostApproval: (card, context = {}) => {
6479
6087
  const signal = context.signal ? AbortSignal.any([context.signal, shutdown.signal]) : shutdown.signal;
6480
- return queue.present(card, (next, lifetime = {}) => args.dialogHost ? args.dialogHost.withKeyboard(() => presentOne(next, lifetime), {
6088
+ return queue.present(card, (next, lifetime = {}) => args.dialogHost ? args.dialogHost.run((anchor) => presentOne(next, lifetime, anchor), {
6481
6089
  signal: lifetime.signal,
6482
6090
  cancelled: () => "cancelled"
6483
6091
  }) : presentOne(next, lifetime), { ...context, signal });
6484
6092
  },
6485
6093
  isActive: () => active !== null,
6486
6094
  handleKey(sequence, context) {
6487
- if (!active || disposed) return false;
6488
- const isConfirm = ENTER.has(sequence);
6489
- const selectAllow = SELECT_ALLOW.has(sequence);
6490
- const selectCancel = SELECT_CANCEL.has(sequence);
6491
- const isEscape = ESCAPE_KEYS.has(sequence);
6492
- if (!context.draftEmpty || !(isConfirm || selectAllow || selectCancel || isEscape)) {
6493
- if (active.allowSelected) {
6494
- active.allowSelected = false;
6495
- try {
6496
- args.write(" Cancel selected (default).\n");
6497
- } catch {
6498
- }
6095
+ const current = active;
6096
+ if (!current || disposed) return false;
6097
+ const confirm = isSubmit(sequence);
6098
+ const allow = isArrowDown(sequence) || SELECT_ALLOW.has(sequence);
6099
+ const cancel = isArrowUp(sequence) || SELECT_CANCEL.has(sequence);
6100
+ const escape = ESCAPE_KEYS.has(sequence);
6101
+ const digit = sequence === "1" || sequence === "2";
6102
+ const page = sequence === PAGE_UP || sequence === PAGE_DOWN;
6103
+ const setFocus = (allowFocused) => {
6104
+ if (current.allowSelected === allowFocused) return;
6105
+ if (current.interactive) {
6106
+ current.allowSelected = allowFocused;
6107
+ current.repaint();
6108
+ return;
6499
6109
  }
6110
+ try {
6111
+ args.write(` ${allowFocused ? t("hostApprovalAllowOnce") : t("hostApprovalCancel")} \xB7 ${t("hostApprovalConfirmHint")}
6112
+ `);
6113
+ current.allowSelected = allowFocused;
6114
+ } catch {
6115
+ current.allowSelected = false;
6116
+ }
6117
+ };
6118
+ if (page && current.page(sequence === PAGE_UP ? -1 : 1)) return true;
6119
+ if (!context.draftEmpty || escape && context.busy || !(confirm || allow || cancel || escape || digit)) {
6120
+ setFocus(false);
6500
6121
  return false;
6501
6122
  }
6502
- if (isEscape && context.busy) {
6503
- active.allowSelected = false;
6504
- return false;
6505
- }
6506
- if (active.card.expiresAt <= now()) {
6123
+ if (current.expiresAt <= now()) {
6507
6124
  settle("expired", "\u231B approval expired \u2014 the action was not run");
6508
6125
  return true;
6509
6126
  }
6510
- if (selectAllow || selectCancel) {
6511
- if (active.allowSelected !== selectAllow) {
6512
- active.allowSelected = false;
6513
- try {
6514
- args.write(selectAllow ? " Allow once selected \xB7 Enter confirms \xB7 \u2190 selects Cancel\n" : " Cancel selected \xB7 Enter cancels\n");
6515
- active.allowSelected = selectAllow;
6516
- } catch {
6517
- settle("deny", "\u2716 selection could not be shown \u2014 the action was not run");
6518
- }
6519
- }
6127
+ const mayApprove = !context.busy || context.canApproveDuringTurn === true;
6128
+ if (allow || cancel) {
6129
+ setFocus(allow && mayApprove);
6520
6130
  return true;
6521
6131
  }
6522
- const isAllow = isConfirm && active.allowSelected;
6523
- settle(
6524
- isAllow ? "allow_once" : "deny",
6525
- isAllow ? "\u2714 allowed once (this action only)" : "\u2716 denied"
6526
- );
6132
+ if (!mayApprove && sequence === "2") {
6133
+ setFocus(false);
6134
+ return true;
6135
+ }
6136
+ const approved = mayApprove && (sequence === "2" || confirm && current.allowSelected);
6137
+ settle(approved ? "allow_once" : "deny", approved ? "\u2714 allowed once (this action only)" : "\u2716 denied");
6527
6138
  return true;
6528
6139
  },
6529
6140
  dispose() {
@@ -7678,7 +7289,19 @@ function createRunRegistryPoller(deps) {
7678
7289
  }
7679
7290
 
7680
7291
  // packages/cli/tui/runCompletionWatcher.ts
7292
+ import {
7293
+ closeSync,
7294
+ constants as fsConstants,
7295
+ fstatSync,
7296
+ lstatSync,
7297
+ openSync,
7298
+ readSync,
7299
+ realpathSync
7300
+ } from "node:fs";
7301
+ import { basename, dirname, resolve as resolve2, sep } from "node:path";
7681
7302
  var WAKE_NOTE_MAX_CHARS = 300;
7303
+ var WAKE_TITLE_MAX_CHARS = 120;
7304
+ var WAKE_AGENT_MAX_CHARS = 80;
7682
7305
  function runDuration(record, nowMs = Date.now()) {
7683
7306
  return formatRunAge(
7684
7307
  {
@@ -7692,6 +7315,7 @@ function isFailureStatus(status) {
7692
7315
  return typeof status === "string" && status !== "done";
7693
7316
  }
7694
7317
  var WAKE_ERROR_PAYLOAD_TOKEN_BUDGET = 500;
7318
+ var WAKE_ERROR_MIN_PAYLOAD_TOKEN_BUDGET = 120;
7695
7319
  var WAKE_TOTAL_TOKEN_BUDGET = 2e3;
7696
7320
  var escapeXmlAttribute = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
7697
7321
  function clipTextToTokenBudget(text, budgetTokens) {
@@ -7715,23 +7339,270 @@ function failureErrorPayload(record, budgetTokens) {
7715
7339
  const raw = typeof record.note === "string" && record.note.trim() ? record.note : typeof recordError === "string" && recordError.trim() ? recordError : "";
7716
7340
  return clipTextToTokenBudget(clipText(raw, 2e3), budgetTokens);
7717
7341
  }
7718
- function buildRunElement(record, nowMs, errorBudgetTokens) {
7342
+ var RESULT_HEAD_MAX_BYTES = 16 * 1024;
7343
+ var WAKE_SUMMARY_MAX_LINES = 25;
7344
+ var WAKE_SUMMARY_MAX_CHARS = 1e3;
7345
+ var WAKE_TOTAL_SUMMARY_CHAR_BUDGET = 2400;
7346
+ var RESULT_FILE_SUFFIX = ".result.md";
7347
+ function isSafeRunId(runId) {
7348
+ if (!runId) return false;
7349
+ if (runId.includes("/") || runId.includes("\\") || runId.includes("\0")) return false;
7350
+ if (runId === "." || runId === ".." || runId.includes("..")) return false;
7351
+ return true;
7352
+ }
7353
+ function canonicalDir(dir) {
7354
+ try {
7355
+ return realpathSync(dir);
7356
+ } catch {
7357
+ return resolve2(dir);
7358
+ }
7359
+ }
7360
+ function isUnderTrustedDir(path3, dir) {
7361
+ const parent = canonicalDir(dirname(path3));
7362
+ const root = canonicalDir(dir);
7363
+ return parent === root || parent.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
7364
+ }
7365
+ function resolveTrustedResultDirs(explicit) {
7366
+ if (Array.isArray(explicit) && explicit.length > 0) return explicit;
7367
+ return [resolveRunsDir(process.env)];
7368
+ }
7369
+ function resolveTrustedResultPath(resultFile, options = {}) {
7370
+ const raw = typeof resultFile === "string" ? resultFile.trim() : "";
7371
+ if (!raw) return null;
7372
+ if (options.runId !== void 0) {
7373
+ if (!isSafeRunId(options.runId)) return null;
7374
+ if (basename(raw) !== `${options.runId}${RESULT_FILE_SUFFIX}`) return null;
7375
+ }
7376
+ const dirs = resolveTrustedResultDirs(options.trustedResultDirs);
7377
+ const trusted = dirs.some(
7378
+ (dir) => typeof dir === "string" && dir.length > 0 && isUnderTrustedDir(raw, dir)
7379
+ );
7380
+ if (!trusted) return null;
7381
+ return raw;
7382
+ }
7383
+ function trimIncompleteUtf8Tail(buf) {
7384
+ if (buf.length === 0) return buf;
7385
+ let start = buf.length - 1;
7386
+ while (start >= 0 && (buf[start] & 192) === 128) start -= 1;
7387
+ if (start < 0) return buf;
7388
+ const lead = buf[start];
7389
+ let need = 1;
7390
+ if (lead < 128) need = 1;
7391
+ else if ((lead & 224) === 192) need = 2;
7392
+ else if ((lead & 240) === 224) need = 3;
7393
+ else if ((lead & 248) === 240) need = 4;
7394
+ const have = buf.length - start;
7395
+ if (have >= need) return buf;
7396
+ return buf.subarray(0, start);
7397
+ }
7398
+ function readResultFileHead(path3, maxBytes = RESULT_HEAD_MAX_BYTES) {
7399
+ let fd = null;
7400
+ try {
7401
+ const flags = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
7402
+ if (!fsConstants.O_NOFOLLOW) {
7403
+ let lst;
7404
+ try {
7405
+ lst = lstatSync(path3);
7406
+ } catch {
7407
+ return null;
7408
+ }
7409
+ if (!lst.isFile()) return null;
7410
+ }
7411
+ fd = openSync(path3, flags);
7412
+ const stat3 = fstatSync(fd);
7413
+ if (!stat3.isFile()) return null;
7414
+ const want = Math.min(stat3.size, maxBytes);
7415
+ if (want <= 0) return null;
7416
+ const buf = Buffer.alloc(want);
7417
+ let read = 0;
7418
+ while (read < want) {
7419
+ const n = readSync(fd, buf, read, want - read, read);
7420
+ if (n <= 0) break;
7421
+ read += n;
7422
+ }
7423
+ if (read <= 0) return null;
7424
+ const sliced = buf.subarray(0, read);
7425
+ const safe = stat3.size > read ? trimIncompleteUtf8Tail(sliced) : sliced;
7426
+ return {
7427
+ head: safe.toString("utf8"),
7428
+ bytesRead: safe.length,
7429
+ bytesTotal: stat3.size
7430
+ };
7431
+ } catch {
7432
+ return null;
7433
+ } finally {
7434
+ if (fd !== null) {
7435
+ try {
7436
+ closeSync(fd);
7437
+ } catch {
7438
+ }
7439
+ }
7440
+ }
7441
+ }
7442
+ function stripLeadingFrontMatter(text) {
7443
+ const open = /^---\r?\n/.exec(text);
7444
+ if (!open) return text;
7445
+ const rest = text.slice(open[0].length);
7446
+ const immediate = /^---\r?\n/.exec(rest);
7447
+ if (immediate) return rest.slice(immediate[0].length);
7448
+ const close = /\r?\n---\r?\n/.exec(rest);
7449
+ if (!close) return text;
7450
+ return rest.slice(close.index + close[0].length);
7451
+ }
7452
+ function hasUnclosedFrontMatter(text) {
7453
+ const open = /^---\r?\n/.exec(text);
7454
+ if (!open) return false;
7455
+ const rest = text.slice(open[0].length);
7456
+ if (/^---\r?\n/.test(rest)) return false;
7457
+ return !/\r?\n---\r?(\n|$)/.test(rest);
7458
+ }
7459
+ function escapeXmlText(text) {
7460
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
7461
+ }
7462
+ var PEM_PRIVATE_KEY_MARKER = /-----(BEGIN|END) (?:[A-Z0-9 ]+)?PRIVATE KEY-----/g;
7463
+ function hasUnpairedPrivateKeyMarker(text) {
7464
+ if (typeof text !== "string" || !text.includes("PRIVATE KEY")) return false;
7465
+ let open = 0;
7466
+ for (const marker of text.matchAll(PEM_PRIVATE_KEY_MARKER)) {
7467
+ if (marker[1] === "BEGIN") open += 1;
7468
+ else if (open === 0) return true;
7469
+ else open -= 1;
7470
+ }
7471
+ return open > 0;
7472
+ }
7473
+ function trimTrailingNewline(text) {
7474
+ return text.replace(/(?:\r?\n)$/, "");
7475
+ }
7476
+ function normalizeNewlines(text) {
7477
+ return text.includes("\r") ? text.replace(/\r\n/g, "\n") : text;
7478
+ }
7479
+ function newlineCount(text) {
7480
+ let count = 0;
7481
+ for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) count += 1;
7482
+ return count;
7483
+ }
7484
+ function scrubWakeBody(body) {
7485
+ const sanitized = trimTrailingNewline(sanitizeToolOutputText(body));
7486
+ if (hasUnpairedPrivateKeyMarker(sanitized)) return null;
7487
+ const scrubbed = scrubSecrets(sanitized).cleaned;
7488
+ return {
7489
+ lines: scrubbed.split("\n"),
7490
+ // 99.9% 的报告换行数不变 → 物理行 1:1,行号可信;折叠/跨行控制串被删就没法保证。
7491
+ lineAligned: newlineCount(normalizeNewlines(trimTrailingNewline(body))) === newlineCount(scrubbed)
7492
+ };
7493
+ }
7494
+ function escapedCharCost(ch) {
7495
+ if (ch === "&") return "&amp;".length;
7496
+ if (ch === "<" || ch === ">") return "&lt;".length;
7497
+ return ch.length;
7498
+ }
7499
+ function cutToEscapedBudget(text, budget) {
7500
+ if (budget <= 0) return { text: "", truncated: text.length > 0 };
7501
+ let used = 0;
7502
+ let i = 0;
7503
+ while (i < text.length) {
7504
+ const cp = text.codePointAt(i);
7505
+ const ch = String.fromCodePoint(cp);
7506
+ const cost = escapedCharCost(ch);
7507
+ if (used + cost > budget) return { text: text.slice(0, i), truncated: true };
7508
+ used += cost;
7509
+ i += ch.length;
7510
+ }
7511
+ return { text, truncated: false };
7512
+ }
7513
+ function extractWakeSummary(resultFile, maxChars = WAKE_SUMMARY_MAX_CHARS, options = {}) {
7514
+ if (typeof resultFile !== "string" || !resultFile.trim() || maxChars <= 0) {
7515
+ return null;
7516
+ }
7517
+ const trustedPath = resolveTrustedResultPath(resultFile, options);
7518
+ if (!trustedPath) return null;
7519
+ const read = readResultFileHead(trustedPath);
7520
+ if (!read) return null;
7521
+ if (hasUnclosedFrontMatter(read.head)) return null;
7522
+ if (hasUnpairedPrivateKeyMarker(read.head)) return null;
7523
+ const body = stripLeadingFrontMatter(read.head);
7524
+ const frontMatterChars = read.head.length - body.length;
7525
+ const frontMatterLines = frontMatterChars > 0 ? read.head.slice(0, frontMatterChars).split("\n").length - 1 : 0;
7526
+ const sourceLines = scrubWakeBody(body);
7527
+ if (!sourceLines) return null;
7528
+ const lines = sourceLines.lines;
7529
+ let start = 0;
7530
+ while (start < lines.length && lines[start].trim() === "") start++;
7531
+ if (start >= lines.length) return null;
7532
+ const lineLimited = lines.length - start > WAKE_SUMMARY_MAX_LINES;
7533
+ const picked = lines.slice(start, start + WAKE_SUMMARY_MAX_LINES);
7534
+ while (picked.length > 1 && picked[picked.length - 1].trim() === "") picked.pop();
7535
+ const joined = picked.join("\n").replace(/\s+$/, "");
7536
+ if (!joined.trim()) return null;
7537
+ const cut = cutToEscapedBudget(joined, maxChars);
7538
+ const finalText = cut.text.replace(/\s+$/, "");
7539
+ if (!finalText.trim()) return null;
7540
+ const retainedLines = Math.min(finalText.split("\n").length, picked.length);
7541
+ const firstSourceLine = frontMatterLines + 1 + start;
7542
+ return {
7543
+ text: escapeXmlText(finalText),
7544
+ ...sourceLines.lineAligned ? { startLine: firstSourceLine, endLine: firstSourceLine + retainedLines - 1 } : {},
7545
+ truncated: lineLimited || cut.truncated || read.bytesTotal > read.bytesRead
7546
+ };
7547
+ }
7548
+ function renderSummaryBlock(summary) {
7549
+ const linesAttr = typeof summary.startLine === "number" && typeof summary.endLine === "number" ? ` lines="${summary.startLine}-${summary.endLine}"` : "";
7550
+ return [
7551
+ `<summary${linesAttr} truncated="${summary.truncated ? "true" : "false"}">`,
7552
+ summary.text,
7553
+ `</summary>`
7554
+ ].join("\n");
7555
+ }
7556
+ var WAKE_SUMMARY_MIN_CHARS = 24;
7557
+ function planWakeSummaries(runs, readSummary = extractWakeSummary, options = {}) {
7558
+ const out = /* @__PURE__ */ new Map();
7559
+ const eligible = runs.filter(
7560
+ (r) => !isFailureStatus(r.status) && typeof r.resultFile === "string" && r.resultFile.trim()
7561
+ );
7562
+ if (!eligible.length) return out;
7563
+ const totalBudget = Math.max(
7564
+ 0,
7565
+ options.totalCharBudget ?? WAKE_TOTAL_SUMMARY_CHAR_BUDGET
7566
+ );
7567
+ const perRunChars = Math.min(
7568
+ WAKE_SUMMARY_MAX_CHARS,
7569
+ Math.floor(totalBudget / eligible.length)
7570
+ );
7571
+ if (perRunChars < WAKE_SUMMARY_MIN_CHARS) return out;
7572
+ for (const r of eligible) {
7573
+ try {
7574
+ const summary = readSummary(r.resultFile.trim(), perRunChars, {
7575
+ runId: r.runId,
7576
+ trustedResultDirs: options.trustedResultDirs
7577
+ });
7578
+ if (summary && summary.text.trim()) out.set(r.runId, summary);
7579
+ } catch {
7580
+ }
7581
+ }
7582
+ return out;
7583
+ }
7584
+ function buildRunElement(record, nowMs, errorBudgetTokens, summary) {
7719
7585
  const attrs = [
7720
7586
  `runId="${escapeXmlAttribute(String(record.runId))}"`,
7721
7587
  // Same rule as describeRun: this attribute is parsed by the model, so the
7722
7588
  // label keeps the agentKey correlation — title never substitutes for it.
7723
7589
  `agent="${escapeXmlAttribute(
7724
- resolveRunLabel({
7725
- agentName: record.agentName,
7726
- agentKey: record.agentKey,
7727
- runId: record.runId
7728
- })
7590
+ clipText(
7591
+ resolveRunLabel({
7592
+ agentName: record.agentName,
7593
+ agentKey: record.agentKey,
7594
+ runId: record.runId
7595
+ }),
7596
+ WAKE_AGENT_MAX_CHARS
7597
+ )
7729
7598
  )}"`,
7730
7599
  `status="${escapeXmlAttribute(String(record.status))}"`
7731
7600
  ];
7732
7601
  const rawTitle = record.title;
7733
7602
  if (typeof rawTitle === "string" && rawTitle.trim()) {
7734
- attrs.push(`title="${escapeXmlAttribute(rawTitle.trim())}"`);
7603
+ attrs.push(
7604
+ `title="${escapeXmlAttribute(clipText(rawTitle.trim(), WAKE_TITLE_MAX_CHARS))}"`
7605
+ );
7735
7606
  }
7736
7607
  if (record.continuedFrom) attrs.push(`continuedFrom="${escapeXmlAttribute(record.continuedFrom)}"`);
7737
7608
  const verbose = isFailureStatus(record.status);
@@ -7755,51 +7626,133 @@ function buildRunElement(record, nowMs, errorBudgetTokens) {
7755
7626
  if (!verbose) {
7756
7627
  const note = typeof record.note === "string" && record.note.trim() ? clipText(record.note, WAKE_NOTE_MAX_CHARS) : "";
7757
7628
  if (note) attrs.push(`note="${escapeXmlAttribute(note)}"`);
7758
- return `<run ${attrs.join(" ")} />`;
7759
7629
  }
7760
7630
  const body = [];
7761
- const errorText = failureErrorPayload(record, errorBudgetTokens);
7762
- if (errorText) body.push(`error: ${errorText}`);
7763
- const counters = record.activity?.counters;
7764
- if (counters && typeof counters.toolCalls === "number" && typeof counters.llmCalls === "number" && typeof counters.fileEdits === "number") {
7765
- body.push(
7766
- `activity: ${counters.toolCalls} tool calls \xB7 ${counters.llmCalls} llm calls \xB7 ${counters.fileEdits} edits`
7767
- );
7631
+ if (summary) body.push(renderSummaryBlock(summary));
7632
+ if (verbose) {
7633
+ const errorText = failureErrorPayload(record, errorBudgetTokens);
7634
+ if (errorText) body.push(`error: ${errorText}`);
7635
+ const counters = record.activity?.counters;
7636
+ if (counters && typeof counters.toolCalls === "number" && typeof counters.llmCalls === "number" && typeof counters.fileEdits === "number") {
7637
+ body.push(
7638
+ `activity: ${counters.toolCalls} tool calls \xB7 ${counters.llmCalls} llm calls \xB7 ${counters.fileEdits} edits`
7639
+ );
7640
+ }
7768
7641
  }
7769
7642
  if (body.length === 0) return `<run ${attrs.join(" ")} />`;
7770
7643
  return `<run ${attrs.join(" ")}>
7771
7644
  ${body.join("\n")}
7772
7645
  </run>`;
7773
7646
  }
7774
- function renderWakeMessage(elements, count) {
7647
+ function renderWakeMessage(elements, count, omittedCount = 0) {
7648
+ const omittedLine = omittedCount > 0 ? `\u2026 \u53CA\u53E6\u5916 ${omittedCount} \u6761\u5DF2\u5B8C\u6210 run\uFF0C\u7528 controlAgentRun(list) \u67E5\u770B` : null;
7775
7649
  return [
7776
7650
  `<background_run_completion count="${count}">`,
7777
7651
  ...elements,
7778
- `\u6709 resultFile \u65F6\u7528 readFile\uFF1B\u672C\u5730\u7F3A\u5931\u5373\u65E0\u7ED3\u8BBA\uFF0C\u4E0D\u8BFB\u65E5\u5FD7\u3002\u7EC8\u6001\u53EA\u8868\u793A run \u7ED3\u675F\uFF0C\u4E0D\u8BC1\u660E\u4EA4\u4ED8\u3001\u6D4B\u8BD5\u3001\u5BA1\u67E5\u3001\u7528\u6237\u9A8C\u6536\u6216\u5408\u5165\u53D1\u5E03\u3002\u6B63\u6587\u662F\u6267\u884C\u8005\u62A5\u544A\uFF1Bruntime acceptance \u4EC5\u4E3A\u8FD0\u884C\u65F6\u89C2\u6D4B\uFF0Cunknown \u4FDD\u6301\u672A\u77E5\u3002continuedFrom \u4EC5\u4E3A\u7EED\u8DD1\u5173\u8054\uFF0C\u4E0D\u7EE7\u627F\u65E7\u7248\u672C APPROVE\uFF1B\u7ED3\u5408\u5F53\u524D\u5B8C\u6574\u7ED3\u679C\u6838\u5BF9\u8303\u56F4\u3001\u963B\u788D\u4E0E\u8BC1\u636E\u3002`,
7652
+ ...omittedLine ? [omittedLine] : [],
7653
+ `\u6709 resultFile \u4E14\u672A\u5185\u8054\u5B8C\u6574\u6458\u8981\uFF08\u65E0\u6458\u8981\u80F6\u56CA\u6216 truncated="true"\uFF09\u3001\u6709\u5F02\u5E38/\u7F3A\u53E3\u3001\u6D89\u9AD8\u98CE\u9669\u51B3\u7B56\u6216\u9700 review verdict \u5168\u91CF\u6838\u9A8C\u65F6\uFF0C\u6709 resultFile \u65F6\u7528 readFile \u5148\u8BFB\u5934\u90E8\u7ED3\u8BBA\uFF08\u5982 lines:"1-60"\uFF09\uFF0C\u518D\u6309\u533A\u95F4\u7EED\u8BFB\uFF1B\u5DF2\u5185\u8054\u5B8C\u6574\u6458\u8981\uFF08truncated="false"\uFF09\u7684\u5E38\u89C4\u975E\u5BA1\u67E5\u7ED3\u679C\u53EF\u76F4\u63A5\u6D88\u8D39\uFF0C\u65E0\u9700\u518D\u8C03 readFile\u3002\u672C\u5730\u7F3A\u5931\u5373\u65E0\u7ED3\u8BBA\uFF0C\u4E0D\u8BFB\u65E5\u5FD7\u3002\u7EC8\u6001\u53EA\u8868\u793A run \u7ED3\u675F\uFF0C\u4E0D\u8BC1\u660E\u4EA4\u4ED8\u3001\u6D4B\u8BD5\u3001\u5BA1\u67E5\u3001\u7528\u6237\u9A8C\u6536\u6216\u5408\u5165\u53D1\u5E03\u3002\u6B63\u6587\u662F\u6267\u884C\u8005\u62A5\u544A\uFF1Bruntime acceptance \u4EC5\u4E3A\u8FD0\u884C\u65F6\u89C2\u6D4B\uFF0Cunknown \u4FDD\u6301\u672A\u77E5\u3002continuedFrom \u4EC5\u4E3A\u7EED\u8DD1\u5173\u8054\uFF0C\u4E0D\u7EE7\u627F\u65E7\u7248\u672C APPROVE\uFF1B\u7ED3\u5408\u5F53\u524D\u5B8C\u6574\u7ED3\u679C\u6838\u5BF9\u8303\u56F4\u3001\u963B\u788D\u4E0E\u8BC1\u636E\u3002`,
7779
7654
  `</background_run_completion>`
7780
7655
  ].join("\n");
7781
7656
  }
7782
- function buildWakeMessage(finished, nowMs = Date.now()) {
7783
- const failedCount = finished.filter((r) => isFailureStatus(r.status)).length;
7784
- const skeleton = renderWakeMessage(
7785
- finished.map((r) => buildRunElement(r, nowMs, 0)),
7786
- finished.length
7787
- );
7788
- const perErrorBudget = failedCount > 0 ? Math.min(
7789
- WAKE_ERROR_PAYLOAD_TOKEN_BUDGET,
7790
- Math.max(
7791
- 0,
7792
- Math.floor(
7793
- (WAKE_TOTAL_TOKEN_BUDGET - estimateTokenCount(skeleton)) / failedCount - 8
7794
- )
7795
- )
7796
- ) : 0;
7797
- return renderWakeMessage(
7798
- finished.map(
7799
- (r) => buildRunElement(r, nowMs, isFailureStatus(r.status) ? perErrorBudget : 0)
7800
- ),
7801
- finished.length
7802
- );
7657
+ function allocateErrorBudgets(failures, availableTokens, needTokens) {
7658
+ const out = /* @__PURE__ */ new Map();
7659
+ const needs = failures.map((r) => ({ runId: r.runId, need: Math.max(0, needTokens(r)) })).sort((a, b) => a.need - b.need);
7660
+ let pool = Math.max(0, availableTokens);
7661
+ for (let i = 0; i < needs.length; i++) {
7662
+ const share = Math.floor(pool / (needs.length - i));
7663
+ const granted = Math.min(needs[i].need, share);
7664
+ out.set(needs[i].runId, granted);
7665
+ pool -= granted;
7666
+ }
7667
+ return out;
7668
+ }
7669
+ function buildWakeMessage(finished, nowMs = Date.now(), options = {}) {
7670
+ const ordered = [
7671
+ ...finished.filter((r) => isFailureStatus(r.status)),
7672
+ ...finished.filter((r) => !isFailureStatus(r.status))
7673
+ ];
7674
+ const attempt = (subset, omittedCount) => {
7675
+ const errorNeed = (r) => Math.min(
7676
+ WAKE_ERROR_PAYLOAD_TOKEN_BUDGET,
7677
+ estimateTokenCount(failureErrorPayload(r, WAKE_ERROR_PAYLOAD_TOKEN_BUDGET)) + 1
7678
+ );
7679
+ const render = (errorBudgets2, summaries) => renderWakeMessage(
7680
+ subset.map(
7681
+ (r) => buildRunElement(
7682
+ r,
7683
+ nowMs,
7684
+ isFailureStatus(r.status) ? errorBudgets2.get(r.runId) ?? 0 : 0,
7685
+ summaries.get(r.runId) ?? null
7686
+ )
7687
+ ),
7688
+ finished.length,
7689
+ omittedCount
7690
+ );
7691
+ const bareTokens = estimateTokenCount(render(/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()));
7692
+ if (bareTokens > WAKE_TOTAL_TOKEN_BUDGET) return null;
7693
+ const failures = subset.filter((r) => isFailureStatus(r.status));
7694
+ const errorBudgets = allocateErrorBudgets(
7695
+ failures,
7696
+ WAKE_TOTAL_TOKEN_BUDGET - bareTokens,
7697
+ errorNeed
7698
+ );
7699
+ const includedSuccessCount = subset.length - failures.length;
7700
+ for (const r of failures) {
7701
+ const granted = errorBudgets.get(r.runId) ?? 0;
7702
+ if (includedSuccessCount > 0) {
7703
+ const floor = Math.min(errorNeed(r), WAKE_ERROR_MIN_PAYLOAD_TOKEN_BUDGET);
7704
+ if (granted < floor) return null;
7705
+ } else if (granted <= 0) {
7706
+ return null;
7707
+ }
7708
+ }
7709
+ let withErrors = render(errorBudgets, /* @__PURE__ */ new Map());
7710
+ let withErrorsTokens = estimateTokenCount(withErrors);
7711
+ if (includedSuccessCount === 0) {
7712
+ for (let round = 0; round < 6 && withErrorsTokens > WAKE_TOTAL_TOKEN_BUDGET; round++) {
7713
+ const excess = withErrorsTokens - WAKE_TOTAL_TOKEN_BUDGET;
7714
+ let victim = null;
7715
+ for (const r of failures) {
7716
+ if (!victim || (errorBudgets.get(r.runId) ?? 0) > (errorBudgets.get(victim.runId) ?? 0)) {
7717
+ victim = r;
7718
+ }
7719
+ }
7720
+ const current = victim ? errorBudgets.get(victim.runId) ?? 0 : 0;
7721
+ if (!victim || current <= 0) break;
7722
+ errorBudgets.set(victim.runId, Math.max(0, current - Math.max(1, excess + 2)));
7723
+ withErrors = render(errorBudgets, /* @__PURE__ */ new Map());
7724
+ withErrorsTokens = estimateTokenCount(withErrors);
7725
+ }
7726
+ }
7727
+ if (withErrorsTokens > WAKE_TOTAL_TOKEN_BUDGET) return null;
7728
+ let summaryCharBudget = Math.min(
7729
+ WAKE_TOTAL_SUMMARY_CHAR_BUDGET,
7730
+ // 最坏情况 1.5 token/字符(中文),据此把剩余 token 折成摘要字符预算。
7731
+ Math.floor(Math.max(0, WAKE_TOTAL_TOKEN_BUDGET - withErrorsTokens) / 1.5)
7732
+ );
7733
+ let message = withErrors;
7734
+ for (let round = 0; round < 8; round++) {
7735
+ const summaries = summaryCharBudget >= WAKE_SUMMARY_MIN_CHARS ? planWakeSummaries(subset, extractWakeSummary, {
7736
+ totalCharBudget: summaryCharBudget,
7737
+ trustedResultDirs: options.trustedResultDirs
7738
+ }) : /* @__PURE__ */ new Map();
7739
+ message = render(errorBudgets, summaries);
7740
+ if (summaries.size === 0) break;
7741
+ if (estimateTokenCount(message) <= WAKE_TOTAL_TOKEN_BUDGET) break;
7742
+ summaryCharBudget = Math.floor(summaryCharBudget / 2);
7743
+ if (summaryCharBudget < WAKE_SUMMARY_MIN_CHARS) {
7744
+ summaryCharBudget = 0;
7745
+ }
7746
+ }
7747
+ return estimateTokenCount(message) <= WAKE_TOTAL_TOKEN_BUDGET ? message : null;
7748
+ };
7749
+ const direct = attempt(finished, 0);
7750
+ if (direct) return direct;
7751
+ for (let keep = ordered.length - 1; keep >= 0; keep--) {
7752
+ const trimmed = attempt(ordered.slice(0, keep), ordered.length - keep);
7753
+ if (trimmed) return trimmed;
7754
+ }
7755
+ return renderWakeMessage([], finished.length, ordered.length);
7803
7756
  }
7804
7757
  function buildWakeDisplayText(finished, nowMs = Date.now()) {
7805
7758
  const tasks = finished.map((record) => ({
@@ -7932,7 +7885,9 @@ function createRunCompletionWatcher(deps) {
7932
7885
  }
7933
7886
  if (finished.length === 0 || now() < retryAt) return;
7934
7887
  const shapes = finished.map((r) => normalizeRunCompletionShape(r));
7935
- const summaryText = buildWakeMessage(finished, now());
7888
+ const summaryText = buildWakeMessage(finished, now(), {
7889
+ trustedResultDirs: [resolveRunsDir(deps.env)]
7890
+ });
7936
7891
  const event = {
7937
7892
  kind: "child-run-completed",
7938
7893
  runs: shapes,
@@ -8015,7 +7970,7 @@ function createRunCompletionWatcher(deps) {
8015
7970
  import { readFileSync, statSync as statSync2 } from "node:fs";
8016
7971
  import { readFile, stat } from "node:fs/promises";
8017
7972
  import { homedir as homedir2 } from "node:os";
8018
- import { isAbsolute, resolve as resolve2 } from "node:path";
7973
+ import { isAbsolute, resolve as resolve3 } from "node:path";
8019
7974
 
8020
7975
  // packages/cli/tui/compressImage.ts
8021
7976
  var MAX_IMAGE_DIMENSION = 1568;
@@ -8305,7 +8260,7 @@ function resolveImageSource(rawPath, cwd) {
8305
8260
  return homedir2() + candidate.slice(1);
8306
8261
  }
8307
8262
  if (isAbsolute(candidate)) return candidate;
8308
- return resolve2(cwd, candidate);
8263
+ return resolve3(cwd, candidate);
8309
8264
  }
8310
8265
  function isImagePath(path3) {
8311
8266
  return IMAGE_EXTENSION_SET.has(extnameOf(path3));
@@ -8638,12 +8593,12 @@ function mergeAttachedImages(existing, incoming) {
8638
8593
  return out;
8639
8594
  }
8640
8595
  async function readImagePaths(paths, options = {}) {
8641
- const resolve4 = options.resolve ?? ((p) => p);
8596
+ const resolve5 = options.resolve ?? ((p) => p);
8642
8597
  const reportedFailures = /* @__PURE__ */ new Set();
8643
8598
  const images = [];
8644
8599
  const failures = [];
8645
8600
  for (const raw of paths) {
8646
- const absolute = resolve4(raw);
8601
+ const absolute = resolve5(raw);
8647
8602
  try {
8648
8603
  const img = await readImageAsDataUrl(absolute, {
8649
8604
  ...options.maxBytes !== void 0 ? { maxBytes: options.maxBytes } : {}
@@ -8749,7 +8704,7 @@ async function probeMedia(filePath, opts = {}) {
8749
8704
  const runner = opts.execFileImpl ?? execFile;
8750
8705
  const ffmpegPath = opts.ffmpegPath ?? DEFAULT_FFMPEG_PATH;
8751
8706
  const ffprobePath = ffmpegPath.replace(/ffmpeg$/, "ffprobe");
8752
- return new Promise((resolve4, reject) => {
8707
+ return new Promise((resolve5, reject) => {
8753
8708
  runner(
8754
8709
  ffprobePath,
8755
8710
  [
@@ -8780,7 +8735,7 @@ async function probeMedia(filePath, opts = {}) {
8780
8735
  const hasAudio = /^codec_type=audio$/m.test(text);
8781
8736
  const rateMatch = text.match(/sample_rate=(\d+)/);
8782
8737
  const sampleRate = rateMatch ? parseInt(rateMatch[1], 10) : null;
8783
- resolve4({ durationSec, hasAudio, sampleRate });
8738
+ resolve5({ durationSec, hasAudio, sampleRate });
8784
8739
  }
8785
8740
  );
8786
8741
  });
@@ -8867,7 +8822,7 @@ async function preprocessMedia(inputPath, opts = {}) {
8867
8822
  args.push("-af", filter);
8868
8823
  }
8869
8824
  args.push("-c:a", "libopus", "-b:a", OPUS_BITRATE, outPath);
8870
- await new Promise((resolve4, reject) => {
8825
+ await new Promise((resolve5, reject) => {
8871
8826
  runner(ffmpegPath, args, { encoding: "utf8", maxBuffer: 8 * 1024 * 1024 }, (error, _stdout, stderr) => {
8872
8827
  if (error) {
8873
8828
  reject(
@@ -8877,7 +8832,7 @@ async function preprocessMedia(inputPath, opts = {}) {
8877
8832
  );
8878
8833
  return;
8879
8834
  }
8880
- resolve4();
8835
+ resolve5();
8881
8836
  });
8882
8837
  }).catch((err) => {
8883
8838
  if (ownOutDir) {
@@ -9575,7 +9530,7 @@ function parseStatusOutput(branch, status) {
9575
9530
  return { branch, modified, untracked };
9576
9531
  }
9577
9532
  function execFileUtf8(file, args, cwd) {
9578
- return new Promise((resolve4, reject) => {
9533
+ return new Promise((resolve5, reject) => {
9579
9534
  execFile3(
9580
9535
  file,
9581
9536
  args,
@@ -9585,7 +9540,7 @@ function execFileUtf8(file, args, cwd) {
9585
9540
  reject(err);
9586
9541
  return;
9587
9542
  }
9588
- resolve4(typeof stdout === "string" ? stdout : String(stdout ?? ""));
9543
+ resolve5(typeof stdout === "string" ? stdout : String(stdout ?? ""));
9589
9544
  }
9590
9545
  );
9591
9546
  });
@@ -9669,7 +9624,7 @@ function renderConversationLinks(extracted, t3, target = "pipe") {
9669
9624
  // packages/cli/tui/sessionDispatch.ts
9670
9625
  import { statSync as statSync5 } from "node:fs";
9671
9626
  import { homedir as homedir4 } from "node:os";
9672
- import { resolve as resolve3 } from "node:path";
9627
+ import { resolve as resolve4 } from "node:path";
9673
9628
 
9674
9629
  // packages/cli/tui/agentPicker.ts
9675
9630
  function toAgentPickerItems(entries) {
@@ -9796,29 +9751,48 @@ function renderRecentDiagnostics(env, events = getProcessRingBuffer()?.drain() ?
9796
9751
  }
9797
9752
 
9798
9753
  // packages/cli/client/estimateCliContext.ts
9799
- var DEFAULT_CLI_PACKS = ["code", "agent-orchestration", "skills"];
9800
- var DEFAULT_CLI_PLATFORM_TOOLS = [
9801
- "exa_search",
9802
- "fetchWebpage"
9803
- ];
9754
+ var CLI_ESTIMATE_ENV = { [RUN_WAKE_CHANNEL_ENV]: "1" };
9755
+ function resolveEstimateEnv(env) {
9756
+ const source = env ?? process.env;
9757
+ const exposeMcp = String(source[MCP_EXPOSURE_ENV] ?? "").trim();
9758
+ const exposeInstaboxParams = String(
9759
+ source[INSTABOX_SCHEMA_EXPOSURE_ENV] ?? ""
9760
+ ).trim();
9761
+ return {
9762
+ ...CLI_ESTIMATE_ENV,
9763
+ ...exposeMcp ? { [MCP_EXPOSURE_ENV]: exposeMcp } : {},
9764
+ ...exposeInstaboxParams ? { [INSTABOX_SCHEMA_EXPOSURE_ENV]: exposeInstaboxParams } : {}
9765
+ };
9766
+ }
9767
+ function resolveDefaultCliToolNames(env) {
9768
+ return canonicalizeToolNames(
9769
+ resolveCliRequestedToolNames(
9770
+ { key: BUILTIN_NOLO_AGENT_KEY },
9771
+ env,
9772
+ null
9773
+ )
9774
+ );
9775
+ }
9776
+ function resolveExposedCliToolNames(requestedToolNames, env) {
9777
+ return canonicalizeToolNames(
9778
+ buildLocalPolicyToolNames({
9779
+ agentKey: BUILTIN_NOLO_AGENT_KEY,
9780
+ toolNames: requestedToolNames,
9781
+ env
9782
+ })
9783
+ );
9784
+ }
9804
9785
  var DEFAULT_PROMPT_ESTIMATE_BASELINE = "\u4F60\u662F\u5171\u4EAB\u7A7A\u95F4\u91CC\u7684\u9AD8\u6027\u4EF7\u6BD4\u901A\u7528 AI \u52A9\u624B\u3002\u4F18\u5148\u5FEB\u901F\u3001\u76F4\u63A5\u3001\u7A33\u5B9A\u5730\u5B8C\u6210\u4EFB\u52A1\uFF1B\u9700\u8981\u63A8\u7406\u65F6\u4FDD\u6301\u6B65\u9AA4\u6E05\u6670\u3002";
9805
9786
  function readAgentsMd(cwd) {
9806
9787
  return readAgentsMdLayerFromDisk(cwd)?.content ?? "";
9807
9788
  }
9808
- function estimateToolSchemas(toolNames) {
9809
- const toolset = buildLocalWorkspaceToolset({
9810
- declaredToolNames: toolNames,
9811
- exposeShellTools: true
9812
- });
9813
- const workspaceTools = buildLocalWorkspaceOpenAiTools({
9814
- toolNames: toolset.toolNames,
9815
- exposeShellTools: true
9789
+ function estimateToolSchemas(toolNames, env) {
9790
+ const tools = buildOpenAiTools({
9791
+ agentKey: BUILTIN_NOLO_AGENT_KEY,
9792
+ toolNames,
9793
+ env
9816
9794
  });
9817
- const platformNames = DEFAULT_CLI_PLATFORM_TOOLS.filter(
9818
- (name) => toolNames.includes(name)
9819
- );
9820
- const platformTools = platformNames.length > 0 ? prepareTools([...platformNames]) : [];
9821
- return estimateTokenCount(JSON.stringify([...workspaceTools, ...platformTools]));
9795
+ return estimateTokenCount(JSON.stringify(tools));
9822
9796
  }
9823
9797
  function buildCliEstimateSystemText(opts = {}) {
9824
9798
  const cwd = opts.cwd?.trim() || process.cwd();
@@ -9826,15 +9800,16 @@ function buildCliEstimateSystemText(opts = {}) {
9826
9800
  const agentName = opts.agentName?.trim() || BUILTIN_NOLO_AGENT_NAME;
9827
9801
  const agentKey = opts.agentKey?.trim() || BUILTIN_NOLO_AGENT_KEY;
9828
9802
  const prompt = opts.agentPrompt?.trim() || DEFAULT_PROMPT_ESTIMATE_BASELINE;
9829
- const packTools = canonicalizeToolNames(
9830
- expandEnabledPacks([...DEFAULT_CLI_PACKS], [])
9803
+ const toolNames = resolveDefaultCliToolNames(resolveEstimateEnv(opts.env));
9804
+ const guidanceToolNames = resolveExposedCliToolNames(
9805
+ toolNames,
9806
+ resolveEstimateEnv(opts.env)
9831
9807
  );
9832
- const toolNames = canonicalizeToolNames([
9833
- ...packTools,
9834
- ...DEFAULT_CLI_PLATFORM_TOOLS
9835
- ]);
9836
- const guidance = buildRuntimeGuidanceBlocks(toolNames);
9837
- const toolSections = resolveToolGuidedSections(toolNames);
9808
+ const guidance = buildRuntimeGuidanceBlocks(guidanceToolNames);
9809
+ const toolSections = resolveToolGuidedSections(guidanceToolNames, {
9810
+ callerModel: opts.model?.trim() || void 0,
9811
+ callerIsPoolTop: opts.callerIsPoolTop
9812
+ });
9838
9813
  const responseGuidelines = resolveResponseGuidelines(
9839
9814
  opts.responseViewport ?? "unknown"
9840
9815
  );
@@ -9863,12 +9838,10 @@ function buildCliEstimateSystemText(opts = {}) {
9863
9838
  return systemParts.filter((part) => part?.trim()).join("\n\n");
9864
9839
  }
9865
9840
  function estimateDefaultCliContextTokens(opts = {}) {
9866
- const toolNames = canonicalizeToolNames([
9867
- ...canonicalizeToolNames(expandEnabledPacks([...DEFAULT_CLI_PACKS], [])),
9868
- ...DEFAULT_CLI_PLATFORM_TOOLS
9869
- ]);
9841
+ const env = resolveEstimateEnv(opts.env);
9842
+ const toolNames = resolveDefaultCliToolNames(env);
9870
9843
  const systemTokens = estimateTokenCount(buildCliEstimateSystemText(opts));
9871
- const toolTokens = estimateToolSchemas(toolNames);
9844
+ const toolTokens = estimateToolSchemas(toolNames, env);
9872
9845
  const historyTokens = opts.messages && opts.messages.length > 0 ? estimateMessagesTokens(opts.messages) : opts.historyText ? estimateTokenCount(opts.historyText) : 0;
9873
9846
  return Math.max(0, systemTokens + toolTokens + historyTokens);
9874
9847
  }
@@ -9952,7 +9925,7 @@ function renderPermissionGrantChip(state) {
9952
9925
  }
9953
9926
  function renderStatusLine(state, maxWidth) {
9954
9927
  const colorEnabled = resolveCliColorEnabled();
9955
- const sep = themeText(" \xB7 ", "chrome", colorEnabled);
9928
+ const sep2 = themeText(" \xB7 ", "chrome", colorEnabled);
9956
9929
  const agentDisplayName = state.agentName;
9957
9930
  const modeSuffix = state.modeLabel && state.modeLabel !== "auto" ? ` \xB7 ${state.modeLabel}` : "";
9958
9931
  const agentLabel = `\u2726 ${agentDisplayName}${modeSuffix}`;
@@ -10109,7 +10082,7 @@ function renderStatusLine(state, maxWidth) {
10109
10082
  visibleParts = fitted ? [fitted.join(" ")] : [overflowMark];
10110
10083
  }
10111
10084
  }
10112
- let body = visibleParts.filter(Boolean).join(sep);
10085
+ let body = visibleParts.filter(Boolean).join(sep2);
10113
10086
  if (maxWidth && maxWidth > 0) {
10114
10087
  const budget = Math.max(0, maxWidth - padWidth);
10115
10088
  if (displayWidth(stripAnsi(body)) > budget) {
@@ -10421,6 +10394,9 @@ function createInitialTuiState(env = process.env) {
10421
10394
  agentKey,
10422
10395
  userLanguage: asOptionalTrimmedString(env.NOLO_LANG),
10423
10396
  responseViewport: TUI_RESPONSE_VIEWPORT,
10397
+ // 估算必须看运行时那同一份 env:`NOLO_EXPOSE_MCP_TOOLS=1` 会让 local 装配
10398
+ // 多出 3 个 MCP 工具 schema,估算器若只看写死的 wake 开关就会低报。
10399
+ env,
10424
10400
  ...resolveAgentModelIdentity({ agentKey, agentName })
10425
10401
  })
10426
10402
  };
@@ -10433,7 +10409,7 @@ function parsePermissionGrants(raw) {
10433
10409
  }
10434
10410
  return grants;
10435
10411
  }
10436
- function applyAgentSwitch(state, target, historyTurns) {
10412
+ function applyAgentSwitch(state, target, historyTurns, estimateEnv) {
10437
10413
  const contextWindow = resolveAgentContextWindow({
10438
10414
  agentKey: target.key,
10439
10415
  agentName: target.name,
@@ -10452,7 +10428,8 @@ function applyAgentSwitch(state, target, historyTurns) {
10452
10428
  model: target.model,
10453
10429
  userLanguage: state.userLanguage,
10454
10430
  responseViewport: TUI_RESPONSE_VIEWPORT,
10455
- messages: historyTurns
10431
+ messages: historyTurns,
10432
+ env: estimateEnv ?? process.env
10456
10433
  })
10457
10434
  },
10458
10435
  output: `Switched to ${target.name}. ${state.dialogId ? `Dialog kept: ${state.dialogId}` : "Dialog kept: new"}`
@@ -10536,6 +10513,9 @@ function formatUnknownSlashCommand(cmd, allowSuggestion = true) {
10536
10513
  function isShellPassthroughInput(input) {
10537
10514
  return input.trimStart().startsWith("!");
10538
10515
  }
10516
+ function resolveEstimateEnv2(deps) {
10517
+ return deps?.estimateEnv ?? deps?.env;
10518
+ }
10539
10519
  function handleTuiInput(input, state, historyTurns, deps) {
10540
10520
  const trimmed = input.trim();
10541
10521
  if (!trimmed) {
@@ -10655,8 +10635,8 @@ ${t("cdUsage")}`
10655
10635
  };
10656
10636
  }
10657
10637
  const unquoted = argText.startsWith('"') && argText.endsWith('"') && argText.length >= 2 || argText.startsWith("'") && argText.endsWith("'") && argText.length >= 2 ? argText.slice(1, -1) : argText;
10658
- const expanded = unquoted === "~" ? homedir4() : unquoted.startsWith("~/") || unquoted.startsWith("~\\") ? resolve3(homedir4(), unquoted.slice(2)) : unquoted;
10659
- const target = resolve3(state.cwd, expanded);
10638
+ const expanded = unquoted === "~" ? homedir4() : unquoted.startsWith("~/") || unquoted.startsWith("~\\") ? resolve4(homedir4(), unquoted.slice(2)) : unquoted;
10639
+ const target = resolve4(state.cwd, expanded);
10660
10640
  try {
10661
10641
  if (!statSync5(target).isDirectory()) {
10662
10642
  return { nextState: state, output: t("cdNotDir", target) };
@@ -10901,7 +10881,7 @@ ${t("autoUsage")}` };
10901
10881
  output: t("agentUnknown", argText)
10902
10882
  };
10903
10883
  }
10904
- return applyAgentSwitch(state, resolvedTarget, historyTurns);
10884
+ return applyAgentSwitch(state, resolvedTarget, historyTurns, resolveEstimateEnv2(deps) ?? process.env);
10905
10885
  }
10906
10886
  case "/lang": {
10907
10887
  const locale = parseCliLocale(argText);
@@ -10922,6 +10902,7 @@ ${t("autoUsage")}` };
10922
10902
  userLanguage: locale,
10923
10903
  responseViewport: TUI_RESPONSE_VIEWPORT,
10924
10904
  messages: historyTurns,
10905
+ env: resolveEstimateEnv2(deps) ?? process.env,
10925
10906
  ...resolveAgentModelIdentity({
10926
10907
  agentKey: state.agentKey,
10927
10908
  agentName: state.agentName
@@ -11241,7 +11222,7 @@ function resolveTuiIdentityEnv(startupEnv, liveEnv) {
11241
11222
  }
11242
11223
 
11243
11224
  // packages/cli/tui/session.ts
11244
- function applyAgentSwitchState(state, target, messages) {
11225
+ function applyAgentSwitchState(state, target, messages, env) {
11245
11226
  return {
11246
11227
  ...state,
11247
11228
  agentName: target.name,
@@ -11254,7 +11235,8 @@ function applyAgentSwitchState(state, target, messages) {
11254
11235
  model: target.model,
11255
11236
  userLanguage: state.userLanguage,
11256
11237
  responseViewport: TUI_RESPONSE_VIEWPORT,
11257
- messages
11238
+ messages,
11239
+ env: env ?? process.env
11258
11240
  }),
11259
11241
  turnTokens: void 0,
11260
11242
  lastAuthorityTurnCount: void 0,
@@ -11309,7 +11291,7 @@ function handleTuiInput2(input, state, historyTurns, deps) {
11309
11291
  ...applyAgentSwitchState(state, {
11310
11292
  key: result.nextState.agentKey,
11311
11293
  name: result.nextState.agentName
11312
- }),
11294
+ }, historyTurns, deps?.estimateEnv ?? deps?.env),
11313
11295
  // The synchronous platform resolver already has the model identity.
11314
11296
  contextWindow: result.nextState.contextWindow,
11315
11297
  estimatedContextTokens: result.nextState.estimatedContextTokens
@@ -11378,6 +11360,45 @@ function splitProbeInput(buffer) {
11378
11360
  function isTerminalDevice(stream) {
11379
11361
  return stream instanceof ReadStream;
11380
11362
  }
11363
+ function readGsettingsValue(raw) {
11364
+ return (raw ?? "").trim().replace(/^'([\s\S]*)'$/, "$1").trim().toLowerCase();
11365
+ }
11366
+ var readGsettingsKey = (schema, key) => {
11367
+ try {
11368
+ return execFileSync("gsettings", ["get", schema, key], {
11369
+ encoding: "utf8",
11370
+ stdio: ["ignore", "pipe", "ignore"],
11371
+ timeout: 200
11372
+ }).trim();
11373
+ } catch {
11374
+ return null;
11375
+ }
11376
+ };
11377
+ function parseGnomeColorScheme(value) {
11378
+ const scheme = readGsettingsValue(value ?? null);
11379
+ if (scheme === "prefer-dark") return "dark";
11380
+ if (scheme === "prefer-light" || scheme === "default") return "light";
11381
+ return null;
11382
+ }
11383
+ function isPtyxisTerminal(env = process.env) {
11384
+ return Boolean(
11385
+ (env.PTYXIS_VERSION ?? "").trim() || (env.PTYXIS_PROFILE ?? "").trim()
11386
+ );
11387
+ }
11388
+ var ptyxisCanvasCache = null;
11389
+ function resetPtyxisCanvasCache() {
11390
+ ptyxisCanvasCache = null;
11391
+ }
11392
+ function detectPtyxisCanvasBrightness(env = process.env, read = readGsettingsKey) {
11393
+ if (ptyxisCanvasCache) return ptyxisCanvasCache.value;
11394
+ if (!isPtyxisTerminal(env)) return null;
11395
+ const style = readGsettingsValue(read("org.gnome.Ptyxis", "interface-style"));
11396
+ const value = style === "light" ? "light" : style === "dark" ? "dark" : parseGnomeColorScheme(
11397
+ read("org.gnome.desktop.interface", "color-scheme")
11398
+ );
11399
+ ptyxisCanvasCache = { value };
11400
+ return value;
11401
+ }
11381
11402
  async function probeTerminalBackground(args = {}) {
11382
11403
  const stdin = args.stdin ?? process.stdin;
11383
11404
  const stdout = args.stdout ?? process.stdout;
@@ -11388,7 +11409,7 @@ async function probeTerminalBackground(args = {}) {
11388
11409
  if (typeof stdin.setRawMode !== "function") return null;
11389
11410
  if (!isTerminal(stdin)) return null;
11390
11411
  const wasRaw = Boolean(stdin.isRaw);
11391
- return await new Promise((resolve4) => {
11412
+ return await new Promise((resolve5) => {
11392
11413
  let buffer = "";
11393
11414
  let settled = false;
11394
11415
  let timer;
@@ -11406,7 +11427,7 @@ async function probeTerminalBackground(args = {}) {
11406
11427
  if (!wasRaw) stdin.setRawMode?.(false);
11407
11428
  } catch {
11408
11429
  }
11409
- resolve4(result);
11430
+ resolve5(result);
11410
11431
  };
11411
11432
  const onData = (chunk) => {
11412
11433
  buffer += chunk.toString("latin1");
@@ -11427,9 +11448,16 @@ async function probeTerminalBackground(args = {}) {
11427
11448
  });
11428
11449
  }
11429
11450
  async function detectTerminalBackground(args = {}) {
11451
+ const hostCanvas = args.trustHostCanvas ? detectPtyxisCanvasBrightness(
11452
+ args.env ?? process.env,
11453
+ args.readGsettings ?? readGsettingsKey
11454
+ ) : null;
11455
+ if (hostCanvas) return { brightness: hostCanvas, hex: "", trustedCanvas: true };
11430
11456
  const r = await probeTerminalBackground(args);
11431
11457
  if (r || !args.allowSystemFallback) return r;
11432
- const brightness = detectSystemBrightness(process.env, { allowSubprocess: true });
11458
+ const brightness = detectSystemBrightness(args.env ?? process.env, {
11459
+ allowSubprocess: true
11460
+ });
11433
11461
  return brightness ? { brightness, hex: "" } : null;
11434
11462
  }
11435
11463
  function detectSystemBrightness(env = process.env, options = {}) {
@@ -11460,6 +11488,8 @@ function detectSystemBrightness(env = process.env, options = {}) {
11460
11488
  timeout: 200
11461
11489
  }
11462
11490
  ).trim();
11491
+ const scheme = parseGnomeColorScheme(out);
11492
+ if (scheme) return scheme;
11463
11493
  const val = out.toLowerCase();
11464
11494
  if (/(?:^|[\s\-_:])dark(?:$|[\s\-_:])/i.test(val)) return "dark";
11465
11495
  if (/(?:^|[\s\-_:])light(?:$|[\s\-_:])/i.test(val)) return "light";
@@ -11477,7 +11507,7 @@ function appendStreamSafeNotice(history, text, deps) {
11477
11507
  history.currentBlocks = [];
11478
11508
  }
11479
11509
  deps.appendLocalTurn(history, "", text);
11480
- if (wasStreamingAssistant) deps.startTurn(history, "assistant");
11510
+ if (wasStreamingAssistant) deps.startTurn(history, "assistant", { continueAssistantTurn: true });
11481
11511
  }
11482
11512
  function createTurnInjectionInbox() {
11483
11513
  let pending = [];
@@ -11604,13 +11634,13 @@ function startCiDeployEventStream(args) {
11604
11634
  let controller = null;
11605
11635
  const timers = /* @__PURE__ */ new Set();
11606
11636
  const sleepWaiters = /* @__PURE__ */ new Set();
11607
- const sleepWithRegisteredTimer = (ms) => new Promise((resolve4) => {
11637
+ const sleepWithRegisteredTimer = (ms) => new Promise((resolve5) => {
11608
11638
  let settled = false;
11609
11639
  const wake = () => {
11610
11640
  if (settled) return;
11611
11641
  settled = true;
11612
11642
  sleepWaiters.delete(wake);
11613
- resolve4();
11643
+ resolve5();
11614
11644
  };
11615
11645
  const timer = setTimeout(() => {
11616
11646
  timers.delete(timer);
@@ -11928,7 +11958,10 @@ function prepareChildRunConsumption(event, host) {
11928
11958
  return {
11929
11959
  ...event,
11930
11960
  runs: remainingRuns,
11931
- text: buildWakeMessage(remainingRuns, now),
11961
+ text: buildWakeMessage(remainingRuns, now, {
11962
+ // 与 run 注册表同一个有效 runs 目录(自定义 NOLO_HOME 也要内联)。
11963
+ trustedResultDirs: [resolveRunsDir(host.env)]
11964
+ }),
11932
11965
  displayText: buildWakeDisplayText(remainingRuns, now)
11933
11966
  };
11934
11967
  }
@@ -12652,11 +12685,11 @@ async function runAskChoiceDialog(args) {
12652
12685
  }
12653
12686
  paint();
12654
12687
  while (state.phase === "active") {
12655
- const sequence = await new Promise((resolve4, reject) => {
12656
- const abort = () => resolve4(STREAM_CLOSED);
12688
+ const sequence = await new Promise((resolve5, reject) => {
12689
+ const abort = () => resolve5(STREAM_CLOSED);
12657
12690
  if (request.signal?.aborted) return abort();
12658
12691
  request.signal?.addEventListener("abort", abort, { once: true });
12659
- Promise.resolve(readKey()).then(resolve4, reject).finally(() => request.signal?.removeEventListener("abort", abort));
12692
+ Promise.resolve(readKey()).then(resolve5, reject).finally(() => request.signal?.removeEventListener("abort", abort));
12660
12693
  });
12661
12694
  if (sequence === STREAM_CLOSED) {
12662
12695
  state = askChoiceReducer(state, { type: "CANCEL" });
@@ -13580,12 +13613,12 @@ async function detectTrailingSilenceSuggestion(filePath, durationSec, opts = {})
13580
13613
  "-"
13581
13614
  ];
13582
13615
  try {
13583
- const stderr = await new Promise((resolve4, reject) => {
13616
+ const stderr = await new Promise((resolve5, reject) => {
13584
13617
  runner(
13585
13618
  opts.ffmpegPath ?? resolveFfmpegPath(),
13586
13619
  args,
13587
13620
  { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
13588
- (error, _stdout, stderrText) => error ? reject(error) : resolve4(String(stderrText ?? ""))
13621
+ (error, _stdout, stderrText) => error ? reject(error) : resolve5(String(stderrText ?? ""))
13589
13622
  );
13590
13623
  });
13591
13624
  return buildTrailingSilenceSuggestion(
@@ -13844,6 +13877,7 @@ function createNoopFixedInput() {
13844
13877
  },
13845
13878
  disable() {
13846
13879
  },
13880
+ isDisabled: () => true,
13847
13881
  getInputLines: () => 1,
13848
13882
  isPaused: () => false,
13849
13883
  setMouseEnabled() {
@@ -13859,7 +13893,9 @@ function createFixedInput(output, config) {
13859
13893
  const getColumns = () => output.columns ?? 80;
13860
13894
  let inputLines = 1;
13861
13895
  let paused = false;
13896
+ let disabled = false;
13862
13897
  const write = (seq) => {
13898
+ if (disabled) return;
13863
13899
  output.write(seq);
13864
13900
  };
13865
13901
  let lastScrollBottom = -1;
@@ -14072,6 +14108,7 @@ function createFixedInput(output, config) {
14072
14108
  return { text, lines, cursorCol, cursorRow: headerRows + cursorRow };
14073
14109
  };
14074
14110
  const repaintAt = (buffer, cursorPos, force = false) => {
14111
+ if (disabled) return;
14075
14112
  const { text, lines, cursorCol, cursorRow } = renderInputArea(buffer, cursorPos);
14076
14113
  let linesChanged = false;
14077
14114
  if (lines !== inputLines) {
@@ -14142,6 +14179,7 @@ function createFixedInput(output, config) {
14142
14179
  return {
14143
14180
  active: true,
14144
14181
  init() {
14182
+ if (disabled) return;
14145
14183
  invalidateComposerCache();
14146
14184
  saveCursor();
14147
14185
  setScrollRegion(inputLines);
@@ -14169,6 +14207,7 @@ function createFixedInput(output, config) {
14169
14207
  resetCursorStyle();
14170
14208
  },
14171
14209
  resumeFromSubprocess() {
14210
+ if (disabled) return;
14172
14211
  paused = false;
14173
14212
  invalidateComposerCache();
14174
14213
  resetHistoryFrameDiffCache(output);
@@ -14181,6 +14220,7 @@ function createFixedInput(output, config) {
14181
14220
  `);
14182
14221
  },
14183
14222
  resumeFromDialog() {
14223
+ if (disabled) return;
14184
14224
  paused = false;
14185
14225
  invalidateComposerCache();
14186
14226
  resetHistoryFrameDiffCache(output);
@@ -14198,7 +14238,9 @@ function createFixedInput(output, config) {
14198
14238
  resetScrollRegion();
14199
14239
  resetCursorStyle();
14200
14240
  leaveAltScreen(output);
14241
+ disabled = true;
14201
14242
  },
14243
+ isDisabled: () => disabled,
14202
14244
  getInputLines: () => inputLines,
14203
14245
  isPaused: () => paused,
14204
14246
  setMouseEnabled(enabled) {
@@ -14211,6 +14253,7 @@ function createFixedInput(output, config) {
14211
14253
  },
14212
14254
  isMouseEnabled: () => mouseEnabled,
14213
14255
  setAltScreenEnabled(enabled) {
14256
+ if (disabled) return;
14214
14257
  if (enabled) {
14215
14258
  enterAltScreen(output);
14216
14259
  } else {
@@ -14745,7 +14788,10 @@ async function runAgentChat(scriptDir, state, message, env, output, agentRunner
14745
14788
  (r) => !!r.parentDialogId && r.parentDialogId === state.dialogId
14746
14789
  );
14747
14790
  const childRunNoticeBlocks = injectedChildRunNoticeItems.length > 0 ? [{
14748
- content: buildWakeMessage(injectedChildRunNoticeItems, Date.now()),
14791
+ content: buildWakeMessage(injectedChildRunNoticeItems, Date.now(), {
14792
+ // WAKE-003-CONFIG:与 run 注册表同一有效 runs 目录(尊重自定义 NOLO_HOME)。
14793
+ trustedResultDirs: [resolveRunsDir(env)]
14794
+ }),
14749
14795
  cacheScope: "turn"
14750
14796
  }] : [];
14751
14797
  const contextBlockScopes = partitionScopedBlocks([
@@ -14946,14 +14992,14 @@ function waitForActionGate(rl, input, output, gate, spawnRunner) {
14946
14992
  const meta = deriveGateMeta(gate);
14947
14993
  const { commandPayload, isConfirmation, displayCommand } = meta;
14948
14994
  writeGatePrompt(output, meta);
14949
- return new Promise((resolve4) => {
14995
+ return new Promise((resolve5) => {
14950
14996
  let settled = false;
14951
14997
  const finish = (result) => {
14952
14998
  if (settled) return;
14953
14999
  settled = true;
14954
15000
  rl.off("close", onClose);
14955
15001
  rl.off("SIGINT", onSigint);
14956
- resolve4(result);
15002
+ resolve5(result);
14957
15003
  };
14958
15004
  const cancelResult = (reason) => buildGateCancelledResult(gate, reason);
14959
15005
  const failResult = (message) => buildGateFailedResult(gate, message);
@@ -15017,7 +15063,7 @@ function waitForRawActionGate(input, output, gate, spawnRunner, hooks) {
15017
15063
  const meta = deriveGateMeta(gate);
15018
15064
  const { commandPayload, isConfirmation, displayCommand } = meta;
15019
15065
  writeGatePrompt(output, meta);
15020
- return new Promise((resolve4) => {
15066
+ return new Promise((resolve5) => {
15021
15067
  const rawInput = input;
15022
15068
  let settled = false;
15023
15069
  let commandRunning = false;
@@ -15029,7 +15075,7 @@ function waitForRawActionGate(input, output, gate, spawnRunner, hooks) {
15029
15075
  input.off("data", onData);
15030
15076
  input.off?.("end", onEnd);
15031
15077
  input.off?.("close", onEnd);
15032
- resolve4(result);
15078
+ resolve5(result);
15033
15079
  };
15034
15080
  const cancel = (reason) => finish(buildGateCancelledResult(gate, reason));
15035
15081
  const fail = (message) => finish(buildGateFailedResult(gate, message));
@@ -15260,14 +15306,14 @@ function buildWakeRetryContinuationMessage(event) {
15260
15306
  }
15261
15307
  function waitForWakeRetryBackoff(delayMs, signal) {
15262
15308
  if (delayMs <= 0 || signal?.aborted) return Promise.resolve();
15263
- return new Promise((resolve4) => {
15309
+ return new Promise((resolve5) => {
15264
15310
  const onAbort = () => {
15265
15311
  clearTimeout(timer);
15266
- resolve4();
15312
+ resolve5();
15267
15313
  };
15268
15314
  const timer = setTimeout(() => {
15269
15315
  signal?.removeEventListener("abort", onAbort);
15270
- resolve4();
15316
+ resolve5();
15271
15317
  }, delayMs);
15272
15318
  signal?.addEventListener("abort", onAbort, { once: true });
15273
15319
  });
@@ -15345,7 +15391,7 @@ async function runOneAgentTurn(ctx, inputMsg, imageUrls, actionGateHandler, conf
15345
15391
  if (!approved) return false;
15346
15392
  const commandText = typeof request.command === "string" ? request.command : "";
15347
15393
  if (commandText) {
15348
- const { runApprovedCredentialCommand } = await import("./hostCredentialCreate-23TX56G7.js");
15394
+ const { runApprovedCredentialCommand } = await import("./hostCredentialCreate-C57T7YPE.js");
15349
15395
  const hostResult = await runApprovedCredentialCommand({
15350
15396
  commandText,
15351
15397
  approvalEventId: request.id,
@@ -15416,6 +15462,9 @@ async function runOneAgentTurn(ctx, inputMsg, imageUrls, actionGateHandler, conf
15416
15462
  userLanguage: ctx.state.userLanguage,
15417
15463
  responseViewport: TUI_RESPONSE_VIEWPORT,
15418
15464
  messages: ctx.history.turns,
15465
+ // 回退估算必须与下面真正发请求的 runAgentChat 共用同一份 env:
15466
+ // NOLO_EXPOSE_MCP_TOOLS / NOLO_EXPOSE_INSTABOX_PARAMS 会改变工具面。
15467
+ env: ctx.options.env ?? process.env,
15419
15468
  ...resolveAgentModelIdentity({
15420
15469
  agentKey: ctx.state.agentKey,
15421
15470
  agentName: ctx.state.agentName
@@ -15817,7 +15866,8 @@ async function runOneAgentTurn(ctx, inputMsg, imageUrls, actionGateHandler, conf
15817
15866
  agentName: ctx.state.agentName,
15818
15867
  userLanguage: ctx.state.userLanguage,
15819
15868
  responseViewport: TUI_RESPONSE_VIEWPORT,
15820
- messages: ctx.history.turns
15869
+ messages: ctx.history.turns,
15870
+ env: ctx.options.env ?? process.env
15821
15871
  }),
15822
15872
  lastAuthorityTurnCount: void 0,
15823
15873
  liveTurnEstimatedTokens: void 0
@@ -16493,16 +16543,30 @@ function createTuiRender(host) {
16493
16543
  let renderScheduled = false;
16494
16544
  let renderTimer = null;
16495
16545
  let syncingLayout = false;
16546
+ let closed = false;
16547
+ const close = () => {
16548
+ closed = true;
16549
+ if (renderTimer !== null) {
16550
+ clearTimeout(renderTimer);
16551
+ renderTimer = null;
16552
+ }
16553
+ renderScheduled = false;
16554
+ };
16496
16555
  const flushPendingRender = () => {
16497
16556
  if (renderTimer !== null) {
16498
16557
  clearTimeout(renderTimer);
16499
16558
  renderTimer = null;
16500
16559
  }
16560
+ if (closed) {
16561
+ renderScheduled = false;
16562
+ return;
16563
+ }
16501
16564
  if (!renderScheduled) return;
16502
16565
  renderScheduled = false;
16503
16566
  paintSyncedFrame();
16504
16567
  };
16505
16568
  const paintSyncedFrame = () => {
16569
+ if (closed) return;
16506
16570
  if (host.fixedInput.isPaused()) {
16507
16571
  host.imageRenderer?.suspend();
16508
16572
  return;
@@ -16517,7 +16581,7 @@ function createTuiRender(host) {
16517
16581
  }
16518
16582
  };
16519
16583
  const scheduleRender = () => {
16520
- if (renderScheduled) return;
16584
+ if (closed || renderScheduled) return;
16521
16585
  renderScheduled = true;
16522
16586
  renderTimer = setTimeout(() => {
16523
16587
  renderScheduled = false;
@@ -16526,7 +16590,7 @@ function createTuiRender(host) {
16526
16590
  }, RENDER_THROTTLE_MS);
16527
16591
  };
16528
16592
  const renderHistoryCore = (withImages) => {
16529
- if (syncingLayout) return;
16593
+ if (closed || syncingLayout) return;
16530
16594
  syncingLayout = true;
16531
16595
  try {
16532
16596
  const reservedRows = host.getReservedRows?.() ?? 0;
@@ -16546,6 +16610,7 @@ function createTuiRender(host) {
16546
16610
  }
16547
16611
  };
16548
16612
  const renderHistoryToOutput = () => {
16613
+ if (closed) return;
16549
16614
  if (host.fixedInput.isPaused()) {
16550
16615
  host.imageRenderer?.suspend();
16551
16616
  return;
@@ -16554,6 +16619,7 @@ function createTuiRender(host) {
16554
16619
  renderHistoryCore(true);
16555
16620
  };
16556
16621
  const renderHistoryUnderDialog = () => {
16622
+ if (closed) return;
16557
16623
  host.imageRenderer?.suspend();
16558
16624
  renderHistoryCore(false);
16559
16625
  };
@@ -16562,6 +16628,9 @@ function createTuiRender(host) {
16562
16628
  renderHistoryUnderDialog,
16563
16629
  scheduleRender,
16564
16630
  flushPendingRender,
16631
+ // 会话收尾:取消防抖定时器并关死全部渲染入口。幂等,交给 workspace 的
16632
+ // 唯一退出汇聚点调用;调用之后本集群不再向 output 写任何字节。
16633
+ close,
16565
16634
  // 立即绘制一帧同步帧(BSU/ESU + 光标隐藏)。流式路径走 33ms 节流的
16566
16635
  // scheduleRender;平滑滚动推进器按 16ms 自己的节奏调用这里,避免被节流
16567
16636
  // 抹平成"每 33ms 一跳"。
@@ -16988,10 +17057,12 @@ function createTuiImageRenderer(options) {
16988
17057
  import { randomInt } from "node:crypto";
16989
17058
 
16990
17059
  // packages/cli/tui/tuiScrollAnimation.ts
16991
- var VELOCITY_WINDOW_MS = 160;
17060
+ var VELOCITY_WINDOW_MS = 240;
16992
17061
  var VELOCITY_SLOW_COUNT = 3;
16993
- var VELOCITY_GAIN_PER_REPORT = 0.35;
16994
- var VELOCITY_MAX_GAIN = 6;
17062
+ var VELOCITY_GAIN_PER_REPORT = 0.65;
17063
+ var VELOCITY_MAX_GAIN = 8;
17064
+ var VELOCITY_CADENCE_SEPARATION_MS = 12;
17065
+ var VELOCITY_CADENCE_PULSE_WEIGHT = 3;
16995
17066
  function velocityGain(recentCount) {
16996
17067
  if (recentCount <= VELOCITY_SLOW_COUNT) return 1;
16997
17068
  return Math.min(
@@ -17047,9 +17118,12 @@ function createScrollAnimator(deps) {
17047
17118
  fractionalLines = 0;
17048
17119
  recentDirection = direction;
17049
17120
  }
17050
- recentReports = recentReports.filter((ts) => t3 - ts < VELOCITY_WINDOW_MS);
17051
- recentReports.push(t3);
17052
- fractionalLines += velocityGain(recentReports.length);
17121
+ recentReports = recentReports.filter((entry) => t3 - entry.ts < VELOCITY_WINDOW_MS);
17122
+ const lastEntry = recentReports.at(-1);
17123
+ const weight = lastEntry !== void 0 && t3 - lastEntry.ts >= VELOCITY_CADENCE_SEPARATION_MS ? VELOCITY_CADENCE_PULSE_WEIGHT : 1;
17124
+ recentReports.push({ ts: t3, weight });
17125
+ const pulsedCount = recentReports.reduce((sum, entry) => sum + entry.weight, 0);
17126
+ fractionalLines += velocityGain(pulsedCount);
17053
17127
  const whole = Math.floor(fractionalLines);
17054
17128
  fractionalLines -= whole;
17055
17129
  return whole;
@@ -17472,7 +17546,7 @@ async function compactDialog(options) {
17472
17546
  fetchImpl,
17473
17547
  agentRef: getActiveDialogAgentId(current) ?? void 0,
17474
17548
  loadAdapter: async () => {
17475
- const { createCliLocalRuntimeAdapter: createCliLocalRuntimeAdapter2 } = await import("./localRuntimeAdapter-MTUWOYPN.js");
17549
+ const { createCliLocalRuntimeAdapter: createCliLocalRuntimeAdapter2 } = await import("./localRuntimeAdapter-OALZPFZU.js");
17476
17550
  return createCliLocalRuntimeAdapter2({ env: { ...options.env ?? {}, AUTH_TOKEN: options.authToken, NOLO_SERVER: options.serverUrl }, fetchImpl });
17477
17551
  }
17478
17552
  }) : void 0);
@@ -18280,6 +18354,10 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18280
18354
  }
18281
18355
  const result = handleTuiInput2(line, host.state, collectConversationTurns(host.history), {
18282
18356
  env: host.taskEnv,
18357
+ // Context estimate must see the runtime's env, not the merged task env:
18358
+ // an explicit `{}` in options.env means the turn runs without the process
18359
+ // env (no MCP/Instabox schemas), so the chip must not count them either.
18360
+ estimateEnv: host.options.env ?? process.env,
18283
18361
  authEnv: resolveTuiIdentityEnv(host.taskEnv, host.options.env ?? process.env),
18284
18362
  // 交互模式下非 chat 输出会进 transcript(emitCommandOutput → appendLocalTurn),
18285
18363
  // /links 的 Ctrl+左键提示才成立;管道/脚本下同一份文本只是 stdout,不能用快捷键承诺。
@@ -18369,6 +18447,7 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18369
18447
  agentKey: host.state.agentKey,
18370
18448
  userLanguage: host.state.userLanguage,
18371
18449
  responseViewport: TUI_RESPONSE_VIEWPORT,
18450
+ env: host.options.env ?? process.env,
18372
18451
  ...resolveAgentModelIdentity({
18373
18452
  agentKey: host.state.agentKey,
18374
18453
  agentName: host.state.agentName
@@ -18377,6 +18456,7 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18377
18456
  };
18378
18457
  history.turns.length = 0;
18379
18458
  history.toolDetails = [];
18459
+ history.lastTurnToolDetailStart = 0;
18380
18460
  history.currentRole = null;
18381
18461
  history.currentContent = "";
18382
18462
  history.scrollTop = 0;
@@ -18473,6 +18553,7 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18473
18553
  agentKey: host.state.agentKey,
18474
18554
  userLanguage: host.state.userLanguage,
18475
18555
  responseViewport: TUI_RESPONSE_VIEWPORT,
18556
+ env: host.options.env ?? process.env,
18476
18557
  messages: [
18477
18558
  ...compactResult.summary ? [{ role: "system", content: compactResult.summary }] : [],
18478
18559
  ...compactResult.compactedMessageCount > 0 ? host.history.turns.slice(compactResult.compactedMessageCount) : compactResult.summaryGenerated ? [] : host.history.turns
@@ -18561,10 +18642,12 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18561
18642
  emitCommandOutput(lines.join("\n"), line);
18562
18643
  }
18563
18644
  if (result.action?.type === "theme-refresh") {
18645
+ resetPtyxisCanvasCache();
18564
18646
  const detected = await detectTerminalBackground({
18565
18647
  stdin: input,
18566
18648
  stdout: output,
18567
- allowSystemFallback: true
18649
+ allowSystemFallback: true,
18650
+ trustHostCanvas: true
18568
18651
  });
18569
18652
  if (detected && applyDetectedBackground(detected)) {
18570
18653
  emitCommandOutput(t("themeRefreshed", detected.brightness));
@@ -18598,7 +18681,7 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18598
18681
  if (!target || !entries.some((entry) => entry.key === target.key)) {
18599
18682
  emitCommandOutput(t("agentUnknown", query));
18600
18683
  } else {
18601
- const nextState = applyAgentSwitchState(host.state, target, host.history.turns);
18684
+ const nextState = applyAgentSwitchState(host.state, target, host.history.turns, options.env ?? process.env);
18602
18685
  const oldKey = host.state.agentKey;
18603
18686
  host.state = nextState;
18604
18687
  clearCliLocalRuntimePreparedAgentCache();
@@ -18642,7 +18725,8 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18642
18725
  model: pickResult.model,
18643
18726
  userLanguage: host.state.userLanguage,
18644
18727
  responseViewport: TUI_RESPONSE_VIEWPORT,
18645
- messages: host.history.turns
18728
+ messages: host.history.turns,
18729
+ env: host.options.env ?? process.env
18646
18730
  }),
18647
18731
  turnTokens: void 0,
18648
18732
  lastAuthorityTurnCount: void 0,
@@ -18716,6 +18800,7 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18716
18800
  const restored = loadedTurns.slice(-MAX_TUI_HISTORY_TURNS);
18717
18801
  history.turns.length = 0;
18718
18802
  history.toolDetails = [];
18803
+ history.lastTurnToolDetailStart = 0;
18719
18804
  history.turns.push(...restored);
18720
18805
  history.currentRole = null;
18721
18806
  history.currentContent = "";
@@ -18744,6 +18829,7 @@ async function runSubmittedSlashLine(line, host, actionGateHandler, confirmDestr
18744
18829
  userLanguage: host.state.userLanguage,
18745
18830
  responseViewport: TUI_RESPONSE_VIEWPORT,
18746
18831
  messages: history.turns,
18832
+ env: host.options.env ?? process.env,
18747
18833
  ...resolveAgentModelIdentity({
18748
18834
  agentKey: host.state.agentKey,
18749
18835
  agentName: host.state.agentName
@@ -19115,10 +19201,6 @@ function isClipboardImageFallbackEligible(error) {
19115
19201
  const code = error instanceof ClipboardImageError ? error.code : typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
19116
19202
  return isTextFallbackEligibleCode(code);
19117
19203
  }
19118
- function shouldRefreshCiStatusOnStartup(env) {
19119
- if (env.NOLO_CLI_CI_STATUS === "0") return false;
19120
- return env.NOLO_CLI_CI_STATUS === "1" || Boolean(env.NOLO_CI_SSH_HOST?.trim() || env.NOLO_CI_RAW_HOST?.trim());
19121
- }
19122
19204
  async function runTuiWorkspace(options) {
19123
19205
  const startupThemeMode = resolveTuiThemeMode(
19124
19206
  options.env ?? process.env,
@@ -19126,6 +19208,7 @@ async function runTuiWorkspace(options) {
19126
19208
  );
19127
19209
  setActiveThemeMode(startupThemeMode);
19128
19210
  const accountSessionRuntime = createTuiAccountSessionRuntime(options.env ?? process.env);
19211
+ let cleanupTitle = null;
19129
19212
  try {
19130
19213
  const runtimeEnv = options.env ?? process.env;
19131
19214
  initCliLocale(runtimeEnv);
@@ -19180,7 +19263,8 @@ async function runTuiWorkspace(options) {
19180
19263
  stdin: input,
19181
19264
  stdout: output,
19182
19265
  allowSystemFallback: startupThemeMode !== "terminal",
19183
- preserveInput: true
19266
+ preserveInput: true,
19267
+ trustHostCanvas: true
19184
19268
  });
19185
19269
  if (detected) applyDetectedBackground(detected);
19186
19270
  let sawOsc11Reply = Boolean(detected?.hex);
@@ -19229,8 +19313,18 @@ async function runTuiWorkspace(options) {
19229
19313
  let lastProtocolReport = "";
19230
19314
  const titleEnv = options.env ?? process.env;
19231
19315
  const titleEnabled = output.isTTY === true && !["0", "false"].includes((titleEnv.NOLO_TUI_TITLE ?? "").trim().toLowerCase());
19316
+ const TITLE_SPINNER_INTERVAL_MS = 200;
19317
+ let titleFrameIndex = 0;
19318
+ let titleAnimTimer = null;
19319
+ const stopTitleAnimation = () => {
19320
+ if (titleAnimTimer !== null) {
19321
+ clearInterval(titleAnimTimer);
19322
+ titleAnimTimer = null;
19323
+ }
19324
+ };
19232
19325
  let titleRestored = false;
19233
19326
  const restoreTitle = () => {
19327
+ stopTitleAnimation();
19234
19328
  if (titleRestored) return;
19235
19329
  titleRestored = true;
19236
19330
  if (titleEnabled) {
@@ -19241,6 +19335,7 @@ async function runTuiWorkspace(options) {
19241
19335
  }
19242
19336
  if (restoreWindowTitle === restoreTitle) restoreWindowTitle = null;
19243
19337
  };
19338
+ cleanupTitle = restoreTitle;
19244
19339
  if (titleEnabled) {
19245
19340
  output.write("\x1B[22;0t");
19246
19341
  restoreWindowTitle = restoreTitle;
@@ -19256,14 +19351,30 @@ async function runTuiWorkspace(options) {
19256
19351
  }
19257
19352
  if (!titleEnabled) return;
19258
19353
  const phase = terminalStatus.state;
19354
+ const isWorking = phase !== "blocked" && phase !== "error" && (phase === "working" || backgroundWorking);
19355
+ if (!isWorking) {
19356
+ stopTitleAnimation();
19357
+ titleFrameIndex = 0;
19358
+ } else if (titleAnimTimer === null) {
19359
+ titleAnimTimer = setInterval(() => {
19360
+ titleFrameIndex = (titleFrameIndex + 1) % ACTIVITY_FRAMES.length;
19361
+ syncWindowTitle();
19362
+ }, TITLE_SPINNER_INTERVAL_MS);
19363
+ titleAnimTimer.unref?.();
19364
+ }
19259
19365
  const rawDialogLabel = state.dialogLabel?.trim();
19260
- const rawLabel = !rawDialogLabel || rawDialogLabel === "new" ? basename(state.cwd) || "Nolo" : rawDialogLabel;
19366
+ const rawLabel = !rawDialogLabel || rawDialogLabel === "new" ? basename2(state.cwd) || "Nolo" : rawDialogLabel;
19261
19367
  const label = stripAnsi(rawLabel).replace(/[\x00-\x1f\x7f-\x9f]+/g, " ");
19262
- const suffix = phase === "blocked" ? " \xB7 \u9700\u63A5\u7BA1 \u2014 Nolo" : phase === "error" ? " \xB7 \u5931\u8D25\u9700\u5904\u7406 \u2014 Nolo" : phase === "working" || backgroundWorking ? " \xB7 \u601D\u8003\u4E2D \u2014 Nolo" : label === "Nolo" ? "" : " \u2014 Nolo";
19368
+ const frame = ACTIVITY_FRAMES[titleFrameIndex % ACTIVITY_FRAMES.length];
19369
+ const suffix = phase === "blocked" ? " \xB7 \u9700\u63A5\u7BA1 \u2014 Nolo" : phase === "error" ? " \xB7 \u5931\u8D25\u9700\u5904\u7406 \u2014 Nolo" : isWorking ? ` \xB7 ${frame} \u601D\u8003\u4E2D \u2014 Nolo` : label === "Nolo" ? "" : " \u2014 Nolo";
19263
19370
  const currentTitle = takeDisplayWidth(label, 80 - displayWidth(suffix)).prefix + suffix;
19264
19371
  if (currentTitle === lastSentTitle) return;
19265
19372
  lastSentTitle = currentTitle;
19266
- output.write(buildWindowTitle(currentTitle));
19373
+ try {
19374
+ output.write(buildWindowTitle(currentTitle));
19375
+ } catch {
19376
+ stopTitleAnimation();
19377
+ }
19267
19378
  };
19268
19379
  const reportTerminalStatus = (report) => {
19269
19380
  const wasWaiting = terminalStatus.state === "blocked";
@@ -19460,7 +19571,8 @@ async function runTuiWorkspace(options) {
19460
19571
  renderHistoryUnderDialog,
19461
19572
  scheduleRender,
19462
19573
  flushPendingRender,
19463
- paintImmediate
19574
+ paintImmediate,
19575
+ close: closeRender
19464
19576
  } = createTuiRender({
19465
19577
  output,
19466
19578
  history,
@@ -19529,16 +19641,6 @@ async function runTuiWorkspace(options) {
19529
19641
  scheduleRender();
19530
19642
  });
19531
19643
  };
19532
- const refreshCiStatus = () => {
19533
- if (!shouldRefreshCiStatusOnStartup(effectiveEnv)) return;
19534
- void fetchCiStatus(void 0, void 0, void 0, effectiveEnv).then((jobs) => {
19535
- if (sessionEnded) return;
19536
- const ciStatusLine = summarizeLatest(jobs);
19537
- if (!ciStatusLine) return;
19538
- state = { ...state, ciStatusLine };
19539
- scheduleRender();
19540
- });
19541
- };
19542
19644
  let repaintingBanner = false;
19543
19645
  const repaintBanner = (frame = 0, maxFrames = 0, underDialog = false) => {
19544
19646
  if (repaintingBanner) return;
@@ -19694,6 +19796,7 @@ async function runTuiWorkspace(options) {
19694
19796
  let hostApprovalPrompt = null;
19695
19797
  let unregisterHostApprovalRenderer = null;
19696
19798
  let draftEpoch = 0;
19799
+ let clipboardReadsInFlight = 0;
19697
19800
  const bumpDraftEpoch = () => {
19698
19801
  draftEpoch += 1;
19699
19802
  };
@@ -19818,6 +19921,14 @@ async function runTuiWorkspace(options) {
19818
19921
  return true;
19819
19922
  };
19820
19923
  const readAndApplyClipboard = async (source) => {
19924
+ clipboardReadsInFlight += 1;
19925
+ try {
19926
+ return await applyClipboardPaste(source);
19927
+ } finally {
19928
+ clipboardReadsInFlight -= 1;
19929
+ }
19930
+ };
19931
+ const applyClipboardPaste = async (source) => {
19821
19932
  const snapshot = { epoch: draftEpoch, sessionEnded };
19822
19933
  const outcome = await resolveClipboardPaste({
19823
19934
  readImage: () => readImage({ env: options.env ?? process.env }),
@@ -20138,6 +20249,24 @@ ${lines}` : lines;
20138
20249
  )
20139
20250
  );
20140
20251
  };
20252
+ const DIRECT_IMAGE_COPY_RE = /^\/images\s+(?:copy\s+)?(\d+)$/;
20253
+ const copyConversationImagePathByIndex = async (targetIndex, emit) => {
20254
+ const target = collectConversationImageArtifacts(history.turns).find(
20255
+ (item) => item.artifactIndex === targetIndex
20256
+ );
20257
+ if (!target) {
20258
+ emit(themeText(`\xB7 \u672A\u627E\u5230\u56FE\u7247\u4EA7\u7269 #${targetIndex}\u3002`, "muted", resolveCliColorEnabled()));
20259
+ return;
20260
+ }
20261
+ const result = await copyImagePath(target.path, writeClipboard2);
20262
+ emit(
20263
+ themeText(
20264
+ `${result.ok ? "\xB7" : "!"} ${result.message}`,
20265
+ result.ok ? "muted" : "warning",
20266
+ resolveCliColorEnabled()
20267
+ )
20268
+ );
20269
+ };
20141
20270
  const manageDraftImages = async () => {
20142
20271
  while (true) {
20143
20272
  const images = state.attachedImages;
@@ -20198,9 +20327,10 @@ ${lines}` : lines;
20198
20327
  }
20199
20328
  };
20200
20329
  const runSubmittedLine = async (line, actionGateHandler, confirmDestructiveAction, directUserSubmission = false) => {
20201
- if (line.trim() === "/tools") {
20330
+ const toolsCommand = line.trim().match(/^\/tools(?:\s+(last))?$/i);
20331
+ if (toolsCommand) {
20202
20332
  emitCommandOutput(
20203
- history.toolDetails?.join("") || themeText(t("noToolDetails"), "muted", resolveCliColorEnabled())
20333
+ formatToolDetails(history, Boolean(toolsCommand[1])) || themeText(t("noToolDetails"), "muted", resolveCliColorEnabled())
20204
20334
  );
20205
20335
  return false;
20206
20336
  }
@@ -20244,17 +20374,9 @@ ${lines}` : lines;
20244
20374
  renderHistoryToOutput();
20245
20375
  return false;
20246
20376
  }
20247
- const directImageMatch = /^\/images\s+(?:copy\s+)?(\d+)$/.exec(line.trim());
20377
+ const directImageMatch = DIRECT_IMAGE_COPY_RE.exec(line.trim());
20248
20378
  if (directImageMatch) {
20249
- const targetIndex = Number(directImageMatch[1]);
20250
- const target = collectConversationImageArtifacts(history.turns).find(
20251
- (item) => item.artifactIndex === targetIndex
20252
- );
20253
- if (!target) {
20254
- emitCommandOutput(themeText(`\xB7 \u672A\u627E\u5230\u56FE\u7247\u4EA7\u7269 #${targetIndex}\u3002`, "muted", resolveCliColorEnabled()));
20255
- } else {
20256
- await copyImagePathWithFeedback(target.path);
20257
- }
20379
+ await copyConversationImagePathByIndex(Number(directImageMatch[1]), emitCommandOutput);
20258
20380
  return false;
20259
20381
  }
20260
20382
  if (line.trim() === "/images") {
@@ -20495,6 +20617,7 @@ ${lines}` : lines;
20495
20617
  hostApprovalPrompt = null;
20496
20618
  childShellApprovals.close();
20497
20619
  sessionEnded = true;
20620
+ closeRender();
20498
20621
  scrollAnimator.cancel();
20499
20622
  if (resizeTimer !== null) {
20500
20623
  clearTimeout(resizeTimer);
@@ -20568,7 +20691,7 @@ ${lines}` : lines;
20568
20691
  onApprove: createSnapshotGuardedApproval("local", () => state.permissionGrants, approveLocalConfirms),
20569
20692
  onApproved: async (approvedGate) => {
20570
20693
  if (approvedGate.kind !== "confirm") return null;
20571
- const { executeApprovedCredentialCreate } = await import("./hostCredentialCreate-23TX56G7.js");
20694
+ const { executeApprovedCredentialCreate } = await import("./hostCredentialCreate-C57T7YPE.js");
20572
20695
  const hostResult = await executeApprovedCredentialCreate({
20573
20696
  gate: approvedGate,
20574
20697
  approvalGateId: approvedGate.id,
@@ -20754,6 +20877,7 @@ ${err.message}` : ""}`)
20754
20877
  }
20755
20878
  };
20756
20879
  let autoScrollDirection = "up";
20880
+ let scrollbarDrag = null;
20757
20881
  const autoScrollStep = () => autoScrollStepForTicks(++autoScrollTicks);
20758
20882
  const startAutoScroll = (direction, mouseX) => {
20759
20883
  autoScrollDirection = direction;
@@ -20961,6 +21085,10 @@ ${err.message}` : ""}`)
20961
21085
  const beforeAgentKey = state.agentKey;
20962
21086
  const res = handleTuiInput2(submittedText, state, collectConversationTurns(history), {
20963
21087
  env: effectiveEnv,
21088
+ // Same env the busy turn runs with; `effectiveEnv` is the merged
21089
+ // startup snapshot and would over-count MCP/Instabox tool schemas when
21090
+ // options.env is an explicit `{}`.
21091
+ estimateEnv: options.env ?? process.env,
20964
21092
  // Identity only: `effectiveEnv` is the startup snapshot, `options.env`
20965
21093
  // is where a `/login` in this session writes its token.
20966
21094
  authEnv: resolveTuiIdentityEnv(effectiveEnv, options.env ?? process.env),
@@ -20977,10 +21105,12 @@ ${err.message}` : ""}`)
20977
21105
  }
20978
21106
  if (res.action?.type === "theme-refresh") {
20979
21107
  state = res.nextState;
21108
+ resetPtyxisCanvasCache();
20980
21109
  const detected2 = await detectTerminalBackground({
20981
21110
  stdin: input,
20982
21111
  stdout: output,
20983
- allowSystemFallback: true
21112
+ allowSystemFallback: true,
21113
+ trustHostCanvas: true
20984
21114
  });
20985
21115
  let refreshMsg = "";
20986
21116
  if (detected2 && applyDetectedBackground(detected2)) {
@@ -21078,8 +21208,9 @@ ${hint}` : hint;
21078
21208
  if (done) return;
21079
21209
  const approvalOwnsKeyboard = hostApprovalPrompt?.isActive() ?? false;
21080
21210
  if (approvalOwnsKeyboard && hostApprovalPrompt?.handleKey(sequence, {
21081
- draftEmpty: buffer.length === 0,
21082
- busy
21211
+ draftEmpty: buffer.length === 0 && state.attachedImages.length === 0 && !preparingImageSubmission && !pendingPasteImagePromise && clipboardReadsInFlight === 0,
21212
+ busy,
21213
+ canApproveDuringTurn: activeTurnAbort !== null && !activeTurnAbort.signal.aborted
21083
21214
  })) return;
21084
21215
  if (!approvalOwnsKeyboard && secretInputCoordinator.isActive()) {
21085
21216
  secretInputCoordinator.handleToken(sequence);
@@ -21170,16 +21301,44 @@ ${hint}` : hint;
21170
21301
  getTopReservedRows(output)
21171
21302
  )
21172
21303
  );
21173
- const { contentWidth, marginLeft } = resolveHistoryLayoutGeometry(columns);
21304
+ const { contentWidth, marginLeft, marginRight } = resolveHistoryLayoutGeometry(columns);
21174
21305
  const screenRow = mouseEvent.y - 1 - getTopReservedRows(output);
21175
21306
  const screenCol = mouseEvent.x - 1;
21176
21307
  const hitContentCol = screenCol - marginLeft;
21177
21308
  const contentCol = Math.max(0, Math.min(contentWidth, screenCol - marginLeft));
21178
21309
  if (mouseEvent.kind === "press" && mouseEvent.button === "left") {
21310
+ scrollbarDrag = null;
21179
21311
  if (screenRow < 0) return;
21180
21312
  stopAutoScroll();
21181
21313
  clearSelectionCopyFeedback();
21182
21314
  scrollAnimator.cancel();
21315
+ if (!mouseEvent.ctrl && screenRow < visibleHeight && isScrollbarColumnHit(screenCol, columns, marginRight)) {
21316
+ const { totalLines } = getAllTurnEntries(history, contentWidth);
21317
+ const geom = computeScrollbarGeometry(
21318
+ visibleHeight,
21319
+ totalLines,
21320
+ history.scrollTop
21321
+ );
21322
+ if (geom) {
21323
+ clearSelection();
21324
+ if (screenRow >= geom.thumbTop && screenRow < geom.thumbBottom) {
21325
+ scrollbarDrag = { grabOffset: screenRow - geom.thumbTop };
21326
+ } else {
21327
+ const grabOffset = Math.floor(geom.thumbSize / 2);
21328
+ scrollbarDrag = { grabOffset };
21329
+ const nextTop = scrollTopFromScrollbarDrag(
21330
+ screenRow,
21331
+ grabOffset,
21332
+ visibleHeight,
21333
+ totalLines
21334
+ );
21335
+ history.scrollTop = nextTop;
21336
+ history.followBottom = nextTop >= geom.maxScrollTop;
21337
+ }
21338
+ paintFrame(buffer);
21339
+ return;
21340
+ }
21341
+ }
21183
21342
  if (mouseEvent.ctrl && screenRow < visibleHeight && hitContentCol >= 0 && hitContentCol < contentWidth && openVisibleUrlAtScreen(
21184
21343
  history,
21185
21344
  contentWidth,
@@ -21217,6 +21376,27 @@ ${hint}` : hint;
21217
21376
  return;
21218
21377
  }
21219
21378
  if (mouseEvent.kind === "drag" && mouseEvent.button === "left") {
21379
+ if (scrollbarDrag) {
21380
+ const { totalLines } = getAllTurnEntries(history, contentWidth);
21381
+ const geom = computeScrollbarGeometry(
21382
+ visibleHeight,
21383
+ totalLines,
21384
+ history.scrollTop
21385
+ );
21386
+ if (geom) {
21387
+ const clampedRow2 = Math.max(0, Math.min(visibleHeight - 1, screenRow));
21388
+ const nextTop = scrollTopFromScrollbarDrag(
21389
+ clampedRow2,
21390
+ scrollbarDrag.grabOffset,
21391
+ visibleHeight,
21392
+ totalLines
21393
+ );
21394
+ history.scrollTop = nextTop;
21395
+ history.followBottom = nextTop >= geom.maxScrollTop;
21396
+ paintFrame(buffer);
21397
+ }
21398
+ return;
21399
+ }
21220
21400
  if (!selectionState.anchor) return;
21221
21401
  selectionState.dragging = true;
21222
21402
  lastDragMouseX = mouseEvent.x;
@@ -21244,6 +21424,28 @@ ${hint}` : hint;
21244
21424
  }
21245
21425
  if (mouseEvent.kind === "release") {
21246
21426
  stopAutoScroll();
21427
+ if (scrollbarDrag) {
21428
+ const { totalLines } = getAllTurnEntries(history, contentWidth);
21429
+ const geom = computeScrollbarGeometry(
21430
+ visibleHeight,
21431
+ totalLines,
21432
+ history.scrollTop
21433
+ );
21434
+ if (geom) {
21435
+ const clampedRow = Math.max(0, Math.min(visibleHeight - 1, screenRow));
21436
+ const nextTop = scrollTopFromScrollbarDrag(
21437
+ clampedRow,
21438
+ scrollbarDrag.grabOffset,
21439
+ visibleHeight,
21440
+ totalLines
21441
+ );
21442
+ history.scrollTop = nextTop;
21443
+ history.followBottom = nextTop >= geom.maxScrollTop;
21444
+ }
21445
+ scrollbarDrag = null;
21446
+ paintFrame(buffer);
21447
+ return;
21448
+ }
21247
21449
  if (selectionState.dragging && selectionState.anchor) {
21248
21450
  const clampedRow = Math.max(0, Math.min(visibleHeight - 1, screenRow));
21249
21451
  const releaseHit = hitTestHistory(
@@ -21389,7 +21591,8 @@ ${hint}` : hint;
21389
21591
  const busySlashCommand = trimmedText.split(/\s+/)[0]?.toLowerCase();
21390
21592
  if (busySlashCommand === "/tools") {
21391
21593
  recordWorkspaceInputHistory(expandedSubmitForHistory);
21392
- printStreamSafeNotice(history.toolDetails?.join("") || t("noToolDetails"));
21594
+ const last = trimmedText.split(/\s+/)[1]?.toLowerCase() === "last";
21595
+ printStreamSafeNotice(formatToolDetails(history, last) || t("noToolDetails"));
21393
21596
  bumpDraftEpoch();
21394
21597
  buffer = "";
21395
21598
  cursorPos = 0;
@@ -21442,6 +21645,28 @@ ${themeText(`! ${error instanceof Error ? error.message : String(error)}`, "dang
21442
21645
  await handleBusyLocalSlash(submittedText, busySlashCommand);
21443
21646
  return;
21444
21647
  }
21648
+ const busyDirectImage = DIRECT_IMAGE_COPY_RE.exec(trimmedText.trim());
21649
+ if (busyDirectImage) {
21650
+ const targetIndex = Number(busyDirectImage[1]);
21651
+ recordWorkspaceInputHistory(expandedSubmitForHistory);
21652
+ bumpDraftEpoch();
21653
+ buffer = "";
21654
+ cursorPos = 0;
21655
+ if (fixedInput.active) fixedInput.repaint(buffer, cursorPos);
21656
+ await copyConversationImagePathByIndex(targetIndex, (text) => printStreamSafeNotice(text, { dim: false }));
21657
+ return;
21658
+ }
21659
+ if (trimmedText.trim() === "/images") {
21660
+ printStreamSafeNotice(
21661
+ themeText(
21662
+ "! \u4EFB\u52A1\u4ECD\u5728\u6267\u884C\uFF1A`/images` \u83DC\u5355\u8981\u7B49\u672C\u8F6E\u7ED3\u675F\u540E\u518D\u7528\uFF1B\u73B0\u5728\u53EF\u7528 `/images <\u5E8F\u53F7>` \u590D\u5236\u8DEF\u5F84\u3002",
21663
+ "warning",
21664
+ resolveCliColorEnabled()
21665
+ ),
21666
+ { dim: false }
21667
+ );
21668
+ return;
21669
+ }
21445
21670
  const { actionGateHandler, confirmDestructiveAction } = buildInteractiveTurnHandlers();
21446
21671
  const binding = ensureChatQueueBinding(turnCtx, actionGateHandler, confirmDestructiveAction);
21447
21672
  const busyImages = detectSubmittedImagePaths(submittedText, state.cwd);
@@ -21619,12 +21844,25 @@ ${themeText(`! ${error instanceof Error ? error.message : String(error)}`, "dang
21619
21844
  {
21620
21845
  onOsc11Background: (bg) => {
21621
21846
  sawOsc11Reply = true;
21847
+ if (isPtyxisTerminal()) return;
21622
21848
  startOsc11AutoThemePoll();
21623
21849
  applyLiveTerminalBackground(bg);
21624
21850
  },
21625
21851
  onColorSchemeReport: (scheme) => {
21852
+ if (isPtyxisTerminal()) {
21853
+ resetPtyxisCanvasCache();
21854
+ void detectTerminalBackground({
21855
+ stdin: input,
21856
+ stdout: output,
21857
+ allowSystemFallback: true,
21858
+ trustHostCanvas: true
21859
+ }).then((next) => {
21860
+ if (next) applyLiveTerminalBackground(next);
21861
+ });
21862
+ return;
21863
+ }
21626
21864
  if (!sawOsc11Reply) {
21627
- applyLiveTerminalBackground({ brightness: scheme, hex: "" });
21865
+ applyLiveTerminalBackground({ brightness: scheme, hex: "", trustedCanvas: true });
21628
21866
  }
21629
21867
  if (!sessionEnded && !done && fixedInput.active && !fixedInput.isPaused()) {
21630
21868
  output.write(OSC11_QUERY);
@@ -21652,6 +21890,8 @@ ${themeText(`! ${error instanceof Error ? error.message : String(error)}`, "dang
21652
21890
  composerDecoderDrain = () => onData.destroy();
21653
21891
  hostApprovalPrompt = createInlineHostApprovalPrompt({
21654
21892
  dialogHost,
21893
+ output,
21894
+ colorEnabled: resolveCliColorEnabled(),
21655
21895
  write: (text) => {
21656
21896
  emitCommandOutput(text.replace(/\n$/, ""));
21657
21897
  },
@@ -21669,12 +21909,11 @@ ${themeText(`! ${error instanceof Error ? error.message : String(error)}`, "dang
21669
21909
  input.once("close", finish);
21670
21910
  if (history.turns.length) renderHistoryToOutput();
21671
21911
  fixedInput.repaint(buffer, cursorPos);
21672
- if (!sawOsc11Reply && isTerminalDevice(input)) requestTerminalBackgroundQuery();
21912
+ if (!sawOsc11Reply && isTerminalDevice(input) && !isPtyxisTerminal()) requestTerminalBackgroundQuery();
21673
21913
  refreshGitStatus();
21674
- refreshCiStatus();
21675
- await new Promise((resolve4) => {
21676
- resolveDone = resolve4;
21677
- if (done) resolve4();
21914
+ await new Promise((resolve5) => {
21915
+ resolveDone = resolve5;
21916
+ if (done) resolve5();
21678
21917
  });
21679
21918
  } finally {
21680
21919
  finish();
@@ -21740,6 +21979,7 @@ ${renderStatusLine(state)}
21740
21979
  }
21741
21980
  childShellApprovals.close();
21742
21981
  sessionEnded = true;
21982
+ closeRender();
21743
21983
  runRegistryPoller.dispose();
21744
21984
  idleHeapReleaser.cancel();
21745
21985
  runCompletionWatcher.dispose();
@@ -21748,6 +21988,7 @@ ${renderStatusLine(state)}
21748
21988
  rl.close();
21749
21989
  }
21750
21990
  } finally {
21991
+ cleanupTitle?.();
21751
21992
  accountSessionRuntime.dispose();
21752
21993
  }
21753
21994
  }
@@ -21792,7 +22033,6 @@ export {
21792
22033
  renderHistory,
21793
22034
  renderPinnedAgentNotice,
21794
22035
  resetHistoryFrameDiffCache,
21795
- shouldRefreshCiStatusOnStartup,
21796
22036
  splitRawInput,
21797
22037
  startTuiWorkspace,
21798
22038
  startTurn,