nolo-cli 0.213.0 → 0.219.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/README.md +3 -2
  2. package/{_executeModel-CUJLCFWR.js → _executeModel-WW57SJN4.js} +111 -82
  3. package/{accountResolver-4LKIHEKL.js → accountResolver-EK2S4PWF.js} +6 -6
  4. package/{action-DF5UYSJF.js → action-CK64LS6S.js} +12 -11
  5. package/{addContentAction-WERAONNY.js → addContentAction-EQXMFNPR.js} +18 -17
  6. package/{addDialogAgentAction-7VI7YRML.js → addDialogAgentAction-RSDZDASD.js} +21 -20
  7. package/{agentDeleteCommand-XJORXPGU.js → agentDeleteCommand-X2VWEKUA.js} +127 -118
  8. package/{agentEmailCommands-XTYYFR6Z.js → agentEmailCommands-6IE773VW.js} +132 -124
  9. package/{agentFavoriteCommands-EDK743YA.js → agentFavoriteCommands-2LKGKSUD.js} +7 -8
  10. package/{agentGrantCommands-RQWK2TEV.js → agentGrantCommands-QQV4N4JW.js} +5 -5
  11. package/{agentListCommands-OBLRBLHS.js → agentListCommands-5UNM7CGG.js} +155 -92
  12. package/{agentMachineCommands-5FMT3OT5.js → agentMachineCommands-EVWFKK6Q.js} +62 -54
  13. package/{agentProviderCommands-Q5O33MED.js → agentProviderCommands-ZCH37KAL.js} +5 -5
  14. package/{agentPullCommand-6EM3URVK.js → agentPullCommand-XN6ZPBUW.js} +7 -7
  15. package/agentRecordCommands-DX2WE6BH.js +176 -0
  16. package/agentRunCommand-KGOT2AFB.js +206 -0
  17. package/{agentRunControl-TAMHJQSR.js → agentRunControl-QDFW5P2T.js} +30 -15
  18. package/{agentRuntimeLocal-SOO2OPJG.js → agentRuntimeLocal-SD7U2EGY.js} +52 -45
  19. package/{agentSlice-CHR6KOZN.js → agentSlice-ACZGTZVW.js} +20 -19
  20. package/{appDeleteCommands-GUP6P5YE.js → appDeleteCommands-NE3NQQJL.js} +61 -53
  21. package/{appDeployCommands-MH2FX4O5.js → appDeployCommands-2BAHY522.js} +61 -53
  22. package/{appDeployStatusCommands-SUHN3HPJ.js → appDeployStatusCommands-JTW6LZNC.js} +61 -53
  23. package/{appGetCommands-YWDEX6Z4.js → appGetCommands-WKFEJO6A.js} +61 -53
  24. package/{appListCommands-ZQVMLPAY.js → appListCommands-HNAZZLFX.js} +61 -53
  25. package/{authCommand-PWX2ZNUP.js → authCommand-4FDPL7WG.js} +29 -28
  26. package/{authCommands-HV3EAU3V.js → authCommands-GAJ3NIXO.js} +14 -13
  27. package/{builtinSkillRegistry-2QETTQPM.js → builtinSkillRegistry-PXH7EGQB.js} +11 -13
  28. package/{chromeCommands-REEAH4SX.js → chromeCommands-G5UDKVSV.js} +3 -3
  29. package/{chromeOpsCommands-DIVM2K3T.js → chromeOpsCommands-YKX2QX3A.js} +20 -10
  30. package/chunk-2KTUDBG7.js +675 -0
  31. package/{chunk-TCZHTTUU.js → chunk-2OLYKYNY.js} +8 -8
  32. package/{chunk-PYRUW7XN.js → chunk-2VUZSVAS.js} +136 -54
  33. package/{chunk-YB3YZK56.js → chunk-2WZXXAQD.js} +1 -67
  34. package/chunk-2YGBI2XB.js +30 -0
  35. package/chunk-2ZKFCIJJ.js +13 -0
  36. package/{chunk-G2BQWAVT.js → chunk-3ESU44FG.js} +4 -4
  37. package/{chunk-HUBHAQK2.js → chunk-3N4ASIP6.js} +29 -29
  38. package/{chunk-4KB6WQUL.js → chunk-4A2JIXR2.js} +1 -1
  39. package/{chunk-MYOH447Z.js → chunk-4JVNURX4.js} +1 -1
  40. package/{chunk-H7PPIYWP.js → chunk-4NMHE7CX.js} +20 -20
  41. package/{chunk-YDH3FDFQ.js → chunk-5FUN7EG4.js} +1 -1
  42. package/chunk-5OZC7R7Y.js +97 -0
  43. package/chunk-5R63B62U.js +364 -0
  44. package/{chunk-INUFILG6.js → chunk-5RKUPJYL.js} +1 -1
  45. package/{chunk-ZNWI6OVT.js → chunk-652XYZGP.js} +80 -11
  46. package/{chunk-QHPRUL4O.js → chunk-65XXHYZ5.js} +4 -4
  47. package/{chunk-MOIJOHA5.js → chunk-6D7NVU66.js} +36 -25
  48. package/{chunk-CRHOO2ZR.js → chunk-6NKA6RKF.js} +2 -2
  49. package/{chunk-ZC3CMUKU.js → chunk-6OVNSQHN.js} +84 -2
  50. package/{chunk-H2TJUNCH.js → chunk-6RQFZCKH.js} +18 -18
  51. package/{chunk-LLRPJECG.js → chunk-7UH3DGV6.js} +17 -159
  52. package/{chunk-X7SDOJUM.js → chunk-7WPAI5JJ.js} +14 -14
  53. package/{chunk-P5L7CXOC.js → chunk-7Z6EW7AH.js} +3 -2
  54. package/{chunk-VO4WSAVP.js → chunk-AFHOCBSP.js} +3 -3
  55. package/{chunk-HPFCI4SK.js → chunk-AK5O76CC.js} +3 -3
  56. package/{chunk-Y63ZSOR6.js → chunk-AL3TYDIF.js} +1 -1
  57. package/{chunk-ALQ3657A.js → chunk-AMEOV5VZ.js} +32 -12
  58. package/chunk-AVHRSJUH.js +1621 -0
  59. package/{chunk-RLBNLZVC.js → chunk-BGGHA5DV.js} +1 -1
  60. package/{chunk-NBTY7YJF.js → chunk-BR3GT6MR.js} +1 -0
  61. package/{chunk-7RFNTILS.js → chunk-BUDVRYES.js} +2 -2
  62. package/{chunk-SVYO6AO7.js → chunk-BV3FLP2L.js} +41 -1
  63. package/{chunk-RZOV7OMV.js → chunk-C4VAR65S.js} +83 -141
  64. package/{chunk-COFEN36Z.js → chunk-C4WTX5TU.js} +2 -2
  65. package/{chunk-F6UUQOG6.js → chunk-CKT6QUE2.js} +4 -4
  66. package/{chunk-6VLJ6YA7.js → chunk-CXDPIPZ4.js} +9 -9
  67. package/{secretCommands-LXDWOLZ6.js → chunk-D726I5AZ.js} +191 -16
  68. package/{chunk-OQPKUBPB.js → chunk-DJSTBAOU.js} +19 -7
  69. package/chunk-DVQH4BTR.js +1137 -0
  70. package/{chunk-7OCO4TDT.js → chunk-EGXPAWLG.js} +1 -1
  71. package/chunk-EOWLBDY6.js +142 -0
  72. package/chunk-EUCFKKDM.js +247 -0
  73. package/chunk-EWQ3HGNZ.js +90 -0
  74. package/{chunk-7Y4YTDQF.js → chunk-F3TQURKK.js} +281 -159
  75. package/{chunk-YTF4WH7J.js → chunk-FIYSMXHY.js} +1 -1
  76. package/{chunk-75XIDFBW.js → chunk-FJ23FZXF.js} +72 -28
  77. package/{chunk-5MQRBSMW.js → chunk-FRSBYNWI.js} +111 -113
  78. package/{chunk-ZXOUUDCG.js → chunk-FVZW66K4.js} +3657 -233
  79. package/{chunk-YUA6OAH5.js → chunk-G2EJ7NL4.js} +2 -2
  80. package/{chunk-PCLE46CE.js → chunk-GBWGPTA7.js} +2 -1
  81. package/{chunk-R5O4QAWG.js → chunk-GGKNJ42M.js} +11 -77
  82. package/{chunk-TAKB25RM.js → chunk-GIABSSWQ.js} +4 -4
  83. package/{chunk-WRYQ35LQ.js → chunk-GNHMRBYZ.js} +859 -57
  84. package/{chunk-NJLL224W.js → chunk-GVGOEMNV.js} +2 -2
  85. package/{chunk-J2NHJ7WX.js → chunk-H7R3365N.js} +4 -4
  86. package/{chunk-7BT37FK3.js → chunk-HCJFGH6Y.js} +648 -131
  87. package/{chunk-3UKL3HPD.js → chunk-HOCHUZQ7.js} +8 -78
  88. package/{chunk-EHSZD5OI.js → chunk-HXER7YJF.js} +4 -4
  89. package/{chunk-CTPXME7U.js → chunk-IWH5SOU4.js} +29 -6
  90. package/{chunk-INN4LTAJ.js → chunk-IWQAOW2X.js} +2 -2
  91. package/{chunk-RPQXPZZF.js → chunk-J6T25AJ6.js} +908 -13
  92. package/{chunk-KIM6CLW5.js → chunk-JC5XLWZK.js} +42 -15
  93. package/chunk-JVRQ6YVK.js +99 -0
  94. package/{chunk-ZRSNONOB.js → chunk-JWXITTQB.js} +8 -3
  95. package/{chunk-NSAPDIN2.js → chunk-K5FNYHZC.js} +541 -31
  96. package/{chunk-TX5EYMGT.js → chunk-KAVGK4ES.js} +30 -254
  97. package/{chunk-H4UOTUOX.js → chunk-KEN3N2TN.js} +148 -18
  98. package/{chunk-LEC5ALIN.js → chunk-KEPOVMF4.js} +1 -1
  99. package/{chunk-Y6ORVLSS.js → chunk-KN3HEZIQ.js} +1 -1
  100. package/{chunk-UYD5HQ6T.js → chunk-KO63FPG3.js} +5429 -1752
  101. package/{chunk-IXNGOHV5.js → chunk-KOXKKHFE.js} +11 -152
  102. package/{chunk-4VJAC32I.js → chunk-L5I543VB.js} +3 -2
  103. package/{chunk-SM3NSZJV.js → chunk-LE6LGAJE.js} +20 -1
  104. package/chunk-LKA64WH4.js +227 -0
  105. package/{chunk-VL5KOY2C.js → chunk-MK2Q7ZJD.js} +67 -5
  106. package/{chunk-YJAFKXMU.js → chunk-MKQ2UTTX.js} +50 -48
  107. package/chunk-MOMR7NMG.js +226 -0
  108. package/{chunk-4T2WNOY7.js → chunk-N3J4VDGV.js} +33 -22
  109. package/{chunk-AZMYUSVF.js → chunk-N5Z2V73W.js} +1 -1
  110. package/{chunk-6DWMYIUY.js → chunk-N7HVLYOY.js} +14 -9
  111. package/{chunk-7QTZCMKL.js → chunk-O2CYENYJ.js} +1204 -1651
  112. package/{chunk-VNYYOX3V.js → chunk-OB6DVWPF.js} +141 -48
  113. package/{chunk-HRMJUN5J.js → chunk-OGHP3CTL.js} +1 -1
  114. package/{chunk-XJWWBO34.js → chunk-OJKUU3LP.js} +5 -7
  115. package/{chunk-G7MLNNEX.js → chunk-OOF7XDZF.js} +5 -5
  116. package/{chunk-QG4AOSON.js → chunk-OXKUPBAQ.js} +13 -32
  117. package/{chunk-6XIE5ZGI.js → chunk-PDCV7P5W.js} +1 -1
  118. package/{chunk-H5HF7TJA.js → chunk-PFJNLBRU.js} +2 -2
  119. package/{chunk-A7TFUNZO.js → chunk-PPJYZRSQ.js} +6 -2
  120. package/chunk-PVZY6P3S.js +271 -0
  121. package/{chunk-ZL5RAEEB.js → chunk-Q6HOUF4O.js} +1 -1
  122. package/{chunk-FUGMREBO.js → chunk-Q7WP5RPC.js} +5 -5
  123. package/chunk-QHEN7NZ7.js +46 -0
  124. package/{chunk-O2TZF4AI.js → chunk-QLFCTYRH.js} +3 -3
  125. package/{chunk-YGILMZ7N.js → chunk-QVBXJNZ2.js} +1 -1
  126. package/{chunk-KFLT5KAD.js → chunk-QWYFFHCJ.js} +20 -20
  127. package/{chunk-C6KNNXWU.js → chunk-RGQ4UUWZ.js} +25 -2
  128. package/{chunk-OWYYDMGJ.js → chunk-S2NTVGA2.js} +4 -2
  129. package/{chunk-BBJ22CLB.js → chunk-S7SB7L2I.js} +60 -30
  130. package/{chunk-W4S457LU.js → chunk-SASHAZ67.js} +41 -5
  131. package/{chunk-KC4XDTT3.js → chunk-SOF4OWDM.js} +6 -4
  132. package/{chunk-YWSEPJ7C.js → chunk-SRL56PI2.js} +3 -3
  133. package/{chunk-WMTBPBMP.js → chunk-SYQR7FQS.js} +52 -50
  134. package/{chunk-JY5NGFFH.js → chunk-SYTHYBMI.js} +5 -5
  135. package/{chunk-XHQC4PXX.js → chunk-T3O6BLYU.js} +426 -196
  136. package/chunk-TLE77UJ5.js +230 -0
  137. package/{chunk-T43B7LB2.js → chunk-TRWT3EE3.js} +1 -1
  138. package/{chunk-RSHTSUEG.js → chunk-TVFRV3UQ.js} +2060 -602
  139. package/{chunk-4VNS5WPM.js → chunk-U67V476Y.js} +1 -8
  140. package/{chunk-F7CI2ZC5.js → chunk-UAIHKQIA.js} +2 -1
  141. package/{chunk-LOEO7LRC.js → chunk-UJKTI5PG.js} +10 -7
  142. package/{chunk-UHJGXRJ4.js → chunk-UMRI2IRY.js} +3 -3
  143. package/{chunk-WPORQFYN.js → chunk-UVLYNWIE.js} +2 -2
  144. package/{chunk-NOKUNJON.js → chunk-UYOICCYG.js} +29 -19
  145. package/{chunk-GOO6G4PY.js → chunk-VALBGPM6.js} +106 -50
  146. package/{chunk-MDB67IWP.js → chunk-VHPAA6MT.js} +10 -10
  147. package/{chunk-4I7ERB7F.js → chunk-VREDDN25.js} +1 -1
  148. package/{chunk-WYDI6TGM.js → chunk-XFJ4ZPFC.js} +91 -132
  149. package/{chunk-TY3TIUJK.js → chunk-XI2BWJM5.js} +65 -0
  150. package/{chunk-V5Y3R6BT.js → chunk-XWGDCWXY.js} +213 -210
  151. package/{chunk-J5JTMQIA.js → chunk-YFLVRVYK.js} +1 -1
  152. package/{chunk-EYLGAEB4.js → chunk-YGMBIXCF.js} +132 -0
  153. package/chunk-YL3EFYL3.js +199 -0
  154. package/{chunk-MMA3LZ3W.js → chunk-YNIYE47Z.js} +1 -1
  155. package/chunk-YZMNK53S.js +68 -0
  156. package/{chunk-FY7F4Q6X.js → chunk-Z4PCXPUE.js} +2 -2
  157. package/{cliAgentConfigHelpers-WJBZQTLW.js → cliAgentConfigHelpers-PO3MVDME.js} +15 -16
  158. package/{cliAuthorityBrokerClient-PM3U6Q6J.js → cliAuthorityBrokerClient-XHH7MH2P.js} +1 -1
  159. package/{cliAuthorityStoreDriver-TKLXNNTG.js → cliAuthorityStoreDriver-6FE3BJNB.js} +1 -1
  160. package/{cliEnvHelpers-BVYTMUPJ.js → cliEnvHelpers-VPSJ4XWC.js} +3 -3
  161. package/{cliExecutor-BWBF2MTI.js → cliExecutor-4MAX3PZL.js} +2 -2
  162. package/cliLocalAgentRecordReader-Z7CH4K4R.js +90 -0
  163. package/{commandRegistry-W63CYRZJ.js → commandRegistry-SDSYBKMC.js} +105 -97
  164. package/{contentThunks-U7PL5MQD.js → contentThunks-G3TRPEAU.js} +47 -43
  165. package/{cooldownCommands-TIGUHXTD.js → cooldownCommands-X7P5M2V5.js} +5 -4
  166. package/{createAgentAutomationAction-OLBQDD6R.js → createAgentAutomationAction-KHA4MXUJ.js} +51 -49
  167. package/{createDialogAction-SVH6B3SB.js → createDialogAction-KWSBNAPJ.js} +46 -48
  168. package/{createPageAction-F4DIWZ2Z.js → createPageAction-HXKJ7OFG.js} +50 -48
  169. package/{cursorProvider-YGGNMVWX.js → cursorProvider-2RACMEMF.js} +1 -1
  170. package/{db-HUCI5R4G.js → db-CS4ZJQKV.js} +1 -1
  171. package/{dbSlice-BVH2YZPQ.js → dbSlice-ZJPDIFER.js} +17 -16
  172. package/{deleteFile-5YOEKV4U.js → deleteFile-Q3YDB4ML.js} +9 -9
  173. package/{desktopFolderProjects-SFY5EZS3.js → desktopFolderProjects-4POAMVJN.js} +2 -2
  174. package/{dialogCommands-KHIEPY3M.js → dialogCommands-6KQEBHSG.js} +64 -57
  175. package/dialogNotifyCommand-WIZFFEY3.js +36 -0
  176. package/{dialogSlice-ZCTDV2PZ.js → dialogSlice-HXPKFGRL.js} +42 -40
  177. package/{dialogUsageCommand-7KCPYGHG.js → dialogUsageCommand-HTVPR2CX.js} +11 -10
  178. package/{docCreateCommands-DPMZI7G5.js → docCreateCommands-XZOLWBRC.js} +61 -55
  179. package/{docDeleteCommands-IRQQLUBT.js → docDeleteCommands-ZSO4LGWE.js} +63 -57
  180. package/{docReadCommands-LK37XH6L.js → docReadCommands-TTMXCDER.js} +61 -55
  181. package/{docStore-V2KECILA.js → docStore-A2B3GH33.js} +21 -20
  182. package/{docUpdateCommands-O6T3HJHH.js → docUpdateCommands-PRG6WOXL.js} +64 -58
  183. package/{fetchMessages-NR4KNQLO.js → fetchMessages-TQEUZD7H.js} +8 -7
  184. package/{getPricing-2MNMXEVG.js → getPricing-YH3VMSVU.js} +6 -6
  185. package/{handleSendMessageAction-2PE25WM3.js → handleSendMessageAction-NWYG3Q72.js} +194 -302
  186. package/{hostCredentialCreate-S233UMAP.js → hostCredentialCreate-WS6D3EHT.js} +123 -114
  187. package/index.js +29 -29
  188. package/{keys-BEGDOTRL.js → keys-RWF7UCB4.js} +5 -4
  189. package/legacyMigration-TF4SYJCZ.js +19 -0
  190. package/{lib-5KKIBFIT.js → lib-OT5OTXRU.js} +7087 -6664
  191. package/{localDialogRead-7NNDVVF7.js → localDialogRead-SVTPA5GY.js} +3 -3
  192. package/{localFirstLog-DHNOY2NA.js → localFirstLog-OIETGK66.js} +1 -1
  193. package/localRecall-2J6QPOK2.js +15 -0
  194. package/{localRuntimeAdapter-KY6WXNBR.js → localRuntimeAdapter-TFYOA6YE.js} +119 -110
  195. package/{localRuntimeAuthority-OYH4AE4G.js → localRuntimeAuthority-IBJAT62G.js} +1 -1
  196. package/{localRuntimeDb-VBIMCWUC.js → localRuntimeDb-N7KHDXS2.js} +2 -2
  197. package/{machineCommands-Q6HA3IXF.js → machineCommands-WFWV25IR.js} +128 -119
  198. package/{machineInfo-UKPTZO5Y.js → machineInfo-LWHTEBHJ.js} +1 -1
  199. package/machineWsRunDispatch-ZGXC3F2R.js +191 -0
  200. package/{memberThunks-7EDJADWU.js → memberThunks-JRYNONYV.js} +29 -28
  201. package/{memoryCommands-ASCE5STX.js → memoryCommands-5WC3T66U.js} +4 -4
  202. package/models-CXINDUJA.js +9 -0
  203. package/{oauthTokenStore-OEERZFUC.js → oauthTokenStore-RUYNYALS.js} +1 -1
  204. package/{offlineMarxistsAgentCommand-2QTHJCHV.js → offlineMarxistsAgentCommand-4IC3Y4C6.js} +4 -4
  205. package/overlay-THLKYIWY.js +11 -0
  206. package/package.json +2 -2
  207. package/{pdf-U6KSUEZZ.js → pdf-KE3QI2V7.js} +1 -1
  208. package/{processSpawn-ZU5QFM43.js → processSpawn-6GEO77KV.js} +1 -1
  209. package/{profileConfig-KN3N2BLF.js → profileConfig-KOWK4HOG.js} +1 -1
  210. package/{projectArchive-DRTDIMEV.js → projectArchive-ULJDLUA6.js} +52 -50
  211. package/{providerPresetApply-YXGV6NXB.js → providerPresetApply-SHT2SUVB.js} +19 -12
  212. package/{providerRegistry-S6UL6UNA.js → providerRegistry-TA7EGCVZ.js} +10 -10
  213. package/{read-4V2RMG7N.js → read-Q7GOHGNP.js} +10 -10
  214. package/{readDocTool-BH6ATGQO.js → readDocTool-Z5OQ6422.js} +2 -2
  215. package/{readlineWorkspace-2W4WRCOU.js → readlineWorkspace-LTCV2BFW.js} +7982 -6274
  216. package/{removeDialogAgentAction-LYAZGNKW.js → removeDialogAgentAction-U3F2MNAY.js} +23 -22
  217. package/{runAgentClientLoop-J2VQBS2Z.js → runAgentClientLoop-BVIEQUB3.js} +81 -79
  218. package/{runtimeDoctorCommands-QAI3MBKQ.js → runtimeDoctorCommands-I47JN4HS.js} +12 -12
  219. package/{runtimeModeArgs-2Y7BALTO.js → runtimeModeArgs-X7DL7PUN.js} +1 -1
  220. package/secretCommands-LJXOOYA7.js +24 -0
  221. package/{setDialogExtraReferencesAction-OCRPGPYH.js → setDialogExtraReferencesAction-G3WSJ7EM.js} +22 -21
  222. package/{setPrimaryDialogAgentAction-HFJDQIBU.js → setPrimaryDialogAgentAction-6FHAHZBB.js} +23 -22
  223. package/{settingThunks-RAMHMTGM.js → settingThunks-AXTBX3Q5.js} +97 -88
  224. package/{skillDiscovery-XKHROSH2.js → skillDiscovery-B5V23AXP.js} +4 -4
  225. package/{skillSummaryMarker-42HKSXYY.js → skillSummaryMarker-62UW7HI7.js} +1 -1
  226. package/{slateToRenderMarkdown-Y5IYN73U.js → slateToRenderMarkdown-R3X74MCX.js} +1 -1
  227. package/{slateUtils-NGV2NMKM.js → slateUtils-ESQAJ6RN.js} +1 -1
  228. package/{spaceCommands-KVJZVKVO.js → spaceCommands-IB6FKWIC.js} +61 -53
  229. package/store-JRVN62NM.js +46 -0
  230. package/{streamAgentChatTurn-GHBMJJ6S.js → streamAgentChatTurn-DNYFHBJM.js} +875 -618
  231. package/{switchDialogAgentAction-EBRMW3RA.js → switchDialogAgentAction-UOFIAGPL.js} +21 -20
  232. package/{tableCommands-MP6VFSVT.js → tableCommands-HITDSLHS.js} +10 -10
  233. package/tombstones-FQQMEDOW.js +32 -0
  234. package/{toolApiClient-HGNO53TC.js → toolApiClient-OGQEBQVX.js} +4 -4
  235. package/{tools-EWKCPKMS.js → tools-JVOJ5HC4.js} +75 -74
  236. package/tuiSummaryLlmCaller-7LWYTHLM.js +44 -0
  237. package/{updateCommands-ZQYU6SCI.js → updateCommands-RJVCRSBP.js} +10 -8
  238. package/{updateDialogTitleAction-5GGMBTDF.js → updateDialogTitleAction-Q57BOSXG.js} +48 -46
  239. package/{usageCommand-F4IPVMIZ.js → usageCommand-RVKHEPLU.js} +11 -10
  240. package/{usageRebuildCommand-HAW2AD5N.js → usageRebuildCommand-GRAFOZF2.js} +12 -11
  241. package/userDataMerge-HT2ZVHBJ.js +13 -0
  242. package/{windowsSelfUpdate-257DV2T6.js → windowsSelfUpdate-KERHIAB4.js} +3 -3
  243. package/{workloadLifecycle-4C42SVBD.js → workloadLifecycle-O2I3NZ2Q.js} +6 -6
  244. package/agentRecordCommands-ZQ7SVYGG.js +0 -167
  245. package/agentRunCommand-WS7IGO2W.js +0 -196
  246. package/chunk-3CGG2PAL.js +0 -594
  247. package/chunk-5XBUWM6I.js +0 -89
  248. package/chunk-CJEIOP3E.js +0 -0
  249. package/chunk-EHGEOAHI.js +0 -636
  250. package/chunk-FW6YHHLI.js +0 -842
  251. package/chunk-GPVRUGGY.js +0 -115
  252. package/chunk-HSVBJRF4.js +0 -339
  253. package/chunk-WJZOQR2J.js +0 -151
  254. package/chunk-ZCWRMUWT.js +0 -89
  255. package/dist-M676ULYG.js +0 -7314
  256. package/machineWsRunDispatch-WWJQ6WR3.js +0 -182
  257. package/models-PJBE6JDV.js +0 -9
  258. package/tuiSummaryLlmCaller-ALQYUUWB.js +0 -189
  259. package/{chunk-WACI5I6V.js → chunk-2THCNKE4.js} +3 -3
  260. package/{chunk-2QHFH3DR.js → chunk-47ITIXO7.js} +6 -6
  261. package/{chunk-OQHIVPG4.js → chunk-SNBZZPYH.js} +3 -3
  262. package/{chunk-AETZ7AD6.js → chunk-W6RFEDN4.js} +3 -3
@@ -1,21 +1,71 @@
1
- import {
2
- findPotentialSecrets
3
- } from "./chunk-6QDYSCPW.js";
4
1
  import {
5
2
  parsePositiveFiniteNumberOrFallback
6
3
  } from "./chunk-Y5GCAMGP.js";
7
4
  import {
5
+ getReadableCliDb
6
+ } from "./chunk-YFLVRVYK.js";
7
+ import {
8
+ INSTABOX_RUN_CONFIG_ENV,
9
+ attachLocalCommandObservations,
8
10
  buildLocalRunEnv,
11
+ captureLocalRunBase,
12
+ collectHostTaskPlannedWorkspace,
13
+ collectHostTaskWorkspace,
14
+ createCliLocalRuntimeAdapter,
15
+ createHostAuthorExecution,
16
+ detectCurrentMachineId,
17
+ formatLocalRunSummary,
18
+ getOrCreateSharedStore,
19
+ hashInstaboxDeliveryManifest,
20
+ hostTaskEventsRoot,
21
+ inspectLocalRunWorkspace,
22
+ isCliProviderAgentConfig,
23
+ isDockerRuntimeKey,
9
24
  isFullstackCodingAgentRef,
25
+ isInstaboxBillingPolicy,
26
+ isLiveAgentRunObservation,
27
+ isMachineBoundLocalhostCustomProvider,
28
+ isSubtaskRun,
29
+ matchesHostReviewDispatch,
30
+ observeLocalCommandResult,
10
31
  parseAgentRunArgs,
32
+ parseAgentRunEvent,
11
33
  readFlagValue,
34
+ readHostTask,
35
+ readHostTaskAcceptancePlan,
36
+ redactSecrets,
37
+ resolveAuthToken as resolveAuthToken2,
38
+ resolveBoundMachineId,
39
+ resolveFileWriteGateEnabled,
12
40
  resolveRawAgentInput,
13
41
  resolveServerUrl,
42
+ safeAskText,
43
+ settleHostReviewsForScope,
44
+ shouldPrintLocalRunSummary,
45
+ unknownLocalRunAcceptance,
46
+ unknownTaskCompletion,
47
+ validateInstaboxWorkspaceSelection,
48
+ withHostReviewDispatch,
49
+ withholdIfSecretLike,
50
+ wrapLocalCommandWorkspaceObservation,
14
51
  writeUsage
15
- } from "./chunk-HSVBJRF4.js";
52
+ } from "./chunk-KO63FPG3.js";
16
53
  import {
17
- getReadableCliDb
18
- } from "./chunk-J5JTMQIA.js";
54
+ clearCredentialAvailability,
55
+ readEffectiveCredentialEntry
56
+ } from "./chunk-FIYSMXHY.js";
57
+ import {
58
+ readDbRecord,
59
+ resolveAgentRecordFromHybridStore
60
+ } from "./chunk-6D7NVU66.js";
61
+ import {
62
+ boxGlyphs,
63
+ displayWidth,
64
+ resolveBoxCharset,
65
+ stripAnsi,
66
+ tokenizeAnsiLine,
67
+ visibleWidth
68
+ } from "./chunk-J6T25AJ6.js";
19
69
  import {
20
70
  _appendEntityBatch,
21
71
  _appendEvidenceBatch,
@@ -29,58 +79,43 @@ import {
29
79
  listMemoryStatesForEntityVNext,
30
80
  loadMemoryVNextCatalog,
31
81
  putMemoryEvidenceVNext
32
- } from "./chunk-TY3TIUJK.js";
82
+ } from "./chunk-XI2BWJM5.js";
33
83
  import {
34
- resolveMachineId
35
- } from "./chunk-S73EPYNC.js";
36
- import {
37
- INSTABOX_RUN_CONFIG_ENV,
38
- createCliLocalRuntimeAdapter,
39
- detectCurrentMachineId,
40
- hashInstaboxDeliveryManifest,
41
- isCliProviderAgentConfig,
42
- isDockerRuntimeKey,
43
- isInstaboxBillingPolicy,
44
- isLiveAgentRunObservation,
45
- isMachineBoundLocalhostCustomProvider,
46
- isSubtaskRun,
47
- parseAgentRunEvent,
48
- resolveAuthToken as resolveAuthToken2,
49
- resolveBoundMachineId,
50
- resolveFileWriteGateEnabled,
51
- validateInstaboxWorkspaceSelection
52
- } from "./chunk-UYD5HQ6T.js";
84
+ rankMemoryCandidates,
85
+ recallMemoryVNextLocal
86
+ } from "./chunk-YL3EFYL3.js";
53
87
  import {
54
- clearCredentialAvailability,
55
- readEffectiveCredentialEntry
56
- } from "./chunk-YTF4WH7J.js";
88
+ DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET,
89
+ EXPLICIT_REMEMBER_PREFIX_REGEX,
90
+ buildMemoryOverlay
91
+ } from "./chunk-EUCFKKDM.js";
57
92
  import {
58
- readDbRecord,
59
- resolveAgentRecordFromHybridStore
60
- } from "./chunk-MOIJOHA5.js";
93
+ buildLegacyMemoryEvidence,
94
+ resolveLegacyMemoryPrincipal
95
+ } from "./chunk-QHEN7NZ7.js";
61
96
  import {
62
97
  isBuiltinNoloAgentRef,
63
98
  resolveLocalUserId
64
- } from "./chunk-G7MLNNEX.js";
65
- import {
66
- isLocalCliAgentKey
67
- } from "./chunk-NBTY7YJF.js";
99
+ } from "./chunk-OOF7XDZF.js";
68
100
  import {
69
101
  CliProviderQuotaError
70
- } from "./chunk-VL5KOY2C.js";
102
+ } from "./chunk-MK2Q7ZJD.js";
103
+ import {
104
+ resolveMachineId
105
+ } from "./chunk-S73EPYNC.js";
106
+ import {
107
+ extractGoogleValidationLink
108
+ } from "./chunk-BMQ2MJUK.js";
71
109
  import {
72
110
  resolveCliLocalRuntimeKeyCapability
73
- } from "./chunk-XHQC4PXX.js";
111
+ } from "./chunk-T3O6BLYU.js";
74
112
  import {
75
113
  isTransientFetchError
76
114
  } from "./chunk-KFHREHUQ.js";
77
- import {
78
- extractGoogleValidationLink
79
- } from "./chunk-BMQ2MJUK.js";
80
115
  import {
81
116
  parseUiCard,
82
117
  uiCardFallback
83
- } from "./chunk-HUBHAQK2.js";
118
+ } from "./chunk-3N4ASIP6.js";
84
119
  import {
85
120
  isGatewayHttpStatus
86
121
  } from "./chunk-NF64D32W.js";
@@ -88,16 +123,19 @@ import {
88
123
  buildMemorySubjectsForAgent,
89
124
  chooseMemoryOwners,
90
125
  loadMemoryCandidatesFromDb,
126
+ loadOwnerItemsFromDb,
91
127
  resolveAgentMemoryPolicy
92
- } from "./chunk-LLRPJECG.js";
128
+ } from "./chunk-7UH3DGV6.js";
93
129
  import {
94
130
  API_REPORTED_COST_MULTIPLIER,
95
131
  estimateMessagesTokens,
132
+ isAgentRunStartFailureStatus,
133
+ isAgentRunStatusNormal,
96
134
  parseUiAskChoiceContent,
97
135
  resolveAgentContextWindow,
98
136
  resolveOccupancy,
99
137
  resolveOccupancyWindow
100
- } from "./chunk-ZXOUUDCG.js";
138
+ } from "./chunk-FVZW66K4.js";
101
139
  import {
102
140
  isCliAuthorityBrokerProtocolError,
103
141
  isCliAuthorityBrokerTimeoutError,
@@ -105,52 +143,43 @@ import {
105
143
  } from "./chunk-5ZMIIR23.js";
106
144
  import {
107
145
  getDefaultCliLocalRuntimeDb
108
- } from "./chunk-AZMYUSVF.js";
109
- import {
110
- buildSkillDiscoveryContextLayer
111
- } from "./chunk-F6UUQOG6.js";
146
+ } from "./chunk-N5Z2V73W.js";
112
147
  import {
113
- parseExternalSkillMarkdown,
114
- parseSkillDocProtocol
115
- } from "./chunk-AETZ7AD6.js";
148
+ isLocalCliAgentKey
149
+ } from "./chunk-BR3GT6MR.js";
116
150
  import {
117
151
  LOCAL_AGENT_CONFIG_MISSING_CODE,
118
152
  LOCAL_TURN_ABORTED_CODE,
153
+ evaluateTaskExecutionContract,
154
+ markCliUserBatchPhase,
119
155
  readActionGate
120
- } from "./chunk-RSHTSUEG.js";
156
+ } from "./chunk-TVFRV3UQ.js";
121
157
  import {
122
158
  resolveAgentRuntimeConfigFromRecord
123
- } from "./chunk-W4S457LU.js";
159
+ } from "./chunk-SASHAZ67.js";
124
160
  import {
125
161
  createThinkParserState,
126
162
  flushThinkParser,
127
163
  processThinkChunk
128
164
  } from "./chunk-56GBUMO5.js";
129
165
  import {
130
- resolveSubtaskBudgetLimits
131
- } from "./chunk-RZOV7OMV.js";
132
- import {
133
- QUOTA_ERROR_PATTERNS,
134
166
  classifyFailureSubclass,
135
167
  isCapacitySaturatedRateLimit,
136
- isQuotaExhaustedError,
137
168
  isQuotaExhaustedText,
138
169
  resolveAvailabilityAction,
139
170
  resolveCredentialKeyWithFallback
140
- } from "./chunk-3UKL3HPD.js";
171
+ } from "./chunk-HOCHUZQ7.js";
141
172
  import {
142
173
  ATTACHMENT_PART_TYPE,
143
174
  ATTACHMENT_PART_VERSION,
144
175
  describeAttachmentForModel,
145
176
  normalizeAttachmentPart
146
- } from "./chunk-WJZOQR2J.js";
177
+ } from "./chunk-XWGDCWXY.js";
147
178
  import {
179
+ findCodexOAuthPinnedContextWindow,
148
180
  normalizeUsage,
149
181
  readCacheReadInputTokensOrNull
150
- } from "./chunk-V5Y3R6BT.js";
151
- import {
152
- findCodexOAuthPinnedContextWindow
153
- } from "./chunk-7BT37FK3.js";
182
+ } from "./chunk-HCJFGH6Y.js";
154
183
  import {
155
184
  isOAuthApiKeyRef
156
185
  } from "./chunk-UKZX3NHN.js";
@@ -160,37 +189,65 @@ import {
160
189
  import {
161
190
  normalizeRuntimeToolPolicyOverride,
162
191
  resolveEffectiveRuntimeToolPolicy
163
- } from "./chunk-2QHFH3DR.js";
192
+ } from "./chunk-47ITIXO7.js";
164
193
  import {
165
194
  compactWhitespace
166
195
  } from "./chunk-DWLEOOGR.js";
167
196
  import {
168
- buildAgentsMdLayer,
169
- buildAgentsMdLayerHeader,
170
- buildMemoryOverlayLayer,
171
- buildMemoryUseGuidanceLayer,
172
- partitionScopedBlocks,
173
- renderTurnContextBlocksWithScope
174
- } from "./chunk-ZRSNONOB.js";
197
+ isAntigravityOAuthAgent
198
+ } from "./chunk-JC5XLWZK.js";
199
+ import {
200
+ parseExternalSkillMarkdown,
201
+ parseSkillDocProtocol
202
+ } from "./chunk-W6RFEDN4.js";
175
203
  import {
176
204
  BUILTIN_NOLO_AGENT_KEY,
177
205
  BUILTIN_NOLO_AGENT_NAME,
178
206
  builtinAgentCatalogEntryById,
179
207
  parseBuiltinPlatformAgentId
180
- } from "./chunk-LOEO7LRC.js";
208
+ } from "./chunk-UJKTI5PG.js";
181
209
  import {
182
210
  parsePublicAgentId
183
211
  } from "./chunk-M2EJHDJP.js";
184
212
  import {
185
- isAntigravityOAuthAgent
186
- } from "./chunk-KIM6CLW5.js";
213
+ createMemoryKey
214
+ } from "./chunk-SYTHYBMI.js";
215
+ import {
216
+ ulid
217
+ } from "./chunk-OJKUU3LP.js";
218
+ import {
219
+ buildSkillDiscoveryContextLayer
220
+ } from "./chunk-CKT6QUE2.js";
221
+ import {
222
+ buildAgentsMdLayer,
223
+ buildAgentsMdLayerHeader,
224
+ buildMemoryOverlayLayer,
225
+ buildMemoryUseGuidanceLayer,
226
+ partitionScopedBlocks,
227
+ renderTurnContextBlocksWithScope
228
+ } from "./chunk-JWXITTQB.js";
187
229
  import {
230
+ exitCliFromWatchdog,
231
+ getLogger,
232
+ normalizeError
233
+ } from "./chunk-YGMBIXCF.js";
234
+ import {
235
+ agentRunCardLabels,
236
+ getCliLocale,
237
+ t,
238
+ toolLabel,
239
+ toolLabelVariants
240
+ } from "./chunk-OB6DVWPF.js";
241
+ import {
242
+ awaitLocalWriterChild,
188
243
  createRunActivityTracker,
189
244
  createShellApprovalChild,
190
245
  getRunResultHeaderMeta,
246
+ isHistoryIntegrityFailure,
191
247
  popSingleQueueMessage,
192
248
  readRunRecord,
193
249
  recordRunResultHeaderMeta,
250
+ registerLocalForegroundWriter,
194
251
  reportRunProcessIdentity,
195
252
  resolveResultServerMeta,
196
253
  resolveRunQueuePath,
@@ -198,7 +255,7 @@ import {
198
255
  serverOriginForDialog,
199
256
  settleRunTerminalAuthoritatively,
200
257
  spawnLocalBackgroundRun
201
- } from "./chunk-NSAPDIN2.js";
258
+ } from "./chunk-K5FNYHZC.js";
202
259
  import {
203
260
  formatAgentListCard,
204
261
  formatFinishedRunCard,
@@ -209,55 +266,41 @@ import {
209
266
  formatStopRunCard,
210
267
  getAgentRunStatusIcon,
211
268
  isAgentRunTerminalStatus
212
- } from "./chunk-ALQ3657A.js";
269
+ } from "./chunk-AMEOV5VZ.js";
213
270
  import {
214
- resolveClientVersion
215
- } from "./chunk-TCZHTTUU.js";
271
+ QUOTA_ERROR_PATTERNS,
272
+ isQuotaExhaustedError
273
+ } from "./chunk-EWQ3HGNZ.js";
216
274
  import {
217
- findModelConfig
218
- } from "./chunk-SM3NSZJV.js";
275
+ resolveClientVersion
276
+ } from "./chunk-2OLYKYNY.js";
219
277
  import {
220
278
  toErrorMessage
221
279
  } from "./chunk-HNMXYYJR.js";
280
+ import {
281
+ asTrimmedString
282
+ } from "./chunk-3EUW3WEO.js";
283
+ import {
284
+ findModelConfig
285
+ } from "./chunk-LE6LGAJE.js";
222
286
  import {
223
287
  CLIENT_VERSION_TOO_OLD_CODE,
224
288
  NOLO_CLIENT_VERSION_HEADER,
225
289
  buildClientVersionUpgradeMessage
226
- } from "./chunk-GOO6G4PY.js";
290
+ } from "./chunk-VALBGPM6.js";
227
291
  import {
228
292
  asTrimmedLowercaseString
229
293
  } from "./chunk-QSJ3HFEF.js";
230
- import {
231
- getLogger,
232
- normalizeError
233
- } from "./chunk-EYLGAEB4.js";
234
294
  import {
235
295
  resolveAuthToken
236
- } from "./chunk-WACI5I6V.js";
237
- import {
238
- readPipeText,
239
- spawnProcess
240
- } from "./chunk-4O22PGNQ.js";
241
- import {
242
- agentRunCardLabels,
243
- getCliLocale,
244
- t,
245
- toolLabel,
246
- toolLabelVariants
247
- } from "./chunk-VNYYOX3V.js";
248
- import {
249
- createMemoryKey
250
- } from "./chunk-JY5NGFFH.js";
251
- import {
252
- ulid
253
- } from "./chunk-XJWWBO34.js";
254
- import {
255
- asTrimmedString
256
- } from "./chunk-3EUW3WEO.js";
296
+ } from "./chunk-2THCNKE4.js";
257
297
  import {
258
298
  asOptionalTrimmedString
259
299
  } from "./chunk-G3SUCT4W.js";
260
300
 
301
+ // packages/cli/agentRunCommand.ts
302
+ import { createHash } from "node:crypto";
303
+
261
304
  // packages/cli/client/instaboxRunConfigWrite.ts
262
305
  import { randomUUID } from "node:crypto";
263
306
  import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -400,6 +443,151 @@ function writeInstaboxRunConfig(options) {
400
443
  return { configPath: targetPath, config };
401
444
  }
402
445
 
446
+ // packages/cli/client/contextRefusal.ts
447
+ function contextRefusalDiagnostics(error) {
448
+ return error && typeof error === "object" ? error.diagnostics : void 0;
449
+ }
450
+ var tokens = (value) => value >= 1e3 ? `${Math.round(value / 100) / 10}k` : String(value);
451
+ function describeContextRefusal(refusal) {
452
+ const budgetDetail = refusal && Number.isFinite(refusal.historyTokens) && refusal.historyTokens >= 0 && Number.isFinite(refusal.budget) && refusal.budget > 0 ? t("contextRefusalBudgetDetail", tokens(refusal.historyTokens), tokens(refusal.budget)) : "";
453
+ switch (refusal?.reason) {
454
+ case "summary-provider-busy":
455
+ return t("contextRefusalSummaryBusy", budgetDetail);
456
+ case "summary-failed":
457
+ return t("contextRefusalSummaryFailed", budgetDetail);
458
+ case "no-compactable-content":
459
+ return t("contextRefusalNoCompactableContent");
460
+ case "single-message-too-large":
461
+ if (refusal.largestMessageTokens >= 0 && Number.isFinite(refusal.largestMessageTokens)) {
462
+ return t("contextRefusalSingleMessageTooLarge", tokens(refusal.largestMessageTokens), tokens(refusal.budget));
463
+ }
464
+ }
465
+ return t("contextPreflightBlockedHint");
466
+ }
467
+
468
+ // packages/cli/client/cliBatchIdentity.ts
469
+ function cliBatchPhaseFailure(args) {
470
+ const { phase, batchId, requestStarted, replyPersisted, cause } = args;
471
+ const message = cause instanceof Error ? cause.message : String(cause);
472
+ const error = new Error(
473
+ `cli batch phase ${phase} failed for ${batchId} (requestStarted=${requestStarted}, replyPersisted=${replyPersisted}): ${message}`
474
+ );
475
+ error.code = "cli_batch_phase_failed";
476
+ error.phase = phase;
477
+ error.batchId = batchId;
478
+ error.requestStarted = requestStarted;
479
+ error.replyPersisted = replyPersisted;
480
+ error.cause = cause;
481
+ return error;
482
+ }
483
+ function resolveCliBatchIdentity(options) {
484
+ const batchId = options.cliBatchId?.trim();
485
+ if (!batchId) return void 0;
486
+ const userMessages = options.userMessages;
487
+ if (!userMessages || userMessages.length === 0) {
488
+ throw cliBatchPhaseFailure({
489
+ phase: "requested",
490
+ batchId,
491
+ requestStarted: false,
492
+ replyPersisted: false,
493
+ cause: new Error("batch identity requires userMessages")
494
+ });
495
+ }
496
+ const tailId = userMessages[userMessages.length - 1]?.cliMessageId;
497
+ if (tailId !== batchId) {
498
+ throw cliBatchPhaseFailure({
499
+ phase: "requested",
500
+ batchId,
501
+ requestStarted: false,
502
+ replyPersisted: false,
503
+ cause: new Error(`batch identity mismatch: tail=${tailId ?? "none"}`)
504
+ });
505
+ }
506
+ const messageIds = userMessages.map((message) => message.cliMessageId);
507
+ if (messageIds.some((id) => !id)) {
508
+ throw cliBatchPhaseFailure({
509
+ phase: "requested",
510
+ batchId,
511
+ requestStarted: false,
512
+ replyPersisted: false,
513
+ cause: new Error("batch user message missing cliMessageId")
514
+ });
515
+ }
516
+ return { batchId, messageIds };
517
+ }
518
+
519
+ // packages/cli/client/agentRun.ts
520
+ import { resolve as resolveHostReviewPath } from "node:path";
521
+
522
+ // packages/cli/client/hostTaskBinding.ts
523
+ import { resolve as resolve2 } from "node:path";
524
+ function bindHostTask(args) {
525
+ let latest;
526
+ let completion;
527
+ function load() {
528
+ if (!args.reference) return void 0;
529
+ if (resolve2(args.reference.workspace) !== resolve2(args.workspace) || args.reference.dialogId !== args.dialogId) {
530
+ return { authorization: "unknown", reason: "scope_mismatch" };
531
+ }
532
+ return readHostTask(hostTaskEventsRoot(args.env), args.reference);
533
+ }
534
+ latest = load();
535
+ const contract = args.completionEvidenceProvider && latest && latest.authorization !== "unknown" ? latest.contract : void 0;
536
+ const adapter = !args.reference ? args.adapter : {
537
+ ...args.adapter,
538
+ // Re-read authority before each protected action. A review-only binding owns
539
+ // typed review tools, not ordinary chat tools or their existing permission gates.
540
+ // Explicit completion tasks retain their all-tool stop semantics; unknown scope
541
+ // fails closed. Already running tools are not cancelled by this entry guard.
542
+ executeTool: async (call, opts) => {
543
+ latest = load();
544
+ const authorization = latest?.authorization ?? "unknown";
545
+ const protectedTool = call.name === "requestTaskReview" || call.name === "recordTaskReviewDecision";
546
+ if (authorization !== "active" && (args.completionEvidenceProvider || protectedTool || authorization === "unknown")) {
547
+ const code = authorization === "paused" ? "authorization_paused" : authorization === "revoked" ? "authorization_revoked" : "authorization_unknown";
548
+ throw Object.assign(new Error(`host task authority ${authorization}: tool "${call.name}" was not executed`), { code });
549
+ }
550
+ return args.adapter.executeTool(call, opts);
551
+ },
552
+ saveTurn: async (input) => {
553
+ latest = load();
554
+ const stopped = args.signal?.aborted || input.result.businessCompletion?.reasons.includes("stopped");
555
+ if (args.completionEvidenceProvider) {
556
+ const snapshot = latest && latest.authorization !== "unknown" ? latest.contract : void 0;
557
+ let evidence;
558
+ try {
559
+ evidence = snapshot ? await args.completionEvidenceProvider(snapshot) : void 0;
560
+ } catch {
561
+ }
562
+ latest = load();
563
+ const current = latest && latest.authorization !== "unknown" ? latest.contract : void 0;
564
+ completion = !current || !evidence || evidence.taskId !== current.taskId ? stopped ? { taskId: args.reference.taskId, status: "blocked", reasons: ["stopped"] } : unknownTaskCompletion(args.reference.taskId) : evaluateTaskExecutionContract({ ...evidence, authorization: current.authorization }, {
565
+ stopped,
566
+ executionFailed: input.result.error === true || !!input.result.runtimeProviderFailure || !!input.result.emptyAssistantFallbackReason,
567
+ budgetExhausted: input.result.businessCompletion?.reasons.includes("budget_exhausted")
568
+ });
569
+ }
570
+ const result = { ...input.result };
571
+ delete result.businessCompletion;
572
+ if (completion) result.businessCompletion = completion;
573
+ try {
574
+ return await args.adapter.saveTurn({ ...input, result });
575
+ } catch (error) {
576
+ if (args.completionEvidenceProvider) completion = { taskId: args.reference.taskId, status: "blocked", reasons: ["execution_failed"] };
577
+ throw error;
578
+ }
579
+ }
580
+ };
581
+ return {
582
+ adapter,
583
+ contract,
584
+ result: () => args.reference ? {
585
+ taskAuthorization: latest?.authorization ?? "unknown",
586
+ ...args.completionEvidenceProvider ? { businessCompletion: completion ?? unknownTaskCompletion(args.reference.taskId) } : {}
587
+ } : {}
588
+ };
589
+ }
590
+
403
591
  // packages/agent-runtime/modelLayerOverride.ts
404
592
  var MODEL_LAYER_KEYS = [
405
593
  "provider",
@@ -688,10 +876,10 @@ function platformCreditsFromUsage(usage) {
688
876
  const cost = typeof usage.cost === "number" ? usage.cost : 0;
689
877
  return Number.isFinite(cost) && cost > 0 ? cost : 0;
690
878
  }
691
- function withTurnCredits(tokens, credits) {
692
- if (!tokens) return tokens;
693
- if (credits === void 0) return tokens;
694
- return { ...tokens, credits };
879
+ function withTurnCredits(tokens2, credits) {
880
+ if (!tokens2) return tokens2;
881
+ if (credits === void 0) return tokens2;
882
+ return { ...tokens2, credits };
695
883
  }
696
884
  function formatCreditsChip(credits, options) {
697
885
  return options?.compact ? `\u26A1${credits.toFixed(2)}` : `\u26A1 ${credits.toFixed(2)} \u79EF\u5206`;
@@ -724,10 +912,18 @@ function computeBaselineContextTokens(options) {
724
912
  }
725
913
  return typeof fallbackEstimate === "function" ? fallbackEstimate() : fallbackEstimate;
726
914
  }
915
+ function preserveContextUsageWithoutReceipt(previous, estimatedContextTokens) {
916
+ return {
917
+ turnTokens: previous.turnTokens,
918
+ lastAuthorityTurnCount: previous.lastAuthorityTurnCount,
919
+ estimatedContextTokens,
920
+ liveTurnEstimatedTokens: previous.turnTokens && previous.turnTokens.input > 0 ? Math.max(0, estimatedContextTokens - previous.turnTokens.input) || void 0 : void 0
921
+ };
922
+ }
727
923
  function resolveContextUsage(opts = {}) {
728
- const tokens = opts.tokens;
729
- const contextWindow = tokens?.contextWindow ?? opts.fallbackContextWindow;
730
- const authoritativeInput = tokens && tokens.input > 0 ? tokens.input : void 0;
924
+ const tokens2 = opts.tokens;
925
+ const contextWindow = tokens2?.contextWindow ?? opts.fallbackContextWindow;
926
+ const authoritativeInput = tokens2 && tokens2.input > 0 ? tokens2.input : void 0;
731
927
  const baselineEstimate = opts.estimatedContextTokens != null && opts.estimatedContextTokens > 0 ? opts.estimatedContextTokens : void 0;
732
928
  const generatedSinceAuthority = opts.turnEstimatedTokens != null && opts.turnEstimatedTokens > 0 ? opts.turnEstimatedTokens : void 0;
733
929
  const occupancy = resolveOccupancy({
@@ -746,27 +942,27 @@ function resolveContextUsage(opts = {}) {
746
942
  }
747
943
  return usage;
748
944
  }
749
- function renderTokenStatus(tokens, fallback) {
945
+ function renderTokenStatus(tokens2, fallback) {
750
946
  const usage = resolveContextUsage({
751
- tokens,
947
+ tokens: tokens2,
752
948
  fallbackContextWindow: fallback?.contextWindow,
753
949
  estimatedContextTokens: fallback?.estimatedContextTokens,
754
950
  turnEstimatedTokens: fallback?.turnEstimatedTokens
755
951
  });
756
- const cache = tokens?.cacheRead != null && tokens.cacheRead > 0 ? ` (cache ${formatTokenCount(tokens.cacheRead)})` : "";
952
+ const cache = tokens2?.cacheRead != null && tokens2.cacheRead > 0 ? ` (cache ${formatTokenCount(tokens2.cacheRead)})` : "";
757
953
  if (usage.contextWindow === void 0) {
758
954
  const inStr = usage.used !== void 0 ? `${usage.estimated ? "~" : ""}${formatTokenCount(usage.used)}` : "\u2014";
759
- const outStr = tokens ? formatTokenCount(tokens.output) : "\u2014";
955
+ const outStr = tokens2 ? formatTokenCount(tokens2.output) : "\u2014";
760
956
  return `in ${inStr}${cache} out ${outStr} left \u2014`;
761
957
  }
762
- if (!tokens) {
958
+ if (!tokens2) {
763
959
  if (usage.used === void 0) return "in \u2014 out \u2014 left \u2014";
764
960
  const left2 = usage.left !== void 0 ? `~${formatTokenCount(usage.left)}` : "\u2014";
765
961
  return `in ~${formatTokenCount(usage.used)} out \u2014 left ${left2}`;
766
962
  }
767
- const inputText = tokens.input > 0 || usage.used === void 0 ? formatTokenCount(tokens.input) : `~${formatTokenCount(usage.used)}`;
768
- const left = tokens.remaining != null ? formatTokenCount(tokens.remaining) : usage.left !== void 0 ? `${usage.estimated ? "~" : ""}${formatTokenCount(usage.left)}` : "\u2014";
769
- return `in ${inputText}${cache} out ${formatTokenCount(tokens.output)} left ${left}`;
963
+ const inputText = tokens2.input > 0 || usage.used === void 0 ? formatTokenCount(tokens2.input) : `~${formatTokenCount(usage.used)}`;
964
+ const left = tokens2.remaining != null ? formatTokenCount(tokens2.remaining) : usage.left !== void 0 ? `${usage.estimated ? "~" : ""}${formatTokenCount(usage.left)}` : "\u2014";
965
+ return `in ${inputText}${cache} out ${formatTokenCount(tokens2.output)} left ${left}`;
770
966
  }
771
967
  function shouldShowUsage(env) {
772
968
  return env.NOLO_DEBUG === "1" || env.NOLO_SHOW_USAGE === "1";
@@ -851,754 +1047,6 @@ function formatCliHyperlink(url, label, enabled = resolveCliHyperlinkEnabled())
851
1047
  return `${OSC8_OPEN}${url}${OSC8_CLOSE}${safeLabel}${OSC8_OPEN}${OSC8_CLOSE}`;
852
1048
  }
853
1049
 
854
- // node_modules/ansi-regex/index.js
855
- function ansiRegex({ onlyFirst = false } = {}) {
856
- const ST2 = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
857
- const osc = `(?:\\u001B\\][^\\u0007\\u001B\\u009C]*${ST2})`;
858
- const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
859
- const pattern = `${osc}|${csi}`;
860
- return new RegExp(pattern, onlyFirst ? void 0 : "g");
861
- }
862
-
863
- // node_modules/strip-ansi/index.js
864
- var regex = ansiRegex();
865
- function stripAnsi(string) {
866
- if (typeof string !== "string") {
867
- throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
868
- }
869
- if (!string.includes("\x1B") && !string.includes("\x9B")) {
870
- return string;
871
- }
872
- return string.replace(regex, "");
873
- }
874
-
875
- // node_modules/get-east-asian-width/lookup-data.js
876
- var ambiguousMinimalCodePoint = 161;
877
- var ambiguousMaximumCodePoint = 1114109;
878
- var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
879
- var fullwidthMinimalCodePoint = 12288;
880
- var fullwidthMaximumCodePoint = 65510;
881
- var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
882
- var wideMinimalCodePoint = 4352;
883
- var wideMaximumCodePoint = 262141;
884
- var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101594, 101631, 101664, 101760, 101874, 101888, 102801, 102816, 102866, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110888, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110952, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127406, 127406, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128729, 128732, 128735, 128747, 128748, 128756, 128764, 128986, 128986, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129734, 129736, 129736, 129740, 129757, 129759, 129771, 129775, 129786, 131072, 196605, 196608, 262141];
885
-
886
- // node_modules/get-east-asian-width/utilities.js
887
- var isInRange = (ranges, codePoint) => {
888
- let low = 0;
889
- let high = Math.floor(ranges.length / 2) - 1;
890
- while (low <= high) {
891
- const mid = Math.floor((low + high) / 2);
892
- const i = mid * 2;
893
- if (codePoint < ranges[i]) {
894
- high = mid - 1;
895
- } else if (codePoint > ranges[i + 1]) {
896
- low = mid + 1;
897
- } else {
898
- return true;
899
- }
900
- }
901
- return false;
902
- };
903
-
904
- // node_modules/get-east-asian-width/lookup.js
905
- var commonCjkCodePoint = 19968;
906
- var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
907
- function findWideFastPathRange(ranges) {
908
- let fastPathStart = ranges[0];
909
- let fastPathEnd = ranges[1];
910
- for (let index = 0; index < ranges.length; index += 2) {
911
- const start = ranges[index];
912
- const end = ranges[index + 1];
913
- if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) {
914
- return [start, end];
915
- }
916
- if (end - start > fastPathEnd - fastPathStart) {
917
- fastPathStart = start;
918
- fastPathEnd = end;
919
- }
920
- }
921
- return [fastPathStart, fastPathEnd];
922
- }
923
- var isAmbiguous = (codePoint) => {
924
- if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
925
- return false;
926
- }
927
- return isInRange(ambiguousRanges, codePoint);
928
- };
929
- var isFullwidth = (codePoint) => {
930
- if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
931
- return false;
932
- }
933
- return isInRange(fullwidthRanges, codePoint);
934
- };
935
- var isWide = (codePoint) => {
936
- if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
937
- return true;
938
- }
939
- if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
940
- return false;
941
- }
942
- return isInRange(wideRanges, codePoint);
943
- };
944
-
945
- // node_modules/get-east-asian-width/index.js
946
- function validate(codePoint) {
947
- if (!Number.isSafeInteger(codePoint)) {
948
- throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
949
- }
950
- }
951
- function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
952
- validate(codePoint);
953
- if (isFullwidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
954
- return 2;
955
- }
956
- return 1;
957
- }
958
-
959
- // node_modules/string-width/index.js
960
- var segmenter = new Intl.Segmenter();
961
- var zeroWidthClusterRegex = new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Nonspacing_Mark}|\\p{Enclosing_Mark}|\\p{Surrogate})+$", "v");
962
- var leadingNonPrintingRegex = new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Nonspacing_Mark}\\p{Enclosing_Mark}\\p{Surrogate}]+", "v");
963
- var spacingMarkRegex = new RegExp("\\p{Spacing_Mark}", "v");
964
- var rgiEmojiRegex = new RegExp("^\\p{RGI_Emoji}$", "v");
965
- var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
966
- var extendedPictographicRegex = new RegExp("\\p{Extended_Pictographic}", "gu");
967
- function isDoubleWidthNonRgiEmojiSequence(segment) {
968
- if (segment.length > 50) {
969
- return false;
970
- }
971
- if (unqualifiedKeycapRegex.test(segment)) {
972
- return true;
973
- }
974
- if (segment.includes("\u200D")) {
975
- const pictographics = segment.match(extendedPictographicRegex);
976
- return pictographics !== null && pictographics.length >= 2;
977
- }
978
- return false;
979
- }
980
- function baseVisible(segment) {
981
- return segment.replace(leadingNonPrintingRegex, "");
982
- }
983
- function isZeroWidthCluster(segment) {
984
- return zeroWidthClusterRegex.test(segment);
985
- }
986
- function isHangulLeadingJamo(codePoint) {
987
- return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
988
- }
989
- function isHangulVowelJamo(codePoint) {
990
- return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
991
- }
992
- function isHangulTrailingJamo(codePoint) {
993
- return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
994
- }
995
- function isHangulJamo(codePoint) {
996
- return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
997
- }
998
- function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
999
- const codePoints = [];
1000
- for (const character of visibleSegment) {
1001
- if (zeroWidthClusterRegex.test(character)) {
1002
- continue;
1003
- }
1004
- codePoints.push(character.codePointAt(0));
1005
- }
1006
- if (codePoints.length === 0) {
1007
- return void 0;
1008
- }
1009
- let width = 0;
1010
- for (let index = 0; index < codePoints.length; index++) {
1011
- const codePoint = codePoints[index];
1012
- if (!isHangulJamo(codePoint)) {
1013
- if (width === 0) {
1014
- return void 0;
1015
- }
1016
- for (let remaining = index; remaining < codePoints.length; remaining++) {
1017
- width += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
1018
- }
1019
- return width;
1020
- }
1021
- if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index + 1])) {
1022
- width += 2;
1023
- index += isHangulTrailingJamo(codePoints[index + 2]) ? 2 : 1;
1024
- continue;
1025
- }
1026
- width += eastAsianWidth(codePoint, eastAsianWidthOptions);
1027
- }
1028
- return width;
1029
- }
1030
- function trailingWidth(visibleSegment, eastAsianWidthOptions) {
1031
- let extra = 0;
1032
- let first = true;
1033
- for (const character of visibleSegment) {
1034
- if (first) {
1035
- first = false;
1036
- continue;
1037
- }
1038
- if (spacingMarkRegex.test(character) || character >= "\uFF00" && character <= "\uFFEF") {
1039
- extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
1040
- }
1041
- }
1042
- return extra;
1043
- }
1044
- function stringWidth(input, options = {}) {
1045
- if (typeof input !== "string" || input.length === 0) {
1046
- return 0;
1047
- }
1048
- const {
1049
- ambiguousIsNarrow = true,
1050
- countAnsiEscapeCodes = false
1051
- } = options;
1052
- let string = input;
1053
- if (!countAnsiEscapeCodes && (string.includes("\x1B") || string.includes("\x9B"))) {
1054
- string = stripAnsi(string);
1055
- }
1056
- if (string.length === 0) {
1057
- return 0;
1058
- }
1059
- if (/^[\u0020-\u007E]*$/.test(string)) {
1060
- return string.length;
1061
- }
1062
- let width = 0;
1063
- const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
1064
- for (const { segment } of segmenter.segment(string)) {
1065
- if (isZeroWidthCluster(segment)) {
1066
- continue;
1067
- }
1068
- if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
1069
- width += 2;
1070
- continue;
1071
- }
1072
- const visibleSegment = baseVisible(segment);
1073
- const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
1074
- if (hangulWidth !== void 0) {
1075
- width += hangulWidth;
1076
- continue;
1077
- }
1078
- const codePoint = visibleSegment.codePointAt(0);
1079
- width += eastAsianWidth(codePoint, eastAsianWidthOptions);
1080
- width += trailingWidth(visibleSegment, eastAsianWidthOptions);
1081
- }
1082
- return width;
1083
- }
1084
-
1085
- // packages/cli/tui/tuiAnsi.ts
1086
- var ANSI_ESCAPE_REGEX = /\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/g;
1087
- var OSC8_HYPERLINK_REGEX = /\x1b\]8;;[^\x1b]*\x1b\\/g;
1088
- var ALL_ANSI_ESCAPE_REGEX = ansiRegex();
1089
- var FIRST_ANSI_ESCAPE_REGEX = ansiRegex({ onlyFirst: true });
1090
- function stripOsc8Hyperlinks(text) {
1091
- return text.replace(OSC8_HYPERLINK_REGEX, "");
1092
- }
1093
- function stripAnsi2(text) {
1094
- return text.replace(ANSI_ESCAPE_REGEX, "").replace(ALL_ANSI_ESCAPE_REGEX, "");
1095
- }
1096
- var SGR_SEQUENCE_REGEX = /^\x1b\[[0-9;]*m/;
1097
- var TRAILING_SGR_REGEX = /(?:\x1b\[[0-9;]*m)+$/;
1098
- function applyTerminalOutputToText(existing, chunk) {
1099
- if (!chunk) return existing;
1100
- let text = existing;
1101
- let index = 0;
1102
- while (index < chunk.length) {
1103
- if (chunk[index] === "\x1B") {
1104
- const sgr = SGR_SEQUENCE_REGEX.exec(chunk.slice(index));
1105
- if (sgr) {
1106
- text += sgr[0];
1107
- index += sgr[0].length;
1108
- continue;
1109
- }
1110
- const osc = chunk.slice(index).match(/^\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)/);
1111
- if (osc) {
1112
- index += osc[0].length;
1113
- continue;
1114
- }
1115
- const csi = chunk.slice(index).match(/^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/);
1116
- if (csi) {
1117
- index += csi[0].length;
1118
- continue;
1119
- }
1120
- index += 1;
1121
- continue;
1122
- }
1123
- const ch = chunk[index];
1124
- if (ch === "\r") {
1125
- const lastNl = text.lastIndexOf("\n");
1126
- text = lastNl === -1 ? "" : text.slice(0, lastNl + 1);
1127
- index += 1;
1128
- continue;
1129
- }
1130
- if (ch === "\n") {
1131
- text += "\n";
1132
- index += 1;
1133
- continue;
1134
- }
1135
- if (ch === "\b") {
1136
- const trailing = TRAILING_SGR_REGEX.exec(text);
1137
- const sgrTail = trailing ? trailing[0] : "";
1138
- const head = sgrTail ? text.slice(0, -sgrTail.length) : text;
1139
- if (head.length > 0 && head[head.length - 1] !== "\n") {
1140
- text = head.slice(0, -1) + sgrTail;
1141
- }
1142
- index += 1;
1143
- continue;
1144
- }
1145
- const code = ch.charCodeAt(0);
1146
- if (code < 32 && ch !== " " || code === 127) {
1147
- index += 1;
1148
- continue;
1149
- }
1150
- text += ch;
1151
- index += 1;
1152
- }
1153
- return text;
1154
- }
1155
- function resolveAmbiguousWidth(explicit, env = process.env) {
1156
- if (explicit === "wide" || explicit === "narrow") return explicit;
1157
- const raw = env.NOLO_TUI_AMBIGUOUS_WIDTH;
1158
- if (typeof raw === "string") {
1159
- const trimmed = raw.trim().toLowerCase();
1160
- if (trimmed === "wide") return "wide";
1161
- if (trimmed === "narrow") return "narrow";
1162
- }
1163
- return "narrow";
1164
- }
1165
- function isAmbiguousWideSymbolCode(code) {
1166
- return code >= 8592 && code <= 8597 || // ←↑→↓↔↕
1167
- code === 8656 || code === 8658 || code === 8660 || // ⇐⇒⇔
1168
- code === 215 || code === 247 || code === 177 || // ×÷±
1169
- code === 8226 || code === 183 || // • ·
1170
- code === 176 || code === 8451 || // ° ℃
1171
- code >= 8208 && code <= 8213 || // ‐‑‒–—―
1172
- code >= 9312 && code <= 9471 || // ①②④⑤ 圈数字/括号序号
1173
- code === 8986 || code === 8987 || // ⌚ ⌛
1174
- code >= 9193 && code <= 9210;
1175
- }
1176
- function isForceWideSymbolCode(code) {
1177
- return code >= 9728 && code <= 10175 && !(code >= 10088 && code <= 10101) || code >= 11008 && code <= 11263 || code >= 127744 && code <= 129791 || isAmbiguousWideSymbolCode(code);
1178
- }
1179
- function isCjkQuoteCode(code) {
1180
- return code === 8220 || code === 8221 || code === 8216 || code === 8217;
1181
- }
1182
- function scanWidthNeeds(plain, locale, ambiguousWidth) {
1183
- let hasNonAscii = false;
1184
- const isWideMode = ambiguousWidth === "wide";
1185
- for (let i = 0; i < plain.length; i++) {
1186
- const cc = plain.charCodeAt(i);
1187
- if (isWideMode && isAmbiguousWideSymbolCode(cc)) {
1188
- return { hasNonAscii: true, hasCandidate: true };
1189
- }
1190
- if (cc < 8192) {
1191
- if (cc >= 128) hasNonAscii = true;
1192
- continue;
1193
- }
1194
- hasNonAscii = true;
1195
- let code = cc;
1196
- if (cc >= 55296 && cc <= 56319 && i + 1 < plain.length) {
1197
- const lo = plain.charCodeAt(i + 1);
1198
- if (lo >= 56320 && lo <= 57343) {
1199
- code = (cc - 55296) * 1024 + (lo - 56320) + 65536;
1200
- i += 1;
1201
- }
1202
- }
1203
- const isSymbolCandidate = isWideMode && isForceWideSymbolCode(code);
1204
- const isQuoteCandidate = locale === "zh" && isCjkQuoteCode(code);
1205
- if (isSymbolCandidate || isQuoteCandidate) {
1206
- return { hasNonAscii: true, hasCandidate: true };
1207
- }
1208
- }
1209
- return { hasNonAscii, hasCandidate: false };
1210
- }
1211
- var displayWidthCache = /* @__PURE__ */ new Map();
1212
- var DISPLAY_WIDTH_CACHE_MAX = 4096;
1213
- function displayWidth(str, ambiguousWidth = resolveAmbiguousWidth()) {
1214
- const plain = stripAnsi2(str);
1215
- const locale = getCliLocale();
1216
- const needs = scanWidthNeeds(plain, locale, ambiguousWidth);
1217
- if (!needs.hasNonAscii) {
1218
- return stringWidth(plain);
1219
- }
1220
- const key = locale + "\0" + ambiguousWidth + "\0" + plain;
1221
- const cached = displayWidthCache.get(key);
1222
- if (cached !== void 0) return cached;
1223
- const base = stringWidth(plain);
1224
- if (!needs.hasCandidate) {
1225
- if (displayWidthCache.size >= DISPLAY_WIDTH_CACHE_MAX) {
1226
- const eldest = displayWidthCache.keys().next().value;
1227
- if (eldest !== void 0) displayWidthCache.delete(eldest);
1228
- }
1229
- displayWidthCache.set(key, base);
1230
- return base;
1231
- }
1232
- let width = base;
1233
- const isWideMode = ambiguousWidth === "wide";
1234
- for (const { segment } of graphemeSegmenter.segment(plain)) {
1235
- const code = segment.codePointAt(0) ?? 0;
1236
- const isSymbol = isWideMode && isForceWideSymbolCode(code);
1237
- const isQuote = locale === "zh" && isCjkQuoteCode(code);
1238
- if (isSymbol || isQuote) {
1239
- if (stringWidth(segment) === 1) width += 1;
1240
- }
1241
- }
1242
- if (displayWidthCache.size >= DISPLAY_WIDTH_CACHE_MAX) {
1243
- const eldest = displayWidthCache.keys().next().value;
1244
- if (eldest !== void 0) displayWidthCache.delete(eldest);
1245
- }
1246
- displayWidthCache.set(key, width);
1247
- return width;
1248
- }
1249
- function visibleWidth(str) {
1250
- return displayWidth(stripAnsi2(str));
1251
- }
1252
- function truncateAnsi(text, maxWidth) {
1253
- if (maxWidth <= 0) return "";
1254
- text = stripOsc8Hyperlinks(text);
1255
- if (visibleWidth(text) <= maxWidth) return text;
1256
- let width = 0;
1257
- let out = "";
1258
- let i = 0;
1259
- let sawAnsi = false;
1260
- while (i < text.length) {
1261
- if (text[i] === "\x1B" && text[i + 1] === "[") {
1262
- sawAnsi = true;
1263
- let j = i + 2;
1264
- while (j < text.length) {
1265
- const code = text.charCodeAt(j);
1266
- j += 1;
1267
- if (code >= 64 && code <= 126) break;
1268
- }
1269
- out += text.slice(i, j);
1270
- i = j;
1271
- continue;
1272
- }
1273
- const codePoint = text.codePointAt(i) ?? 0;
1274
- const char = String.fromCodePoint(codePoint);
1275
- const charWidth = displayWidth(char);
1276
- if (width + charWidth > maxWidth) break;
1277
- out += char;
1278
- width += charWidth;
1279
- i += char.length;
1280
- }
1281
- return sawAnsi ? `${out}\x1B[0m` : out;
1282
- }
1283
- function fitAnsiLine(text, width, ellipsis = "\u2026") {
1284
- if (width <= 0) return "";
1285
- if (visibleWidth(text) <= width) return text;
1286
- const ellipsisWidth = displayWidth(ellipsis);
1287
- if (width < ellipsisWidth) return truncateAnsi(text, width);
1288
- if (width === ellipsisWidth) return truncateAnsi(ellipsis, width) || truncateAnsi(text, width);
1289
- return `${truncateAnsi(text, width - ellipsisWidth)}${ellipsis}`;
1290
- }
1291
- function countPhysicalLines(text, columns) {
1292
- const lines = text.split("\n");
1293
- let total = 0;
1294
- for (const line of lines) {
1295
- const width = visibleWidth(stripOsc8Hyperlinks(line));
1296
- total += Math.max(1, Math.ceil(width / columns));
1297
- }
1298
- return Math.max(total, 1);
1299
- }
1300
- function takeDisplayWidth(text, width) {
1301
- let used = 0;
1302
- let index = 0;
1303
- for (const char of text) {
1304
- const charWidth = displayWidth(char);
1305
- if (used + charWidth > width && used > 0) break;
1306
- used += charWidth;
1307
- index += char.length;
1308
- }
1309
- return { prefix: text.slice(0, index), rest: text.slice(index) };
1310
- }
1311
- function padOrTruncateToWidth(text, width) {
1312
- const textWidth = visibleWidth(text);
1313
- if (textWidth > width) {
1314
- return truncateAnsi(text, width);
1315
- }
1316
- return `${text}${" ".repeat(width - textWidth)}`;
1317
- }
1318
- var SGR_RESET_REGEX = /^\x1b\[0?m$/;
1319
- var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1320
- function tokenizeAnsiLine(line) {
1321
- const tokens = [];
1322
- let index = 0;
1323
- while (index < line.length) {
1324
- if (line[index] === "\x1B") {
1325
- const osc = line.slice(index).match(/^\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)/);
1326
- if (osc) {
1327
- tokens.push({ kind: "sgr", value: osc[0], width: 0, charIndex: index });
1328
- index += osc[0].length;
1329
- continue;
1330
- }
1331
- const sgr = SGR_SEQUENCE_REGEX.exec(line.slice(index));
1332
- if (sgr) {
1333
- tokens.push({ kind: "sgr", value: sgr[0], width: 0, charIndex: index });
1334
- index += sgr[0].length;
1335
- continue;
1336
- }
1337
- const csi = line.slice(index).match(/^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/);
1338
- if (csi) {
1339
- index += csi[0].length;
1340
- continue;
1341
- }
1342
- const escape = FIRST_ANSI_ESCAPE_REGEX.exec(line.slice(index));
1343
- if (escape?.index === 0) {
1344
- index += escape[0].length;
1345
- continue;
1346
- }
1347
- index += 1;
1348
- continue;
1349
- }
1350
- let nextEsc = line.indexOf("\x1B", index);
1351
- if (nextEsc === -1) nextEsc = line.length;
1352
- const chunk = line.slice(index, nextEsc);
1353
- for (const item of graphemeSegmenter.segment(chunk)) {
1354
- tokens.push({
1355
- kind: "char",
1356
- value: item.segment,
1357
- width: displayWidth(item.segment),
1358
- charIndex: index + item.index
1359
- });
1360
- }
1361
- index = nextEsc;
1362
- }
1363
- return tokens;
1364
- }
1365
- function buildSourceMapping(rawLine, styledLine, prefixCharCount) {
1366
- let contentStart = 0;
1367
- const headingMatch = rawLine.match(/^(#{1,3})\s+(.+)$/);
1368
- let lineToParse = rawLine;
1369
- if (headingMatch) {
1370
- contentStart = headingMatch[1].length + 1;
1371
- while (contentStart < rawLine.length && rawLine[contentStart] === " ") contentStart++;
1372
- lineToParse = rawLine.slice(contentStart);
1373
- }
1374
- const INLINE_RE = /(\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*(.+?)\*\*|(?<!\*)\*([^*]+?)\*(?!\*)|~~([^~]+?)~~)/g;
1375
- const mapping = [];
1376
- let lastIdx = 0;
1377
- let match;
1378
- while ((match = INLINE_RE.exec(lineToParse)) !== null) {
1379
- const plainBefore = lineToParse.slice(lastIdx, match.index);
1380
- for (let c = 0; c < plainBefore.length; c++) {
1381
- mapping.push(contentStart + lastIdx + c);
1382
- }
1383
- const fullMatch = match[0];
1384
- if (match[2] !== void 0 && match[3] !== void 0) {
1385
- const linkText = match[2];
1386
- const linkUrl = match[3];
1387
- const textOffset = contentStart + match.index + 1;
1388
- for (let c = 0; c < linkText.length; c++) {
1389
- mapping.push(textOffset + c);
1390
- }
1391
- const parenOffset = textOffset + linkText.length;
1392
- mapping.push(parenOffset);
1393
- mapping.push(parenOffset + 1);
1394
- const urlOffset = parenOffset + 2;
1395
- for (let c = 0; c < linkUrl.length; c++) {
1396
- mapping.push(urlOffset + c);
1397
- }
1398
- mapping.push(urlOffset + linkUrl.length);
1399
- } else if (match[4] !== void 0) {
1400
- const codeText = match[4];
1401
- const codeOffset = contentStart + match.index + 1;
1402
- for (let c = 0; c < codeText.length; c++) {
1403
- mapping.push(codeOffset + c);
1404
- }
1405
- } else if (match[5] !== void 0) {
1406
- const boldText = match[5];
1407
- const boldOffset = contentStart + match.index + 2;
1408
- for (let c = 0; c < boldText.length; c++) {
1409
- mapping.push(boldOffset + c);
1410
- }
1411
- } else if (match[6] !== void 0) {
1412
- const italicText = match[6];
1413
- const italicOffset = contentStart + match.index + 1;
1414
- for (let c = 0; c < italicText.length; c++) {
1415
- mapping.push(italicOffset + c);
1416
- }
1417
- } else if (match[7] !== void 0) {
1418
- const strikeText = match[7];
1419
- const strikeOffset = contentStart + match.index + 2;
1420
- for (let c = 0; c < strikeText.length; c++) {
1421
- mapping.push(strikeOffset + c);
1422
- }
1423
- }
1424
- lastIdx = match.index + fullMatch.length;
1425
- }
1426
- const plainRest = lineToParse.slice(lastIdx);
1427
- for (let c = 0; c < plainRest.length; c++) {
1428
- mapping.push(contentStart + lastIdx + c);
1429
- }
1430
- return mapping;
1431
- }
1432
- function wrapTranscriptLineWithLayout(line, columns, hangingIndent = "", lineSourceStart = 0, prefixWidth = 0, prefixCharCount = 0, sourceMapping, rawLineLength) {
1433
- if (line === "") {
1434
- const rawLen = rawLineLength ?? 0;
1435
- return [
1436
- {
1437
- rendered: "",
1438
- sourceStart: lineSourceStart,
1439
- sourceEnd: lineSourceStart + rawLen,
1440
- prefixWidth
1441
- }
1442
- ];
1443
- }
1444
- const tokens = tokenizeAnsiLine(line);
1445
- const rows = [];
1446
- let activeStyles = [];
1447
- const applyStyleToken = (value) => {
1448
- if (SGR_RESET_REGEX.test(value)) {
1449
- activeStyles = [];
1450
- } else {
1451
- activeStyles.push(value);
1452
- }
1453
- };
1454
- let lastContentTokenIndex = -1;
1455
- for (let i = tokens.length - 1; i >= 0; i -= 1) {
1456
- if (tokens[i].kind !== "sgr") {
1457
- lastContentTokenIndex = i;
1458
- break;
1459
- }
1460
- }
1461
- let plainCharIndexAtStart = 0;
1462
- let start = 0;
1463
- while (start < tokens.length) {
1464
- if (start > lastContentTokenIndex && rows.length > 0) break;
1465
- const openingStyles = [...activeStyles];
1466
- const isContinuation = rows.length > 0;
1467
- const currentPrefixWidth = isContinuation ? visibleWidth(hangingIndent) : prefixWidth;
1468
- const indentWidth = isContinuation ? visibleWidth(hangingIndent) : 0;
1469
- const maxSegmentWidth = Math.max(1, columns - indentWidth);
1470
- let width = 0;
1471
- let end = start;
1472
- let lastBreak2 = -1;
1473
- while (end < tokens.length) {
1474
- const token = tokens[end];
1475
- if (token.kind === "sgr") {
1476
- end += 1;
1477
- continue;
1478
- }
1479
- if (width + token.width > maxSegmentWidth && width > 0) break;
1480
- width += token.width;
1481
- end += 1;
1482
- if ((token.value === " " || token.value === " ") && token.charIndex >= prefixCharCount) {
1483
- lastBreak2 = end;
1484
- }
1485
- }
1486
- let segmentEnd = end;
1487
- if (end < tokens.length && lastBreak2 > start) {
1488
- const overflowToken = tokens[end];
1489
- if (overflowToken.kind === "char" && overflowToken.value !== " " && overflowToken.width === 1) {
1490
- segmentEnd = lastBreak2;
1491
- }
1492
- }
1493
- if (segmentEnd === start) segmentEnd = start + 1;
1494
- let segment = "";
1495
- let sawStyle = openingStyles.length > 0;
1496
- for (let i = start; i < segmentEnd; i += 1) {
1497
- const token = tokens[i];
1498
- segment += token.value;
1499
- if (token.kind === "sgr") {
1500
- sawStyle = true;
1501
- applyStyleToken(token.value);
1502
- }
1503
- }
1504
- const prefix = openingStyles.join("");
1505
- const needsReset = (sawStyle || activeStyles.length > 0) && !segment.endsWith("\x1B[0m");
1506
- const lineContent = `${prefix}${segment}${needsReset ? "\x1B[0m" : ""}`;
1507
- const rowRendered = isContinuation && hangingIndent.length > 0 ? `${hangingIndent}${lineContent}` : lineContent;
1508
- let segSourceStart = lineSourceStart;
1509
- let segSourceEnd = lineSourceStart;
1510
- let foundFirst = false;
1511
- const rowMapping = [];
1512
- let plainCharIndex = plainCharIndexAtStart;
1513
- for (let i = start; i < segmentEnd; i++) {
1514
- const tok = tokens[i];
1515
- if (tok.kind === "char" && tok.charIndex >= prefixCharCount) {
1516
- const mappedOffset = sourceMapping && sourceMapping[plainCharIndex] !== void 0 ? sourceMapping[plainCharIndex] : plainCharIndex;
1517
- if (!foundFirst) {
1518
- segSourceStart = lineSourceStart + mappedOffset;
1519
- foundFirst = true;
1520
- }
1521
- for (let c = 0; c < tok.value.length; c++) {
1522
- const idx = plainCharIndex + c;
1523
- const mapped = sourceMapping && sourceMapping[idx] !== void 0 ? sourceMapping[idx] : idx;
1524
- rowMapping.push(lineSourceStart + mapped);
1525
- }
1526
- const lastCharIdx = plainCharIndex + tok.value.length - 1;
1527
- const mappedEndOffset = sourceMapping && sourceMapping[lastCharIdx] !== void 0 ? sourceMapping[lastCharIdx] + 1 : plainCharIndex + tok.value.length;
1528
- segSourceEnd = lineSourceStart + mappedEndOffset;
1529
- plainCharIndex += tok.value.length;
1530
- }
1531
- }
1532
- start = segmentEnd;
1533
- let softWrapJoiner = "";
1534
- while (start < tokens.length) {
1535
- const token = tokens[start];
1536
- if (token.kind === "char" && token.value === " " && token.charIndex >= prefixCharCount) {
1537
- softWrapJoiner += token.value;
1538
- const mappedOffset = sourceMapping && sourceMapping[plainCharIndex] !== void 0 ? sourceMapping[plainCharIndex] + 1 : plainCharIndex + 1;
1539
- segSourceEnd = lineSourceStart + mappedOffset;
1540
- plainCharIndex += token.value.length;
1541
- start += 1;
1542
- continue;
1543
- }
1544
- break;
1545
- }
1546
- if (start >= tokens.length && rawLineLength !== void 0) {
1547
- segSourceEnd = lineSourceStart + rawLineLength;
1548
- }
1549
- plainCharIndexAtStart = plainCharIndex;
1550
- rows.push({
1551
- rendered: rowRendered,
1552
- sourceStart: segSourceStart,
1553
- sourceEnd: segSourceEnd,
1554
- prefixWidth: currentPrefixWidth,
1555
- sourceMapping: rowMapping.length > 0 ? rowMapping : void 0,
1556
- softWrapped: start < tokens.length,
1557
- softWrapJoiner
1558
- });
1559
- }
1560
- return rows.length > 0 ? rows : [
1561
- {
1562
- rendered: "",
1563
- sourceStart: lineSourceStart,
1564
- sourceEnd: lineSourceStart + (rawLineLength ?? 0),
1565
- prefixWidth
1566
- }
1567
- ];
1568
- }
1569
- function wrapTranscriptLine(line, columns, hangingIndent = "") {
1570
- return wrapTranscriptLineWithLayout(line, columns, hangingIndent).map((r) => r.rendered);
1571
- }
1572
- function buildWindowTitle(title) {
1573
- const plain = stripAnsi2(title).replace(/[\x00-\x1f\x7f]+/g, " ");
1574
- let truncated = "";
1575
- let width = 0;
1576
- const maxCols = 80;
1577
- for (const char of plain) {
1578
- const charWidth = displayWidth(char);
1579
- if (width + charWidth > maxCols) break;
1580
- truncated += char;
1581
- width += charWidth;
1582
- }
1583
- return `\x1B]0;${truncated}\x07\x1B]2;${truncated}\x07`;
1584
- }
1585
- function wrapTextToLines(text, columns) {
1586
- const result = [];
1587
- for (const logicalLine of text.split("\n")) {
1588
- if (logicalLine === "") {
1589
- result.push("");
1590
- continue;
1591
- }
1592
- let remaining = logicalLine;
1593
- while (remaining.length > 0) {
1594
- const { prefix, rest } = takeDisplayWidth(remaining, columns);
1595
- result.push(prefix);
1596
- remaining = rest;
1597
- }
1598
- }
1599
- return result;
1600
- }
1601
-
1602
1050
  // packages/cli/tui/theme.ts
1603
1051
  var THEME_PALETTES = {
1604
1052
  trail: {
@@ -2997,7 +2445,7 @@ var WIDTHS = [
2997
2445
  ];
2998
2446
 
2999
2447
  // node_modules/lovely-mermaid/dist/width.js
3000
- var segmenter2 = new Intl.Segmenter("en", { granularity: "grapheme" });
2448
+ var segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
3001
2449
  var VS16 = 65039;
3002
2450
  var isRegionalIndicator = (cp) => cp >= 127462 && cp <= 127487;
3003
2451
  function codePointWidth(cp) {
@@ -3032,12 +2480,12 @@ function clusterWidth(cluster) {
3032
2480
  return vs16 || regional >= 2 ? 2 : w;
3033
2481
  }
3034
2482
  function* measured(s) {
3035
- for (const { segment } of segmenter2.segment(s))
2483
+ for (const { segment } of segmenter.segment(s))
3036
2484
  yield [segment, clusterWidth(segment)];
3037
2485
  }
3038
- function stringWidth2(s) {
2486
+ function stringWidth(s) {
3039
2487
  let w = 0;
3040
- for (const { segment } of segmenter2.segment(s))
2488
+ for (const { segment } of segmenter.segment(s))
3041
2489
  w += clusterWidth(segment);
3042
2490
  return w;
3043
2491
  }
@@ -3234,7 +2682,7 @@ function wrapLabel(label, width, maxLines) {
3234
2682
  let cur = "";
3235
2683
  let curW = 0;
3236
2684
  for (const word of label.split(/\s+/).filter((w) => w !== "")) {
3237
- const ww = stringWidth2(word);
2685
+ const ww = stringWidth(word);
3238
2686
  if (ww > width) {
3239
2687
  if (cur !== "") {
3240
2688
  lines.push(cur);
@@ -3248,7 +2696,7 @@ function wrapLabel(label, width, maxLines) {
3248
2696
  const carry = p === -1 ? "" : chunk.slice(p + 1);
3249
2697
  lines.push(p === -1 ? chunk : chunk.slice(0, p + 1));
3250
2698
  chunk = carry;
3251
- chunkW = stringWidth2(carry);
2699
+ chunkW = stringWidth(carry);
3252
2700
  }
3253
2701
  chunk += ch;
3254
2702
  chunkW += cw;
@@ -3287,7 +2735,7 @@ function wrapLabel(label, width, maxLines) {
3287
2735
  return lines;
3288
2736
  }
3289
2737
  function fitLabel(label, inner) {
3290
- if (stringWidth2(label) <= inner)
2738
+ if (stringWidth(label) <= inner)
3291
2739
  return label;
3292
2740
  let out = "";
3293
2741
  let used = 0;
@@ -4079,7 +3527,7 @@ function placeTd(ranks, maxRank, byRank, sizes, graph, placed) {
4079
3527
  const edgeLabelLeft = new Array(graph.edges.length).fill(false);
4080
3528
  const labelW = (e) => {
4081
3529
  const parts = [e.label, e.cardTo].filter((p) => p != null);
4082
- return parts.length === 0 ? -1 : Math.max(...parts.map((p) => Math.min(stringWidth2(p), MAX_LABEL)));
3530
+ return parts.length === 0 ? -1 : Math.max(...parts.map((p) => Math.min(stringWidth(p), MAX_LABEL)));
4083
3531
  };
4084
3532
  const skipsInto = graph.nodes.map(() => []);
4085
3533
  const fwdsInto = graph.nodes.map(() => []);
@@ -4247,21 +3695,21 @@ function placeTd(ranks, maxRank, byRank, sizes, graph, placed) {
4247
3695
  if (ranks[e.to] === ranks[e.from] + 1) {
4248
3696
  const parts = [e.label, e.cardTo].filter((part) => part != null);
4249
3697
  for (const part of parts) {
4250
- const lw = Math.min(stringWidth2(part), MAX_LABEL);
3698
+ const lw = Math.min(stringWidth(part), MAX_LABEL);
4251
3699
  contentW = Math.max(contentW, placed[e.to].cx + 2 + lw);
4252
3700
  }
4253
3701
  if (e.cardFrom !== void 0) {
4254
- contentW = Math.max(contentW, placed[e.from].cx + 2 + stringWidth2(e.cardFrom));
3702
+ contentW = Math.max(contentW, placed[e.from].cx + 2 + stringWidth(e.cardFrom));
4255
3703
  }
4256
3704
  } else if (isAdjacentBack(ranks, e)) {
4257
3705
  const text = edgeText(e);
4258
3706
  if (text !== null) {
4259
- contentW = Math.max(contentW, placed[e.to].cx + 2 + Math.min(stringWidth2(text), MAX_LABEL));
3707
+ contentW = Math.max(contentW, placed[e.to].cx + 2 + Math.min(stringWidth(text), MAX_LABEL));
4260
3708
  }
4261
3709
  } else {
4262
3710
  const text = edgeText(e);
4263
3711
  if (text !== null) {
4264
- contentW = Math.max(contentW, diagramW + Math.min(stringWidth2(text), MAX_LABEL) + 1);
3712
+ contentW = Math.max(contentW, diagramW + Math.min(stringWidth(text), MAX_LABEL) + 1);
4265
3713
  }
4266
3714
  }
4267
3715
  }
@@ -4315,8 +3763,8 @@ function placeLr(ranks, maxRank, byRank, sizes, graph, placed) {
4315
3763
  return;
4316
3764
  if (ranks[e.to] !== ranks[e.from] + 1 && !edgeStraight[i])
4317
3765
  return;
4318
- const verb = e.label === null ? 0 : Math.min(stringWidth2(e.label), MAX_LABEL);
4319
- const cards = [e.cardFrom, e.cardTo].filter((c) => c !== void 0).reduce((w, c) => w + stringWidth2(c) + 1, 0);
3766
+ const verb = e.label === null ? 0 : Math.min(stringWidth(e.label), MAX_LABEL);
3767
+ const cards = [e.cardFrom, e.cardTo].filter((c) => c !== void 0).reduce((w, c) => w + stringWidth(c) + 1, 0);
4320
3768
  bandLabel[ranks[e.from]] = Math.max(bandLabel[ranks[e.from]], verb + cards);
4321
3769
  });
4322
3770
  const edgeBus = new Array(graph.edges.length).fill(0);
@@ -4427,10 +3875,10 @@ function layoutCanvas(graph, extras) {
4427
3875
  for (const row of byRank)
4428
3876
  row.sort((a, b) => Number(inLane[a]) - Number(inLane[b]));
4429
3877
  const wrapped = graph.nodes.map((node) => wrapLabel(node.label, WRAP_WIDTH, MAX_LINES));
4430
- const widest = (lines) => Math.max(1, lines.length === 0 ? 1 : Math.max(...lines.map(stringWidth2)));
3878
+ const widest = (lines) => Math.max(1, lines.length === 0 ? 1 : Math.max(...lines.map(stringWidth)));
4431
3879
  const boxW = extras.map((extra, i) => {
4432
3880
  if (extra.kind === "frame") {
4433
- return Math.max(extra.sub.w + 2, stringWidth2(fitLabel(graph.nodes[i].label, WRAP_WIDTH)) + 4);
3881
+ return Math.max(extra.sub.w + 2, stringWidth(fitLabel(graph.nodes[i].label, WRAP_WIDTH)) + 4);
4434
3882
  }
4435
3883
  if (extra.kind === "compartments")
4436
3884
  return widest(extra.sections.flat()) + 2 * PAD + 2;
@@ -4453,7 +3901,7 @@ function layoutCanvas(graph, extras) {
4453
3901
  extraH[e.from] = 2;
4454
3902
  const text = edgeText(e);
4455
3903
  if (text !== null) {
4456
- selfLabelW[e.from] = Math.max(selfLabelW[e.from], Math.min(stringWidth2(text), MAX_LABEL));
3904
+ selfLabelW[e.from] = Math.max(selfLabelW[e.from], Math.min(stringWidth(text), MAX_LABEL));
4457
3905
  }
4458
3906
  }
4459
3907
  for (let i = 0; i < n; i++)
@@ -4719,7 +4167,7 @@ function drawBox(canvas, p, lines, shape, mirrored = false) {
4719
4167
  const ordered = mirrored ? [...lines].reverse() : lines;
4720
4168
  ordered.forEach((line, li) => {
4721
4169
  const text = fitLabel(line, inner);
4722
- const textX = x + 1 + PAD + half(sat(inner, stringWidth2(text)));
4170
+ const textX = x + 1 + PAD + half(sat(inner, stringWidth(text)));
4723
4171
  drawText(canvas, text, textX, y + 1 + li, "text");
4724
4172
  });
4725
4173
  }
@@ -4745,7 +4193,7 @@ function drawClassBox(canvas, p, sections, mirrored = false) {
4745
4193
  canvas.set(x, row, "\u2500", "border");
4746
4194
  canvas.set(p.x + p.w - 1, row, "\u2524", "border");
4747
4195
  } else {
4748
- const tx = r.center ? p.x + 1 + PAD + half(sat(inner, stringWidth2(r.text))) : p.x + 1 + PAD;
4196
+ const tx = r.center ? p.x + 1 + PAD + half(sat(inner, stringWidth(r.text))) : p.x + 1 + PAD;
4749
4197
  drawTextOverEdges(canvas, r.text, tx, row, "text");
4750
4198
  }
4751
4199
  });
@@ -4795,7 +4243,7 @@ function routeForward(canvas, from, to, edge, bus, entryX = -1, labelLeft = fals
4795
4243
  canvas.set(bx, by, headGlyph(edge.headFrom, "\u25B2"), "edge");
4796
4244
  if (edge.cardFrom === void 0 && edge.cardTo === void 0) {
4797
4245
  if (edge.label !== null) {
4798
- const start = labelLeft ? sat(tx, Math.min(stringWidth2(edge.label), MAX_LABEL)) : tx + 1;
4246
+ const start = labelLeft ? sat(tx, Math.min(stringWidth(edge.label), MAX_LABEL)) : tx + 1;
4799
4247
  placeLabel(canvas, edge.label, headRow, start);
4800
4248
  }
4801
4249
  return;
@@ -4811,7 +4259,7 @@ function routeForward(canvas, from, to, edge, bus, entryX = -1, labelLeft = fals
4811
4259
  const lineX = midRow > bus ? tx : bx;
4812
4260
  placeLabel(canvas, edge.label, midRow, lineX + 1);
4813
4261
  } else {
4814
- placeLabel(canvas, edge.label, headRow, tx + 1 + (edge.cardTo === void 0 ? 0 : stringWidth2(edge.cardTo) + 1));
4262
+ placeLabel(canvas, edge.label, headRow, tx + 1 + (edge.cardTo === void 0 ? 0 : stringWidth(edge.cardTo) + 1));
4815
4263
  }
4816
4264
  }
4817
4265
  }
@@ -4880,7 +4328,7 @@ function routeSkip(canvas, from, to, edge, at) {
4880
4328
  canvas.set(bx, bottom, headGlyph(edge.headFrom, "\u25B2"), "edge");
4881
4329
  const text = edgeText(edge);
4882
4330
  if (text !== null) {
4883
- const start = labelLeft ? sat(entryX, Math.min(stringWidth2(text), MAX_LABEL)) : entryX + 1;
4331
+ const start = labelLeft ? sat(entryX, Math.min(stringWidth(text), MAX_LABEL)) : entryX + 1;
4884
4332
  placeLabel(canvas, text, to.y - 1, start);
4885
4333
  }
4886
4334
  }
@@ -4901,7 +4349,7 @@ function routeBack(canvas, from, to, edge, laneX) {
4901
4349
  else
4902
4350
  canvas.set(tx + 1, tyc, headGlyph(edge.headTo, "\u25C4"), "edge");
4903
4351
  if (backText !== null) {
4904
- placeLabel(canvas, backText, sat(tyc, 1), sat(laneX, stringWidth2(backText) + 1));
4352
+ placeLabel(canvas, backText, sat(tyc, 1), sat(laneX, stringWidth(backText) + 1));
4905
4353
  }
4906
4354
  }
4907
4355
  function routeForwardLr(canvas, from, to, edge, bus) {
@@ -4928,7 +4376,7 @@ function routeForwardLr(canvas, from, to, edge, bus) {
4928
4376
  if (edge.cardFrom !== void 0)
4929
4377
  placeLabel(canvas, edge.cardFrom, sat(ry, 1), rx + 1);
4930
4378
  if (edge.cardTo !== void 0) {
4931
- placeLabel(canvas, edge.cardTo, sat(ly, 1), sat(headCol, stringWidth2(edge.cardTo)));
4379
+ placeLabel(canvas, edge.cardTo, sat(ly, 1), sat(headCol, stringWidth(edge.cardTo)));
4932
4380
  }
4933
4381
  }
4934
4382
  function routeSkipLr(canvas, from, to, edge, bus) {
@@ -4978,7 +4426,7 @@ function routeBackLr(canvas, from, to, edge, laneY, laneLabels) {
4978
4426
  }
4979
4427
  function placeLaneLabels(canvas, labels) {
4980
4428
  for (const { text, y, lo, hi } of labels) {
4981
- const tw = stringWidth2(text);
4429
+ const tw = stringWidth(text);
4982
4430
  const lastStart = hi - 1 - tw;
4983
4431
  if (lastStart < lo + 1 || y >= canvas.h)
4984
4432
  continue;
@@ -5488,10 +4936,10 @@ function parseEr(src) {
5488
4936
  }
5489
4937
  const rel = splitErRelationship(st);
5490
4938
  if (rel) {
5491
- const tokens = erTokens(rel.rel);
5492
- const op = tokens.length === 3 ? parseErOp(tokens[1]) : null;
5493
- const f = op === null ? null : erEntity(graph, tokens[0]);
5494
- const t2 = f === null ? null : erEntity(graph, tokens[2]);
4939
+ const tokens2 = erTokens(rel.rel);
4940
+ const op = tokens2.length === 3 ? parseErOp(tokens2[1]) : null;
4941
+ const f = op === null ? null : erEntity(graph, tokens2[0]);
4942
+ const t2 = f === null ? null : erEntity(graph, tokens2[2]);
5495
4943
  if (op === null || f === null || t2 === null) {
5496
4944
  graph.drop(st);
5497
4945
  } else {
@@ -6076,7 +5524,7 @@ var gitgraph = {
6076
5524
  parts.push([`\u21D0 ${branches[c.mergeFrom]}`, "edgeLabel"]);
6077
5525
  return parts;
6078
5526
  });
6079
- const width = graphW + Math.max(1, ...labels.map((parts) => parts === null ? 0 : parts.reduce((w, [t2]) => w + stringWidth2(t2) + 1, 0) - 1));
5527
+ const width = graphW + Math.max(1, ...labels.map((parts) => parts === null ? 0 : parts.reduce((w, [t2]) => w + stringWidth(t2) + 1, 0) - 1));
6080
5528
  const canvas = new Canvas(width, rows.length);
6081
5529
  const live = /* @__PURE__ */ new Set();
6082
5530
  rows.forEach((row, y) => {
@@ -6091,7 +5539,7 @@ var gitgraph = {
6091
5539
  let x = graphW;
6092
5540
  for (const [text, role] of labels[y] ?? []) {
6093
5541
  drawText(canvas, text, x, y, role);
6094
- x += stringWidth2(text) + 1;
5542
+ x += stringWidth(text) + 1;
6095
5543
  }
6096
5544
  return;
6097
5545
  }
@@ -6222,11 +5670,11 @@ var mindmap = {
6222
5670
  };
6223
5671
  for (const root of roots)
6224
5672
  walk(root, "", "");
6225
- const width = Math.max(...rows.map(([p, t2]) => stringWidth2(p) + stringWidth2(t2)));
5673
+ const width = Math.max(...rows.map(([p, t2]) => stringWidth(p) + stringWidth(t2)));
6226
5674
  const canvas = new Canvas(width, rows.length);
6227
5675
  rows.forEach(([prefix, text], y) => {
6228
5676
  drawText(canvas, prefix, 0, y, "edge");
6229
- drawText(canvas, text, stringWidth2(prefix), y, "text");
5677
+ drawText(canvas, text, stringWidth(prefix), y, "text");
6230
5678
  });
6231
5679
  return { canvas, warnings, classDefs: {} };
6232
5680
  }
@@ -6301,7 +5749,7 @@ var pie = {
6301
5749
  if (parsed === null)
6302
5750
  return null;
6303
5751
  const { title, slices, showData, warnings } = parsed;
6304
- const labelW = Math.max(...slices.map((s) => stringWidth2(s.label)));
5752
+ const labelW = Math.max(...slices.map((s) => stringWidth(s.label)));
6305
5753
  const total = slices.reduce((sum, s) => sum + s.value, 0);
6306
5754
  const rows = slices.map((s) => {
6307
5755
  const share = total === 0 ? 0 : s.value / total;
@@ -6311,11 +5759,11 @@ var pie = {
6311
5759
  });
6312
5760
  const barX = labelW + 2;
6313
5761
  const suffixX = barX + BAR_W + 1;
6314
- const width = suffixX + Math.max(...rows.map((r) => stringWidth2(r.suffix)));
5762
+ const width = suffixX + Math.max(...rows.map((r) => stringWidth(r.suffix)));
6315
5763
  const top = title === null ? 0 : 1;
6316
5764
  const canvas = new Canvas(width, top + rows.length);
6317
5765
  if (title !== null) {
6318
- drawText(canvas, title, Math.max(0, Math.floor((width - stringWidth2(title)) / 2)), 0, "title");
5766
+ drawText(canvas, title, Math.max(0, Math.floor((width - stringWidth(title)) / 2)), 0, "title");
6319
5767
  }
6320
5768
  rows.forEach((r, i) => {
6321
5769
  const y = top + i;
@@ -6325,7 +5773,7 @@ var pie = {
6325
5773
  if (bar === "" && r.value > 0)
6326
5774
  bar = "\u258F";
6327
5775
  drawText(canvas, bar, barX, y, "edge");
6328
- drawText(canvas, "\u2591".repeat(BAR_W - stringWidth2(bar)), barX + stringWidth2(bar), y, "border");
5776
+ drawText(canvas, "\u2591".repeat(BAR_W - stringWidth(bar)), barX + stringWidth(bar), y, "border");
6329
5777
  drawText(canvas, r.suffix, suffixX, y, "edgeLabel");
6330
5778
  });
6331
5779
  return { canvas, warnings, classDefs: {} };
@@ -6389,11 +5837,11 @@ function noteGeometry(xs, anchor, textW) {
6389
5837
  return { x: sat(xs[anchor.at], 2 + w - 1), w };
6390
5838
  return { x: xs[anchor.at] + 2, w };
6391
5839
  }
6392
- var itemTextW = (text) => text === null ? 0 : stringWidth2(text);
5840
+ var itemTextW = (text) => text === null ? 0 : stringWidth(text);
6393
5841
  function layoutSequence(seq) {
6394
5842
  const n = seq.labels.length;
6395
5843
  const labels = seq.labels.map((l) => fitLabel(l, WRAP_WIDTH));
6396
- const boxW = labels.map((l) => Math.max(1, stringWidth2(l)) + 2 * PAD + 2);
5844
+ const boxW = labels.map((l) => Math.max(1, stringWidth(l)) + 2 * PAD + 2);
6397
5845
  const boxH = 3;
6398
5846
  const gaps = Array.from({ length: sat(n, 1) }, (_, i) => Math.max(SEQ_GAP, Math.ceil(boxW[i] / 2) + Math.ceil(boxW[i + 1] / 2) + 1));
6399
5847
  const reqs = [];
@@ -6406,7 +5854,7 @@ function layoutSequence(seq) {
6406
5854
  reqs.push([item.from, item.from + 1, 5 + tw + 2]);
6407
5855
  }
6408
5856
  } else if (item.kind === "note") {
6409
- const tw = stringWidth2(item.text);
5857
+ const tw = stringWidth(item.text);
6410
5858
  const a = item.anchor;
6411
5859
  if (a.kind === "over" && a.from < a.to) {
6412
5860
  reqs.push([a.from, a.to, sat(tw, 1)]);
@@ -6438,7 +5886,7 @@ function layoutSequence(seq) {
6438
5886
  let leftPad = 0;
6439
5887
  for (const item of seq.items) {
6440
5888
  if (item.kind === "note" && item.anchor.kind === "left" && item.anchor.at === 0) {
6441
- const w = stringWidth2(item.text) + 2 * PAD + 2;
5889
+ const w = stringWidth(item.text) + 2 * PAD + 2;
6442
5890
  leftPad = Math.max(leftPad, sat(w + 1, xs[0]));
6443
5891
  }
6444
5892
  }
@@ -6450,10 +5898,10 @@ function layoutSequence(seq) {
6450
5898
  if (item.kind === "message" && item.from === item.to) {
6451
5899
  canvasW = Math.max(canvasW, xs[item.from] + 5 + itemTextW(item.text) + 1);
6452
5900
  } else if (item.kind === "note") {
6453
- const g = noteGeometry(xs, item.anchor, stringWidth2(item.text));
5901
+ const g = noteGeometry(xs, item.anchor, stringWidth(item.text));
6454
5902
  canvasW = Math.max(canvasW, g.x + g.w + 1);
6455
5903
  } else if (item.kind === "divider") {
6456
- canvasW = Math.max(canvasW, stringWidth2(item.text) + 4);
5904
+ canvasW = Math.max(canvasW, stringWidth(item.text) + 4);
6457
5905
  }
6458
5906
  }
6459
5907
  const rows = [];
@@ -6475,7 +5923,7 @@ function layoutSequence(seq) {
6475
5923
  seq.items.forEach((item, k) => {
6476
5924
  if (item.kind !== "note")
6477
5925
  return;
6478
- const g = noteGeometry(xs, item.anchor, stringWidth2(item.text));
5926
+ const g = noteGeometry(xs, item.anchor, stringWidth(item.text));
6479
5927
  drawBox(canvas, box(g.x, rows[k], g.w, 3), [item.text], "rect");
6480
5928
  });
6481
5929
  for (const x of xs) {
@@ -6558,7 +6006,7 @@ function drawMessage(canvas, item, xs, r) {
6558
6006
  if (item.text !== null) {
6559
6007
  const span = hi - lo - 1;
6560
6008
  const t2 = fitLabel(item.text, Math.max(1, span));
6561
- drawTextOverEdges(canvas, t2, lo + 1 + half(sat(span, stringWidth2(t2))), r, "text");
6009
+ drawTextOverEdges(canvas, t2, lo + 1 + half(sat(span, stringWidth(t2))), r, "text");
6562
6010
  }
6563
6011
  }
6564
6012
  function drawDivider(canvas, text, r, canvasW) {
@@ -7058,16 +6506,16 @@ var timeline = {
7058
6506
  if (parsed === null)
7059
6507
  return null;
7060
6508
  const { title, rows, warnings } = parsed;
7061
- const periodW = Math.max(...rows.map((r) => r.section ? 0 : stringWidth2(r.period)));
6509
+ const periodW = Math.max(...rows.map((r) => r.section ? 0 : stringWidth(r.period)));
7062
6510
  const top = title === null ? 0 : 1;
7063
- const width = Math.max(title === null ? 0 : stringWidth2(title) + 6, ...rows.map((r) => r.section ? stringWidth2(r.event) : periodW + 3 + stringWidth2(r.event)));
6511
+ const width = Math.max(title === null ? 0 : stringWidth(title) + 6, ...rows.map((r) => r.section ? stringWidth(r.event) : periodW + 3 + stringWidth(r.event)));
7064
6512
  const canvas = new Canvas(width, top + rows.length);
7065
6513
  if (title !== null) {
7066
6514
  const t2 = ` ${title} `;
7067
- const x = Math.max(0, Math.floor((width - stringWidth2(t2) - 4) / 2));
6515
+ const x = Math.max(0, Math.floor((width - stringWidth(t2) - 4) / 2));
7068
6516
  drawText(canvas, "\u2500\u2500", x, 0, "edge");
7069
6517
  drawText(canvas, t2, x + 2, 0, "title");
7070
- drawText(canvas, "\u2500\u2500", x + 2 + stringWidth2(t2), 0, "edge");
6518
+ drawText(canvas, "\u2500\u2500", x + 2 + stringWidth(t2), 0, "edge");
7071
6519
  }
7072
6520
  rows.forEach((row, i) => {
7073
6521
  const y = top + i;
@@ -7394,11 +6842,11 @@ function sourceBox(src, maxWidth) {
7394
6842
  acc.lines.push(...chunkLine(l, limit));
7395
6843
  return acc;
7396
6844
  }, { started: false, lines: [] }).lines;
7397
- const contentW = body.reduce((w, l) => Math.max(w, stringWidth2(l)), stringWidth2(title));
6845
+ const contentW = body.reduce((w, l) => Math.max(w, stringWidth(l)), stringWidth(title));
7398
6846
  const inner = contentW + 2;
7399
6847
  const plain = [];
7400
6848
  const styled = [];
7401
- const rule = "\u2500".repeat(sat(inner, stringWidth2(title)));
6849
+ const rule = "\u2500".repeat(sat(inner, stringWidth(title)));
7402
6850
  plain.push(`\u256D${title}${rule}\u256E`);
7403
6851
  styled.push([
7404
6852
  { text: "\u256D", role: "border" },
@@ -7406,7 +6854,7 @@ function sourceBox(src, maxWidth) {
7406
6854
  { text: `${rule}\u256E`, role: "border" }
7407
6855
  ]);
7408
6856
  for (const line of body) {
7409
- const pad = " ".repeat(sat(contentW, stringWidth2(line)));
6857
+ const pad = " ".repeat(sat(contentW, stringWidth(line)));
7410
6858
  plain.push(`\u2502 ${line}${pad} \u2502`);
7411
6859
  styled.push([
7412
6860
  { text: "\u2502 ", role: "border" },
@@ -7437,7 +6885,7 @@ function expandTabs(line) {
7437
6885
  return out;
7438
6886
  }
7439
6887
  function chunkLine(line, limit) {
7440
- if (limit === void 0 || stringWidth2(line) <= limit)
6888
+ if (limit === void 0 || stringWidth(line) <= limit)
7441
6889
  return [line];
7442
6890
  const out = [];
7443
6891
  let cur = "";
@@ -7467,7 +6915,7 @@ function render(src) {
7467
6915
  const art = drawn.canvas.toLines();
7468
6916
  const title = frontmatterTitle(src);
7469
6917
  if (title !== null) {
7470
- const tw = stringWidth2(title);
6918
+ const tw = stringWidth(title);
7471
6919
  art.width = Math.max(art.width, tw);
7472
6920
  const pad = " ".repeat(Math.floor((art.width - tw) / 2));
7473
6921
  art.plain.unshift(pad + title, "");
@@ -7936,7 +7384,7 @@ function renderMathBlock(latex, options = {}) {
7936
7384
  const den = transpileLatexToUnicode(fracMatch[2] ?? "");
7937
7385
  if (num.length > 8 || den.length > 8 || num.includes("+") || den.includes("+") || num.includes("-") || den.includes("-")) {
7938
7386
  const width = Math.max(visibleWidth(num), visibleWidth(den)) + 2;
7939
- const bar = "\u2500".repeat(width);
7387
+ const bar = boxGlyphs(resolveBoxCharset()).h.repeat(width);
7940
7388
  const padNum = " ".repeat(Math.max(0, Math.floor((width - visibleWidth(num)) / 2)));
7941
7389
  const padDen = " ".repeat(Math.max(0, Math.floor((width - visibleWidth(den)) / 2)));
7942
7390
  const l1 = padNum + num;
@@ -8183,21 +7631,21 @@ function resolveTableWidth(explicit, env = process.env) {
8183
7631
  }
8184
7632
  function wrapCellToWidth(text, max) {
8185
7633
  if (max <= 0 || displayWidth(text) <= max) return [text];
8186
- const tokens = tokenizeAnsiLine(text);
7634
+ const tokens2 = tokenizeAnsiLine(text);
8187
7635
  const charTokenIdx = [];
8188
- tokens.forEach((t2, i) => {
7636
+ tokens2.forEach((t2, i) => {
8189
7637
  if (t2.kind === "char") charTokenIdx.push(i);
8190
7638
  });
8191
7639
  const n = charTokenIdx.length;
8192
7640
  if (n === 0) return [text];
8193
- const widths = charTokenIdx.map((i) => tokens[i].width);
7641
+ const widths = charTokenIdx.map((i) => tokens2[i].width);
8194
7642
  const prefix = [0];
8195
7643
  for (let i = 0; i < widths.length; i += 1) prefix.push(prefix[i] + widths[i]);
8196
7644
  const segWidth = (a, b) => prefix[b] - prefix[a];
8197
7645
  const sliceTokens = (a, b) => {
8198
7646
  const startTok = a === 0 ? 0 : charTokenIdx[a - 1] + 1;
8199
- const endTok = b < n ? charTokenIdx[b] - 1 : tokens.length - 1;
8200
- return tokens.slice(startTok, endTok + 1);
7647
+ const endTok = b < n ? charTokenIdx[b] - 1 : tokens2.length - 1;
7648
+ return tokens2.slice(startTok, endTok + 1);
8201
7649
  };
8202
7650
  const applyStyles = (slice, state2) => {
8203
7651
  const next = [...state2];
@@ -8212,7 +7660,7 @@ function wrapCellToWidth(text, max) {
8212
7660
  }
8213
7661
  } else if (OSC8_OPENER_REGEX.test(t2.value)) {
8214
7662
  next.push(t2.value);
8215
- } else if (SGR_RESET_REGEX2.test(t2.value)) {
7663
+ } else if (SGR_RESET_REGEX.test(t2.value)) {
8216
7664
  for (let i = next.length - 1; i >= 0; i -= 1) {
8217
7665
  if (!OSC8_OPENER_REGEX.test(next[i]) && !OSC8_CLOSER_REGEX.test(next[i])) {
8218
7666
  next.splice(i, 1);
@@ -8244,7 +7692,7 @@ function wrapCellToWidth(text, max) {
8244
7692
  if (segWidth(start, i + 1) <= max) continue;
8245
7693
  let cut = -1;
8246
7694
  for (let j = i - 1; j > start; j -= 1) {
8247
- if (tokens[charTokenIdx[j]].value !== " ") continue;
7695
+ if (tokens2[charTokenIdx[j]].value !== " ") continue;
8248
7696
  if (segWidth(start, j) <= max && segWidth(j + 1, i + 1) <= max) {
8249
7697
  cut = j;
8250
7698
  break;
@@ -8275,7 +7723,7 @@ function wrapCellToWidth(text, max) {
8275
7723
  }
8276
7724
  return segments.length > 0 ? segments : [text];
8277
7725
  }
8278
- var SGR_RESET_REGEX2 = /^\x1b\[0?m$/;
7726
+ var SGR_RESET_REGEX = /^\x1b\[0?m$/;
8279
7727
  var OSC8_OPENER_REGEX = /^\x1b\]8;;[^\x07\x1b]+(?:\x07|\x1b\\)$/;
8280
7728
  var OSC8_CLOSER_REGEX = /^\x1b\]8;;\x1b\\$/;
8281
7729
  function padCell(text, width, align) {
@@ -8330,21 +7778,22 @@ function makeStyle(brightness, headerToken) {
8330
7778
  const paint = (t2) => `${color}${boldOn}${t2}${reset}`;
8331
7779
  return { header: paint, label: paint };
8332
7780
  }
8333
- function boxLine(left, mid, right, widths) {
8334
- const seg = widths.map((w) => "\u2500".repeat(w + 2));
7781
+ function boxLine(glyphs, left, mid, right, widths) {
7782
+ const seg = widths.map((w) => glyphs.h.repeat(w + 2));
8335
7783
  return `${left}${seg.join(mid)}${right}`;
8336
7784
  }
8337
- function dataRow(cells, aligns, widths, style, header) {
7785
+ function dataRow(cells, aligns, widths, style, header, glyphs) {
8338
7786
  const parts = cells.map((cell, i) => {
8339
7787
  const width = widths[i] ?? 0;
8340
7788
  const align = aligns[i] ?? "left";
8341
7789
  const padded = padCell(cell, width, align);
8342
7790
  const styled = header ? style.header(padded) : padded;
8343
- return ` ${styled} \u2502`;
7791
+ return ` ${styled} ${glyphs.v}`;
8344
7792
  });
8345
- return `\u2502${parts.join("")}`;
7793
+ return `${glyphs.v}${parts.join("")}`;
8346
7794
  }
8347
- function renderBoxTable(table, width, style) {
7795
+ function renderBoxTable(table, width, style, charset = resolveBoxCharset()) {
7796
+ const glyphs = boxGlyphs(charset);
8348
7797
  const colCount = table.headers.length;
8349
7798
  const widths = computeColumnWidths(table.headers, table.rows, width);
8350
7799
  const headerGrid = table.headers.map(
@@ -8358,7 +7807,7 @@ function renderBoxTable(table, width, style) {
8358
7807
  (r) => Math.max(1, ...r.map((g) => g.length))
8359
7808
  );
8360
7809
  const lines = [];
8361
- lines.push(boxLine("\u250C", "\u252C", "\u2510", widths));
7810
+ lines.push(boxLine(glyphs, glyphs.tl, glyphs.tm, glyphs.tr, widths));
8362
7811
  for (let r = 0; r < headerDisplayRows; r += 1) {
8363
7812
  lines.push(
8364
7813
  dataRow(
@@ -8366,15 +7815,16 @@ function renderBoxTable(table, width, style) {
8366
7815
  table.aligns,
8367
7816
  widths,
8368
7817
  style,
8369
- true
7818
+ true,
7819
+ glyphs
8370
7820
  )
8371
7821
  );
8372
7822
  }
8373
- lines.push(boxLine("\u251C", "\u253C", "\u2524", widths));
7823
+ lines.push(boxLine(glyphs, glyphs.ml, glyphs.mm, glyphs.mr, widths));
8374
7824
  const hasMultiLineRecord = bodyDisplayRows.some((rows) => rows > 1);
8375
7825
  bodyGrids.forEach((_, rec) => {
8376
7826
  if (hasMultiLineRecord && rec > 0) {
8377
- lines.push(boxLine("\u251C", "\u253C", "\u2524", widths));
7827
+ lines.push(boxLine(glyphs, glyphs.ml, glyphs.mm, glyphs.mr, widths));
8378
7828
  }
8379
7829
  for (let r = 0; r < bodyDisplayRows[rec]; r += 1) {
8380
7830
  lines.push(
@@ -8386,12 +7836,13 @@ function renderBoxTable(table, width, style) {
8386
7836
  table.aligns,
8387
7837
  widths,
8388
7838
  style,
8389
- false
7839
+ false,
7840
+ glyphs
8390
7841
  )
8391
7842
  );
8392
7843
  }
8393
7844
  });
8394
- lines.push(boxLine("\u2514", "\u2534", "\u2518", widths));
7845
+ lines.push(boxLine(glyphs, glyphs.bl, glyphs.bm, glyphs.br, widths));
8395
7846
  return lines.join("\n");
8396
7847
  }
8397
7848
  function renderRecordCards(table, width, style) {
@@ -8435,7 +7886,12 @@ function renderMarkdownTable(table, options = {}) {
8435
7886
  if (width < 40 || table.headers.length > 6) {
8436
7887
  return renderRecordCards(styledTable, width, style);
8437
7888
  }
8438
- return renderBoxTable(styledTable, width, style);
7889
+ return renderBoxTable(
7890
+ styledTable,
7891
+ width,
7892
+ style,
7893
+ options.boxCharset ?? resolveBoxCharset()
7894
+ );
8439
7895
  }
8440
7896
 
8441
7897
  // packages/cli/client/assistantOutput.ts
@@ -8684,11 +8140,10 @@ function normalizeListLine(line) {
8684
8140
  }
8685
8141
  return line;
8686
8142
  }
8687
- var TOOL_TREE_HEADER_RE = /^•\s+(.+?)\s+\((\d+)\)$/;
8688
- var TOOL_TREE_LEAF_RE = /^([├└]──\s+)(.*?)\s{2}(✓|✗|!)(?:\s+(.*))?$/;
8143
+ var TOOL_TREE_HEADER_RE = /^•\s+(.+?)\s+\((\d+)\) · (.*?) ✓$/;
8689
8144
  var TOOL_SINGLE_RE = /^▸\s+(.+?)(?:\s+·\s+(.*?))?(?:\s{2}(✓|✗|!)(?:\s+(.*))?)$/;
8690
8145
  function plainToolLine(line) {
8691
- return stripAnsi2(line);
8146
+ return stripAnsi(line);
8692
8147
  }
8693
8148
  var TOOL_TREE_GROUP_LABELS = new Set(
8694
8149
  ["execShell", "readFile", "fetchWebpage", "exa_search"].flatMap(toolLabelVariants)
@@ -8703,9 +8158,6 @@ function toolTreeHeaderMatch(line) {
8703
8158
  function isToolTreeHeaderLine(line) {
8704
8159
  return toolTreeHeaderMatch(line) !== null;
8705
8160
  }
8706
- function isToolTreeLeafLine(line) {
8707
- return TOOL_TREE_LEAF_RE.test(plainToolLine(line));
8708
- }
8709
8161
  function isToolSingleLine(line) {
8710
8162
  return TOOL_SINGLE_RE.test(plainToolLine(line));
8711
8163
  }
@@ -8724,17 +8176,10 @@ function toolGroupKeyOf(line) {
8724
8176
  return null;
8725
8177
  }
8726
8178
  function toolRowBoundary(cur, next) {
8727
- const curLeaf = isToolTreeLeafLine(cur);
8728
- const curHeader = isToolTreeHeaderLine(cur);
8729
- const nextLeaf = isToolTreeLeafLine(next);
8730
8179
  const curKey = toolGroupKeyOf(cur);
8731
8180
  const nextKey = toolGroupKeyOf(next);
8732
- if (curKey === null && !curLeaf) return null;
8733
- if (nextKey === null && !nextLeaf) return null;
8734
- if (curLeaf) return !nextLeaf;
8735
- if (curHeader && nextLeaf) return false;
8736
- if (curKey !== null && nextKey !== null) return curKey !== nextKey;
8737
- return true;
8181
+ if (curKey === null || nextKey === null) return null;
8182
+ return isToolTreeHeaderLine(cur) || isToolTreeHeaderLine(next) || curKey !== nextKey;
8738
8183
  }
8739
8184
  function statusColorSeq(marker, brightness) {
8740
8185
  if (marker === "\u2713") return colorSeq("success", brightness);
@@ -8747,18 +8192,7 @@ function styleTuiToolLine(line, brightness) {
8747
8192
  const muted = colorSeq("muted", brightness);
8748
8193
  const header = toolTreeHeaderMatch(plain);
8749
8194
  if (header) {
8750
- return `${chrome}\u2022${STYLE.reset} ${STYLE.bold}${muted}${header[1]}${STYLE.reset} ${chrome}${STYLE.dim}(${header[2]})${STYLE.reset}`;
8751
- }
8752
- const leaf = plain.match(TOOL_TREE_LEAF_RE);
8753
- if (leaf) {
8754
- const [, connector, detail, marker, statusDetail] = leaf;
8755
- let rendered = `${chrome}${connector}${STYLE.reset}${chrome}${detail}${STYLE.reset}`;
8756
- rendered += ` ${statusColorSeq(marker, brightness)}${marker}${STYLE.reset}`;
8757
- if (statusDetail) {
8758
- const metaSeq = marker === "\u2713" ? chrome : statusColorSeq(marker, brightness);
8759
- rendered += ` ${metaSeq}${STYLE.dim}${statusDetail}${STYLE.reset}`;
8760
- }
8761
- return rendered;
8195
+ return `${chrome}\u2022${STYLE.reset} ${STYLE.bold}${muted}${header[1]}${STYLE.reset} ${chrome}${STYLE.dim}(${header[2]})${STYLE.reset} ${chrome}\xB7 ${header[3]}${STYLE.reset} ${statusColorSeq("\u2713", brightness)}\u2713${STYLE.reset}`;
8762
8196
  }
8763
8197
  const single = plain.match(TOOL_SINGLE_RE);
8764
8198
  if (single) {
@@ -8782,14 +8216,14 @@ function isPolishFenceInteriorLine(line) {
8782
8216
  return /^\x00F\d+\x00$/.test(line);
8783
8217
  }
8784
8218
  function polishHeadingLevel(line) {
8785
- const match = stripAnsi2(line).match(/^(#{1,6})\s/);
8219
+ const match = stripAnsi(line).match(/^(#{1,6})\s/);
8786
8220
  return match ? match[1].length : null;
8787
8221
  }
8788
8222
  function isPolishHeadingLine(line) {
8789
8223
  return polishHeadingLevel(line) !== null;
8790
8224
  }
8791
8225
  function isPolishIntroLine(line) {
8792
- const plain = stripAnsi2(line).trimEnd();
8226
+ const plain = stripAnsi(line).trimEnd();
8793
8227
  return plain.endsWith("\uFF1A") || plain.endsWith(":");
8794
8228
  }
8795
8229
  function polishBreathInsertsBlankBetween(cur, next) {
@@ -8917,7 +8351,7 @@ function styleRichMarkdownLine(line, brightness) {
8917
8351
  return `${border}\u2502${STYLE.reset} ${STYLE.dim}${styled}${STYLE.reset}`;
8918
8352
  }
8919
8353
  if (THEMATIC_BREAK_RE.test(line)) {
8920
- return `${colorSeq("chrome", brightness)}${STYLE.dim}${"\u2500".repeat(36)}${STYLE.reset}`;
8354
+ return `${colorSeq("chrome", brightness)}${STYLE.dim}${boxGlyphs(resolveBoxCharset()).h.repeat(36)}${STYLE.reset}`;
8921
8355
  }
8922
8356
  const bullet = line.match(/^(\s*)(•)\s(.+)$/);
8923
8357
  if (bullet) {
@@ -9091,7 +8525,6 @@ function classifyStreamLine(line) {
9091
8525
  if (line === "") return "blank";
9092
8526
  const plain = plainToolLine(line);
9093
8527
  if (isToolTreeHeaderLine(plain)) return "tool-header";
9094
- if (isToolTreeLeafLine(plain)) return "tool-leaf";
9095
8528
  if (isToolSingleLine(plain)) return "tool";
9096
8529
  if (TASK_LIST_RE.test(plain) || UNORDERED_LIST_RE.test(plain) || ORDERED_LIST_RE.test(plain) || /^\s*(?:•|◦|☐|☑)\s/.test(plain) || /^\s*[\u2460-\u2473]/.test(plain)) {
9097
8530
  return "list";
@@ -9101,10 +8534,10 @@ function classifyStreamLine(line) {
9101
8534
  return "prose";
9102
8535
  }
9103
8536
  function isStreamToolKind(kind) {
9104
- return kind === "tool-header" || kind === "tool-leaf" || kind === "tool";
8537
+ return kind === "tool-header" || kind === "tool";
9105
8538
  }
9106
8539
  function isStreamListLike(kind) {
9107
- return kind === "list" || kind === "tool-header" || kind === "tool-leaf" || kind === "tool";
8540
+ return kind === "list" || kind === "tool-header" || kind === "tool";
9108
8541
  }
9109
8542
  function needsListProseBreath(prev, next, prevLine = "", nextLine = "") {
9110
8543
  if (prev === null || prev === "blank" || next === "blank") return false;
@@ -9300,44 +8733,35 @@ function formatAssistantTextForCli(text) {
9300
8733
  return text.replace(/\u003cthink\u003e[\s\S]*?\u003c\/think\u003e\s*/gi, "").replace(/\n{3,}/g, "\n\n").trim();
9301
8734
  }
9302
8735
 
9303
- // packages/cli/tui/redactSecrets.ts
9304
- var REDACTED = "\u27E8redacted\u27E9";
9305
- function redactSecrets(text) {
9306
- return text.replace(/\b(?:sk|pk)-[A-Za-z0-9_-]{10,}/g, REDACTED).replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi, `$1${REDACTED}`).replace(
9307
- /\b((?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|credential)s?\s*[=:]\s*["']?)[^\s"',;]{8,}/gi,
9308
- `$1${REDACTED}`
9309
- ).replace(
9310
- /\b((?:--[a-z-]*(?:token|key|secret|password|credential)[a-z-]*)\s+)[^\s"']{8,}/gi,
9311
- `$1${REDACTED}`
9312
- );
9313
- }
9314
-
9315
- // packages/cli/tui/askTextSanitize.ts
9316
- var ASK_SECRET_PLACEHOLDER = "\u27E8redacted\u27E9";
9317
- var C0_C1_CONTROL_REGEX = /[\x00-\x1f\x7f-\x9f]/g;
9318
- var NORMAL_GIST_SECRET_PATTERNS = [
9319
- /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i,
9320
- /\bsk-(?:ant-)?(?:api)?[0-9a-zA-Z-]{10,}/,
9321
- /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/,
9322
- /\bxox[baprs]-[A-Za-z0-9-]{10,}/
9323
- ];
9324
- function withholdIfSecretLike(gist) {
9325
- if (!gist) return "";
9326
- if (findPotentialSecrets(gist).length > 0) return "";
9327
- if (NORMAL_GIST_SECRET_PATTERNS.some((pattern) => pattern.test(gist))) return "";
9328
- return gist;
9329
- }
9330
- function toText(value) {
9331
- return typeof value === "string" ? value : String(value ?? "");
9332
- }
9333
- function cleanAskText(value) {
9334
- return stripAnsi2(toText(value)).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").replace(C0_C1_CONTROL_REGEX, "").replace(/\s+/g, " ").trim();
8736
+ // packages/cli/tui/tuiLayout.ts
8737
+ var DEFAULT_TERMINAL_ROWS = 24;
8738
+ var DEFAULT_TERMINAL_COLUMNS = 80;
8739
+ var TUI_MARGIN_LEFT = 1;
8740
+ var TUI_MARGIN_RIGHT = 1;
8741
+ var TUI_MARGIN_RESPONSIVE_MIN_COLUMNS = 40;
8742
+ function resolveHistoryLayoutGeometry(columns) {
8743
+ const cols = Math.max(1, (columns ?? 0) > 0 ? columns : DEFAULT_TERMINAL_COLUMNS);
8744
+ if (cols <= TUI_MARGIN_RESPONSIVE_MIN_COLUMNS) {
8745
+ return {
8746
+ contentWidth: Math.max(1, cols - 1),
8747
+ marginLeft: 0,
8748
+ marginRight: 0
8749
+ };
8750
+ }
8751
+ const marginLeft = TUI_MARGIN_LEFT;
8752
+ const marginRight = TUI_MARGIN_RIGHT;
8753
+ const contentWidth = Math.max(1, cols - 1 - marginLeft - marginRight);
8754
+ return {
8755
+ contentWidth,
8756
+ marginLeft,
8757
+ marginRight
8758
+ };
9335
8759
  }
9336
- function safeAskText(value, max) {
9337
- const cleaned = redactSecrets(cleanAskText(value));
9338
- if (!cleaned) return "";
9339
- const guarded = withholdIfSecretLike(cleaned) || ASK_SECRET_PLACEHOLDER;
9340
- return max === void 0 ? guarded : clipCompactText(guarded, max, "\u2026");
8760
+ function resolveHistoryViewportHeight(terminalRows, composerRows, foregroundReservedRows = 0) {
8761
+ const rows = Math.max(1, terminalRows > 0 ? terminalRows : DEFAULT_TERMINAL_ROWS);
8762
+ const composer = Math.max(0, composerRows);
8763
+ const reserved = Math.max(0, foregroundReservedRows);
8764
+ return Math.max(0, rows - composer - reserved);
9341
8765
  }
9342
8766
 
9343
8767
  // node_modules/diff/libesm/diff/base.js
@@ -9686,9 +9110,6 @@ function formatConservativeActiveToolLabel(event) {
9686
9110
  function isRunToolName(name) {
9687
9111
  return name === "execShell" || name === "runCommand" || name === "launchProcess";
9688
9112
  }
9689
- function isReadToolName(name) {
9690
- return name === "readFile";
9691
- }
9692
9113
  function isFailedToolResult(event) {
9693
9114
  const exitCode = event.metadata?.exitCode;
9694
9115
  if (event.metadata?.actionGate) return false;
@@ -9880,7 +9301,7 @@ function formatToolTraceLine(text, colorEnabled, accent = "none") {
9880
9301
  return `${dimCliText(text, true)}
9881
9302
  `;
9882
9303
  }
9883
- var cleanUserText = (value) => stripAnsi2(value).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
9304
+ var cleanUserText = (value) => stripAnsi(value).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
9884
9305
  function renderRunCard(snapshot, opts) {
9885
9306
  const labels = agentRunCardLabels();
9886
9307
  const timing = { startedAt: snapshot.startedAt, finishedAt: snapshot.finishedAt };
@@ -9995,7 +9416,7 @@ function formatOrchestrationCardBlock(event, toolName, colorEnabled, opts) {
9995
9416
  const failed = event.type === "tool-error" || isFailedToolResult(event) || Boolean(event.metadata?.failed) || listFailed || /^Error:/i.test(rawDataStr.trim());
9996
9417
  if (failed) {
9997
9418
  const failureSnapshot = toolName === "startAgentRun" ? parseAgentRunEvent(event)?.snapshot : void 0;
9998
- const firstLine = stripAnsi2(failureSnapshot?.errorMessage || rawDataStr.trim().split("\n")[0] || event.summary || event.message || t("toolFailed"));
9419
+ const firstLine = stripAnsi(failureSnapshot?.errorMessage || rawDataStr.trim().split("\n")[0] || event.summary || event.message || t("toolFailed"));
9999
9420
  const message = clip(redactSecrets(firstLine), 96);
10000
9421
  if (!colorEnabled) {
10001
9422
  return `\u2717 ${rawLabel} ${message}
@@ -10007,8 +9428,24 @@ function formatOrchestrationCardBlock(event, toolName, colorEnabled, opts) {
10007
9428
  return `${cross} ${labelPart2} ${msgPart}
10008
9429
  `;
10009
9430
  }
9431
+ if (opts?.visibleRunIds && toolName === "startAgentRun") {
9432
+ const started = parseAgentRunEvent(event);
9433
+ const runId = started?.snapshot.runId;
9434
+ const startedStatus = started?.snapshot.status;
9435
+ if (started?.kind === "start" && typeof runId === "string" && runId.length > 0 && !started.snapshot.errorMessage && // 只认 core 定义的已知正常态。unknown/cancelling/not_found/未来新增状态
9436
+ // 都不算正常 → 保留回执。
9437
+ isAgentRunStatusNormal(startedStatus)) {
9438
+ let visible;
9439
+ try {
9440
+ visible = opts.visibleRunIds();
9441
+ } catch {
9442
+ visible = void 0;
9443
+ }
9444
+ if (visible?.has(runId)) return "";
9445
+ }
9446
+ }
10010
9447
  const parsedStart = toolName === "startAgentRun" ? parseAgentRunEvent(event) : null;
10011
- const startFailed = parsedStart && ["failed", "timeout", "orphaned", "cancelled", "killed"].includes(parsedStart.snapshot.status);
9448
+ const startFailed = parsedStart && isAgentRunStartFailureStatus(parsedStart.snapshot.status);
10012
9449
  let heading = parsedStart ? t(startFailed ? "agentStartFailedLabel" : "agentStartedLabel") : rawLabel;
10013
9450
  const displayData = rawDataStr.trim();
10014
9451
  const lines = displayData ? displayData.split("\n") : [];
@@ -10021,7 +9458,13 @@ function formatOrchestrationCardBlock(event, toolName, colorEnabled, opts) {
10021
9458
  heading = t("agentsCompactCount", String(total));
10022
9459
  if (total !== count) heading += ` \xB7 ${t("agentsPageCount", String(count))}`;
10023
9460
  if (listPayload.truncated === true) heading += ` \xB7 ${t("agentsTruncated")}`;
10024
- if (/^(?:Agents|智能体)\s*\(\d+\)$/.test(projected[0]?.trim() ?? "")) {
9461
+ if (/^(?:Agents|智能体|🤖)\s*\(\d+\)$/.test(projected[0]?.trim() ?? "")) {
9462
+ projected = projected.slice(1);
9463
+ }
9464
+ } else {
9465
+ const bakedHeader = /^(?:Agents|智能体|🤖)\s*\((\d+)\)$/.exec(projected[0]?.trim() ?? "");
9466
+ if (bakedHeader) {
9467
+ heading = t("agentsCompactCount", bakedHeader[1]);
10025
9468
  projected = projected.slice(1);
10026
9469
  }
10027
9470
  }
@@ -10064,7 +9507,7 @@ function sanitizeRunCardForNormal(lines) {
10064
9507
  break;
10065
9508
  }
10066
9509
  if (/^\s*error\b/i.test(line)) {
10067
- out.push(clip(redactSecrets(stripAnsi2(line)), 160));
9510
+ out.push(clip(redactSecrets(stripAnsi(line)), 160));
10068
9511
  errorIndent = line.length - line.trimStart().length;
10069
9512
  continue;
10070
9513
  }
@@ -10297,7 +9740,7 @@ function formatNormalToolDuration(elapsedMs) {
10297
9740
  if (elapsedMs < 1e3) return `${Math.round(elapsedMs)}ms`;
10298
9741
  return `${(elapsedMs / 1e3).toFixed(1)}s`;
10299
9742
  }
10300
- function formatNormalToolLine(event, pending, colorEnabled) {
9743
+ function formatNormalToolLine(event, pending, colorEnabled, opts) {
10301
9744
  if (event.type === "tool-call") return "";
10302
9745
  const toolName = event.toolName || pending?.toolName || "tool";
10303
9746
  if (event.type === "tool-result" && (event.toolName === "ask_user" || event.metadata?.uiAskChoice)) {
@@ -10305,7 +9748,10 @@ function formatNormalToolLine(event, pending, colorEnabled) {
10305
9748
  if (block) return block;
10306
9749
  }
10307
9750
  if (event.type === "tool-result" && (toolName === "listAgents" || toolName === "startAgentRun" || toolName === "controlAgentRun")) {
10308
- return formatOrchestrationCardBlock(event, toolName, colorEnabled, { safe: true });
9751
+ return formatOrchestrationCardBlock(event, toolName, colorEnabled, {
9752
+ safe: true,
9753
+ visibleRunIds: opts?.visibleRunIds
9754
+ });
10309
9755
  }
10310
9756
  if (event.type === "tool-result" && toolName === "loadSkill") {
10311
9757
  return formatLoadSkillBlock({ ...event, argumentsPreview: event.argumentsPreview || pending?.argumentsPreview }, colorEnabled, { safe: true }) ?? "";
@@ -10353,7 +9799,7 @@ function toolFailureReason(event) {
10353
9799
  return lines.slice(start + 1, end < 0 ? lines.length : end);
10354
9800
  };
10355
9801
  const reasonLine = sectionLines("stderr")[0] ?? sectionLines("stdout")[0] ?? lines.find((line) => !/^(stdout|stderr|exitCode)\s*:/i.test(line)) ?? lines[0] ?? "";
10356
- return reasonLine ? clip(redactSecrets(stripAnsi2(reasonLine)), 96) : "";
9802
+ return reasonLine ? clip(redactSecrets(stripAnsi(reasonLine)), 96) : "";
10357
9803
  }
10358
9804
  function resolveLoadSkillName(event) {
10359
9805
  const content = typeof event.content === "string" ? event.content : "";
@@ -10419,14 +9865,34 @@ function formatLoadSkillBlock(event, colorEnabled, opts) {
10419
9865
  }
10420
9866
  var TUI_TREE_MARKER = "TUI_TREE\n";
10421
9867
  var TUI_TREE_END = "";
9868
+ var TUI_TREE_TOOLS = {
9869
+ Run: ["execShell", "runCommand", "launchProcess"],
9870
+ Read: ["readFile"],
9871
+ Search: ["exa_search"],
9872
+ Fetch: ["fetchWebpage"]
9873
+ };
10422
9874
  function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts = {}) {
10423
9875
  const pending = /* @__PURE__ */ new Map();
10424
9876
  let tree = null;
10425
- const treeKind = (name) => isRunToolName(name) ? "Run" : isReadToolName(name) ? "Read" : name === "exa_search" ? "Search" : name === "fetchWebpage" ? "Fetch" : null;
10426
- const treeLine = (kind, items) => {
9877
+ const treeKind = (name) => Object.keys(TUI_TREE_TOOLS).find((kind) => TUI_TREE_TOOLS[kind].includes(name)) ?? null;
9878
+ const treeLine = (kind, items, fallback) => {
10427
9879
  const label = kind === "Run" ? toolLabel("execShell") : kind === "Read" ? toolLabel("readFile") : kind === "Fetch" ? toolLabel("fetchWebpage") : toolLabel("exa_search");
10428
- return `${TUI_TREE_MARKER}${label} (${items.length})
10429
- ${items.map((item, i) => `${i === items.length - 1 ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "}${item} \u2713`).join("\n")}${TUI_TREE_END}
9880
+ const header = `${label} (${items.length}) \xB7 `;
9881
+ const columns = resolveHistoryLayoutGeometry(process.stdout.columns).contentWidth - displayWidth("\u25C8 ");
9882
+ let shown = 1;
9883
+ for (let count = 2; count <= items.length; count++) {
9884
+ const omitted2 = items.length - count;
9885
+ const suffix = omitted2 ? `, \u2026 +${omitted2}` : "";
9886
+ if (displayWidth(`\u2022 ${header}${items.slice(0, count).join(", ")}${suffix} \u2713`) > columns) break;
9887
+ shown = count;
9888
+ }
9889
+ const omitted = items.length - shown;
9890
+ const payload = {
9891
+ kind,
9892
+ summary: `${header}${items.slice(0, shown).join(", ")}${omitted ? `, \u2026 +${omitted}` : ""} \u2713`,
9893
+ fallback
9894
+ };
9895
+ return `${TUI_TREE_MARKER}${JSON.stringify(payload)}${TUI_TREE_END}
10430
9896
  `;
10431
9897
  };
10432
9898
  const formatTreeEvent = (event, call) => {
@@ -10453,8 +9919,8 @@ ${items.map((item, i) => `${i === items.length - 1 ? "\u2514\u2500\u2500 " : "\u
10453
9919
  item = withholdIfSecretLike(item) || toolLabel(name);
10454
9920
  if (tree?.kind !== kind) tree = { kind, items: [] };
10455
9921
  tree.items.push(item);
10456
- if (tree.items.length < 2) return formatNormalToolLine(event, call, colorEnabled);
10457
- return treeLine(kind, tree.items);
9922
+ if (tree.items.length < 2) return formatNormalToolLine(event, call, colorEnabled, opts);
9923
+ return treeLine(kind, tree.items, formatNormalToolLine(event, call, colorEnabled, opts));
10458
9924
  };
10459
9925
  const format = (event) => {
10460
9926
  if (event.type === "tool-call") {
@@ -10468,7 +9934,7 @@ ${items.map((item, i) => `${i === items.length - 1 ? "\u2514\u2500\u2500 " : "\u
10468
9934
  pending.delete(event.toolCallId);
10469
9935
  const treeOutput = formatTreeEvent(event, call);
10470
9936
  if (treeOutput !== null) return treeOutput;
10471
- return formatNormalToolLine(event, call, colorEnabled);
9937
+ return formatNormalToolLine(event, call, colorEnabled, opts);
10472
9938
  };
10473
9939
  format.reset = () => {
10474
9940
  tree = null;
@@ -10664,7 +10130,7 @@ function formatCompactionSummaryLine(event) {
10664
10130
  if (!event) return "";
10665
10131
  if (event.failed) {
10666
10132
  const reason = event.detail ? `\uFF1A${event.detail}` : "";
10667
- return `${STYLE.dim}\u81EA\u52A8\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25${reason}\uFF0C\u672C\u8F6E\u4EE5\u672A\u538B\u7F29\u4E0A\u4E0B\u6587\u7EE7\u7EED\u3002\u82E5\u53CD\u590D\u51FA\u73B0\u53EF\u624B\u52A8 /compact\u3002${STYLE.reset}
10133
+ return `${STYLE.dim}\u81EA\u52A8\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25${reason}\uFF0C\u4FDD\u7559\u5DF2\u6709\u5386\u53F2\uFF1B\u8D85\u51FA\u8BF7\u6C42\u9884\u7B97\u65F6\u5C06\u505C\u6B62\u53D1\u9001\u3002\u53EF\u624B\u52A8 /compact \u91CD\u8BD5\u3002${STYLE.reset}
10668
10134
  `;
10669
10135
  }
10670
10136
  if (event.skipped) {
@@ -10720,7 +10186,7 @@ function shouldPromoteTuiNarration(text) {
10720
10186
  return /(^|\n)\s*(?:#{1,3}\s|```|[-*+]\s|\d+[.)]\s)/.test(text);
10721
10187
  }
10722
10188
  function narrationActivityLabel(text) {
10723
- const oneLine = stripAnsi2(text).replace(/[`*_#>]/g, "").replace(/\s+/g, " ").trim();
10189
+ const oneLine = stripAnsi(text).replace(/[`*_#>]/g, "").replace(/\s+/g, " ").trim();
10724
10190
  return truncateThinkingHint(oneLine, 60);
10725
10191
  }
10726
10192
  function createCliTurnOutput(params) {
@@ -10728,7 +10194,8 @@ function createCliTurnOutput(params) {
10728
10194
  const workingLabel = params.workingLabel ?? `${options.agentName} -> working`;
10729
10195
  const spinner = params.spinner ?? new Spinner(options.output, workingLabel, Boolean(options.activityReporter));
10730
10196
  const formatToolEvent = createToolEventFormatter(void 0, {
10731
- tuiTrees: options.output.tuiTrees === true
10197
+ tuiTrees: options.output.tuiTrees === true,
10198
+ visibleRunIds: options.output.visibleRunIds
10732
10199
  });
10733
10200
  const eventMode = resolveAgentEventMode(options);
10734
10201
  const assistantLabelManaged = options.output.assistantLabelManaged === true;
@@ -10957,8 +10424,17 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10957
10424
  */
10958
10425
  showPhase(phase) {
10959
10426
  const label = phase === "validating-context" ? t("contextChecking") : phase === "compacting" ? t("contextCompacting") : t("waitingForModel");
10960
- spinner.show(label);
10961
- options.activityReporter?.(label);
10427
+ this.showWorking(label);
10428
+ },
10429
+ handleCompactionActivity(event) {
10430
+ if (event.kind === "compaction-retry") {
10431
+ this.showWorking(t("contextCompactingRetry", String(event.attempt), String(event.maxAttempts)));
10432
+ } else if (event.kind === "compaction-start") {
10433
+ this.showPhase("compacting");
10434
+ } else if (event.kind === "compaction-end" || // Failed compaction continues with trimmed history; abort owns its terminal cleanup.
10435
+ event.kind === "compaction-failed" && event.reason !== "aborted") {
10436
+ this.showPhase("waiting-provider");
10437
+ }
10962
10438
  },
10963
10439
  finish(fallbackContent) {
10964
10440
  const flushedThink = flushThinkParser(thinkState);
@@ -11493,9 +10969,57 @@ function isBalanceExhaustedError(error) {
11493
10969
  return matchesBalanceError(message);
11494
10970
  }
11495
10971
 
10972
+ // packages/cli/client/hostTaskWorkspaceAssessment.ts
10973
+ import { resolve as resolve3 } from "node:path";
10974
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10975
+ var present = (value) => typeof value === "string" && value.trim().length > 0;
10976
+ function resolveCurrentHostTaskReference(input) {
10977
+ const ref = input.reference;
10978
+ if (!ref || !present(ref.taskId) || !present(ref.workspace) || !present(ref.dialogId) || ref.dialogId !== input.dialogId || resolve3(ref.workspace) !== resolve3(input.workspace) || readHostTask(hostTaskEventsRoot(input.env), ref).authorization === "unknown") return void 0;
10979
+ return structuredClone(ref);
10980
+ }
10981
+ async function assessHostTaskWorkspace(input) {
10982
+ const ref = resolveCurrentHostTaskReference(input);
10983
+ if (!ref) return void 0;
10984
+ const root = hostTaskEventsRoot(input.env);
10985
+ const blocked = (reason, businessReason = "invalid_contract") => ({
10986
+ exitCode: 1,
10987
+ hostTaskWorkspaceBlocker: reason,
10988
+ businessCompletion: { taskId: ref.taskId, status: "blocked", reasons: [businessReason] }
10989
+ });
10990
+ const fresh = await collectHostTaskWorkspace(ref, input.env);
10991
+ const plan = readHostTaskAcceptancePlan(ref, input.env);
10992
+ let planned;
10993
+ if (plan) {
10994
+ try {
10995
+ planned = { status: "ready", context: await collectHostTaskPlannedWorkspace(ref, input.env) };
10996
+ } catch {
10997
+ planned = { status: "blocked", reason: "task_planned_workspace_unavailable" };
10998
+ }
10999
+ }
11000
+ const authority = readHostTask(root, ref).authorization;
11001
+ if (authority === "paused" || authority === "revoked") return blocked(`authorization_${authority}`, `authorization_${authority}`);
11002
+ if (authority !== "active") return blocked("task_authority_unavailable");
11003
+ const supplied = object(input.evidence);
11004
+ if (supplied?.status === "blocked") return blocked(present(supplied.reason) ? supplied.reason : "workspace_blocked");
11005
+ if (fresh.status === "blocked") return blocked(fresh.reason);
11006
+ if (planned?.status === "blocked") return blocked(planned.reason);
11007
+ if (planned?.status === "ready" && planned.context.baseline !== fresh.context.baseline) {
11008
+ return blocked("task_plan_baseline_mismatch");
11009
+ }
11010
+ const context = object(supplied?.context);
11011
+ const scope = object(context?.scope);
11012
+ if (supplied?.status !== "ready" || !context || !scope || scope.taskId !== ref.taskId || scope.dialogId !== ref.dialogId || scope.taskInstanceId !== ref.taskInstanceId || !present(scope.workspace) || resolve3(scope.workspace) !== resolve3(ref.workspace)) return blocked("workspace_evidence_mismatch");
11013
+ const matches = (canonical) => context.baseline === canonical.baseline && context.revision === canonical.revision && Array.isArray(context.taskPaths) && context.taskPaths.length === canonical.taskPaths.length && context.taskPaths.every((path2, index) => path2 === canonical.taskPaths[index]);
11014
+ if (!matches(fresh.context) && !(planned?.status === "ready" && matches(planned.context))) {
11015
+ return blocked("workspace_evidence_mismatch");
11016
+ }
11017
+ return void 0;
11018
+ }
11019
+
11496
11020
  // packages/cli/client/agentRun.ts
11497
11021
  async function loadRunLocalAgentTurn() {
11498
- const { runLocalAgentTurn } = await import("./agentRuntimeLocal-SOO2OPJG.js");
11022
+ const { runLocalAgentTurn } = await import("./agentRuntimeLocal-SD7U2EGY.js");
11499
11023
  return runLocalAgentTurn;
11500
11024
  }
11501
11025
  var stripDebugNoise = (s) => s.replace(/\s*raw="[\s\S]*"/g, "").replace(/\s*raw=\S+/g, "").replace(/\s*headers=\[[^\]]*\]/g, "").replace(/\s*headers=\S+/g, "").trim();
@@ -11771,6 +11295,7 @@ function looksLikeQuotaExhaustedText(message) {
11771
11295
  }
11772
11296
  var BARE_UPSTREAM_5XX_RE = /\bHTTP[:\s]+(5\d\d)\b|\bstatus[:\s=]+(5\d\d)\b|\breturned error\s+(5\d\d)\b/i;
11773
11297
  function classifyLocalRunError(message) {
11298
+ if (isHistoryIntegrityFailure(message)) return { kind: "history_integrity" };
11774
11299
  const m = message.match(PROVIDER_HTTP_FAILED_RE);
11775
11300
  if (m) {
11776
11301
  const status = Number(m[2]);
@@ -12137,17 +11662,61 @@ function buildBalanceFailure(ctx) {
12137
11662
  return `${lines.join("\n")}
12138
11663
  `;
12139
11664
  }
12140
- function buildTransientFailure(ctx) {
12141
- return `${RUN_UNAVAILABLE_PREFIX} (${ctx.where} returned HTTP ${ctx.status}; this is an upstream/gateway issue, not your local credential or config). Detail: ${ctx.message} ${NO_FALLBACK} Retry shortly, ${SERVER_FALLBACK_HINT}
11665
+ function buildTransientFailure(ctx) {
11666
+ return `${RUN_UNAVAILABLE_PREFIX} (${ctx.where} returned HTTP ${ctx.status}; this is an upstream/gateway issue, not your local credential or config). Detail: ${ctx.message} ${NO_FALLBACK} Retry shortly, ${SERVER_FALLBACK_HINT}
11667
+ `;
11668
+ }
11669
+ function buildUpstreamFailure(ctx) {
11670
+ const fix = ctx.where === "server chat proxy" ? `Check the agent's provider/api-key settings on nolo.chat` : `Check the agent's endpoint/model settings`;
11671
+ return `${RUN_UNAVAILABLE_PREFIX} (${ctx.where} returned HTTP ${ctx.status}). Detail: ${ctx.message} ${NO_FALLBACK} ${fix}, ${SERVER_FALLBACK_HINT}
11672
+ `;
11673
+ }
11674
+ function describeHistoryIntegrityFailure(message) {
11675
+ const ids = [...new Set(message.match(/\bcall_[A-Za-z0-9_-]+\b/g) ?? [])];
11676
+ const pairing = ids.length ? ` Missing tool result pairing: ${ids.join(", ")}.` : "";
11677
+ return `[nolo] history_integrity: Strict continuation history could not be verified.${pairing} Restore verified complete history from the original host or finish verified history recovery before retrying. No history was discarded or fabricated; blind retry will not repair coverage.
11678
+ `;
11679
+ }
11680
+ var LOCAL_CONTEXT_COVERAGE_TEXT = "Context protection: history cannot fit without losing messages";
11681
+ function isLocalContextCoverageFailure(error) {
11682
+ return error?.code === "LOCAL_CONTEXT_COVERAGE_REQUIRED" || toErrorMessage(error).includes(LOCAL_CONTEXT_COVERAGE_TEXT);
11683
+ }
11684
+ var BATCH_RECEIPT_MISSING_TEXT = "Missing durable batch receipt";
11685
+ function isMissingBatchReceiptFailure(message) {
11686
+ return message.includes(BATCH_RECEIPT_MISSING_TEXT);
11687
+ }
11688
+ function describeMissingBatchReceipt() {
11689
+ return "this turn's queued message batch has no durable admission receipt in this dialog, so the send state cannot be verified from local records. Your messages are kept. Re-send only if the previous reply never arrived; if it repeats, restart the TUI to restore the queue. This is not a credential or config problem";
11690
+ }
11691
+ function describeCliBatchPhaseFailure(error) {
11692
+ const cause = error.cause instanceof Error ? error.cause.message : String(error.cause ?? "");
11693
+ if (!error.requestStarted) {
11694
+ if (/already requested/i.test(cause)) {
11695
+ return `[nolo] queued batch ${error.batchId} was already requested; this attempt was blocked and not re-sent. The earlier attempt may have been sent and billed \u2014 check the dialog history before resending.
12142
11696
  `;
12143
- }
12144
- function buildUpstreamFailure(ctx) {
12145
- const fix = ctx.where === "server chat proxy" ? `Check the agent's provider/api-key settings on nolo.chat` : `Check the agent's endpoint/model settings`;
12146
- return `${RUN_UNAVAILABLE_PREFIX} (${ctx.where} returned HTTP ${ctx.status}). Detail: ${ctx.message} ${NO_FALLBACK} ${fix}, ${SERVER_FALLBACK_HINT}
11697
+ }
11698
+ return `[nolo] queued batch ${error.batchId} was blocked before the model was called; this attempt was not sent and was not re-sent. The prior send state is unknown. ${cause} Your messages are kept.
11699
+ `;
11700
+ }
11701
+ return `[nolo] queued batch ${error.batchId}: the model was called but the reply/completion evidence was not confirmed saved. It was not re-sent. Check the dialog history before resending. ${cause}
12147
11702
  `;
12148
11703
  }
11704
+ function isCliBatchPhaseFailure(error) {
11705
+ return error?.code === "cli_batch_phase_failed";
11706
+ }
12149
11707
  function formatLocalTurnFailureLine(error) {
12150
11708
  const message = toErrorMessage(error);
11709
+ if (isCliBatchPhaseFailure(error)) {
11710
+ return describeCliBatchPhaseFailure(error);
11711
+ }
11712
+ if (isLocalContextCoverageFailure(error)) {
11713
+ return `[nolo] ${describeContextRefusal(contextRefusalDiagnostics(error))}
11714
+ `;
11715
+ }
11716
+ if (isMissingBatchReceiptFailure(message)) {
11717
+ return `[nolo] ${describeMissingBatchReceipt()}.
11718
+ `;
11719
+ }
12151
11720
  if (error?.code === "LLM_REQUEST_TIMEOUT") {
12152
11721
  const msMatch = /after (\d+)ms/.exec(message);
12153
11722
  const deadline = msMatch && Number.isFinite(Number(msMatch[1])) ? formatElapsed(Math.round(Number(msMatch[1]) / 1e3)) : "the configured window";
@@ -12155,6 +11724,7 @@ function formatLocalTurnFailureLine(error) {
12155
11724
  `;
12156
11725
  }
12157
11726
  const cls = classifyLocalRunError(message);
11727
+ if (cls.kind === "history_integrity") return describeHistoryIntegrityFailure(message);
12158
11728
  if (cls.kind === "rate-limit") {
12159
11729
  const rawCooldownUntil = error && typeof error === "object" ? error.cooldownUntil : void 0;
12160
11730
  return buildRateLimitFailure({
@@ -12233,9 +11803,21 @@ function describeLocalRunFailure(message, rawError) {
12233
11803
  if (isCliAuthorityBrokerProtocolError(rawError) || /CLI authority broker protocol|CLI authority broker .* returned malformed response/i.test(message)) {
12234
11804
  const cleaned = stripDebugNoise(message);
12235
11805
  return `${RUN_UNAVAILABLE_PREFIX} (${cleaned}). ${NO_FALLBACK} The local authority broker returned a protocol or malformed response error. Check the running broker process and retry, ${SERVER_FALLBACK_HINT}
11806
+ `;
11807
+ }
11808
+ if (isCliBatchPhaseFailure(rawError)) {
11809
+ return describeCliBatchPhaseFailure(rawError);
11810
+ }
11811
+ if (isLocalContextCoverageFailure(rawError ?? message)) {
11812
+ return `[nolo] ${describeContextRefusal(contextRefusalDiagnostics(rawError))}
11813
+ `;
11814
+ }
11815
+ if (isMissingBatchReceiptFailure(message)) {
11816
+ return `[nolo] ${describeMissingBatchReceipt()}.
12236
11817
  `;
12237
11818
  }
12238
11819
  const cls = classifyLocalRunError(message);
11820
+ if (cls.kind === "history_integrity") return describeHistoryIntegrityFailure(message);
12239
11821
  if (cls.kind === "generic") {
12240
11822
  if (/owner-required route not acknowledged/i.test(message)) {
12241
11823
  return `${RUN_UNAVAILABLE_PREFIX} (${message}). ${NO_FALLBACK} The server returned a successful response but did not acknowledge the owner route. Check server version or proxy configuration, ${SERVER_FALLBACK_HINT}
@@ -12607,6 +12189,12 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12607
12189
  } : void 0;
12608
12190
  const currentDialogId = options.continueDialogId ?? ulid2();
12609
12191
  const freshDialog = options.freshDialog ?? !options.continueDialogId;
12192
+ options = { ...options, hostTaskRef: resolveCurrentHostTaskReference({
12193
+ reference: options.hostTaskRef,
12194
+ workspace: options.localRuntimeCwd ?? process.cwd(),
12195
+ dialogId: currentDialogId,
12196
+ env: options.env
12197
+ }) };
12610
12198
  const turnId = `turn-${ulid2()}`;
12611
12199
  const runtimeContextWithOwnership = {
12612
12200
  ...runtimeContext ?? {},
@@ -12614,8 +12202,176 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12614
12202
  turnId,
12615
12203
  getProcessCausalDepth: options.getProcessCausalDepth
12616
12204
  };
12617
- const adapter = baseAdapter;
12205
+ const installReviewHost = baseAdapter.installTaskReviewHost;
12206
+ if (options.hostTaskRef && installReviewHost) {
12207
+ const scope = structuredClone(options.hostTaskRef);
12208
+ const authorExecutionId = createHostAuthorExecution(options.env, scope, turnId);
12209
+ installReviewHost({ scope, authorExecutionId, authorize: async () => {
12210
+ if (!scope.taskId?.trim() || !scope.workspace?.trim() || !scope.dialogId?.trim() || scope.dialogId !== currentDialogId || resolveHostReviewPath(scope.workspace) !== resolveHostReviewPath(options.localRuntimeCwd ?? process.cwd())) throw new Error("task_review_host_scope_mismatch");
12211
+ } });
12212
+ }
12213
+ let reviewContext;
12214
+ const requestedReview = options.hostReviewDispatch;
12215
+ if (requestedReview && options.hostTaskRef && requestedReview.scope.taskId === options.hostTaskRef.taskId && requestedReview.scope.dialogId === currentDialogId && resolveHostReviewPath(requestedReview.scope.workspace) === resolveHostReviewPath(options.hostTaskRef.workspace)) {
12216
+ reviewContext = { ...requestedReview, authorExecutionId: createHostAuthorExecution(options.env, options.hostTaskRef, turnId) };
12217
+ }
12218
+ const commandVersionBindings = /* @__PURE__ */ new Map();
12219
+ const commandAdapter = !options.runtimeKey || options.runtimeKey === "local" ? wrapLocalCommandWorkspaceObservation(baseAdapter, options.localRuntimeCwd ?? process.cwd(), commandVersionBindings, void 0, options.abortSignal) : baseAdapter;
12220
+ const reviewAdapter = {
12221
+ ...commandAdapter,
12222
+ executeTool: async (call, opts) => {
12223
+ let args = {};
12224
+ try {
12225
+ args = typeof call.arguments === "string" ? JSON.parse(call.arguments) : call.arguments ?? {};
12226
+ } catch {
12227
+ }
12228
+ const matched = call.name === "startAgentRun" && matchesHostReviewDispatch(reviewContext, call, args);
12229
+ const result = await withHostReviewDispatch(matched ? reviewContext : void 0, () => commandAdapter.executeTool(call, opts));
12230
+ return result;
12231
+ }
12232
+ };
12233
+ const completionEvidenceProvider = options.hostTaskRef ? options.hostTaskCompletionEvidenceProvider : void 0;
12234
+ let hostTask = bindHostTask({
12235
+ adapter: reviewAdapter,
12236
+ reference: options.hostTaskRef,
12237
+ workspace: options.localRuntimeCwd ?? process.cwd(),
12238
+ dialogId: currentDialogId,
12239
+ env: options.env,
12240
+ signal: options.abortSignal,
12241
+ completionEvidenceProvider
12242
+ });
12243
+ if (options.hostTaskRef && options.hostTaskWorkspaceEvidence !== void 0 && readHostTask(hostTaskEventsRoot(options.env), options.hostTaskRef).authorization === "active") {
12244
+ const blocker = await assessHostTaskWorkspace({
12245
+ reference: options.hostTaskRef,
12246
+ workspace: options.localRuntimeCwd ?? process.cwd(),
12247
+ dialogId: currentDialogId,
12248
+ env: options.env,
12249
+ evidence: options.hostTaskWorkspaceEvidence
12250
+ });
12251
+ if (blocker) {
12252
+ options.output.write(`[auto-review] blocked: ${blocker.hostTaskWorkspaceBlocker}
12253
+ `);
12254
+ try {
12255
+ const saved = await reviewAdapter.saveTurn({
12256
+ agentKey: options.agentKey,
12257
+ messages: [{ role: "user", content: options.message }],
12258
+ continueDialogId: currentDialogId,
12259
+ runtimeContext: runtimeContextWithOwnership,
12260
+ result: {
12261
+ model: "host-workspace-assessment",
12262
+ content: "",
12263
+ error: true,
12264
+ businessCompletion: blocker.businessCompletion
12265
+ }
12266
+ });
12267
+ return {
12268
+ ...blocker,
12269
+ hostTaskRef: options.hostTaskRef,
12270
+ dialogId: saved.dialogId,
12271
+ taskAuthorization: readHostTask(hostTaskEventsRoot(options.env), options.hostTaskRef).authorization
12272
+ };
12273
+ } catch (localError) {
12274
+ return { ...blocker, hostTaskRef: options.hostTaskRef, localError };
12275
+ }
12276
+ }
12277
+ }
12278
+ let usedReviewTool = false;
12279
+ let batchProviderStarted = false;
12280
+ let mainProviderStarted = false;
12281
+ let refusalModel = "";
12282
+ let turnPersisted = false;
12283
+ let batchIdentity;
12284
+ try {
12285
+ batchIdentity = resolveCliBatchIdentity(options);
12286
+ } catch (error) {
12287
+ options.output.write(`[nolo] ${error instanceof Error ? error.message : String(error)}
12288
+ `);
12289
+ return { exitCode: 1, localError: error };
12290
+ }
12291
+ const markBatch = async (phase) => {
12292
+ if (!batchIdentity) return;
12293
+ const store = await getOrCreateSharedStore({ env: options.env, cwd: options.localRuntimeCwd, fetchImpl: options.fetchImpl });
12294
+ try {
12295
+ await markCliUserBatchPhase(store, currentDialogId, batchIdentity.batchId, phase, batchIdentity.messageIds, phase === "requested" ? options.userMessages : void 0);
12296
+ } catch (error) {
12297
+ throw cliBatchPhaseFailure({ phase, batchId: batchIdentity.batchId, requestStarted: false, replyPersisted: false, cause: error });
12298
+ }
12299
+ };
12300
+ const adapter = {
12301
+ ...hostTask.adapter,
12302
+ resolveProvider: async (...args) => {
12303
+ const provider = await hostTask.adapter.resolveProvider(...args);
12304
+ const isTextOnly = Boolean(args[1]?.textOnly);
12305
+ if (!isTextOnly) refusalModel = provider.model;
12306
+ return {
12307
+ ...provider,
12308
+ complete: async (...completeArgs) => {
12309
+ if (!isTextOnly) {
12310
+ mainProviderStarted = true;
12311
+ }
12312
+ if (batchIdentity && !isTextOnly && !batchProviderStarted) {
12313
+ await markBatch("requested");
12314
+ batchProviderStarted = true;
12315
+ }
12316
+ return provider.complete(...completeArgs);
12317
+ }
12318
+ };
12319
+ },
12320
+ executeTool: async (call, opts) => {
12321
+ const protectedReview = call.name === "requestTaskReview" || call.name === "recordTaskReviewDecision";
12322
+ if (!protectedReview) return reviewAdapter.executeTool(call, opts);
12323
+ usedReviewTool = true;
12324
+ if (options.hostTaskRef?.taskInstanceId) {
12325
+ const authorize = baseAdapter.authorizeAccountTask;
12326
+ if (!authorize) throw new Error("task_review_account_authorization_unavailable");
12327
+ await authorize(options.hostTaskRef);
12328
+ }
12329
+ if (!options.hostTaskRef && ["requestTaskReview", "recordTaskReviewDecision"].includes(call.name)) {
12330
+ const admit = baseAdapter.admitAccountReviewTurn;
12331
+ if (!admit) throw new Error("task_review_account_admission_unavailable");
12332
+ const reference = await admit(currentDialogId, turnId);
12333
+ options = { ...options, hostTaskRef: reference };
12334
+ hostTask = bindHostTask({ adapter: reviewAdapter, reference, workspace: options.localRuntimeCwd ?? process.cwd(), dialogId: currentDialogId, env: options.env, signal: options.abortSignal });
12335
+ }
12336
+ return hostTask.adapter.executeTool(call, opts);
12337
+ },
12338
+ saveTurn: async (input) => {
12339
+ if (usedReviewTool && options.hostTaskRef) await settleHostReviewsForScope(options.hostTaskRef, options.env, options.hostReviewContentAcceptance);
12340
+ const completeBatch = Boolean(batchIdentity && batchProviderStarted && !input.result.error);
12341
+ const injectedBatches = options.drainInjectedBatches ?? [];
12342
+ const injectedMessageIds = new Set(injectedBatches.flatMap((batch) => batch.messageIds));
12343
+ const completeBatchIds = [
12344
+ ...completeBatch ? [batchIdentity.batchId] : [],
12345
+ ...!input.result.error ? injectedBatches.map((batch) => batch.batchId) : []
12346
+ ];
12347
+ try {
12348
+ const saved = await hostTask.adapter.saveTurn({
12349
+ ...input,
12350
+ messages: input.messages.filter((message) => {
12351
+ const cliMessageId = message.cliMessageId;
12352
+ if (!cliMessageId) return true;
12353
+ if (options.userMessages?.some((user) => user.cliMessageId === cliMessageId)) return false;
12354
+ if (injectedMessageIds.has(cliMessageId)) return false;
12355
+ return true;
12356
+ }),
12357
+ ...completeBatchIds.length ? { cliBatchCompletion: { batchIds: completeBatchIds } } : {}
12358
+ });
12359
+ turnPersisted = true;
12360
+ return saved;
12361
+ } catch (error) {
12362
+ if (batchIdentity && batchProviderStarted) {
12363
+ throw cliBatchPhaseFailure({ phase: "completed", batchId: batchIdentity.batchId, requestStarted: true, replyPersisted: false, cause: error });
12364
+ }
12365
+ throw error;
12366
+ }
12367
+ }
12368
+ };
12618
12369
  const expandedMessage = options.pastedTextStore?.items.size ? expandCollapsedPastes(options.message, options.pastedTextStore) : options.message;
12370
+ const commandObservations = [];
12371
+ const retainCommandObservations = (result) => {
12372
+ recordRunResultHeaderMeta(result, { commandObservations });
12373
+ return result;
12374
+ };
12619
12375
  const workingLabel = `${options.agentName} -> working locally`;
12620
12376
  const turnOutput = createCliTurnOutput({
12621
12377
  options,
@@ -12637,9 +12393,11 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12637
12393
  const runLocalAgentTurn = await loadRunLocalAgentTurn();
12638
12394
  const result = await runLocalAgentTurn({
12639
12395
  adapter,
12396
+ ...hostTask.contract ? { taskExecutionContract: hostTask.contract } : {},
12640
12397
  agentRef: options.agentKey,
12641
12398
  userLanguage: options.userLanguage ?? options.env.NOLO_LANG ?? null,
12642
12399
  input: buildUserInputContent(messageForLocal, options.imageUrls),
12400
+ userMessages: options.userMessages,
12643
12401
  ...expandedMessage !== options.message || localAttachmentCard !== "" ? {
12644
12402
  persistedInput: hasDurableAttachments ? buildUserInputContent(
12645
12403
  expandedMessage,
@@ -12669,7 +12427,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12669
12427
  parentDialogId: options.parentDialogId,
12670
12428
  runtimeContext: runtimeContextWithOwnership,
12671
12429
  runKind: options.env.NOLO_AGENT_RUN_CHILD === "1" ? "subtask" : "interactive",
12672
- ...options.env.NOLO_AGENT_RUN_CHILD === "1" ? { subtaskBudgetLimits: resolveSubtaskBudgetLimits({ env: options.env }) } : {},
12673
12430
  // 展示能力由宿主声明(TUI=narrow),非交互 CLI/后台留空 → unknown;
12674
12431
  // 排版段只在能力已知时由 localLoop 注入,server 线不读该字段。
12675
12432
  ...options.responseViewport ? { responseViewport: options.responseViewport } : {},
@@ -12688,15 +12445,7 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12688
12445
  if (event.kind === "turn-phase") {
12689
12446
  turnOutput.showPhase(event.phase);
12690
12447
  }
12691
- if (event.kind === "compaction-start") {
12692
- turnOutput.showPhase("compacting");
12693
- }
12694
- if (event.kind === "compaction-end" || // 压缩失败(timeout/provider-error)时 localLoop 按失败原子性语义
12695
- // 带着裁剪后的历史继续本轮,切回等待模型文案;aborted 时 turn 随即
12696
- // 结束,不再切文案(终态由 abort 路径收尾)。
12697
- event.kind === "compaction-failed" && event.reason !== "aborted") {
12698
- turnOutput.showPhase("waiting-provider");
12699
- }
12448
+ turnOutput.handleCompactionActivity(event);
12700
12449
  if (event.kind === "image-downgraded") {
12701
12450
  options.output.write(
12702
12451
  "[nolo] \u5F53\u524D agent \u88AB\u914D\u7F6E\u4E3A\u4E0D\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF0C\u56FE\u7247\u5DF2\u7528\u5360\u4F4D\u6587\u672C\u66FF\u4EE3\u3002\u8BF7\u68C0\u67E5\u6A21\u578B\u7684\u56FE\u7247\u80FD\u529B\u914D\u7F6E\uFF0C\u6216\u7528 /switch \u9009\u62E9\u652F\u6301\u56FE\u7247\u7684 agent \u540E\u91CD\u65B0\u53D1\u9001\u56FE\u7247\u3002\n"
@@ -12713,6 +12462,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12713
12462
  // tool-gist-fold 后 onToolEvent 无条件挂载(不再受 traceLocalTools 开关
12714
12463
  // 控制,显示模式合并为单一 gist/折叠通道)——保留 alpha 的新形态。
12715
12464
  onToolEvent: (event) => {
12465
+ const observation = observeLocalCommandResult(event, options.localRuntimeCwd ?? process.cwd());
12466
+ if (observation) commandObservations.push({ ...observation, ...commandVersionBindings.get(event.toolCallId) });
12716
12467
  turnOutput.handleToolEvent(event);
12717
12468
  },
12718
12469
  ...!options.noStream ? {
@@ -12725,21 +12476,30 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12725
12476
  } : {}
12726
12477
  });
12727
12478
  turnOutput.finish(result.content);
12479
+ const usageRecords = result.usageRecords?.filter(
12480
+ (record) => Object.keys(record.usage ?? {}).length > 0
12481
+ );
12728
12482
  const turnCredits = sumPlatformCredits(result.usageRecords);
12483
+ const turnTokens = withTurnCredits(buildTurnTokenUsage(result.usage, result.model), turnCredits);
12729
12484
  const turnResult = {
12485
+ savedTurnPersisted: turnPersisted,
12486
+ mainProviderAttempted: mainProviderStarted,
12730
12487
  exitCode: 0,
12488
+ stopReason: result.stopReason,
12489
+ ...hostTask.result(),
12490
+ ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12731
12491
  dialogId: result.dialogId,
12732
12492
  ...typeof result.content === "string" && result.content.trim() ? { finalText: result.content } : {},
12733
- title: result.title,
12493
+ ...result.title !== void 0 ? { title: result.title } : {},
12734
12494
  ...result.titlePatchPromise ? { titlePatchPromise: result.titlePatchPromise } : {},
12735
12495
  ...pickEmptyAssistantFlags(result),
12736
12496
  // 积分口径按「全轮」而非「最后一次调用」:result.usage 只是收尾那次
12737
12497
  // provider 调用的 usage,本轮前面 N-1 次工具循环调用(以及自动压缩摘要)
12738
12498
  // 的 cost 都只存在于 usageRecords 里。token 字段仍取 result.usage——
12739
12499
  // 上下文占用本来就该看最后一次调用的累计输入,不是各次相加。
12740
- turnTokens: withTurnCredits(buildTurnTokenUsage(result.usage, result.model), turnCredits),
12500
+ ...turnTokens !== void 0 ? { turnTokens } : {},
12741
12501
  ...turnCredits !== void 0 ? { turnCredits } : {},
12742
- ...result.usageRecords?.length ? { usageRecords: result.usageRecords } : {}
12502
+ ...usageRecords?.length ? { usageRecords } : {}
12743
12503
  };
12744
12504
  const serverMeta = resolveResultServerMeta({
12745
12505
  env: options.env ?? {},
@@ -12747,6 +12507,7 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12747
12507
  hasSubjectRefs: (buildSubjectRefs(options)?.length ?? 0) > 0
12748
12508
  });
12749
12509
  recordRunResultHeaderMeta(turnResult, {
12510
+ commandObservations,
12750
12511
  model: result.model,
12751
12512
  dialogServer: serverMeta.server,
12752
12513
  serverSync: serverMeta.serverSync
@@ -12762,14 +12523,18 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12762
12523
  const abortedTurnCredits = sumPlatformCredits(abortedUsageRecords);
12763
12524
  if (error?.code === LOCAL_TURN_ABORTED_CODE || options.abortSignal?.aborted) {
12764
12525
  const pendingToolName = error?.pendingToolName;
12765
- return {
12526
+ return retainCommandObservations({
12766
12527
  exitCode: 0,
12528
+ ...hostTask.result(),
12529
+ savedTurnPersisted: turnPersisted,
12530
+ mainProviderAttempted: mainProviderStarted,
12531
+ ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12767
12532
  streamInterrupted: true,
12768
12533
  ...savedDialogId ? { dialogId: savedDialogId } : {},
12769
12534
  ...pendingToolName ? { pendingToolName } : {},
12770
12535
  ...abortedTurnCredits !== void 0 ? { turnCredits: abortedTurnCredits } : {},
12771
12536
  ...abortedUsageRecords?.length ? { usageRecords: abortedUsageRecords } : {}
12772
- };
12537
+ });
12773
12538
  }
12774
12539
  const cooldownUntil = await markStartupRateLimitCooldown(
12775
12540
  options,
@@ -12780,24 +12545,56 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12780
12545
  error.cooldownUntil = cooldownUntil;
12781
12546
  }
12782
12547
  if (settings.reportFailure) {
12783
- const failureLine = formatLocalTurnFailureLine(error);
12784
- if (typeof options.output.writeErr === "function") {
12785
- options.output.writeErr(failureLine);
12786
- } else {
12787
- options.output.write(failureLine);
12548
+ const suppressOutput = options.interactiveHost && isLocalContextCoverageFailure(error);
12549
+ if (!suppressOutput) {
12550
+ const failureLine = formatLocalTurnFailureLine(error);
12551
+ if (typeof options.output.writeErr === "function") {
12552
+ options.output.writeErr(failureLine);
12553
+ } else {
12554
+ options.output.write(failureLine);
12555
+ }
12788
12556
  }
12789
12557
  }
12790
- return {
12558
+ const isCoverage = isLocalContextCoverageFailure(error);
12559
+ const persisted = turnPersisted;
12560
+ const isTruePreflight = isCoverage && !persisted && !mainProviderStarted;
12561
+ const refusal = isCoverage ? contextRefusalDiagnostics(error) : void 0;
12562
+ if (isCoverage) {
12563
+ console.warn(`[nolo] context-refusal ${JSON.stringify({
12564
+ dialogId: savedDialogId ?? currentDialogId,
12565
+ agentKey: options.agentKey,
12566
+ model: refusalModel,
12567
+ reason: refusal?.reason ?? "unknown",
12568
+ historyTokens: refusal?.historyTokens ?? -1,
12569
+ budget: refusal?.budget ?? -1,
12570
+ largestMessageTokens: refusal?.largestMessageTokens ?? -1,
12571
+ droppedCount: refusal?.droppedCount ?? 0,
12572
+ detail: refusal?.detail ?? "diagnostics-unavailable"
12573
+ })}`);
12574
+ }
12575
+ return retainCommandObservations({
12791
12576
  exitCode: 1,
12577
+ ...hostTask.result(),
12792
12578
  localError: error,
12579
+ savedTurnPersisted: persisted,
12580
+ mainProviderAttempted: mainProviderStarted,
12793
12581
  failureSubclass: classifyFailureSubclass({
12794
12582
  message: toErrorMessage(error),
12795
12583
  body: error
12796
12584
  }),
12797
- ...savedDialogId ? { dialogId: savedDialogId } : {},
12585
+ ...savedDialogId ? { dialogId: savedDialogId } : isCoverage ? { dialogId: currentDialogId } : {},
12586
+ ...isTruePreflight ? {
12587
+ preflightBlocked: {
12588
+ code: "LOCAL_CONTEXT_COVERAGE_REQUIRED",
12589
+ phase: "preflight",
12590
+ retryable: true,
12591
+ mainRequestSent: false,
12592
+ ...refusal ? { refusal } : {}
12593
+ }
12594
+ } : {},
12798
12595
  ...abortedTurnCredits !== void 0 ? { turnCredits: abortedTurnCredits } : {},
12799
12596
  ...abortedUsageRecords?.length ? { usageRecords: abortedUsageRecords } : {}
12800
- };
12597
+ });
12801
12598
  }
12802
12599
  }
12803
12600
  async function resolveLocalCredentialKeysForDispatch(options) {
@@ -12833,9 +12630,19 @@ async function resolveLocalCredentialKeysForDispatch(options) {
12833
12630
  recordSuccess: recorder.recordStartupAvailabilityForAgent ? (status, body) => recorder.recordStartupAvailabilityForAgent(options.agentKey, status, body) : void 0
12834
12631
  };
12835
12632
  }
12633
+ function projectLocalTurnFacts(result) {
12634
+ return {
12635
+ ...result.savedTurnPersisted !== void 0 ? { savedTurnPersisted: result.savedTurnPersisted } : {},
12636
+ ...result.mainProviderAttempted !== void 0 ? { mainProviderAttempted: result.mainProviderAttempted } : {},
12637
+ ...result.preflightBlocked !== void 0 ? { preflightBlocked: result.preflightBlocked } : {},
12638
+ ...result.localError !== void 0 ? { localError: result.localError } : {}
12639
+ };
12640
+ }
12836
12641
  function foldLocalResultForTui(localResult) {
12837
12642
  const folded = {
12838
12643
  exitCode: localResult.exitCode,
12644
+ ...projectLocalTurnFacts(localResult),
12645
+ ...localResult.hostTaskRef ? { hostTaskRef: localResult.hostTaskRef } : {},
12839
12646
  ...localResult.dialogId ? { dialogId: localResult.dialogId } : {},
12840
12647
  title: localResult.title,
12841
12648
  ...localResult.titlePatchPromise ? { titlePatchPromise: localResult.titlePatchPromise } : {},
@@ -12905,7 +12712,7 @@ async function runAgentTurn(options) {
12905
12712
  }
12906
12713
  const skipLocal = await shouldSkipAutoLocalForServerPlatformTools(options);
12907
12714
  if (!skipLocal) {
12908
- const localResult = await runLocalAgentTurnForCli(options, {
12715
+ let localResult = await runLocalAgentTurnForCli(options, {
12909
12716
  reportFailure: false
12910
12717
  });
12911
12718
  if (localResult.exitCode === 0) {
@@ -12923,6 +12730,7 @@ async function runAgentTurn(options) {
12923
12730
  const retriedLocalResult = await runLocalAgentTurnForCli(options, {
12924
12731
  reportFailure: false
12925
12732
  });
12733
+ localResult = retriedLocalResult;
12926
12734
  if (retriedLocalResult.exitCode === 0) {
12927
12735
  return foldLocalResultForTui(retriedLocalResult);
12928
12736
  }
@@ -12937,19 +12745,30 @@ async function runAgentTurn(options) {
12937
12745
  message: localErrorMessage,
12938
12746
  body: localResult.localError
12939
12747
  });
12940
- options.output.write(describeLocalRunFailure(localErrorMessage, localResult.localError));
12941
- return {
12748
+ const suppressAutoFailureOutput = options.interactiveHost && Boolean(localResult.preflightBlocked || isLocalContextCoverageFailure(localResult.localError));
12749
+ if (!suppressAutoFailureOutput) {
12750
+ options.output.write(describeLocalRunFailure(localErrorMessage, localResult.localError));
12751
+ }
12752
+ const failureCoverageUsage = localResult.localError?.compactionUsage;
12753
+ const failureUsageRecords = failureCoverageUsage ? [...localResult.usageRecords ?? [], {
12754
+ // 形状对齐逐帧明细:callId 必填且本轮只有这一条救援摘要,
12755
+ // model 用固定标签(摘要走平台托管或当前 provider,无法从错误取得)。
12756
+ callId: "compaction-rescue",
12757
+ usage: failureCoverageUsage,
12758
+ model: "context-compaction"
12759
+ }] : localResult.usageRecords;
12760
+ const failedResult = {
12942
12761
  exitCode: 1,
12762
+ ...projectLocalTurnFacts(localResult),
12943
12763
  failureSubclass,
12944
12764
  ...localResult.dialogId ? { dialogId: localResult.dialogId } : {},
12945
- // Keep localError so TUI can show balance/quota/dialog-preserved hints
12946
- // instead of only the raw auto-runtime line.
12947
- ...localResult.localError ? { localError: localResult.localError } : {},
12948
12765
  // 失败轮同样可能已发生平台计费(abort/失败照样扣费):turnCredits 与
12949
12766
  // 逐帧明细一起随行,否则审计日志在 auto 失败路径上缺账。
12950
12767
  ...localResult.turnCredits !== void 0 ? { turnCredits: localResult.turnCredits } : {},
12951
- ...localResult.usageRecords?.length ? { usageRecords: localResult.usageRecords } : {}
12768
+ ...failureUsageRecords?.length ? { usageRecords: failureUsageRecords } : {}
12952
12769
  };
12770
+ recordRunResultHeaderMeta(failedResult, getRunResultHeaderMeta(localResult));
12771
+ return failedResult;
12953
12772
  }
12954
12773
  }
12955
12774
  if (!authToken) {
@@ -13167,7 +12986,7 @@ function buildHostEnvironmentLayer(options) {
13167
12986
 
13168
12987
  // packages/agent-runtime/agentsMd.ts
13169
12988
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
13170
- import { resolve as resolve2 } from "node:path";
12989
+ import { resolve as resolve4 } from "node:path";
13171
12990
  var AGENTS_MD_MAX_BYTES = 8192;
13172
12991
  var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
13173
12992
  var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
@@ -13227,6 +13046,37 @@ var parseAgentsMdItem = (body) => {
13227
13046
  rest: body.slice(firstClause.length).replace(/^[::\s]+/, "")
13228
13047
  };
13229
13048
  };
13049
+ var AGENTS_MD_COMMAND_TOKEN_PREFIX = /^(bunx?|npx|node|npm|pnpm|yarn|git|gh|tsc|deno)\b\s/;
13050
+ var extractAgentsMdCommandTokens = (body) => {
13051
+ const tokens2 = [];
13052
+ const seen = /* @__PURE__ */ new Set();
13053
+ for (const match of body.matchAll(/`([^`\n]+)`/g)) {
13054
+ const raw = match[1];
13055
+ if (!AGENTS_MD_COMMAND_TOKEN_PREFIX.test(raw)) continue;
13056
+ if (seen.has(raw)) continue;
13057
+ seen.add(raw);
13058
+ tokens2.push(raw);
13059
+ }
13060
+ return tokens2;
13061
+ };
13062
+ var buildAgentsMdItemGist = (firstSentence, bulletBody) => {
13063
+ const max = AGENTS_MD_SUMMARY_ITEM_MAX_CHARS;
13064
+ const clipped = clipToChars(firstSentence, max);
13065
+ const missing = extractAgentsMdCommandTokens(bulletBody).filter(
13066
+ (token) => !clipped.includes(token)
13067
+ );
13068
+ if (missing.length === 0) return clipped;
13069
+ let tail = "";
13070
+ for (const token of missing) {
13071
+ const candidate = tail ? `${tail} \`${token}\`` : `\`${token}\``;
13072
+ if (candidate.length > max) continue;
13073
+ tail = candidate;
13074
+ }
13075
+ if (!tail) return clipped;
13076
+ const room = max - tail.length - 2;
13077
+ const head = room > 0 ? clipToChars(firstSentence, room) : "";
13078
+ return head ? `${head} ${tail}` : tail;
13079
+ };
13230
13080
  var priorityOf = (label) => {
13231
13081
  const lowered = label.toLowerCase();
13232
13082
  for (let i = 0; i < AGENTS_MD_SUMMARY_PRIORITY_KEYWORDS.length; i += 1) {
@@ -13260,7 +13110,7 @@ var collectAgentsMdSummaryItems = (content) => {
13260
13110
  items.push({
13261
13111
  section,
13262
13112
  label,
13263
- gist: clipToChars(firstSentence, AGENTS_MD_SUMMARY_ITEM_MAX_CHARS),
13113
+ gist: buildAgentsMdItemGist(firstSentence, bullet[1]),
13264
13114
  priority: priorityOf(label)
13265
13115
  });
13266
13116
  }
@@ -13283,8 +13133,9 @@ ${AGENTS_MD_SUMMARY_DELETE_REFERENCE}
13283
13133
  ...items.filter((item) => item.priority >= 0).sort((a, b) => a.priority - b.priority),
13284
13134
  ...items.filter((item) => item.priority < 0)
13285
13135
  ];
13286
- const note = "\u2026\uFF08\u7D22\u5F15\u5DF2\u622A\u65AD\uFF0C\u5176\u4F59\u951A\u70B9\u89C1\u5B8C\u6574\u6587\u4EF6\uFF09";
13287
- const noteBytes = Buffer.byteLength(note, "utf8");
13136
+ const noteBlock = `
13137
+ \u2026\uFF08\u7D22\u5F15\u5DF2\u622A\u65AD\uFF0C\u5176\u4F59\u951A\u70B9\u89C1\u5B8C\u6574\u6587\u4EF6\uFF09`;
13138
+ const noteBytes = Buffer.byteLength(noteBlock, "utf8");
13288
13139
  let used = Buffer.byteLength(head, "utf8");
13289
13140
  const admitted = [];
13290
13141
  const seenSections = /* @__PURE__ */ new Set();
@@ -13318,8 +13169,7 @@ ${line}`, "utf8");
13318
13169
  }
13319
13170
  }
13320
13171
  if (admitted.length === 0) return null;
13321
- return `${head}${renderSummarySections(frozen)}${truncated ? `
13322
- ${note}` : ""}`;
13172
+ return `${head}${renderSummarySections(frozen)}${truncated ? noteBlock : ""}`;
13323
13173
  }
13324
13174
  var renderSummarySections = (entries) => {
13325
13175
  let rendered = "";
@@ -13337,7 +13187,7 @@ ${entry.line}`;
13337
13187
  };
13338
13188
  function readAgentsMdLayerFromDisk(cwd) {
13339
13189
  for (const name of AGENTS_MD_CANDIDATES) {
13340
- const filePath = resolve2(cwd, name);
13190
+ const filePath = resolve4(cwd, name);
13341
13191
  if (!existsSync2(filePath)) continue;
13342
13192
  try {
13343
13193
  const raw = readFileSync3(filePath, "utf8");
@@ -13479,16 +13329,16 @@ function runDoDCommands(commands, cwd, deps = {}) {
13479
13329
 
13480
13330
  // packages/cli/agentRunPrompts.ts
13481
13331
  import { existsSync as existsSync3, readFileSync as readFileSync4, readdirSync, statSync as statSync2 } from "node:fs";
13482
- import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve3, sep } from "node:path";
13332
+ import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve5, sep } from "node:path";
13483
13333
  function workflowRefToCandidatePath(cwd, ref) {
13484
13334
  const normalized = ref.trim();
13485
13335
  if (!normalized) return "";
13486
13336
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13487
- const directPath = resolve3(cwd, normalized);
13337
+ const directPath = resolve5(cwd, normalized);
13488
13338
  if (existsSync3(directPath)) return directPath;
13489
13339
  }
13490
13340
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13491
- return resolve3(cwd, "docs", "workflows", `${fileName}.md`);
13341
+ return resolve5(cwd, "docs", "workflows", `${fileName}.md`);
13492
13342
  }
13493
13343
  var SKILL_SEARCH_DIRS = [
13494
13344
  ".agents/skills"
@@ -13497,15 +13347,15 @@ function skillRefToCandidatePath(cwd, ref) {
13497
13347
  const normalized = ref.trim();
13498
13348
  if (!normalized) return "";
13499
13349
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13500
- const directPath = resolve3(cwd, normalized);
13350
+ const directPath = resolve5(cwd, normalized);
13501
13351
  if (existsSync3(directPath)) return directPath;
13502
13352
  }
13503
13353
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13504
13354
  for (const dir of SKILL_SEARCH_DIRS) {
13505
- const skillMdPath = resolve3(cwd, dir, fileName, "SKILL.md");
13355
+ const skillMdPath = resolve5(cwd, dir, fileName, "SKILL.md");
13506
13356
  if (existsSync3(skillMdPath)) return skillMdPath;
13507
13357
  }
13508
- return resolve3(cwd, ".agents", "skills", fileName, "SKILL.md");
13358
+ return resolve5(cwd, ".agents", "skills", fileName, "SKILL.md");
13509
13359
  }
13510
13360
  async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13511
13361
  const path2 = workflowRefToCandidatePath(cwd, ref);
@@ -13522,11 +13372,11 @@ async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13522
13372
  }
13523
13373
  function inlineRelativeRefs(body, skillDir) {
13524
13374
  const refPattern = /\[([^\]]+)\]\((\.\/[^)]+|[^)]+\/[^)]+)\)/g;
13525
- const normalizedSkillDir = resolve3(skillDir) + sep;
13375
+ const normalizedSkillDir = resolve5(skillDir) + sep;
13526
13376
  return body.replace(refPattern, (match, label, relPath) => {
13527
13377
  const cleaned = relPath.trim();
13528
13378
  if (!cleaned.startsWith("./") && !cleaned.startsWith("../")) return match;
13529
- const absPath = resolve3(skillDir, cleaned);
13379
+ const absPath = resolve5(skillDir, cleaned);
13530
13380
  const relative = relativePath(normalizedSkillDir, absPath);
13531
13381
  if (relative.startsWith("..") || isAbsolute2(relative)) return match;
13532
13382
  if (!existsSync3(absPath) || !absPath.endsWith(".md")) return match;
@@ -13676,7 +13526,7 @@ function prependSubjectDialogMarker(message, subjectDialogKey) {
13676
13526
  }
13677
13527
  function normalizeCliImageInput(input) {
13678
13528
  if (/^(https?:|data:|file:)/i.test(input)) return input;
13679
- const absolutePath = resolve3(input);
13529
+ const absolutePath = resolve5(input);
13680
13530
  if (!existsSync3(absolutePath)) return input;
13681
13531
  const base64 = readFileSync4(absolutePath).toString("base64");
13682
13532
  return `data:${imageMimeTypeForPath(absolutePath)};base64,${base64}`;
@@ -13695,55 +13545,6 @@ function imageMimeTypeForPath(path2) {
13695
13545
  }
13696
13546
  }
13697
13547
 
13698
- // packages/cli/agentRunLocalWorkspace.ts
13699
- async function runGitForLocalSummary(args, deps = {}) {
13700
- const spawn = deps.spawnProcess ?? spawnProcess;
13701
- const read = deps.readPipeText ?? readPipeText;
13702
- const proc = spawn({
13703
- cmd: ["git", ...args.gitArgs],
13704
- cwd: args.cwd,
13705
- stdout: "pipe",
13706
- stderr: "pipe"
13707
- });
13708
- const [stdout, stderr, exitCode] = await Promise.all([
13709
- read(proc.stdout),
13710
- read(proc.stderr),
13711
- proc.exited
13712
- ]);
13713
- if (exitCode !== 0) {
13714
- throw new Error((stderr || stdout || `git ${args.gitArgs.join(" ")} failed`).trim());
13715
- }
13716
- return stdout.trim();
13717
- }
13718
- async function inspectLocalRunWorkspace(cwd, deps = {}) {
13719
- const run = (gitArgs) => runGitForLocalSummary({ cwd, gitArgs }, deps);
13720
- const status = await run(["status", "--short"]);
13721
- const rawCommit = await run(["log", "-1", "--format=%h%x00%s"]).catch(() => "");
13722
- const [hash, subject] = rawCommit.split("\0");
13723
- return {
13724
- cwd,
13725
- clean: status.trim() === "",
13726
- status,
13727
- ...hash ? { commit: { hash, subject: subject ?? "" } } : {}
13728
- };
13729
- }
13730
- function shouldPrintLocalRunSummary(args) {
13731
- return Boolean(args.localRuntimeCwd && args.parsed.runtimeMode === "local");
13732
- }
13733
- function formatLocalRunSummary(args) {
13734
- return [
13735
- "",
13736
- "[nolo] local run summary",
13737
- `workspace: ${args.inspection.cwd}`,
13738
- ...args.dialogId ? [`dialog: ${args.dialogId}`] : [],
13739
- ...args.inspection.commit ? [`commit: ${args.inspection.commit.hash} ${args.inspection.commit.subject}`] : [],
13740
- `dirty: ${args.inspection.clean ? "clean" : "dirty"}`,
13741
- ...!args.inspection.clean && args.inspection.status.trim() ? [`status:
13742
- ${args.inspection.status.trim()}`] : [],
13743
- ""
13744
- ].join("\n");
13745
- }
13746
-
13747
13548
  // packages/ai/memory/storeShared.ts
13748
13549
  var retrievalCountOf = (item) => item.activationCount ?? 0;
13749
13550
  var touchMemoryItemsInDb = async (db, items, now = (/* @__PURE__ */ new Date()).toISOString()) => {
@@ -13760,367 +13561,6 @@ var touchMemoryItemsInDb = async (db, items, now = (/* @__PURE__ */ new Date()).
13760
13561
  await batch.write();
13761
13562
  };
13762
13563
 
13763
- // packages/ai/memory/constants.ts
13764
- var EXPLICIT_REMEMBER_PREFIX_REGEX = /^(你要记住|请记住|以后记住|记住)[,,。.\s::]*/u;
13765
-
13766
- // packages/ai/memory/source.ts
13767
- var getMemorySourceKind = (item) => {
13768
- if (item.sourceKind) return item.sourceKind;
13769
- if (item.patternKey === "explicit-remember") return "explicit-user-directive";
13770
- if (item.patternKey === "agent-remember" || item.patternKey === "procedural-runbook")
13771
- return "agent-tool";
13772
- if (item.patternKey?.startsWith("dialog-learning:"))
13773
- return "dialog-learning";
13774
- if (item.tags?.includes("understanding-memory"))
13775
- return "inferred-understanding";
13776
- return "agent-tool";
13777
- };
13778
-
13779
- // packages/ai/memory/overlay.ts
13780
- var KIND_TITLES = {
13781
- episodic: "Episodic",
13782
- semantic: "Semantic",
13783
- procedural: "Procedural"
13784
- };
13785
- var estimateTokens = (text) => {
13786
- let cjk = 0;
13787
- let ascii = 0;
13788
- for (const ch of text) {
13789
- const code = ch.codePointAt(0) ?? 0;
13790
- if (code >= 13312 && code <= 40959) cjk += 1;
13791
- else ascii += 1;
13792
- }
13793
- return Math.ceil(cjk * 1.5 + ascii / 4);
13794
- };
13795
- var OVERLAY_HEADER_LINES = [
13796
- "--- Memory (\u76F8\u5173\u65F6\u53C2\u8003\uFF0C\u7528\u6237\u8F93\u5165\u4F18\u5148) ---",
13797
- ""
13798
- ];
13799
- var OVERLAY_HEADER_TOKENS = estimateTokens(OVERLAY_HEADER_LINES.join("\n"));
13800
- var KIND_PRIORITY = {
13801
- semantic: 0,
13802
- procedural: 1,
13803
- episodic: 2
13804
- };
13805
- var FACET_DISPLAY = {
13806
- unfinished: { label: "\u8FD8\u6CA1\u5B9A\u4E0B", strip: "\u8FD8\u6CA1\u51B3\u5B9A" },
13807
- tension: { label: "\u5728\u6743\u8861", strip: "\u5728\u6743\u8861" },
13808
- preference: { label: "\u66F4\u5728\u610F", strip: "\u66F4\u5728\u610F" },
13809
- style: { label: "\u66F4\u504F\u597D", strip: "\u66F4\u559C\u6B22" },
13810
- goal: { label: "\u60F3\u63A8\u8FDB", strip: "\u60F3\u63A8\u8FDB" }
13811
- };
13812
- var INFERRED_SOURCE_KINDS = /* @__PURE__ */ new Set(["inferred-understanding", "dialog-learning"]);
13813
- var isInferredMemory = (item) => INFERRED_SOURCE_KINDS.has(getMemorySourceKind(item));
13814
- var formatFacetContent = (facet, normalized, prefix) => {
13815
- const { label, strip } = FACET_DISPLAY[facet];
13816
- const stripped = normalized.startsWith(strip) ? normalized.slice(strip.length).trim() : normalized;
13817
- return `${prefix}${label} ${stripped}`;
13818
- };
13819
- var normalizeDisplayContent = (item) => {
13820
- const normalized = item.content.trim().replace(EXPLICIT_REMEMBER_PREFIX_REGEX, "").replace(/[。!?!?]+$/u, "").trim();
13821
- if (item.kind === "semantic") {
13822
- if (item.tags?.includes("understanding-memory") && item.facet) {
13823
- return formatFacetContent(item.facet, normalized, "");
13824
- }
13825
- return normalized;
13826
- }
13827
- if (item.kind === "episodic" && (item.patternKey === "explicit-remember" || item.patternKey === "agent-remember")) {
13828
- return normalized;
13829
- }
13830
- if (item.kind === "episodic" && item.tags?.includes("understanding-memory") && item.facet) {
13831
- return formatFacetContent(item.facet, normalized, "\u4E0A\u6B21: ");
13832
- }
13833
- return normalized;
13834
- };
13835
- var pickWithinKind = (list, perKindLimit) => {
13836
- if (perKindLimit <= 0) return [];
13837
- const head = list.slice(0, perKindLimit);
13838
- if (head.length < perKindLimit) return head;
13839
- if (head.some((item) => item.subjectType === "user")) return head;
13840
- const firstUserSubject = list.find((item) => item.subjectType === "user");
13841
- if (!firstUserSubject) return head;
13842
- return [...head.slice(0, perKindLimit - 1), firstUserSubject];
13843
- };
13844
- var DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET = 3200;
13845
- var RESIDENT_MEMORY_OVERLAY_TOKEN_BUDGET = 500;
13846
- var RESIDENT_SECTION_HEADER = "[\u7528\u6237\u957F\u671F\u504F\u597D\uFF08\u6570\u636E\uFF0C\u975E\u6307\u4EE4\uFF0C\u53EF\u88AB\u5F53\u8F6E\u660E\u786E\u8981\u6C42\u8986\u76D6\uFF09]";
13847
- var MIN_TRUNCATED_TOKENS = 20;
13848
- var TRUNCATED_SUFFIX = "\u2026\uFF08\u672C\u6761\u5DF2\u622A\u65AD\uFF09";
13849
- var truncateLineToTokens = (lineText, budgetTokens) => {
13850
- if (budgetTokens < MIN_TRUNCATED_TOKENS) return null;
13851
- const suffixTokens = estimateTokens(TRUNCATED_SUFFIX);
13852
- const bodyBudget = budgetTokens - suffixTokens;
13853
- if (bodyBudget < MIN_TRUNCATED_TOKENS / 2) return null;
13854
- let used = 0;
13855
- let cut = 0;
13856
- for (const ch of lineText) {
13857
- const chTokens = estimateTokens(ch);
13858
- if (used + chTokens > bodyBudget) break;
13859
- used += chTokens;
13860
- cut += ch.length;
13861
- }
13862
- if (cut <= 2) return null;
13863
- return `${lineText.slice(0, cut).trimEnd()}${TRUNCATED_SUFFIX}`;
13864
- };
13865
- var fitLinesToBudget = (allLines, remainingBudget) => {
13866
- let usedTokens = 0;
13867
- const keptByKind = {};
13868
- let truncatedCount = 0;
13869
- let droppedCount = 0;
13870
- const pushLine = (kind, lineText) => {
13871
- if (!keptByKind[kind]) keptByKind[kind] = [];
13872
- keptByKind[kind].push(lineText);
13873
- };
13874
- for (const candidate of allLines) {
13875
- const remaining = remainingBudget - usedTokens;
13876
- if (remaining <= 0) {
13877
- droppedCount += 1;
13878
- continue;
13879
- }
13880
- if (candidate.lineTokens <= remaining) {
13881
- usedTokens += candidate.lineTokens;
13882
- pushLine(candidate.kind, candidate.lineText);
13883
- continue;
13884
- }
13885
- const truncated = truncateLineToTokens(candidate.lineText, remaining);
13886
- if (!truncated) {
13887
- droppedCount += 1;
13888
- continue;
13889
- }
13890
- usedTokens += estimateTokens(truncated);
13891
- pushLine(candidate.kind, truncated);
13892
- truncatedCount += 1;
13893
- }
13894
- return { keptByKind, truncatedCount, droppedCount };
13895
- };
13896
- var EMPTY_RETRIEVAL_FIT = {
13897
- keptByKind: {},
13898
- truncatedCount: 0,
13899
- droppedCount: 0
13900
- };
13901
- var EMPTY_RESIDENT_FIT = {
13902
- keptLines: [],
13903
- truncatedCount: 0,
13904
- droppedCount: 0
13905
- };
13906
- var fitResidentLines = (lines, remainingBudget) => {
13907
- let usedTokens = 0;
13908
- const keptLines = [];
13909
- let truncatedCount = 0;
13910
- let droppedCount = 0;
13911
- for (const candidate of lines) {
13912
- const remaining = remainingBudget - usedTokens;
13913
- if (remaining <= 0) {
13914
- droppedCount += 1;
13915
- continue;
13916
- }
13917
- if (candidate.lineTokens <= remaining) {
13918
- usedTokens += candidate.lineTokens;
13919
- keptLines.push(candidate.lineText);
13920
- continue;
13921
- }
13922
- const truncated = truncateLineToTokens(candidate.lineText, remaining);
13923
- if (!truncated) {
13924
- droppedCount += 1;
13925
- continue;
13926
- }
13927
- usedTokens += estimateTokens(truncated);
13928
- keptLines.push(truncated);
13929
- truncatedCount += 1;
13930
- }
13931
- return { keptLines, truncatedCount, droppedCount };
13932
- };
13933
- var buildBudgetFooter = (fit, residentFit) => {
13934
- const notices = [];
13935
- if (residentFit.truncatedCount > 0) {
13936
- notices.push(`${residentFit.truncatedCount} \u6761\u957F\u671F\u504F\u597D\u56E0\u9884\u7B97\u88AB\u622A\u65AD`);
13937
- }
13938
- if (residentFit.droppedCount > 0) {
13939
- notices.push(`${residentFit.droppedCount} \u6761\u957F\u671F\u504F\u597D\u672A\u663E\u793A`);
13940
- }
13941
- if (fit.truncatedCount > 0) {
13942
- notices.push(`${fit.truncatedCount} \u6761\u56E0\u9884\u7B97\u88AB\u622A\u65AD`);
13943
- }
13944
- if (fit.droppedCount > 0) {
13945
- notices.push(`${fit.droppedCount} \u6761\u672A\u663E\u793A`);
13946
- }
13947
- if (notices.length === 0) return [];
13948
- return [`\uFF08${notices.join("\u3001")}\uFF1B\u9700\u8981\u5B8C\u6574\u5185\u5BB9\u6216\u66F4\u591A\u76F8\u5173\u8BB0\u5FC6\u65F6\u7528 queryMemory \u68C0\u7D22\uFF09`];
13949
- };
13950
- var buildMemoryOverlay = (items, options) => {
13951
- if (items.length === 0) return null;
13952
- const maxTokens = options?.maxTokens ?? DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET;
13953
- const perKindLimit = options?.perKindLimit ?? 3;
13954
- const residentMaxTokens = options?.residentMaxTokens ?? RESIDENT_MEMORY_OVERLAY_TOKEN_BUDGET;
13955
- const residentItems = items.filter((item) => item.resident === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
13956
- const retrievalItems = items.filter((item) => item.resident !== true);
13957
- const residentFit = residentItems.length === 0 ? EMPTY_RESIDENT_FIT : fitResidentLines(
13958
- residentItems.map((item) => {
13959
- const lineText = `- ${isInferredMemory(item) ? "\uFF08\u63A8\u65AD\uFF09" : ""}${normalizeDisplayContent(item)}`;
13960
- return { kind: item.kind, lineText, lineTokens: estimateTokens(lineText) };
13961
- }),
13962
- residentMaxTokens - estimateTokens(RESIDENT_SECTION_HEADER)
13963
- );
13964
- const byKind = {
13965
- episodic: [],
13966
- semantic: [],
13967
- procedural: []
13968
- };
13969
- for (const item of retrievalItems) {
13970
- byKind[item.kind].push(item);
13971
- }
13972
- const remainingBudget = maxTokens - OVERLAY_HEADER_TOKENS;
13973
- let retrievalFit = EMPTY_RETRIEVAL_FIT;
13974
- let retrievalSections = [];
13975
- if (remainingBudget > 0 && retrievalItems.length > 0) {
13976
- const allLines = Object.entries(byKind).filter(([, list]) => list.length > 0).flatMap(
13977
- ([kind, list]) => pickWithinKind(list, perKindLimit).map((item) => {
13978
- const lineText = `- ${isInferredMemory(item) ? "\uFF08\u63A8\u65AD\uFF09" : ""}${normalizeDisplayContent(item)}`;
13979
- return { kind, lineText, lineTokens: estimateTokens(lineText) };
13980
- })
13981
- ).sort((a, b) => (KIND_PRIORITY[a.kind] ?? 99) - (KIND_PRIORITY[b.kind] ?? 99));
13982
- retrievalFit = fitLinesToBudget(allLines, remainingBudget);
13983
- const kindOrder = ["semantic", "procedural", "episodic"];
13984
- retrievalSections = kindOrder.filter(
13985
- (kind) => retrievalFit.keptByKind[kind] && retrievalFit.keptByKind[kind].length > 0
13986
- ).map((kind) => {
13987
- return [`[${KIND_TITLES[kind]}]`, ...retrievalFit.keptByKind[kind]].join("\n");
13988
- });
13989
- }
13990
- const sections = [
13991
- ...residentFit.keptLines.length > 0 ? [[RESIDENT_SECTION_HEADER, ...residentFit.keptLines].join("\n")] : [],
13992
- ...retrievalSections
13993
- ];
13994
- if (sections.length === 0) {
13995
- return OVERLAY_HEADER_LINES.join("\n");
13996
- }
13997
- return [
13998
- ...OVERLAY_HEADER_LINES,
13999
- ...sections,
14000
- ...buildBudgetFooter(retrievalFit, residentFit)
14001
- ].join("\n");
14002
- };
14003
-
14004
- // packages/ai/memory/rank.ts
14005
- var CJK_SEQUENCE_REGEX = /[\u3400-\u4dbf\u4e00-\u9fff]+/g;
14006
- var MEMORY_IDENTIFIER_REGEX = /\b(?:memory|noise)-[a-z0-9][a-z0-9-]*/gi;
14007
- var buildCjkTokens = (text) => {
14008
- const sequences = text.match(CJK_SEQUENCE_REGEX) ?? [];
14009
- const tokens = [];
14010
- for (const sequence2 of sequences) {
14011
- if (sequence2.length >= 2) {
14012
- tokens.push(sequence2);
14013
- }
14014
- for (let index = 0; index < sequence2.length - 1; index += 1) {
14015
- tokens.push(sequence2.slice(index, index + 2));
14016
- }
14017
- }
14018
- return tokens;
14019
- };
14020
- var tokenize2 = (text) => {
14021
- const normalized = text.toLowerCase();
14022
- const wordTokens = normalized.split(/[\s,.;:!?()[\]{}"'`,。!?:;、]+/).map((token) => token.trim()).filter((token) => token.length >= 2);
14023
- return [...wordTokens, ...buildCjkTokens(normalized)];
14024
- };
14025
- var keywordScore = (query, item) => {
14026
- const queryTokens = new Set(tokenize2(query));
14027
- if (queryTokens.size === 0) return 0;
14028
- const haystack = /* @__PURE__ */ new Set([
14029
- ...tokenize2(item.content),
14030
- ...(item.tags ?? []).map((tag) => tag.toLowerCase()),
14031
- item.patternKey?.toLowerCase() ?? ""
14032
- ]);
14033
- let matches = 0;
14034
- for (const token of queryTokens) {
14035
- if (haystack.has(token)) matches += 1;
14036
- }
14037
- return Math.min(1, matches / Math.max(2, queryTokens.size));
14038
- };
14039
- var identifierScore = (query, item) => {
14040
- const identifiers = query.match(MEMORY_IDENTIFIER_REGEX) ?? [];
14041
- if (identifiers.length === 0) return 0;
14042
- const content = item.content.toLowerCase();
14043
- const matches = identifiers.filter(
14044
- (identifier) => content.includes(identifier.toLowerCase())
14045
- ).length;
14046
- return matches / identifiers.length;
14047
- };
14048
- var DAY_MS = 864e5;
14049
- var UNRETRIEVED_MEMORY_GRACE_DAYS = 3;
14050
- var MIN_UNRETRIEVED_SCORE_FACTOR = 0.3;
14051
- var UNRETRIEVED_DECAY_HALF_LIFE_DAYS = 7;
14052
- var retrievalFrequencyScore = (item, nowMs) => {
14053
- const lastRetrievedMs = Date.parse(item.lastActivatedAt || item.createdAt);
14054
- const ageDays = Math.max(0, (nowMs - lastRetrievedMs) / DAY_MS);
14055
- const recency = 1 / (1 + ageDays / 7);
14056
- const frequency = Math.min(1, Math.log1p(item.activationCount ?? 0) / 3);
14057
- return 0.7 * recency + 0.3 * frequency;
14058
- };
14059
- var unretrievedDecayFactor = (item, nowMs) => {
14060
- if ((item.activationCount ?? 0) !== 0) return 1;
14061
- const createdAgeDays = Math.max(0, (nowMs - Date.parse(item.createdAt)) / DAY_MS);
14062
- if (createdAgeDays <= UNRETRIEVED_MEMORY_GRACE_DAYS) return 1;
14063
- const overdue = createdAgeDays - UNRETRIEVED_MEMORY_GRACE_DAYS;
14064
- return Math.max(
14065
- MIN_UNRETRIEVED_SCORE_FACTOR,
14066
- 1 / (1 + overdue / UNRETRIEVED_DECAY_HALF_LIFE_DAYS)
14067
- );
14068
- };
14069
- var retrievalScore = (item, nowMs) => retrievalFrequencyScore(item, nowMs) * unretrievedDecayFactor(item, nowMs);
14070
- var creationRecencyScore = (item, nowMs) => {
14071
- const createdMs = Date.parse(item.createdAt);
14072
- const ageDays = Math.max(0, (nowMs - createdMs) / 864e5);
14073
- return 1 / (1 + ageDays / 7);
14074
- };
14075
- var typeFitScore = (item) => {
14076
- if (item.kind === "episodic") return 0.75;
14077
- if (item.kind === "semantic") return 0.9;
14078
- return 0.85;
14079
- };
14080
- var understandingScore = (item) => {
14081
- if (!item.tags?.includes("understanding-memory")) return 0;
14082
- if (item.facet === "unfinished") return 1;
14083
- if (item.facet === "tension") return 0.95;
14084
- if (item.facet === "preference") return 0.85;
14085
- if (item.facet === "style") return 0.75;
14086
- return 0.8;
14087
- };
14088
- var pathScore = (item, context) => {
14089
- let score = 0;
14090
- if (context?.currentOwner && item.ownerType === context.currentOwner.ownerType && item.ownerId === context.currentOwner.ownerId) {
14091
- score += 0.65;
14092
- }
14093
- if (context?.currentSubject && item.subjectType === context.currentSubject.subjectType && item.subjectId === context.currentSubject.subjectId) {
14094
- score += 0.85;
14095
- }
14096
- return Math.min(1, score);
14097
- };
14098
- var scoreMemoryItem = (item, query, nowMs = Date.now(), context) => {
14099
- const queryMatch = keywordScore(query, item);
14100
- const identifierMatch = identifierScore(query, item);
14101
- const retrieval = retrievalScore(item, nowMs);
14102
- const createdRecency = creationRecencyScore(item, nowMs);
14103
- const importance = item.importance ?? 0;
14104
- const confidence = item.confidence ?? 0;
14105
- const typeFit = typeFitScore(item);
14106
- const understanding = understandingScore(item);
14107
- const path2 = pathScore(item, context);
14108
- return 0.25 * queryMatch + 0.2 * identifierMatch + 0.2 * path2 + 0.09 * retrieval + // weak retrieval signal, NOT successful-use reinforcement
14109
- 0.16 * createdRecency + 0.06 * importance + 0.03 * confidence + 0.02 * typeFit + 0.01 * understanding;
14110
- };
14111
- var rankMemoryCandidates = (items, query, context) => {
14112
- const nowMs = Date.now();
14113
- return [...items].sort((a, b) => {
14114
- const aExplicit = a.sourceKind === "explicit-user-directive";
14115
- const bExplicit = b.sourceKind === "explicit-user-directive";
14116
- if (aExplicit !== bExplicit) return bExplicit ? 1 : -1;
14117
- if (aExplicit) {
14118
- return Date.parse(b.createdAt) - Date.parse(a.createdAt);
14119
- }
14120
- return scoreMemoryItem(b, query, nowMs, context) - scoreMemoryItem(a, query, nowMs, context);
14121
- });
14122
- };
14123
-
14124
13564
  // packages/ai/memory/vnext/detachedThrottle.ts
14125
13565
  var DEFAULT_DETACHED_MEMORY_COOLDOWN_MS = 10 * 60 * 1e3;
14126
13566
  var MAX_COOLDOWN_KEYS = 512;
@@ -14289,43 +13729,6 @@ ${catalogText(entities, states)}`
14289
13729
  };
14290
13730
  };
14291
13731
 
14292
- // packages/ai/memory/vnext/legacyMigration.ts
14293
- import { createHash } from "crypto";
14294
- var LEGACY_MEMORY_SOURCE_REF_PREFIX = "legacy-memory";
14295
- var LEGACY_MEMORY_EVIDENCE_ID_PREFIX = "mem-legacy-";
14296
- var resolveLegacyMemoryPrincipal = (item) => ({
14297
- ownerType: item.ownerType,
14298
- ownerId: item.ownerId,
14299
- principalId: `${item.ownerType}:${encodeURIComponent(item.ownerId)}`
14300
- });
14301
- var buildLegacyMemorySourceRef = (item) => {
14302
- const { principalId } = resolveLegacyMemoryPrincipal(item);
14303
- return `${LEGACY_MEMORY_SOURCE_REF_PREFIX}:${principalId}:${encodeURIComponent(item.id)}`;
14304
- };
14305
- var legacyEvidenceSeed = (principalId, itemId) => JSON.stringify([principalId, itemId]);
14306
- var buildLegacyEvidenceId = (item) => {
14307
- const { principalId } = resolveLegacyMemoryPrincipal(item);
14308
- const digest = createHash("sha256").update(legacyEvidenceSeed(principalId, item.id)).digest("hex");
14309
- return `${LEGACY_MEMORY_EVIDENCE_ID_PREFIX}${digest.slice(0, 32)}`;
14310
- };
14311
- var clampLegacyConfidence = (value) => {
14312
- if (typeof value !== "number" || !Number.isFinite(value)) return 0;
14313
- if (value < 0) return 0;
14314
- if (value > 1) return 1;
14315
- return value;
14316
- };
14317
- var buildLegacyMemoryEvidence = (item) => {
14318
- const { principalId } = resolveLegacyMemoryPrincipal(item);
14319
- return {
14320
- id: buildLegacyEvidenceId(item),
14321
- ownerId: principalId,
14322
- text: item.content,
14323
- sourceRef: buildLegacyMemorySourceRef(item),
14324
- confidence: clampLegacyConfidence(item.confidence),
14325
- createdAt: item.createdAt
14326
- };
14327
- };
14328
-
14329
13732
  // packages/ai/memory/vnext/shadowRead.ts
14330
13733
  var SHADOW_TIMEOUT_MS = 2e4;
14331
13734
  var ERROR_MESSAGE_MAX = 120;
@@ -14739,7 +14142,7 @@ var MEMORY_RELATION_TYPES = [
14739
14142
  var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
14740
14143
  var isString = (value) => typeof value === "string" && value.trim().length > 0;
14741
14144
  var isStringArray = (value) => Array.isArray(value) && value.every(isString);
14742
- var optionalArray = (value, validate2) => value === void 0 || Array.isArray(value) && value.every(validate2);
14145
+ var optionalArray = (value, validate) => value === void 0 || Array.isArray(value) && value.every(validate);
14743
14146
  var ACTIONS = /* @__PURE__ */ new Set([
14744
14147
  "no_op",
14745
14148
  "create",
@@ -15322,46 +14725,15 @@ var isMemoryVNextLazyPromotionEnabled = (env = typeof process !== "undefined" ?
15322
14725
  // packages/ai/memory/vnext/pureReadGate.ts
15323
14726
  var isMemoryVNextPureReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_PURE_READ === "1" || env.NOLO_MEMORY_VNEXT_PURE_READ === "true";
15324
14727
 
15325
- // packages/ai/memory/vnext/localRecall.ts
15326
- var MIN_SHARED_TOKENS = 2;
15327
- var MAX_LOCAL_RECALL_STATES = 8;
15328
- var SAFE_TECHNICAL_SYNONYMS = {
15329
- pr: ["\u5BA1\u67E5", "\u4EE3\u7801\u5BA1\u67E5", "diff"],
15330
- diff: ["\u5BA1\u67E5", "\u4EE3\u7801\u5BA1\u67E5"],
15331
- review: ["\u5BA1\u67E5", "\u4EE3\u7801\u5BA1\u67E5"],
15332
- deploy: ["\u90E8\u7F72", "\u53D1\u7248"],
15333
- release: ["\u53D1\u7248", "\u53D1\u5E03"],
15334
- desktop: ["\u684C\u9762", "\u684C\u9762\u7AEF"]
15335
- };
15336
- var distinctTokens = (text) => new Set(tokenize2(text).filter((token) => token.length >= 2));
15337
- var recallMemoryVNextLocal = (input) => {
15338
- const rawTokens = distinctTokens(input.query);
15339
- if (rawTokens.size === 0) return [];
15340
- const queryTokens = new Set(rawTokens);
15341
- for (const token of rawTokens) {
15342
- const syns = SAFE_TECHNICAL_SYNONYMS[token.toLowerCase()];
15343
- if (syns) {
15344
- for (const syn of syns) {
15345
- for (const t2 of distinctTokens(syn)) queryTokens.add(t2);
15346
- }
15347
- }
15348
- }
15349
- const entityById = new Map(input.entities.map((entity) => [entity.id, entity]));
15350
- const hits = [];
15351
- for (const state2 of input.states) {
15352
- if (state2.retiredAt || !state2.text.trim()) continue;
15353
- const entity = entityById.get(state2.entityId);
15354
- const haystack = distinctTokens(
15355
- [state2.facet, state2.text, entity?.name ?? "", ...entity?.aliases ?? []].join(" ")
15356
- );
15357
- let sharedTokens = 0;
15358
- for (const token of queryTokens) if (haystack.has(token)) sharedTokens++;
15359
- if (sharedTokens >= MIN_SHARED_TOKENS) hits.push({ state: state2, sharedTokens });
15360
- }
15361
- return hits.sort((a, b) => b.sharedTokens - a.sharedTokens || a.state.id.localeCompare(b.state.id)).slice(0, input.limit ?? MAX_LOCAL_RECALL_STATES);
15362
- };
14728
+ // packages/ai/memory/remember.ts
14729
+ var RESIDENT_MAX_CONTENT_CHARS = 240;
15363
14730
 
15364
14731
  // packages/ai/memory/vnext/pureVNextRuntime.ts
14732
+ function deriveStateResident(state2, ownerType) {
14733
+ if (ownerType !== "user") return false;
14734
+ if (state2.text.trim().length > RESIDENT_MAX_CONTENT_CHARS) return false;
14735
+ return state2.facet === "preference" || state2.facet === "style";
14736
+ }
15365
14737
  var buildSynthesizedStateItem = (state2, entity, ownerType, ownerId) => ({
15366
14738
  id: `vnext-state-${state2.id}`,
15367
14739
  ownerType,
@@ -15376,7 +14748,7 @@ var buildSynthesizedStateItem = (state2, entity, ownerType, ownerId) => ({
15376
14748
  activationCount: 1,
15377
14749
  importance: 0.9,
15378
14750
  confidence: 0.9,
15379
- resident: state2.facet === "preference" || state2.facet === "style"
14751
+ resident: deriveStateResident(state2, ownerType)
15380
14752
  });
15381
14753
  async function resolvePureVNextRuntime(input) {
15382
14754
  const { db, owners, userInput } = input;
@@ -15615,12 +14987,106 @@ var resolveMemoryRuntime = async (input) => {
15615
14987
  return { selectedItems: [], promptBlock: null };
15616
14988
  }
15617
14989
  if (isMemoryVNextPureReadEnabled()) {
15618
- const pure = await resolvePureVNextRuntime({
15619
- db: input.db,
15620
- owners,
15621
- userInput: input.userInput,
15622
- maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET
15623
- });
14990
+ const pureStartedAt = performance.now();
14991
+ let pure;
14992
+ let pureError = null;
14993
+ try {
14994
+ pure = await resolvePureVNextRuntime({
14995
+ db: input.db,
14996
+ owners,
14997
+ userInput: input.userInput,
14998
+ maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET
14999
+ });
15000
+ } catch (error) {
15001
+ pureError = error;
15002
+ pure = { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
15003
+ }
15004
+ const pureLatencyMs = Math.round((performance.now() - pureStartedAt) * 10) / 10;
15005
+ const emitPureRead = (observation) => {
15006
+ try {
15007
+ if (input.pureReadEmit) {
15008
+ input.pureReadEmit(observation);
15009
+ } else if (input.primaryReadEmit) {
15010
+ input.primaryReadEmit({
15011
+ source: observation.source === "vnext" ? "vnext" : "none",
15012
+ legacyHitCount: 0,
15013
+ recalledStateCount: observation.vnextItemCount,
15014
+ vnextLatencyMs: observation.vnextLatencyMs,
15015
+ legacyLatencyMs: 0,
15016
+ contextChars: observation.contextChars,
15017
+ fallbackReason: observation.fallbackReason,
15018
+ error: observation.error
15019
+ });
15020
+ } else {
15021
+ console.info("[memory] vnext pure read", {
15022
+ event: "memory_vnext_pure_read",
15023
+ ...observation
15024
+ });
15025
+ }
15026
+ } catch {
15027
+ }
15028
+ };
15029
+ if (pureError != null) {
15030
+ emitPureRead({
15031
+ source: "none",
15032
+ itemCount: 0,
15033
+ vnextItemCount: 0,
15034
+ vnextLatencyMs: pureLatencyMs,
15035
+ contextChars: 0,
15036
+ fallbackReason: "vnext_error",
15037
+ error: pureError instanceof Error ? pureError.message : String(pureError)
15038
+ });
15039
+ } else if (pure.selectedItems.length === 0) {
15040
+ emitPureRead({
15041
+ source: "none",
15042
+ itemCount: 0,
15043
+ vnextItemCount: 0,
15044
+ vnextLatencyMs: pureLatencyMs,
15045
+ contextChars: 0,
15046
+ fallbackReason: "no_vnext_context"
15047
+ });
15048
+ } else {
15049
+ emitPureRead({
15050
+ source: "vnext",
15051
+ itemCount: pure.selectedItems.length,
15052
+ vnextItemCount: pure.recalledStateCount,
15053
+ vnextLatencyMs: pureLatencyMs,
15054
+ contextChars: pure.promptBlock?.length ?? 0
15055
+ });
15056
+ }
15057
+ const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
15058
+ if (lazyPromotionEnabled2) {
15059
+ void (async () => {
15060
+ const ownerItems = await Promise.all(
15061
+ owners.map(
15062
+ (owner) => loadOwnerItemsFromDb(
15063
+ input.db,
15064
+ owner,
15065
+ input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT
15066
+ )
15067
+ )
15068
+ );
15069
+ const legacyCandidates = ownerItems.flat();
15070
+ if (legacyCandidates.length > 0) {
15071
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
15072
+ input.db,
15073
+ legacyCandidates
15074
+ );
15075
+ if (promotionPick) {
15076
+ await runMemoryVNextLazyPromotion({
15077
+ db: input.db,
15078
+ item: promotionPick.item,
15079
+ selectedIndex: promotionPick.selectedIndex,
15080
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
15081
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
15082
+ provider: input.vNextShadowProvider,
15083
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
15084
+ });
15085
+ }
15086
+ }
15087
+ })().catch(() => {
15088
+ });
15089
+ }
15624
15090
  return {
15625
15091
  selectedItems: pure.selectedItems,
15626
15092
  promptBlock: pure.promptBlock
@@ -15961,11 +15427,49 @@ async function runAgentRunCommand(args, deps) {
15961
15427
  writeUsage(output, deps.commandPath);
15962
15428
  return 1;
15963
15429
  }
15964
- const runner = deps.runner ?? runAgentTurn;
15430
+ const rawRunner = deps.runner ?? runAgentTurn;
15431
+ const watchdogAbort = new AbortController();
15432
+ let activeRunner;
15433
+ const runner = (options) => {
15434
+ activeRunner = Promise.resolve().then(() => rawRunner({ ...options, abortSignal: watchdogAbort.signal })).then((result) => {
15435
+ watchdogAbort.signal.throwIfAborted();
15436
+ return result;
15437
+ });
15438
+ return activeRunner;
15439
+ };
15440
+ const stopWatchdogRunner = async () => {
15441
+ watchdogAbort.abort(new Error("watchdog_stop"));
15442
+ if (!activeRunner) return true;
15443
+ let timer;
15444
+ try {
15445
+ return await Promise.race([
15446
+ activeRunner.then(() => true, () => true),
15447
+ new Promise((resolve6) => {
15448
+ timer = setTimeout(() => resolve6(false), 100);
15449
+ })
15450
+ ]);
15451
+ } finally {
15452
+ if (timer) clearTimeout(timer);
15453
+ }
15454
+ };
15965
15455
  const nowMs = () => deps.now ? deps.now().getTime() : Date.now();
15966
- const childRunId = env.NOLO_AGENT_RUN_ID;
15967
- const hasRegistry = typeof childRunId === "string" && childRunId.length > 0;
15968
- if (hasRegistry) reportRunProcessIdentity(childRunId, { env, homedir: deps.homedir, fs: deps.fs, now: deps.now });
15456
+ let childRunId = env.NOLO_AGENT_RUN_ID;
15457
+ let hasRegistry = typeof childRunId === "string" && childRunId.length > 0;
15458
+ const hostPolicy = () => ({
15459
+ runtimeKey: "local",
15460
+ hostWritesAuthorized: args.includes("--allow-host-writes"),
15461
+ readOnly: args.includes("--read-only"),
15462
+ ...parsed.allowedToolNames ? { allowedToolNames: parsed.allowedToolNames } : {},
15463
+ ...parsed.blockedToolNames ? { blockedToolNames: parsed.blockedToolNames } : {},
15464
+ provenance: "cli-command-authorized"
15465
+ });
15466
+ const locatedExecution = hasRegistry ? readRunRecord(childRunId, { env, homedir: deps.homedir, fs: deps.fs })?.execution : void 0;
15467
+ if (hasRegistry && (parsed.runtimeKey?.trim() === "local" || locatedExecution?.state === "known")) {
15468
+ const implicitReadonlyHost = !parsed.runtimeKey && args.includes("--read-only") && locatedExecution?.state === "known" && locatedExecution.runtimeKey === "local" && locatedExecution.permissions.readOnly;
15469
+ if (parsed.runtimeKey?.trim() !== "local" && !implicitReadonlyHost) throw new Error("[local-writer-resource] child binding runtime mismatch");
15470
+ await awaitLocalWriterChild(childRunId, parsed.cwd ?? process.cwd(), hostPolicy(), { env, homedir: deps.homedir, fs: deps.fs });
15471
+ }
15472
+ if (hasRegistry && parsed.runtimeKey?.trim() !== "local" && locatedExecution?.state !== "known") reportRunProcessIdentity(childRunId, { env, homedir: deps.homedir, fs: deps.fs, now: deps.now });
15969
15473
  const processExit = deps.processExit ?? ((code) => process.exit(code));
15970
15474
  const stallTimeoutMs = resolvePositiveMs(
15971
15475
  deps.stallTimeoutMs ?? env.NOLO_LOCAL_RUN_STALL_TIMEOUT_MS,
@@ -16007,9 +15511,9 @@ async function runAgentRunCommand(args, deps) {
16007
15511
  throw error;
16008
15512
  });
16009
15513
  };
16010
- const exitFromWatchdog = (code) => {
15514
+ const exitFromWatchdog = async (code) => {
16011
15515
  try {
16012
- processExit(code);
15516
+ await exitCliFromWatchdog(code, processExit, stopWatchdogRunner);
16013
15517
  } catch {
16014
15518
  }
16015
15519
  };
@@ -16056,8 +15560,8 @@ async function runAgentRunCommand(args, deps) {
16056
15560
  failureReason: "stalled",
16057
15561
  toolCallCount: currentActivity?.counters?.toolCalls
16058
15562
  });
15563
+ await exitFromWatchdog(outcome.exitCode);
16059
15564
  rejectOnWatchdogFailure?.(new Error(`[nolo] local run ${note}`));
16060
- exitFromWatchdog(outcome.exitCode);
16061
15565
  }
16062
15566
  }, Math.min(stallTimeoutMs, 1e4));
16063
15567
  }
@@ -16071,8 +15575,8 @@ async function runAgentRunCommand(args, deps) {
16071
15575
  terminalStatus.fail();
16072
15576
  const outcome = resolveRunOutcome({ kind: "timeout" });
16073
15577
  await finalizeWatchdogOutcome(outcome, note);
15578
+ await exitFromWatchdog(outcome.exitCode);
16074
15579
  rejectOnWatchdogFailure?.(new Error(`[nolo] local run ${note}`));
16075
- exitFromWatchdog(outcome.exitCode);
16076
15580
  }, parsed.timeoutMs);
16077
15581
  }
16078
15582
  const wantsFallbackSuggestions = parsed.fallbackAgentKeys && parsed.fallbackAgentKeys.length > 0;
@@ -16081,8 +15585,8 @@ async function runAgentRunCommand(args, deps) {
16081
15585
  const explicitLocalCli = isLocalCliAgentKey(parsed.agentKey);
16082
15586
  const dockerRuntimeLocal = typeof parsed.runtimeKey === "string" && /^docker(:.+)?$/.test(parsed.runtimeKey.trim());
16083
15587
  const instaboxRuntimeLocal = typeof parsed.runtimeKey === "string" && parsed.runtimeKey.trim() === "instabox";
16084
- const hostRuntimeLocal = typeof parsed.runtimeKey === "string" && parsed.runtimeKey.trim() === "local";
16085
- if (hostRuntimeLocal && !args.includes("--allow-host-writes")) {
15588
+ const hostRuntimeLocal = typeof parsed.runtimeKey === "string" && parsed.runtimeKey.trim() === "local" || !parsed.runtimeKey && args.includes("--read-only") && locatedExecution?.state === "known" && locatedExecution.runtimeKey === "local" && locatedExecution.permissions.readOnly;
15589
+ if (hostRuntimeLocal && !args.includes("--read-only") && !args.includes("--allow-host-writes")) {
16086
15590
  output.write(t("agentRun.hostWriteGuard"));
16087
15591
  return 1;
16088
15592
  }
@@ -16219,6 +15723,9 @@ async function runAgentRunCommand(args, deps) {
16219
15723
  if (!localRuntimeCwd && (parsed.runtimeMode === "local" || hostRuntimeLocal)) {
16220
15724
  localRuntimeCwd = process.cwd();
16221
15725
  }
15726
+ const acceptanceCwd = localRuntimeCwd && (parsed.runtimeMode === "local" || hostRuntimeLocal) ? localRuntimeCwd : void 0;
15727
+ const acceptanceBase = acceptanceCwd ? await (deps.captureLocalRunBase ?? captureLocalRunBase)(acceptanceCwd, deps.localRunBaseCaptureOptions) : null;
15728
+ let finalWorkspaceInspection;
16222
15729
  if (parsed.runtimeKey === "instabox") {
16223
15730
  try {
16224
15731
  writeInstaboxRunConfig({
@@ -16246,9 +15753,20 @@ async function runAgentRunCommand(args, deps) {
16246
15753
  cliEntrypointPath: deps.cliEntrypointPath,
16247
15754
  agentKey,
16248
15755
  cwd: localRuntimeCwd,
15756
+ ...hostRuntimeLocal ? { localExecution: {
15757
+ runtimeKey: "local",
15758
+ hostWritesAuthorized: args.includes("--allow-host-writes"),
15759
+ readOnly: args.includes("--read-only"),
15760
+ ...parsed.allowedToolNames ? { allowedToolNames: parsed.allowedToolNames } : {},
15761
+ ...parsed.blockedToolNames ? { blockedToolNames: parsed.blockedToolNames } : {},
15762
+ provenance: "cli-command-authorized"
15763
+ } } : {},
15764
+ // Explicit host target is authorized above; read-only retains its existing tool restrictions.
15765
+ ...hostRuntimeLocal && !args.includes("--read-only") ? { claimLocalWrites: true } : {},
16249
15766
  msgFile: readFlagValue(args, "--msg-file"),
16250
15767
  message: parsed.message,
16251
15768
  timeoutMs: parsed.timeoutMs,
15769
+ ...parsed.ephemeral ? { ephemeral: true } : {},
16252
15770
  ...parsed.dodCommands?.length ? { dodCommands: parsed.dodCommands } : {},
16253
15771
  output
16254
15772
  },
@@ -16278,6 +15796,15 @@ async function runAgentRunCommand(args, deps) {
16278
15796
  const isSubtask = isSubtaskRun(env);
16279
15797
  const scopedLayers = [];
16280
15798
  const skillContentBlocks = [];
15799
+ if (hostRuntimeLocal && !parsed.background) {
15800
+ const policy = { ...hostPolicy(), ...skillAllowedToolOverride !== void 0 ? { allowedToolNames: skillAllowedToolOverride } : {} };
15801
+ if (hasRegistry) {
15802
+ await awaitLocalWriterChild(childRunId, localRuntimeCwd, policy, { env, homedir: deps.homedir, fs: deps.fs });
15803
+ } else if (!policy.readOnly) {
15804
+ childRunId = registerLocalForegroundWriter(localRuntimeCwd, policy, agentKey, { env, homedir: deps.homedir, fs: deps.fs, now: deps.now });
15805
+ hasRegistry = true;
15806
+ }
15807
+ }
16281
15808
  const extraContextBlocks = [];
16282
15809
  const contextBlockScopes = [];
16283
15810
  let memoryPromptBlock = null;
@@ -16408,6 +15935,7 @@ async function runAgentRunCommand(args, deps) {
16408
15935
  })
16409
15936
  );
16410
15937
  clearWatchdogs();
15938
+ const runCommandObservations = [...getRunResultHeaderMeta(result).commandObservations ?? []];
16411
15939
  let runCreditsTotal = result.turnCredits;
16412
15940
  let runCacheUsage = summarizeCacheUsageRecords(result.usageRecords);
16413
15941
  if (result.exitCode !== 0 && isQuotaExhaustedError(result.localError) && isLocalRun && parsed.fallbackAgentKeys && parsed.fallbackAgentKeys.length > 0) {
@@ -16423,6 +15951,7 @@ async function runAgentRunCommand(args, deps) {
16423
15951
  })
16424
15952
  );
16425
15953
  clearWatchdogs();
15954
+ runCommandObservations.push(...getRunResultHeaderMeta(fallbackResult).commandObservations ?? []);
16426
15955
  if (fallbackResult.exitCode === 0) {
16427
15956
  result = fallbackResult;
16428
15957
  }
@@ -16475,6 +16004,7 @@ async function runAgentRunCommand(args, deps) {
16475
16004
  })
16476
16005
  );
16477
16006
  clearWatchdogs();
16007
+ runCommandObservations.push(...getRunResultHeaderMeta(turnResult).commandObservations ?? []);
16478
16008
  result = turnResult;
16479
16009
  if (turnResult.turnCredits !== void 0) {
16480
16010
  runCreditsTotal = (runCreditsTotal ?? 0) + turnResult.turnCredits;
@@ -16503,11 +16033,6 @@ async function runAgentRunCommand(args, deps) {
16503
16033
  );
16504
16034
  }
16505
16035
  }
16506
- terminalStatus.settle({
16507
- exitCode: result.exitCode,
16508
- streamInterrupted: result.streamInterrupted,
16509
- stalledOrTruncated: isRunResultStalledOrTruncated(result)
16510
- });
16511
16036
  if (result.dialogId) {
16512
16037
  if (parsed.background) {
16513
16038
  output.write(`
@@ -16521,11 +16046,12 @@ async function runAgentRunCommand(args, deps) {
16521
16046
  `);
16522
16047
  }
16523
16048
  }
16524
- if (shouldPrintLocalRunSummary({ parsed, localRuntimeCwd })) {
16049
+ if (acceptanceCwd || shouldPrintLocalRunSummary({ parsed, localRuntimeCwd })) {
16525
16050
  try {
16526
16051
  const inspect = deps.inspectLocalRunWorkspace ?? inspectLocalRunWorkspace;
16527
- const inspection = await inspect(localRuntimeCwd);
16528
- output.write(formatLocalRunSummary({
16052
+ const inspection = await inspect(localRuntimeCwd, {}, acceptanceCwd ? acceptanceBase : void 0);
16053
+ finalWorkspaceInspection = inspection;
16054
+ if (shouldPrintLocalRunSummary({ parsed, localRuntimeCwd })) output.write(formatLocalRunSummary({
16529
16055
  dialogId: result.dialogId,
16530
16056
  inspection
16531
16057
  }));
@@ -16564,6 +16090,8 @@ async function runAgentRunCommand(args, deps) {
16564
16090
  if (outcome.status === "failed") {
16565
16091
  if (result.emptyAssistantFallbackReason === "repetition_loop" || result.emptyAssistantFallbackReason === "stagnant_tool_calls") {
16566
16092
  failureReason = "stalled";
16093
+ } else if (result.localError && isHistoryIntegrityFailure(toErrorMessage(result.localError))) {
16094
+ failureReason = "history_integrity";
16567
16095
  } else if (result.localError && isQuotaExhaustedError(result.localError)) {
16568
16096
  failureReason = "provider_rate_limited";
16569
16097
  } else if (result.localError) {
@@ -16580,37 +16108,74 @@ async function runAgentRunCommand(args, deps) {
16580
16108
  toolCallCount = rawToolCount;
16581
16109
  }
16582
16110
  }
16583
- await settleRunTerminalAuthoritatively(
16584
- childRunId,
16585
- {
16586
- status: outcome.status,
16587
- exitCode: outcome.exitCode,
16588
- dialogId: result.dialogId,
16589
- ...dodResults ? { dodResults } : {},
16590
- // run 级累计的平台积分(主轮 + fallback + drain 轮):dock 行据此显示
16591
- // 「⚡ x.xx」,让派发任务的消耗可见。undefined = 全程无平台计费。
16592
- ...runCreditsTotal !== void 0 ? { credits: runCreditsTotal } : {},
16593
- // run 级缓存命中汇总:只进 .result.md 的 front matter(cached_tokens
16594
- // 为 null 表示 provider 未报缓存指标,与「命中 0」严格区分)。
16595
- ...runCacheUsage ? { cacheUsage: runCacheUsage } : {},
16596
- ...failureReason ? { failureReason } : {},
16597
- ...toolCallCount !== void 0 ? { toolCallCount } : {},
16598
- ...result.finalText ? { lastAssistantText: result.finalText } : {},
16599
- // 仅用于 .result.md 头(front matter):旁路读取,不改 result 形状。
16600
- ...getRunResultHeaderMeta(result),
16601
- ...truncationNote
16602
- },
16603
- {
16604
- env,
16605
- homedir: deps.homedir,
16606
- fs: deps.fs,
16607
- now: deps.now,
16608
- sleep: deps.sleep
16609
- },
16610
- deps.transitionRunToTerminal
16111
+ const acceptance = acceptanceCwd ? finalWorkspaceInspection?.acceptance ?? unknownLocalRunAcceptance(acceptanceCwd, acceptanceBase) : void 0;
16112
+ if (acceptance && dodResults?.length) {
16113
+ acceptance.checks.observations = dodResults.map((check, index) => ({
16114
+ // Command lines/output can contain credentials. Persist only a digest
16115
+ // here; the pre-existing registry is the execution evidence reference.
16116
+ commandFingerprint: `sha256:${createHash("sha256").update(check.command).digest("hex")}`,
16117
+ cwd: childRecordForDoD?.cwd || process.cwd(),
16118
+ exitCode: check.exitCode,
16119
+ evidence: `${childRunId}.json#/dodResults/${index}`,
16120
+ versionBinding: "unknown"
16121
+ }));
16122
+ }
16123
+ if (acceptance) attachLocalCommandObservations(
16124
+ acceptance,
16125
+ runCommandObservations,
16126
+ `${childRunId}.result.md`
16611
16127
  );
16128
+ let settlement;
16129
+ try {
16130
+ settlement = await settleRunTerminalAuthoritatively(
16131
+ childRunId,
16132
+ {
16133
+ status: outcome.status,
16134
+ exitCode: outcome.exitCode,
16135
+ dialogId: result.dialogId,
16136
+ ...dodResults ? { dodResults } : {},
16137
+ // run 级累计的平台积分(主轮 + fallback + drain 轮):dock 行据此显示
16138
+ // 「⚡ x.xx」,让派发任务的消耗可见。undefined = 全程无平台计费。
16139
+ ...runCreditsTotal !== void 0 ? { credits: runCreditsTotal } : {},
16140
+ // run 级缓存命中汇总:只进 .result.md 的 front matter(cached_tokens
16141
+ // 为 null 表示 provider 未报缓存指标,与「命中 0」严格区分)。
16142
+ ...runCacheUsage ? { cacheUsage: runCacheUsage } : {},
16143
+ ...failureReason ? { failureReason } : {},
16144
+ ...toolCallCount !== void 0 ? { toolCallCount } : {},
16145
+ ...acceptance ? { acceptance } : {},
16146
+ ...result.finalText ? { lastAssistantText: result.finalText } : {},
16147
+ // 仅用于 .result.md 头(front matter):旁路读取,不改 result 形状。
16148
+ ...getRunResultHeaderMeta(result),
16149
+ ...truncationNote
16150
+ },
16151
+ {
16152
+ env,
16153
+ homedir: deps.homedir,
16154
+ fs: deps.fs,
16155
+ now: deps.now,
16156
+ sleep: deps.sleep
16157
+ },
16158
+ deps.transitionRunToTerminal
16159
+ );
16160
+ } catch (error) {
16161
+ terminalStatus.fail();
16162
+ output.write(`[nolo] terminal settlement failed: ${error instanceof Error ? error.message : String(error)}
16163
+ `);
16164
+ return 1;
16165
+ }
16166
+ if (settlement && (settlement.kind === "transitioned" || settlement.kind === "kept" || settlement.kind === "contended") && settlement.record.status !== "done" && result.exitCode === 0) {
16167
+ result = { ...result, exitCode: settlement.record.exitCode || 1 };
16168
+ }
16612
16169
  }
16170
+ terminalStatus.settle({
16171
+ exitCode: result.exitCode,
16172
+ streamInterrupted: result.streamInterrupted,
16173
+ stalledOrTruncated: isRunResultStalledOrTruncated(result)
16174
+ });
16613
16175
  return result.exitCode;
16176
+ } catch (error) {
16177
+ terminalStatus.fail();
16178
+ throw error;
16614
16179
  } finally {
16615
16180
  shellApprovalChild?.close();
16616
16181
  if (shellApprovalChild && process.connected) process.disconnect();
@@ -16620,22 +16185,6 @@ async function runAgentRunCommand(args, deps) {
16620
16185
  export {
16621
16186
  resolveCliColorEnabled,
16622
16187
  dimCliText,
16623
- ANSI_ESCAPE_REGEX,
16624
- stripAnsi2 as stripAnsi,
16625
- applyTerminalOutputToText,
16626
- displayWidth,
16627
- visibleWidth,
16628
- truncateAnsi,
16629
- fitAnsiLine,
16630
- countPhysicalLines,
16631
- takeDisplayWidth,
16632
- padOrTruncateToWidth,
16633
- tokenizeAnsiLine,
16634
- buildSourceMapping,
16635
- wrapTranscriptLineWithLayout,
16636
- wrapTranscriptLine,
16637
- buildWindowTitle,
16638
- wrapTextToLines,
16639
16188
  THEME_PALETTES,
16640
16189
  getActiveThemeName,
16641
16190
  setActiveThemeName,
@@ -16657,9 +16206,10 @@ export {
16657
16206
  setMathRenderingEnabled,
16658
16207
  polishBreathInsertsBlankBetween,
16659
16208
  formatAssistantDisplay,
16660
- redactSecrets,
16661
- safeAskText,
16209
+ resolveHistoryLayoutGeometry,
16210
+ resolveHistoryViewportHeight,
16662
16211
  TUI_TREE_MARKER,
16212
+ TUI_TREE_TOOLS,
16663
16213
  resolveAgentModelIdentity,
16664
16214
  resolveAgentContextWindow2 as resolveAgentContextWindow,
16665
16215
  platformCreditsFromUsage,
@@ -16667,6 +16217,7 @@ export {
16667
16217
  formatTokenCount,
16668
16218
  resolveAuthorityTurnCount,
16669
16219
  computeBaselineContextTokens,
16220
+ preserveContextUsageWithoutReceipt,
16670
16221
  resolveContextUsage,
16671
16222
  renderTokenStatus,
16672
16223
  createIdleHeapReleaser,
@@ -16682,10 +16233,13 @@ export {
16682
16233
  findCollapsedPasteSpanAt,
16683
16234
  readAgentsMdLayerFromDisk,
16684
16235
  emitTerminalProgramStatus,
16236
+ contextRefusalDiagnostics,
16237
+ describeContextRefusal,
16685
16238
  isBalanceExhaustedError,
16686
16239
  OWNER_OAUTH_UNAVAILABLE_HINT,
16687
16240
  isOwnerOAuthUnavailableError,
16688
16241
  isInvalidGrantError,
16242
+ isLocalContextCoverageFailure,
16689
16243
  runAgentTurn,
16690
16244
  resolveWorkflowReference,
16691
16245
  resolveSkillReference,
@@ -16697,7 +16251,6 @@ export {
16697
16251
  FAILED_EMPTY_ASSISTANT_REASONS,
16698
16252
  isRunResultStalledOrTruncated,
16699
16253
  resolveTerminalProgramStatusState,
16700
- inspectLocalRunWorkspace,
16701
16254
  resolveRunOutcome,
16702
16255
  resolveRunSettlementNote,
16703
16256
  runAgentRunCommand