nolo-cli 0.212.0-alpha.1 → 0.222.0-alpha.2

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 (263) hide show
  1. package/README.md +3 -2
  2. package/{_executeModel-KE6MBNUJ.js → _executeModel-4GGQQHOB.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-N2YC5IL3.js → addContentAction-GDHDOF4U.js} +18 -17
  6. package/{addDialogAgentAction-3NKVQCEC.js → addDialogAgentAction-CAKRU3ZT.js} +21 -20
  7. package/{agentDeleteCommand-NWK7VU4N.js → agentDeleteCommand-BPV2XZL7.js} +128 -119
  8. package/{agentEmailCommands-UZ4DHEX2.js → agentEmailCommands-EJOS75YL.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-HE7L2A6L.js → agentListCommands-HIZODBF3.js} +196 -124
  12. package/{agentMachineCommands-6TE4MBMP.js → agentMachineCommands-ZMQ2CY7Y.js} +62 -53
  13. package/{agentProviderCommands-Q5O33MED.js → agentProviderCommands-WKJOAWBP.js} +5 -5
  14. package/{agentPullCommand-6EM3URVK.js → agentPullCommand-XN6ZPBUW.js} +7 -7
  15. package/agentRecordCommands-OMXVDLDX.js +176 -0
  16. package/agentRunCommand-CB34YWMV.js +206 -0
  17. package/{agentRunControl-OI3LOENH.js → agentRunControl-JNONH3RP.js} +30 -15
  18. package/{agentRuntimeLocal-HL526DNQ.js → agentRuntimeLocal-QZPFWMLG.js} +52 -45
  19. package/{agentSlice-TMYP2UEA.js → agentSlice-RD2CDU7T.js} +20 -19
  20. package/{appDeleteCommands-ZERW4AXY.js → appDeleteCommands-QCCFDIEQ.js} +61 -52
  21. package/{appDeployCommands-DUWSMYHL.js → appDeployCommands-V2T7TNMQ.js} +61 -52
  22. package/{appDeployStatusCommands-N2KIE4BF.js → appDeployStatusCommands-6PGH7ZCG.js} +61 -52
  23. package/{appGetCommands-YVR4NPVY.js → appGetCommands-3L7WWJA6.js} +61 -52
  24. package/{appListCommands-JS6HOHZS.js → appListCommands-ENJCK4PO.js} +61 -52
  25. package/{authCommand-FE2C3ZUM.js → authCommand-6V47SYGK.js} +29 -28
  26. package/{authCommands-HV3EAU3V.js → authCommands-GAJ3NIXO.js} +14 -13
  27. package/{builtinSkillRegistry-3YOIGEF6.js → builtinSkillRegistry-2ECA42FC.js} +11 -13
  28. package/{chromeCommands-REEAH4SX.js → chromeCommands-G5UDKVSV.js} +3 -3
  29. package/{chromeOpsCommands-HEN5AX2J.js → chromeOpsCommands-YKX2QX3A.js} +20 -10
  30. package/{chunk-DM6UMOEL.js → chunk-27PCUMJI.js} +2 -2
  31. package/chunk-2CI3ZFWD.js +97 -0
  32. package/{chunk-HIRC32DV.js → chunk-2GJKRKI6.js} +543 -29
  33. package/{chunk-SM3NSZJV.js → chunk-2UCBGYO4.js} +20 -1
  34. package/{chunk-PYRUW7XN.js → chunk-2VUZSVAS.js} +136 -54
  35. package/chunk-2YGBI2XB.js +30 -0
  36. package/chunk-2ZKFCIJJ.js +13 -0
  37. package/{chunk-CJRONOYL.js → chunk-34J5K2YA.js} +19 -75
  38. package/{chunk-LOEO7LRC.js → chunk-3IK6ILVW.js} +4 -1
  39. package/{chunk-CTPXME7U.js → chunk-3LMUPOHG.js} +29 -6
  40. package/chunk-44X52WOJ.js +1621 -0
  41. package/{chunk-6VLJ6YA7.js → chunk-4DESLZTK.js} +9 -9
  42. package/{chunk-MYOH447Z.js → chunk-4JVNURX4.js} +1 -1
  43. package/chunk-5CHGAKRT.js +364 -0
  44. package/{chunk-YDH3FDFQ.js → chunk-5FUN7EG4.js} +1 -1
  45. package/{chunk-LKDF3ATR.js → chunk-5RKUPJYL.js} +1 -1
  46. package/{chunk-ZC3CMUKU.js → chunk-6OVNSQHN.js} +84 -2
  47. package/{chunk-IF45XG7K.js → chunk-6WU5572L.js} +40 -24
  48. package/{chunk-OHNELDTO.js → chunk-7EEZJ6BS.js} +11 -152
  49. package/{chunk-Y6ORVLSS.js → chunk-7ET2U67U.js} +1 -1
  50. package/{chunk-G7MLNNEX.js → chunk-7JLY4WYF.js} +5 -5
  51. package/{chunk-P5L7CXOC.js → chunk-7Z6EW7AH.js} +3 -2
  52. package/{chunk-IIQ6JGRI.js → chunk-AD5EWDFD.js} +2 -2
  53. package/{chunk-WXYLV624.js → chunk-AIHYNKGV.js} +4 -4
  54. package/{chunk-HPFCI4SK.js → chunk-AK5O76CC.js} +3 -3
  55. package/{chunk-Y63ZSOR6.js → chunk-AL3TYDIF.js} +1 -1
  56. package/{chunk-PJNFNEJE.js → chunk-AMEOV5VZ.js} +59 -13
  57. package/chunk-AN74ON4G.js +675 -0
  58. package/{chunk-HRMJUN5J.js → chunk-AQZ6BMRK.js} +1 -1
  59. package/{chunk-CQ46IRNN.js → chunk-B4GOW4MT.js} +445 -201
  60. package/{chunk-4KB6WQUL.js → chunk-BGP2EDFG.js} +1 -1
  61. package/{chunk-NBTY7YJF.js → chunk-BR3GT6MR.js} +1 -0
  62. package/{chunk-7RFNTILS.js → chunk-BUDVRYES.js} +2 -2
  63. package/{chunk-D2MDMY2M.js → chunk-BV3FLP2L.js} +47 -1
  64. package/{chunk-25JZEIXN.js → chunk-C4VAR65S.js} +92 -150
  65. package/{chunk-AVTVGMDY.js → chunk-C4WTX5TU.js} +2 -2
  66. package/{chunk-ZL5RAEEB.js → chunk-CIRB724Q.js} +1 -1
  67. package/{chunk-F6UUQOG6.js → chunk-CKT6QUE2.js} +4 -4
  68. package/{chunk-M6RL5JCD.js → chunk-CMZ3Z5PT.js} +14 -14
  69. package/{secretCommands-4QS3HCA2.js → chunk-D726I5AZ.js} +191 -16
  70. package/{chunk-INSBKSBB.js → chunk-DNKTQ3IN.js} +4 -4
  71. package/chunk-DVQH4BTR.js +1137 -0
  72. package/{chunk-SOHTHFV2.js → chunk-DWX2HEVC.js} +91 -132
  73. package/{chunk-NOMIGOST.js → chunk-EIAI3PPH.js} +116 -124
  74. package/chunk-EUCFKKDM.js +247 -0
  75. package/chunk-EWQ3HGNZ.js +90 -0
  76. package/{chunk-RPQXPZZF.js → chunk-F3GRJO4Z.js} +908 -13
  77. package/{chunk-GSQNH63I.js → chunk-FIYSMXHY.js} +3 -19
  78. package/{chunk-KSTEXKL6.js → chunk-FJ23FZXF.js} +76 -31
  79. package/{chunk-INN4LTAJ.js → chunk-FJK526XH.js} +2 -2
  80. package/chunk-FS2XP5D7.js +142 -0
  81. package/{chunk-QT6PKHYJ.js → chunk-FYF2TONJ.js} +5 -5
  82. package/{chunk-OXME3PEE.js → chunk-GBWGPTA7.js} +2 -1
  83. package/{chunk-RU4SD66C.js → chunk-GYVCJABP.js} +30 -254
  84. package/{chunk-YUXQAVRD.js → chunk-HOCHUZQ7.js} +257 -90
  85. package/{chunk-Y2WUYX4I.js → chunk-HXER7YJF.js} +4 -4
  86. package/chunk-HYIETXA6.js +99 -0
  87. package/{chunk-H2TJUNCH.js → chunk-I4EADJ4P.js} +6 -6
  88. package/{chunk-TCZHTTUU.js → chunk-I7WBYGBP.js} +8 -8
  89. package/{chunk-5RYBGBQH.js → chunk-IILMY4W4.js} +14 -9
  90. package/chunk-JA3ICVJY.js +271 -0
  91. package/{chunk-ZRSNONOB.js → chunk-JWXITTQB.js} +8 -3
  92. package/{chunk-JNKSDZFS.js → chunk-KEN3N2TN.js} +310 -66
  93. package/{chunk-LEC5ALIN.js → chunk-KEPOVMF4.js} +1 -1
  94. package/{chunk-UHJGXRJ4.js → chunk-KQSYAIZR.js} +3 -3
  95. package/{chunk-4VJAC32I.js → chunk-L5I543VB.js} +3 -2
  96. package/chunk-LKA64WH4.js +227 -0
  97. package/{chunk-6OQUPIQF.js → chunk-LVL6GFCM.js} +4 -4
  98. package/{chunk-UTV2AYEG.js → chunk-MAIITKBT.js} +2 -2
  99. package/chunk-MBG66ZBH.js +226 -0
  100. package/{chunk-YUA6OAH5.js → chunk-MDLS23JK.js} +2 -2
  101. package/{chunk-VL5KOY2C.js → chunk-MK2Q7ZJD.js} +67 -5
  102. package/{chunk-B7NJ3T4A.js → chunk-MS4NZNKI.js} +10 -10
  103. package/{chunk-3AKFVZ2I.js → chunk-MYHNBEXD.js} +3 -3
  104. package/{chunk-VZKUKCA6.js → chunk-MZLE5HQ3.js} +3673 -241
  105. package/{chunk-AZMYUSVF.js → chunk-N5Z2V73W.js} +1 -1
  106. package/chunk-NIZ2BXFD.js +526 -0
  107. package/{chunk-YPD3VJZW.js → chunk-NWP2OYOX.js} +20 -20
  108. package/{chunk-3FOQHGHN.js → chunk-O6J3OTOP.js} +4 -4
  109. package/{chunk-3RQVYR4B.js → chunk-OB6DVWPF.js} +197 -65
  110. package/{chunk-YWSEPJ7C.js → chunk-OBWT45ZU.js} +3 -3
  111. package/{chunk-5AQR3DGV.js → chunk-ODJ7BVSI.js} +80 -11
  112. package/{chunk-XJWWBO34.js → chunk-OJKUU3LP.js} +5 -7
  113. package/{chunk-GNDJKC4B.js → chunk-ON37YXGX.js} +29 -29
  114. package/{chunk-D5RCRX4A.js → chunk-P5ZJRTCH.js} +9415 -5169
  115. package/{chunk-6XIE5ZGI.js → chunk-PDCV7P5W.js} +1 -1
  116. package/{chunk-EZFQ6XRV.js → chunk-PJCIP64Z.js} +861 -59
  117. package/{chunk-GPO7FCEZ.js → chunk-PJVKMGPZ.js} +1222 -1719
  118. package/{chunk-CKAHAVMK.js → chunk-PPJYZRSQ.js} +40 -26
  119. package/chunk-QHEN7NZ7.js +46 -0
  120. package/{chunk-4KH4J3G5.js → chunk-QNWG52I4.js} +19 -7
  121. package/{chunk-YGILMZ7N.js → chunk-QVBXJNZ2.js} +1 -1
  122. package/chunk-RDH5CQ4T.js +1382 -0
  123. package/{chunk-C6KNNXWU.js → chunk-RGQ4UUWZ.js} +25 -2
  124. package/{chunk-OWYYDMGJ.js → chunk-S2NTVGA2.js} +4 -2
  125. package/{chunk-KC4XDTT3.js → chunk-SOF4OWDM.js} +6 -4
  126. package/{chunk-IAPCBNEE.js → chunk-SQYIK6HO.js} +1 -1
  127. package/{chunk-22CIEBYO.js → chunk-SVT62ULE.js} +50 -48
  128. package/{chunk-KIM6CLW5.js → chunk-SY3C4SQ7.js} +42 -15
  129. package/{chunk-JY5NGFFH.js → chunk-SYTHYBMI.js} +5 -5
  130. package/{chunk-6NSSLV67.js → chunk-T6DXNI6Z.js} +52 -50
  131. package/chunk-TLE77UJ5.js +230 -0
  132. package/{chunk-4VNS5WPM.js → chunk-U67V476Y.js} +1 -8
  133. package/{chunk-F7CI2ZC5.js → chunk-UAIHKQIA.js} +2 -1
  134. package/{chunk-MMNYUVLW.js → chunk-UB3D4TRQ.js} +11 -77
  135. package/{chunk-WPORQFYN.js → chunk-UVLYNWIE.js} +2 -2
  136. package/{chunk-YOIW77S2.js → chunk-UYOICCYG.js} +29 -19
  137. package/{chunk-4I7ERB7F.js → chunk-VREDDN25.js} +1 -1
  138. package/{chunk-JIT6FSXJ.js → chunk-WAE3GFCJ.js} +3 -3
  139. package/{chunk-IJXYFTV7.js → chunk-WI67URFP.js} +20 -20
  140. package/{chunk-7OCO4TDT.js → chunk-WJVYAO6P.js} +1 -1
  141. package/{chunk-T43B7LB2.js → chunk-WKGQSYTB.js} +1 -1
  142. package/{chunk-YJMRHHGY.js → chunk-WUUH4LWZ.js} +60 -30
  143. package/{chunk-PDGKOTO7.js → chunk-X7UF53VA.js} +33 -22
  144. package/{chunk-TY3TIUJK.js → chunk-XI2BWJM5.js} +65 -0
  145. package/{chunk-OOF4UPC5.js → chunk-XWVCYUUU.js} +16 -159
  146. package/{chunk-J5JTMQIA.js → chunk-YFLVRVYK.js} +1 -1
  147. package/{chunk-EYLGAEB4.js → chunk-YGMBIXCF.js} +132 -0
  148. package/chunk-YL3EFYL3.js +199 -0
  149. package/{chunk-MMA3LZ3W.js → chunk-YNIYE47Z.js} +1 -1
  150. package/{chunk-W4S457LU.js → chunk-YU4ZPWVF.js} +41 -5
  151. package/{chunk-NJR3WKVP.js → chunk-YWWDC3O7.js} +281 -159
  152. package/chunk-YZMNK53S.js +68 -0
  153. package/{chunk-FHU44LN3.js → chunk-Z2PITYZN.js} +2179 -552
  154. package/{chunk-FY7F4Q6X.js → chunk-Z4PCXPUE.js} +2 -2
  155. package/{cliAgentConfigHelpers-WJBZQTLW.js → cliAgentConfigHelpers-TKYL43MT.js} +15 -16
  156. package/{cliAuthorityBrokerClient-PM3U6Q6J.js → cliAuthorityBrokerClient-XHH7MH2P.js} +1 -1
  157. package/{cliAuthorityStoreDriver-TKLXNNTG.js → cliAuthorityStoreDriver-6FE3BJNB.js} +1 -1
  158. package/{cliEnvHelpers-BVYTMUPJ.js → cliEnvHelpers-VPSJ4XWC.js} +3 -3
  159. package/{cliExecutor-BWBF2MTI.js → cliExecutor-4MAX3PZL.js} +2 -2
  160. package/cliLocalAgentRecordReader-MHHD4T7R.js +90 -0
  161. package/{commandRegistry-VVMTPFAX.js → commandRegistry-5DA5UP7S.js} +106 -98
  162. package/{contentThunks-N52O67MI.js → contentThunks-5GUQ7FWJ.js} +47 -43
  163. package/{cooldownCommands-YXLWOXWR.js → cooldownCommands-X7P5M2V5.js} +5 -4
  164. package/{createAgentAutomationAction-ZC57YRSV.js → createAgentAutomationAction-UCLTHQRI.js} +51 -49
  165. package/{createDialogAction-VQW5WDYX.js → createDialogAction-UPN774AF.js} +46 -48
  166. package/{createPageAction-M5VDA7SC.js → createPageAction-JRQ2TA4O.js} +50 -48
  167. package/{cursorProvider-YGGNMVWX.js → cursorProvider-2RACMEMF.js} +1 -1
  168. package/{db-HUCI5R4G.js → db-CS4ZJQKV.js} +1 -1
  169. package/{dbSlice-HP7G4LX3.js → dbSlice-WNON7TOL.js} +17 -16
  170. package/{deleteFile-7VQGLK2V.js → deleteFile-Q3YDB4ML.js} +9 -9
  171. package/{desktopFolderProjects-SFY5EZS3.js → desktopFolderProjects-4POAMVJN.js} +2 -2
  172. package/{dialogCommands-JHMR2N2Y.js → dialogCommands-VRI7VCXH.js} +64 -57
  173. package/dialogNotifyCommand-6TMCX4D2.js +36 -0
  174. package/{dialogSlice-GRSVGDTF.js → dialogSlice-LFNVUSAN.js} +42 -40
  175. package/{dialogUsageCommand-7KCPYGHG.js → dialogUsageCommand-HTVPR2CX.js} +11 -10
  176. package/{docCreateCommands-F2K3UPSQ.js → docCreateCommands-AMPXMOX3.js} +61 -54
  177. package/{docDeleteCommands-XGXB5RFT.js → docDeleteCommands-I5WFAEHP.js} +63 -57
  178. package/{docReadCommands-7HWZZV6J.js → docReadCommands-X53ELNIE.js} +61 -54
  179. package/{docStore-KNZK6Y2G.js → docStore-2VAWVLWH.js} +21 -20
  180. package/{docUpdateCommands-OZZ7NQII.js → docUpdateCommands-6QPNDC7M.js} +64 -57
  181. package/{fetchMessages-M3QU7ZCQ.js → fetchMessages-TQEUZD7H.js} +8 -7
  182. package/{getPricing-2MNMXEVG.js → getPricing-MB2GBXOK.js} +6 -6
  183. package/{handleSendMessageAction-SHIH74GJ.js → handleSendMessageAction-AAJOHXOB.js} +193 -301
  184. package/{hostCredentialCreate-X64WK4JD.js → hostCredentialCreate-GLMJ22M6.js} +123 -114
  185. package/index.js +29 -29
  186. package/{keys-BEGDOTRL.js → keys-RWF7UCB4.js} +5 -4
  187. package/legacyMigration-TF4SYJCZ.js +19 -0
  188. package/{lib-5KKIBFIT.js → lib-OT5OTXRU.js} +7087 -6664
  189. package/{localDialogRead-XRLAH4CZ.js → localDialogRead-SVTPA5GY.js} +3 -3
  190. package/{localFirstLog-DHNOY2NA.js → localFirstLog-OIETGK66.js} +1 -1
  191. package/localRecall-2J6QPOK2.js +15 -0
  192. package/{localRuntimeAdapter-A7K3ABA6.js → localRuntimeAdapter-BMP57P42.js} +119 -110
  193. package/{localRuntimeAuthority-OYH4AE4G.js → localRuntimeAuthority-IBJAT62G.js} +1 -1
  194. package/{localRuntimeDb-VBIMCWUC.js → localRuntimeDb-N7KHDXS2.js} +2 -2
  195. package/{machineCommands-DE3MR7CJ.js → machineCommands-3MLIAK5Q.js} +128 -119
  196. package/{machineInfo-UKPTZO5Y.js → machineInfo-LWHTEBHJ.js} +1 -1
  197. package/machineWsRunDispatch-FKIGROQF.js +191 -0
  198. package/{memberThunks-7WJAY5V6.js → memberThunks-ZGLZ36PK.js} +29 -28
  199. package/{memoryCommands-ASCE5STX.js → memoryCommands-5WC3T66U.js} +4 -4
  200. package/models-ULVWLSQ6.js +9 -0
  201. package/{oauthTokenStore-OEERZFUC.js → oauthTokenStore-RUYNYALS.js} +1 -1
  202. package/{offlineMarxistsAgentCommand-2QTHJCHV.js → offlineMarxistsAgentCommand-4IC3Y4C6.js} +4 -4
  203. package/overlay-THLKYIWY.js +11 -0
  204. package/package.json +2 -2
  205. package/{pdf-U6KSUEZZ.js → pdf-KE3QI2V7.js} +1 -1
  206. package/{processSpawn-ZU5QFM43.js → processSpawn-6GEO77KV.js} +1 -1
  207. package/{profileConfig-KN3N2BLF.js → profileConfig-KOWK4HOG.js} +1 -1
  208. package/{projectArchive-GGL5HLMD.js → projectArchive-HK63GMF4.js} +52 -50
  209. package/{providerPresetApply-YXGV6NXB.js → providerPresetApply-OIFQ73LH.js} +19 -12
  210. package/{providerRegistry-S6UL6UNA.js → providerRegistry-KZ3SDZ3D.js} +10 -10
  211. package/{read-4VZQODSN.js → read-MRQHJMJ2.js} +10 -10
  212. package/{readDocTool-AVD32RUJ.js → readDocTool-4BGTXTXA.js} +2 -2
  213. package/{readlineWorkspace-XKYKNL2I.js → readlineWorkspace-AKAHSCNY.js} +6505 -4634
  214. package/{removeDialogAgentAction-FKL4BYMR.js → removeDialogAgentAction-B6H7DXFM.js} +23 -22
  215. package/{runAgentClientLoop-V7E2WBVM.js → runAgentClientLoop-UVAWGEON.js} +81 -79
  216. package/{runtimeDoctorCommands-QAI3MBKQ.js → runtimeDoctorCommands-FW6XKDUG.js} +12 -12
  217. package/{runtimeModeArgs-2Y7BALTO.js → runtimeModeArgs-X7DL7PUN.js} +1 -1
  218. package/secretCommands-LJXOOYA7.js +24 -0
  219. package/{setDialogExtraReferencesAction-TLIOLWWI.js → setDialogExtraReferencesAction-EVCY3TRW.js} +22 -21
  220. package/{setPrimaryDialogAgentAction-2OLWRFYR.js → setPrimaryDialogAgentAction-KPFVPHCJ.js} +23 -22
  221. package/{settingThunks-UGBPCNYF.js → settingThunks-ENOAK2WV.js} +97 -88
  222. package/{skillDiscovery-XKHROSH2.js → skillDiscovery-B5V23AXP.js} +4 -4
  223. package/{skillSummaryMarker-42HKSXYY.js → skillSummaryMarker-62UW7HI7.js} +1 -1
  224. package/{slateToRenderMarkdown-Y5IYN73U.js → slateToRenderMarkdown-R3X74MCX.js} +1 -1
  225. package/{slateUtils-NGV2NMKM.js → slateUtils-ESQAJ6RN.js} +1 -1
  226. package/{spaceCommands-4KSLKVNF.js → spaceCommands-DTTNAS2L.js} +61 -53
  227. package/store-JRVN62NM.js +46 -0
  228. package/{streamAgentChatTurn-7FR7X2NU.js → streamAgentChatTurn-R5UY25VB.js} +875 -618
  229. package/{switchDialogAgentAction-UZSAG2N5.js → switchDialogAgentAction-SZ44XDRY.js} +21 -20
  230. package/{tableCommands-MP6VFSVT.js → tableCommands-HITDSLHS.js} +10 -10
  231. package/tombstones-FQQMEDOW.js +32 -0
  232. package/{toolApiClient-HGNO53TC.js → toolApiClient-OGQEBQVX.js} +4 -4
  233. package/{tools-ZLKCC25W.js → tools-HWFG6GMJ.js} +75 -74
  234. package/tuiSummaryLlmCaller-HQQZAMYF.js +44 -0
  235. package/{updateCommands-4744PL3P.js → updateCommands-RJVCRSBP.js} +10 -8
  236. package/{updateDialogTitleAction-U53ZT7PJ.js → updateDialogTitleAction-KNPOAMVS.js} +48 -46
  237. package/{usageCommand-F4IPVMIZ.js → usageCommand-FWZCB7AM.js} +11 -10
  238. package/{usageRebuildCommand-HAW2AD5N.js → usageRebuildCommand-SP2BLNJU.js} +12 -11
  239. package/userDataMerge-HT2ZVHBJ.js +13 -0
  240. package/{windowsSelfUpdate-XSQVF2GK.js → windowsSelfUpdate-KERHIAB4.js} +3 -3
  241. package/{workloadLifecycle-4BEQHMSD.js → workloadLifecycle-DYNEYHV5.js} +7 -6
  242. package/agentRecordCommands-L3QQ7HZ4.js +0 -167
  243. package/agentRunCommand-2IFGQHCO.js +0 -196
  244. package/chunk-3CGG2PAL.js +0 -594
  245. package/chunk-5XBUWM6I.js +0 -89
  246. package/chunk-BFM34N54.js +0 -842
  247. package/chunk-CJEIOP3E.js +0 -0
  248. package/chunk-CZM5YTZ7.js +0 -977
  249. package/chunk-EYUBHHFB.js +0 -636
  250. package/chunk-JTDORD5P.js +0 -415
  251. package/chunk-NRFKLKRU.js +0 -339
  252. package/chunk-VPAZOH2D.js +0 -115
  253. package/chunk-WJZOQR2J.js +0 -151
  254. package/chunk-ZCWRMUWT.js +0 -89
  255. package/dist-M676ULYG.js +0 -7314
  256. package/machineWsRunDispatch-R26P5V36.js +0 -182
  257. package/models-PJBE6JDV.js +0 -9
  258. package/tuiSummaryLlmCaller-WC54MVGP.js +0 -160
  259. package/{chunk-WACI5I6V.js → chunk-2THCNKE4.js} +3 -3
  260. package/{chunk-2QHFH3DR.js → chunk-47ITIXO7.js} +6 -6
  261. package/{chunk-GOO6G4PY.js → chunk-CKG3PRZ7.js} +0 -0
  262. package/{chunk-OQHIVPG4.js → chunk-SNBZZPYH.js} +3 -3
  263. package/{chunk-AETZ7AD6.js → chunk-W6RFEDN4.js} +3 -3
@@ -0,0 +1,1382 @@
1
+ import {
2
+ normalizeTimingMs
3
+ } from "./chunk-H57T64RA.js";
4
+ import {
5
+ isAbortError
6
+ } from "./chunk-7DPNBQSV.js";
7
+ import {
8
+ ALL_MODELS
9
+ } from "./chunk-WKGQSYTB.js";
10
+ import {
11
+ asTrimmedNonEmptyStringArray
12
+ } from "./chunk-I42VC5KR.js";
13
+ import {
14
+ estimateTokenCount
15
+ } from "./chunk-PSCNXBYA.js";
16
+ import {
17
+ MODEL_LOOKUP_MAP
18
+ } from "./chunk-2UCBGYO4.js";
19
+ import {
20
+ PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL,
21
+ isPlatformManagedProvider,
22
+ resolvePlatformEffectiveModel
23
+ } from "./chunk-CKG3PRZ7.js";
24
+ import {
25
+ asOptionalFiniteNumber
26
+ } from "./chunk-WWC7I6TA.js";
27
+ import {
28
+ asOptionalTrimmedString
29
+ } from "./chunk-G3SUCT4W.js";
30
+
31
+ // packages/core/chat/messageContentSerialize.ts
32
+ var serializeMessageContent = (content, imagePlaceholder = "[\u56FE\u7247]") => {
33
+ if (typeof content === "string") {
34
+ return content.trim() || null;
35
+ }
36
+ if (Array.isArray(content)) {
37
+ const fragments = [];
38
+ for (const part of content) {
39
+ if (!part || typeof part !== "object") continue;
40
+ if (part.type === "text" && typeof part.text === "string") {
41
+ const text = part.text.trim();
42
+ if (text) fragments.push(text);
43
+ } else if (part.type === "image_url") {
44
+ fragments.push(imagePlaceholder);
45
+ }
46
+ }
47
+ const joined = fragments.join("\n").trim();
48
+ return joined || null;
49
+ }
50
+ return null;
51
+ };
52
+
53
+ // packages/ai/token/cacheTokenFields.ts
54
+ var finiteTokenCount = (value) => {
55
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
56
+ return Math.max(0, Math.floor(value));
57
+ };
58
+ var readNested = (value, path) => {
59
+ let cursor = value;
60
+ for (const key of path) {
61
+ if (!cursor || typeof cursor !== "object") return void 0;
62
+ cursor = cursor[key];
63
+ }
64
+ return finiteTokenCount(cursor);
65
+ };
66
+ var firstPositive = (usage, readers) => {
67
+ for (const read of readers) {
68
+ const value = read(usage);
69
+ if (value !== void 0 && value !== 0) return value;
70
+ }
71
+ return 0;
72
+ };
73
+ var topLevel = (field) => (usage) => {
74
+ if (!usage || typeof usage !== "object") return void 0;
75
+ return finiteTokenCount(usage[field]);
76
+ };
77
+ var nested = (path) => (usage) => readNested(usage, path);
78
+ var firstPresentAsNumber = (usage, readers) => {
79
+ let sawField = false;
80
+ for (const read of readers) {
81
+ const value = read(usage);
82
+ if (value === void 0) continue;
83
+ sawField = true;
84
+ if (value !== 0) return value;
85
+ }
86
+ return sawField ? 0 : null;
87
+ };
88
+ var CACHE_READ_READERS = [
89
+ topLevel("cache_read_input_tokens"),
90
+ topLevel("prompt_cache_hit_tokens"),
91
+ nested(["input_tokens_details", "cached_tokens"]),
92
+ nested(["prompt_tokens_details", "cached_tokens"])
93
+ ];
94
+ var CACHE_CREATION_READERS = [
95
+ topLevel("cache_creation_input_tokens"),
96
+ topLevel("prompt_cache_miss_tokens"),
97
+ nested(["input_tokens_details", "cache_write_tokens"])
98
+ ];
99
+ var readCacheReadInputTokens = (usage) => firstPositive(usage, CACHE_READ_READERS);
100
+ var readCacheReadInputTokensOrNull = (usage) => firstPresentAsNumber(usage, CACHE_READ_READERS);
101
+ var readCacheCreationInputTokens = (usage) => firstPositive(usage, CACHE_CREATION_READERS);
102
+
103
+ // packages/ai/token/normalizeUsage.ts
104
+ var normalizeStringArray = (value) => {
105
+ if (!Array.isArray(value)) return void 0;
106
+ const normalized = [...new Set(asTrimmedNonEmptyStringArray(value))];
107
+ return normalized.length > 0 ? normalized : void 0;
108
+ };
109
+ var finiteTokenCount2 = (value) => {
110
+ const finite = asOptionalFiniteNumber(value);
111
+ if (finite === void 0) return void 0;
112
+ return Math.max(0, Math.floor(finite));
113
+ };
114
+ var readFiniteNumberField = (usage, field) => {
115
+ if (!usage || typeof usage !== "object") return void 0;
116
+ if (!(field in usage)) return void 0;
117
+ const candidate = usage[field];
118
+ return asOptionalFiniteNumber(candidate);
119
+ };
120
+ var readOptionalOutputTokens = (usage) => {
121
+ if (!usage || typeof usage !== "object") return void 0;
122
+ const field = "output_tokens" in usage && usage.output_tokens != null ? "output_tokens" : "completion_tokens";
123
+ return readFiniteNumberField(usage, field);
124
+ };
125
+ var readCostInUsdTicks = (usage) => readFiniteNumberField(usage, "cost_in_usd_ticks");
126
+ var normalizeUsage = (usage) => {
127
+ if (!usage || typeof usage !== "object") {
128
+ return {
129
+ input_tokens: 0,
130
+ output_tokens: 0,
131
+ total_tokens: 0,
132
+ cache_creation_input_tokens: 0,
133
+ cache_read_input_tokens: 0,
134
+ cost: 0
135
+ };
136
+ }
137
+ const inputTokens = "input_tokens" in usage ? usage.input_tokens ?? 0 : "prompt_tokens" in usage ? usage.prompt_tokens : 0;
138
+ const outputTokens = "output_tokens" in usage ? usage.output_tokens ?? 0 : "completion_tokens" in usage ? usage.completion_tokens : 0;
139
+ const cacheCreationInputTokens = readCacheCreationInputTokens(usage);
140
+ const cacheReadInputTokens = readCacheReadInputTokens(usage);
141
+ let cost = 0;
142
+ const providedCost = readFiniteNumberField(usage, "cost");
143
+ if (providedCost !== void 0) {
144
+ cost = providedCost;
145
+ }
146
+ const xaiTicks = readCostInUsdTicks(usage);
147
+ if (xaiTicks !== void 0 && providedCost === void 0) {
148
+ cost = xaiTicks / 1e10;
149
+ }
150
+ const billingProvider = asOptionalTrimmedString(usage.billing_provider);
151
+ const billingModel = asOptionalTrimmedString(usage.billing_model);
152
+ const billingServiceTier = asOptionalTrimmedString(usage.billing_service_tier);
153
+ const billingEstimated = "billing_estimated" in usage && usage.billing_estimated === true;
154
+ const serverBilled = "server_billed" in usage && usage.server_billed === true;
155
+ const providerCallId = asOptionalTrimmedString(usage.provider_call_id);
156
+ const imageGenerationCount = "image_generation_count" in usage ? asOptionalFiniteNumber(usage.image_generation_count) : void 0;
157
+ const providerResponseIds = normalizeStringArray(
158
+ usage.provider_response_ids
159
+ );
160
+ const providerRequestIds = normalizeStringArray(
161
+ usage.provider_request_ids
162
+ );
163
+ const firstOutputMs = normalizeTimingMs(
164
+ readFiniteNumberField(usage, "firstOutputMs") ?? readFiniteNumberField(usage, "firstTokenMs")
165
+ );
166
+ const callDurationMs = normalizeTimingMs(
167
+ readFiniteNumberField(usage, "callDurationMs") ?? readFiniteNumberField(usage, "durationMs")
168
+ );
169
+ return {
170
+ input_tokens: inputTokens,
171
+ output_tokens: outputTokens,
172
+ total_tokens: finiteTokenCount2(usage.total_tokens) ?? inputTokens + outputTokens,
173
+ cache_creation_input_tokens: cacheCreationInputTokens,
174
+ cache_read_input_tokens: cacheReadInputTokens,
175
+ cost,
176
+ ...typeof imageGenerationCount === "number" ? { image_generation_count: imageGenerationCount } : {},
177
+ ...providerResponseIds ? { provider_response_ids: providerResponseIds } : {},
178
+ ...providerRequestIds ? { provider_request_ids: providerRequestIds } : {},
179
+ ...billingProvider ? { billing_provider: billingProvider } : {},
180
+ ...billingModel ? { billing_model: billingModel } : {},
181
+ ...billingServiceTier ? { billing_service_tier: billingServiceTier } : {},
182
+ ...billingEstimated ? { billing_estimated: true } : {},
183
+ ...serverBilled ? { server_billed: true } : {},
184
+ ...providerCallId ? { provider_call_id: providerCallId } : {},
185
+ ...xaiTicks !== void 0 ? { cost_in_usd_ticks: xaiTicks } : {},
186
+ ...firstOutputMs !== void 0 ? { firstOutputMs } : {},
187
+ ...callDurationMs !== void 0 ? { callDurationMs } : {}
188
+ };
189
+ };
190
+
191
+ // packages/ai/context/summaryContract.ts
192
+ var SUMMARY_TOTAL_BUDGET_MS = { automatic: 6e4, manual: 12e4 };
193
+ var realClock = {
194
+ now: Date.now,
195
+ setTimeout: (callback, ms) => setTimeout(callback, ms),
196
+ clearTimeout: (handle) => clearTimeout(handle)
197
+ };
198
+ function createSummaryBudget(options) {
199
+ const clock = options.clock ?? realClock;
200
+ if (options.deadlineMs !== void 0 && !Number.isFinite(options.deadlineMs)) {
201
+ throw new RangeError("Summary deadline must be finite");
202
+ }
203
+ const deadlineMs = Math.min(clock.now() + SUMMARY_TOTAL_BUDGET_MS[options.mode], options.deadlineMs ?? Infinity);
204
+ const controller = new AbortController();
205
+ const cancel = () => controller.abort(new DOMException("Summary cancelled", "AbortError"));
206
+ const expire = () => controller.abort(new DOMException("Summary deadline exceeded", "TimeoutError"));
207
+ const remainingMs = () => Math.max(0, deadlineMs - clock.now());
208
+ const check = () => {
209
+ if (!controller.signal.aborted && remainingMs() === 0) expire();
210
+ if (controller.signal.aborted) throw controller.signal.reason;
211
+ };
212
+ let timer;
213
+ const cleanup = () => {
214
+ if (timer !== void 0) clock.clearTimeout(timer);
215
+ options.signal?.removeEventListener("abort", cancel);
216
+ };
217
+ controller.signal.addEventListener("abort", cleanup, { once: true });
218
+ options.signal?.addEventListener("abort", cancel, { once: true });
219
+ if (options.signal?.aborted) cancel();
220
+ else if (remainingMs() === 0) expire();
221
+ else timer = clock.setTimeout(expire, remainingMs());
222
+ const budget = {
223
+ deadlineMs,
224
+ signal: controller.signal,
225
+ remainingMs,
226
+ async run(operation) {
227
+ check();
228
+ let onAbort;
229
+ const stopped = new Promise((_, reject) => {
230
+ onAbort = () => reject(controller.signal.reason);
231
+ controller.signal.addEventListener("abort", onAbort, { once: true });
232
+ });
233
+ try {
234
+ const value = await Promise.race([Promise.resolve().then(() => {
235
+ check();
236
+ return operation({ deadlineMs, signal: controller.signal });
237
+ }), stopped]);
238
+ check();
239
+ return value;
240
+ } finally {
241
+ if (onAbort) controller.signal.removeEventListener("abort", onAbort);
242
+ }
243
+ },
244
+ dispose() {
245
+ cancel();
246
+ cleanup();
247
+ }
248
+ };
249
+ return budget;
250
+ }
251
+ function record(value) {
252
+ return value !== null && typeof value === "object" ? value : {};
253
+ }
254
+ function identifier(value) {
255
+ return typeof value === "string" && value.length <= 128 && /^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$/.test(value) && !/https?:|^bearer|^sk-|^vault-cred|^nolo_cred/i.test(value) ? value : void 0;
256
+ }
257
+ function classifySummaryError(error, context = {}) {
258
+ const top = record(error);
259
+ const nested2 = record(top.error);
260
+ const rawStatus = top.status ?? top.statusCode ?? nested2.status;
261
+ const status = typeof rawStatus === "number" && Number.isInteger(rawStatus) && rawStatus >= 100 && rawStatus <= 599 ? rawStatus : void 0;
262
+ const code = identifier(top.code ?? nested2.code);
263
+ const errorType = identifier(top.type ?? nested2.type);
264
+ const balanceSource = errorType === "insufficient_balance_error" || top.balanceSource === "upstream" ? "upstream" : code === "INSUFFICIENT_BALANCE" ? "platform-user" : void 0;
265
+ const category = top.name === "TimeoutError" || code === "ETIMEDOUT" || code === "DEADLINE_EXCEEDED" ? "timeout" : isAbortError(error) ? "cancelled" : status !== void 0 ? "http" : code ? "provider" : "unknown";
266
+ return {
267
+ category,
268
+ message: `Summary ${category} failure`,
269
+ ...status === void 0 ? {} : { status },
270
+ ...code === void 0 ? {} : { code },
271
+ ...errorType === void 0 ? {} : { errorType },
272
+ ...balanceSource === void 0 ? {} : { balanceSource },
273
+ model: identifier(top.model) ?? identifier(context.model),
274
+ provider: identifier(top.provider) ?? identifier(context.provider),
275
+ attemptId: identifier(top.attemptId) ?? identifier(context.attemptId),
276
+ stage: identifier(top.stage) ?? identifier(context.stage) ?? "attempt",
277
+ ...Object.fromEntries(["finishReason", "responseStatus", "incompleteReason"].flatMap((key) => {
278
+ const value = identifier(top[key]);
279
+ return value === void 0 ? [] : [[key, value]];
280
+ })),
281
+ ...Object.fromEntries(["maxOutputTokens", "completionTokens", "outputChars"].flatMap((key) => typeof top[key] === "number" && Number.isSafeInteger(top[key]) && top[key] >= 0 ? [[key, top[key]]] : []))
282
+ };
283
+ }
284
+ function isTruncatedCompletion(completion) {
285
+ return completion.truncated === true || completion.finishReason === "length" || completion.finishReason === "max_tokens" || completion.responseStatus === "incomplete" || completion.incompleteReason !== void 0;
286
+ }
287
+ function summaryCompletionTokens(usage) {
288
+ const tokens = readOptionalOutputTokens(usage);
289
+ return typeof tokens === "number" && Number.isSafeInteger(tokens) && tokens >= 0 ? tokens : void 0;
290
+ }
291
+
292
+ // packages/ai/context/summaryRouting.ts
293
+ function selectSummaryRoute(input) {
294
+ return input.authenticated && input.platformAvailable && !!input.userId && input.userId !== "local" && input.userId !== "guest" && typeof input.credits === "number" && Number.isFinite(input.credits) && input.credits > 0 ? { kind: "platform", model: PLATFORM_HOSTED_DEEPSEEK_FLASH_MODEL } : { kind: "current" };
295
+ }
296
+ async function runSummaryWithContract(args) {
297
+ const attempts = [];
298
+ const execute = async (route) => {
299
+ const attempt = args[route];
300
+ try {
301
+ const completion = await args.budget.run((context) => attempt.run(context));
302
+ if (typeof completion?.text !== "string") {
303
+ throw { code: "INVALID_SUMMARY_COMPLETION", stage: "decode" };
304
+ }
305
+ const text = completion.text.trim();
306
+ const kind = isTruncatedCompletion(completion) ? "truncated" : text ? "success" : "empty";
307
+ attempts.push({ route, outcome: kind });
308
+ if (kind === "empty") return { kind, route, attempts, completion };
309
+ return { kind, text, route, attempts, completion };
310
+ } catch (cause) {
311
+ const error = classifySummaryError(args.budget.signal.aborted ? args.budget.signal.reason : cause, attempt);
312
+ const kind = error.category === "cancelled" ? "cancelled" : "error";
313
+ attempts.push({ route, outcome: kind, error });
314
+ return { kind, error, route, attempts };
315
+ }
316
+ };
317
+ if (selectSummaryRoute(args.eligibility).kind === "platform") {
318
+ const result = await execute("platform");
319
+ if (result.kind !== "error" || result.error.code !== "INSUFFICIENT_BALANCE" || result.error.balanceSource !== "platform-user" || result.error.category === "timeout" || args.budget.signal.aborted) return result;
320
+ }
321
+ return execute("current");
322
+ }
323
+
324
+ // packages/core/sha256.ts
325
+ import SHA256 from "crypto-js/sha256.js";
326
+ function sha256Hex(text) {
327
+ return SHA256(text).toString();
328
+ }
329
+
330
+ // packages/ai/context/toolOutputCap.ts
331
+ var TOOL_OUTPUT_CAP_WINDOW_RATIO = 0.12;
332
+ var TOOL_OUTPUT_CAP_MIN_TOKENS = 4e3;
333
+ var TOOL_OUTPUT_CAP_MAX_TOKENS = 5e4;
334
+ var COMPRESSION_TRIGGER_RATIO_MAX = 0.9;
335
+ var clamp = (v, min, max) => Math.min(max, Math.max(min, v));
336
+ var capToolOutputTokens = (contextWindow) => clamp(
337
+ Math.floor(contextWindow * TOOL_OUTPUT_CAP_WINDOW_RATIO),
338
+ TOOL_OUTPUT_CAP_MIN_TOKENS,
339
+ TOOL_OUTPUT_CAP_MAX_TOKENS
340
+ );
341
+ var resolveCompressionTriggerRatio = (_contextWindow) => COMPRESSION_TRIGGER_RATIO_MAX;
342
+ var truncateToolOutputForContext = (text, contextWindow) => {
343
+ if (!text) return text;
344
+ const capTokens = capToolOutputTokens(contextWindow);
345
+ if (estimateTokenCount(text) <= capTokens) return text;
346
+ const build = (keepChars) => {
347
+ const headChars = Math.floor(keepChars * 0.6);
348
+ const tailChars = keepChars - headChars;
349
+ const omittedTokens = estimateTokenCount(
350
+ text.slice(headChars, text.length - tailChars)
351
+ );
352
+ return text.slice(0, headChars) + `
353
+ ...[tool output truncated: ~${omittedTokens} tokens omitted]...
354
+ ` + text.slice(text.length - tailChars);
355
+ };
356
+ let lo = 0;
357
+ let hi = text.length;
358
+ while (lo < hi) {
359
+ const mid = Math.ceil((lo + hi) / 2);
360
+ if (estimateTokenCount(build(mid)) <= capTokens) lo = mid;
361
+ else hi = mid - 1;
362
+ }
363
+ return build(lo);
364
+ };
365
+
366
+ // packages/ai/context/planCompression.ts
367
+ var MIN_COMPRESS_COUNT = 5;
368
+ var INPUT_ITEM_TRIGGER_RATIO = 0.9;
369
+ var INPUT_ITEM_RETENTION_RATIO = 0.6;
370
+ var ACTIVE_SUMMARY_TAIL_KEEP_COUNT = 2;
371
+ var RECENT_ORIGINAL_TOKEN_BUDGET = 2e4;
372
+ var MIN_TRIGGER_PENDING_COUNT = MIN_COMPRESS_COUNT + ACTIVE_SUMMARY_TAIL_KEEP_COUNT;
373
+ var getMessageTokenCount = (msg) => {
374
+ const content = serializeMessageContent(msg.content) || "";
375
+ let tokens = estimateTokenCount(content);
376
+ if (Array.isArray(msg.tool_calls)) {
377
+ for (const call of msg.tool_calls) {
378
+ const fn = call?.function;
379
+ if (fn?.name) tokens += estimateTokenCount(fn.name);
380
+ const args = fn?.arguments;
381
+ if (args) {
382
+ tokens += estimateTokenCount(
383
+ typeof args === "string" ? args : JSON.stringify(args)
384
+ );
385
+ }
386
+ }
387
+ }
388
+ return tokens;
389
+ };
390
+ var hasOpenEndedToolCall = (msg) => !!msg && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;
391
+ var normalizeContextUsageRatio = (value) => {
392
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
393
+ const ratio = value > 1 ? value / 100 : value;
394
+ return ratio >= 0 && ratio <= 1 ? ratio : void 0;
395
+ };
396
+ var emptyPlan = (startIndex, diagnostics) => ({
397
+ shouldCompress: false,
398
+ compressCount: 0,
399
+ msgsToCompress: [],
400
+ msgsToKeep: [],
401
+ newSummarizedBeforeId: void 0,
402
+ startIndex,
403
+ ...diagnostics ? { diagnostics } : {}
404
+ });
405
+ function findPendingMessages(allMsgs, summarizedBeforeId) {
406
+ let startIndex = 0;
407
+ if (summarizedBeforeId) {
408
+ const found = allMsgs.findIndex((m) => m.id === summarizedBeforeId);
409
+ if (found !== -1) startIndex = found + 1;
410
+ }
411
+ return { pendingMsgs: allMsgs.slice(startIndex), startIndex };
412
+ }
413
+ function shouldTriggerCompaction(args) {
414
+ const {
415
+ totalUsed,
416
+ historyBudget,
417
+ triggerRatio,
418
+ force,
419
+ reason,
420
+ realContextUsagePercent
421
+ } = args;
422
+ const usageRatio = normalizeContextUsageRatio(realContextUsagePercent);
423
+ const triggeredByRealUsage = usageRatio !== void 0 && usageRatio >= triggerRatio;
424
+ const triggeredByEstimate = usageRatio === void 0 && totalUsed >= historyBudget;
425
+ const shouldRunActiveSummary = force && (reason === "manual" || reason === "budget_rescue");
426
+ const triggeredByColdResume = false;
427
+ return {
428
+ trigger: triggeredByRealUsage || triggeredByEstimate || shouldRunActiveSummary || triggeredByColdResume,
429
+ triggeredByRealUsage,
430
+ shouldRunActiveSummary,
431
+ triggeredByColdResume
432
+ };
433
+ }
434
+ function calculateCompressCount(pendingMsgs, rawMessageBudget) {
435
+ let tokensToKeep = 0;
436
+ let keepCount = 0;
437
+ for (let i = pendingMsgs.length - 1; i >= 0; i--) {
438
+ const t = getMessageTokenCount(pendingMsgs[i]);
439
+ if (tokensToKeep + t > rawMessageBudget) break;
440
+ tokensToKeep += t;
441
+ keepCount++;
442
+ }
443
+ return pendingMsgs.length - keepCount;
444
+ }
445
+ function resolveEffectiveCompactionBudgets(args) {
446
+ const effectiveHistoryBudget = Math.max(0, Math.min(
447
+ Math.floor(args.contextWindow),
448
+ Math.floor(args.historyBudget)
449
+ ));
450
+ const newSummaryTokenReserve = args.newSummaryTokenReserve ?? Math.min(8192, Math.max(1, Math.floor(args.contextWindow / 4)));
451
+ return {
452
+ effectiveHistoryBudget,
453
+ effectiveRawMessageBudget: Math.max(0, Math.min(
454
+ RECENT_ORIGINAL_TOKEN_BUDGET,
455
+ effectiveHistoryBudget - Math.max(0, newSummaryTokenReserve)
456
+ ))
457
+ };
458
+ }
459
+ function guardToolChainBoundary(pendingMsgs, compressCount, preserveByProjection) {
460
+ let safeLimit = Math.max(0, pendingMsgs.length - 1);
461
+ if (!preserveByProjection) {
462
+ for (let i = pendingMsgs.length - 1; i >= 0; i--) {
463
+ if (pendingMsgs[i].role === "user") {
464
+ safeLimit = i;
465
+ break;
466
+ }
467
+ }
468
+ }
469
+ let count = Math.min(compressCount, safeLimit);
470
+ while (count > 0 && (pendingMsgs[count]?.role === "tool" || hasOpenEndedToolCall(pendingMsgs[count - 1]))) {
471
+ count--;
472
+ }
473
+ return count;
474
+ }
475
+ function calculateItemCompressCount(pendingMsgs, maxInputItems, preserveByProjection) {
476
+ const keepCount = Math.max(0, Math.floor(maxInputItems * INPUT_ITEM_RETENTION_RATIO) - 2 - (preserveByProjection ? 1 : 0));
477
+ return Math.max(0, pendingMsgs.length - keepCount);
478
+ }
479
+ function planCompression(input) {
480
+ const {
481
+ allMsgs,
482
+ summarizedBeforeId,
483
+ summary,
484
+ contextWindow,
485
+ force = false,
486
+ reason,
487
+ realContextUsagePercent,
488
+ preserveLatestUserByProjection = false
489
+ } = input;
490
+ const { pendingMsgs, startIndex } = findPendingMessages(allMsgs, summarizedBeforeId);
491
+ if (pendingMsgs.length === 0) {
492
+ return emptyPlan(startIndex, {
493
+ pendingMsgCount: 0,
494
+ totalUsed: estimateTokenCount(summary || ""),
495
+ historyBudget: 0,
496
+ triggerRatio: resolveCompressionTriggerRatio(contextWindow),
497
+ realUsageRatio: normalizeContextUsageRatio(realContextUsagePercent),
498
+ triggeredByRealUsage: false,
499
+ triggeredByEstimate: false,
500
+ triggeredByColdResume: false,
501
+ shouldRunActiveSummary: false,
502
+ emptyReason: "no-pending"
503
+ });
504
+ }
505
+ const summaryTokens = estimateTokenCount(summary || "");
506
+ const pendingTokens = pendingMsgs.reduce((sum, msg) => sum + getMessageTokenCount(msg), 0);
507
+ let coveredUserTokens = 0;
508
+ if (preserveLatestUserByProjection && summary && startIndex > 0) {
509
+ for (let i = startIndex - 1; i >= 0; i--) {
510
+ if (allMsgs[i].role === "user") {
511
+ coveredUserTokens = getMessageTokenCount(allMsgs[i]);
512
+ break;
513
+ }
514
+ }
515
+ }
516
+ const maxInputItems = typeof input.maxInputItems === "number" && Number.isFinite(input.maxInputItems) && input.maxInputItems > 0 ? input.maxInputItems : void 0;
517
+ const itemCount = pendingMsgs.length + (summary ? 1 : 0) + 1 + (coveredUserTokens > 0 ? 1 : 0);
518
+ const triggeredByItemLimit = maxInputItems !== void 0 && itemCount >= maxInputItems * INPUT_ITEM_TRIGGER_RATIO;
519
+ const totalUsed = summaryTokens + coveredUserTokens + pendingTokens;
520
+ const triggerRatio = resolveCompressionTriggerRatio(contextWindow);
521
+ const historyBudget = Math.floor(contextWindow * triggerRatio);
522
+ const rawMessageBudget = Math.max(0, historyBudget - summaryTokens);
523
+ const {
524
+ trigger,
525
+ triggeredByRealUsage,
526
+ shouldRunActiveSummary,
527
+ triggeredByColdResume
528
+ } = shouldTriggerCompaction({
529
+ totalUsed,
530
+ historyBudget,
531
+ triggerRatio,
532
+ force,
533
+ reason,
534
+ realContextUsagePercent
535
+ });
536
+ const diagnostics = {
537
+ pendingMsgCount: pendingMsgs.length,
538
+ ...maxInputItems !== void 0 ? { itemCount, maxInputItems, triggeredByItemLimit } : {},
539
+ totalUsed,
540
+ historyBudget,
541
+ triggerRatio,
542
+ realUsageRatio: normalizeContextUsageRatio(realContextUsagePercent),
543
+ triggeredByRealUsage,
544
+ triggeredByEstimate: normalizeContextUsageRatio(realContextUsagePercent) === void 0 && totalUsed >= historyBudget,
545
+ triggeredByColdResume,
546
+ shouldRunActiveSummary
547
+ };
548
+ if (!trigger && !triggeredByItemLimit) {
549
+ return emptyPlan(startIndex, {
550
+ ...diagnostics,
551
+ emptyReason: "not-triggered"
552
+ });
553
+ }
554
+ const { effectiveRawMessageBudget } = resolveEffectiveCompactionBudgets({
555
+ contextWindow,
556
+ triggerRatio,
557
+ historyBudget: Math.min(historyBudget, input.availableHistoryTokens ?? historyBudget),
558
+ rawMessageBudget,
559
+ summaryTokens,
560
+ newSummaryTokenReserve: input.newSummaryTokenReserve
561
+ });
562
+ const minimumPrefixTokens = Math.min(1e3, Math.floor(contextWindow * 0.1));
563
+ const tailBudget = triggeredByItemLimit ? effectiveRawMessageBudget : Math.min(effectiveRawMessageBudget, Math.max(0, pendingTokens - minimumPrefixTokens));
564
+ const itemCompressCount = maxInputItems !== void 0 ? calculateItemCompressCount(pendingMsgs, maxInputItems, preserveLatestUserByProjection) : 0;
565
+ const guardedCut = (tokenCompressCount) => {
566
+ let candidate = Math.max(tokenCompressCount, itemCompressCount);
567
+ let guarded = guardToolChainBoundary(pendingMsgs, candidate, preserveLatestUserByProjection);
568
+ while (guarded < itemCompressCount && candidate < pendingMsgs.length - 1) {
569
+ candidate++;
570
+ const next = guardToolChainBoundary(pendingMsgs, candidate, preserveLatestUserByProjection);
571
+ if (next === guarded && pendingMsgs[next]?.role === "user" && !preserveLatestUserByProjection) break;
572
+ guarded = next;
573
+ }
574
+ return guarded;
575
+ };
576
+ let compressCount = guardedCut(calculateCompressCount(pendingMsgs, tailBudget));
577
+ if (preserveLatestUserByProjection) {
578
+ let latestUser = -1;
579
+ for (let i = pendingMsgs.length - 1; i >= 0; i--) {
580
+ if (pendingMsgs[i].role === "user") {
581
+ latestUser = i;
582
+ break;
583
+ }
584
+ }
585
+ const preservedTokens = latestUser >= 0 && latestUser < compressCount ? getMessageTokenCount(pendingMsgs[latestUser]) : latestUser < 0 ? coveredUserTokens : 0;
586
+ if (preservedTokens > 0) {
587
+ compressCount = guardedCut(
588
+ calculateCompressCount(pendingMsgs, Math.max(0, tailBudget - preservedTokens))
589
+ );
590
+ }
591
+ }
592
+ if (compressCount === 0) {
593
+ return emptyPlan(startIndex, { ...diagnostics, compressCount, emptyReason: "no-safe-prefix" });
594
+ }
595
+ const allowSmallPrefix = reason !== "task_completed" && (shouldRunActiveSummary || triggeredByRealUsage || diagnostics.triggeredByEstimate);
596
+ const compressibleTokens = pendingMsgs.slice(0, compressCount).reduce((sum, msg) => sum + getMessageTokenCount(msg), 0);
597
+ if (compressCount < MIN_COMPRESS_COUNT && !(allowSmallPrefix && compressibleTokens >= 1e3)) {
598
+ return emptyPlan(startIndex, {
599
+ ...diagnostics,
600
+ compressCount,
601
+ emptyReason: "below-min-compress-count"
602
+ });
603
+ }
604
+ const msgsToCompress = pendingMsgs.slice(0, compressCount);
605
+ const msgsToKeep = pendingMsgs.slice(compressCount);
606
+ const newSummarizedBeforeId = msgsToCompress[msgsToCompress.length - 1].id;
607
+ return {
608
+ shouldCompress: true,
609
+ compressCount,
610
+ msgsToCompress,
611
+ msgsToKeep,
612
+ newSummarizedBeforeId,
613
+ startIndex,
614
+ diagnostics: {
615
+ ...diagnostics,
616
+ compressCount,
617
+ recentOriginalTokenBudget: tailBudget,
618
+ retainedTailOverBudget: msgsToKeep.reduce((sum, msg) => sum + getMessageTokenCount(msg), 0) > tailBudget
619
+ }
620
+ };
621
+ }
622
+
623
+ // packages/ai/context/compactionShared.ts
624
+ var COMPACTION_SUMMARY_SCHEMA_VERSION = 2;
625
+ var COMPACTION_SUMMARY_SYSTEM_PROMPT = `\u4F60\u662F\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u538B\u7F29\u5668\u3002\u6839\u636E\u3010\u73B0\u6709\u8BB0\u5FC6\u3011\u548C\u3010\u65B0\u589E\u5BF9\u8BDD\u3011\uFF0C\u8F93\u51FA\u53EF\u66FF\u4EE3\u539F\u59CB\u6D88\u606F\u7684\u4E8B\u5B9E\u6027\u8981\u70B9\uFF0C\u4F9B\u540E\u7EED\u5BF9\u8BDD\u76F4\u63A5\u4F7F\u7528\u3002
626
+
627
+ \u4E25\u683C\u53EA\u8F93\u51FA\u4E0B\u9762\u4E09\u90E8\u5206\uFF0C\u6807\u9898\u5FC5\u987B\u5B8C\u5168\u4E00\u81F4\uFF1A
628
+ \u5173\u952E\u4E8B\u5B9E\u6863\u6848
629
+ - ...
630
+ \u5BF9\u8BDD\u8FDB\u5C55\u4E0E\u5F85\u529E
631
+ - ...
632
+ \u6587\u4EF6\u64CD\u4F5C\u6E05\u5355
633
+ - ...
634
+
635
+ \u8981\u6C42\uFF1A
636
+ 1) \u4F7F\u7528\u5BF9\u8BDD\u4E3B\u8BED\u8A00\uFF1B\u6DF7\u5408\u8BED\u8A00\u65F6\u4F18\u5148\u7528\u6237\u4E3B\u8981\u8BED\u8A00\uFF1B\u4E13\u6709\u540D\u8BCD\u3001\u6587\u4EF6\u8DEF\u5F84\u3001\u6807\u8BC6\u7B26\u3001\u547D\u4EE4\u4FDD\u7559\u539F\u6587\uFF0C\u4E0D\u8981\u7FFB\u8BD1\u6216\u8F6C\u8FF0\u3002
637
+ 2) \u5173\u952E\u4E8B\u5B9E\u6863\u6848\u7684**\u524D\u4E24\u9879\u56FA\u5B9A\u662F**\uFF1A
638
+ - \u300C\u539F\u59CB\u76EE\u6807\u300D\uFF1A\u8FD9\u6BB5\u5BF9\u8BDD**\u6700\u521D**\u7684\u610F\u56FE\u4E0E\u539F\u8BDD\uFF08\u5C3D\u91CF\u4FDD\u7559\u4ED6\u7684\u539F\u8BDD\u4E0E\u7528\u8BCD\uFF0C\u4E0D\u8981\u6539\u5199\u6210\u4EFB\u52A1\u6E05\u5355\uFF09\u3002
639
+ "\u6700\u521D"\u6307\u5F00\u5BF9\u8BDD\u90A3\u4E00\u523B\u2014\u2014\u4E0D\u5F97\u7528\u5BF9\u8BDD\u540E\u6765\u7684\u67D0\u53E5\u7528\u6237\u8BDD\uFF08\u5982\u4E34\u7761\u59D4\u6258\u3001\u4E2D\u671F\u8F6C\u8FF0\uFF09\u66FF\u4EE3\u6700\u521D\u76EE\u6807\uFF1B
640
+ \u6700\u521D\u539F\u8BDD\u4E0D\u5728\u672C\u6B21\u538B\u7F29\u8303\u56F4\u5185\u65F6\uFF0C\u6309\u300C\u8F93\u5165\u672A\u8986\u76D6\u300D\u5199"\u8F93\u5165\u4E2D\u672A\u89C1"\uFF0C\u518D\u4F9D\u636E\u5BF9\u8BDD\u5185\u6700\u65E9\u53EF\u8003\u7684\u590D\u8FF0\u5E76\u6CE8\u660E\u3002
641
+ \u589E\u91CF\u66F4\u65B0\u65F6\u6CBF\u7528\u3010\u73B0\u6709\u8BB0\u5FC6\u3011\u91CC\u5DF2\u6709\u7684\u300C\u539F\u59CB\u76EE\u6807\u300D\uFF0C\u4E0D\u8981\u88AB\u65B0\u589E\u5BF9\u8BDD\u6539\u5199\u2014\u2014\u5B83\u662F\u7A33\u5B9A\u5B57\u6BB5\uFF1B
642
+ \u4EC5\u5F53\u65B0\u5BF9\u8BDD\u660E\u786E\u8868\u660E\u539F\u6587\u6709\u4E8B\u5B9E\u6027\u9519\u8BEF\u65F6\u624D\u4FEE\u6B63\uFF0C\u5E76\u5728\u300C\u76EE\u6807\u6F14\u5316\u300D\u91CC\u6CE8\u660E\u3002
643
+ - \u300C\u76EE\u6807\u6F14\u5316\u300D\uFF1A\u82E5\u4E2D\u9014\u8F6C\u5411\uFF0C\u5199\u6E05\u8F6C\u5411\u4E86\u4EC0\u4E48\u3001\u56E0\u4E3A\u4EC0\u4E48\uFF1B\u6CA1\u6709\u8F6C\u5411\u5C31\u5199\u300C\u65E0\u8F6C\u5411\u300D\u6216\u7701\u7565\u8FD9\u4E00\u9879\uFF0C\u4E0D\u8981\u786C\u51D1\u3002
644
+ \u88AB\u540E\u7EED\u5DE5\u4F5C\u53D6\u4EE3\u7684\u662F"\u65B9\u6848"\uFF0C\u4E0D\u662F"\u7528\u6237\u7684\u521D\u59CB\u610F\u56FE"\u2014\u2014\u521D\u59CB\u610F\u56FE\u4E0D\u5F97\u7701\u7565\u3002
645
+ \u5176\u540E\u624D\u662F\uFF1A\u7528\u6237\u504F\u597D\u3001\u7EA6\u675F\u3001\u6280\u672F\u6808\u3001\u786E\u5B9A\u7684\u6587\u4EF6\u8DEF\u5F84\u3001\u6838\u5FC3\u51B3\u7B56\u3001\u672A\u5B8C\u6210\u5F85\u529E\u3002\u4FDD\u7559\u786E\u5207\u503C\uFF08\u7AEF\u53E3\u53F7\u3001\u7248\u672C\u53F7\u3001\u8DEF\u5F84\u3001\u53D8\u91CF\u540D\u3001\u9519\u8BEF\u4FE1\u606F\u539F\u6587\uFF09\uFF0C\u4E0D\u8981\u6982\u62EC\u6210"\u67D0\u4E2A\u7AEF\u53E3"\u6216"\u67D0\u4E2A\u6587\u4EF6"\u6216"\u67D0\u62A5\u9519"\u3002
646
+ \u5173\u952E\u4E8B\u5B9E\u6863\u6848\u8FD8\u5FC5\u987B\u5305\u542B\u4EE5\u4E0B\u4E09\u9879\uFF08\u53EF\u63A5\u5728\u56FA\u5B9A\u4E24\u9879\u4E4B\u540E\uFF0C\u7F3A\u4FE1\u606F\u65F6\u5982\u5B9E\u5199\u660E\uFF0C\u4E0D\u5F97\u7701\u7565\uFF09\uFF1A
647
+ - \u300C\u5DF2\u8BC1\u4F2A\u7684\u5047\u8BBE\u300D\uFF1A\u88AB\u8BC1\u636E\u5426\u51B3\u6216\u51B3\u5B9A\u4E0D\u91C7\u7528\u7684\u7ED3\u8BBA\u5355\u5217\uFF0C\u6CE8\u660E"\u5DF2\u8BC1\u4F2A/\u4E0D\u91C7\u7528"\u53CA\u4F9D\u636E\uFF0C\u9632\u6B62\u7EED\u4F5C\u628A\u5B83\u5F53\u4E8B\u5B9E\u91CD\u542F\u3002
648
+ - \u300C\u5361\u70B9\u4E0E\u9700\u7528\u6237\u51B3\u5B9A\u300D\uFF1A\u963B\u585E\u9879\u5361\u5728\u54EA\u3001\u9700\u8981\u7528\u6237\u63D0\u4F9B\u4EC0\u4E48\uFF08\u6388\u6743 / \u51ED\u636E / \u51B3\u5B9A\uFF09\uFF0C\u5199\u6E05\u695A\uFF0C\u4E0D\u5F97\u542B\u7CCA\u3002
649
+ - \u300C\u8F93\u5165\u672A\u8986\u76D6\u300D\uFF1A\u538B\u7F29\u8303\u56F4\u5185\u67E5\u4E0D\u5230\u7684\u5173\u952E\u4FE1\u606F\uFF08\u5982\u521D\u59CB\u539F\u8BDD\u3001\u6307\u5B9A id\uFF09\uFF0C\u5FC5\u987B\u5199"\u8F93\u5165\u4E2D\u672A\u89C1"\uFF0C\u7981\u6B62\u8111\u8865\u3002
650
+ 3) \u5BF9\u8BDD\u8FDB\u5C55\u4E0E\u5F85\u529E\u4EE5\u7B2C\u4E00\u4EBA\u79F0\u7EED\u4F5C\u7B14\u8BB0\u7684\u53E3\u543B\u5199\uFF08"\u6211\u505A\u4E86\u2026""\u7528\u6237\u8981\u6C42\u2026""\u4E0B\u4E00\u6B65\u6211\u9700\u8981\u2026"\uFF09\uFF0C\u4E0D\u8981\u5199\u6210\u7B2C\u4E09\u65B9\u89C2\u5BDF\u62A5\u544A\u3002\u5148\u6781\u7B80\u6982\u62EC\u65E7\u4E0A\u4E0B\u6587\uFF0C\u518D\u66F4\u8BE6\u7EC6\u8BB0\u5F55\u6700\u8FD1\u8FDB\u5C55\u3001\u7ED3\u8BBA\u3001\u5206\u6B67\u4E0E\u4E0B\u4E00\u6B65\u3002\u5BF9\u4E8E\u58F0\u79F0\u5DF2\u5B8C\u6210\u4F46\u5C1A\u672A\u9A8C\u8BC1\u7684\u5DE5\u4F5C\uFF08\u5982\u5DE5\u5177\u8C03\u7528\u8FD4\u56DE\u6210\u529F\u4F46\u7ED3\u679C\u672A\u4EBA\u5DE5\u786E\u8BA4\uFF09\uFF0C\u660E\u786E\u6807\u6CE8"\uFF08\u5F85\u9A8C\u8BC1\uFF09"\u2014\u2014\u4E0D\u8981\u9ED8\u8BA4\u4FE1\u4EFB\u5DE5\u5177\u8FD4\u56DE\u503C\u3002
651
+ 4) \u6587\u4EF6\u64CD\u4F5C\u6E05\u5355\uFF1A\u6309\u8BFB\u53D6\u3001\u5199\u5165\u3001\u7F16\u8F91\u5217\u51FA\u8DEF\u5F84\uFF08\u5982: - \u8BFB\u53D6: path/to/file\uFF1B\u672A\u6D89\u53CA\u5219\u5199"\u65E0"\uFF09\u3002\u6709\u957F\u5EA6\u7EA6\u675F\u65F6\u5408\u5E76\u65E7\u64CD\u4F5C\uFF0C\u7701\u7565\u65E0\u5173\u8BFB\u53D6\u3002
652
+ 5) \u5FFD\u7565\u5BD2\u6684\u3001\u91CD\u590D\u5C1D\u8BD5\u548C\u65E0\u4EF7\u503C\u5E9F\u8BDD\uFF1B**\u5DF2\u653E\u5F03\u7684\u65B9\u6848/\u5C1D\u8BD5**\u53EF\u4EE5\u7701\u7565\uFF0C\u4F46\u7528\u6237\u5F53\u521D\u7684\u610F\u56FE\u4E0E\u7406\u7531\u4E0D\u53EF\u7701\u7565\uFF08\u89C1\u7B2C 2 \u6761\uFF09\u3002
653
+ 6) \u4E0D\u8981\u7F16\u9020\u672A\u51FA\u73B0\u7684\u4FE1\u606F\uFF1B\u4E0D\u8981\u5F00\u573A\u767D\u3001\u7ED3\u675F\u8BED\u3001markdown \u4EE3\u7801\u5757\u6216\u989D\u5916\u7AE0\u8282\uFF1B\u4E0D\u8981\u8C03\u7528\u4EFB\u4F55\u5DE5\u5177\u3002`;
654
+ function formatMessageContentFallback(msg) {
655
+ const content = serializeMessageContent(msg.content);
656
+ if (content) return content;
657
+ if (Array.isArray(msg.tool_calls)) {
658
+ return `[tool_calls:${msg.tool_calls.map((c) => c.function?.name).filter(Boolean).join(",")}]`;
659
+ }
660
+ return "[\u975E\u6587\u672C\u5185\u5BB9]";
661
+ }
662
+ function buildCompactionUserContent(args) {
663
+ const parts = [];
664
+ if (args.outputTokenBudget !== void 0) {
665
+ const budget = args.outputTokenBudget;
666
+ if (!Number.isFinite(budget) || budget < 1) throw new RangeError("Invalid summary output budget");
667
+ const limit = Math.floor(budget);
668
+ const target = Math.max(1, Math.min(2e3, Math.floor(limit / 2)));
669
+ parts.push(`Summary target: ${target} tokens; hard output limit: ${limit} tokens. Complete 3 sections; merge old progress/files.`);
670
+ }
671
+ parts.push(`\u3010\u73B0\u6709\u8BB0\u5FC6\u3011\uFF1A
672
+ ${args.previousSummary || "(\u65E0)"}`);
673
+ if (args.fileOpsText !== void 0) {
674
+ parts.push(`\u3010\u6587\u4EF6\u64CD\u4F5C\u6E05\u5355\u3011\uFF1A
675
+ ${args.fileOpsText || "\u65E0"}`);
676
+ }
677
+ parts.push(`\u3010\u65B0\u589E\u5BF9\u8BDD\u3011\uFF1A
678
+ ${args.messagesText}`);
679
+ return parts.join("\n\n").trim();
680
+ }
681
+ function extractFileOperationsFromCalls(calls, resolveCanonicalName) {
682
+ const result = [];
683
+ const seen = /* @__PURE__ */ new Set();
684
+ const fileOperationByTool = {
685
+ readFile: "read",
686
+ writeFile: "write",
687
+ editFile: "edit"
688
+ };
689
+ for (const call of calls) {
690
+ const rawName = call.function?.name || call.name || "";
691
+ if (!rawName) continue;
692
+ const canonicalName = resolveCanonicalName(rawName);
693
+ const opType = fileOperationByTool[canonicalName];
694
+ if (!opType) continue;
695
+ let rawArgs = call.function?.arguments;
696
+ let parsedArgs = null;
697
+ if (typeof rawArgs === "string") {
698
+ try {
699
+ parsedArgs = JSON.parse(rawArgs);
700
+ } catch {
701
+ }
702
+ } else if (typeof rawArgs === "object" && rawArgs !== null) {
703
+ parsedArgs = rawArgs;
704
+ }
705
+ const path = parsedArgs?.path ?? parsedArgs?.filePath ?? parsedArgs?.file;
706
+ if (typeof path === "string" && path.trim()) {
707
+ const key = `${opType}:${path.trim()}`;
708
+ if (!seen.has(key)) {
709
+ seen.add(key);
710
+ result.push({ type: opType, path: path.trim() });
711
+ }
712
+ }
713
+ }
714
+ return result;
715
+ }
716
+ function makeBoundedExcerpt(content) {
717
+ const evidence = selectEvidenceLines(content.split("\n"));
718
+ return (maxChars) => {
719
+ if (content.length <= maxChars) return content;
720
+ const marker = `
721
+ [... ${content.length} chars projected ...]
722
+ `;
723
+ const available = maxChars - marker.length;
724
+ if (available < 3) return marker.trim();
725
+ const evidenceCap = Math.floor(available * 0.2);
726
+ const selected = [];
727
+ let evidenceLength = 0;
728
+ for (const line of evidence) {
729
+ const cost = line.length + 1;
730
+ if (evidenceLength + cost > evidenceCap) continue;
731
+ selected.push(line);
732
+ evidenceLength += cost;
733
+ }
734
+ const remainder = available - evidenceLength;
735
+ const headLength = Math.ceil(remainder / 2);
736
+ const tailLength = Math.floor(remainder / 2);
737
+ return content.slice(0, headLength) + marker + (selected.length ? selected.join("\n") + "\n" : "") + (tailLength ? content.slice(-tailLength) : "");
738
+ };
739
+ }
740
+ var OMITTED_ROLE_ORDER = ["user", "assistant", "tool", "system"];
741
+ var MIN_INLINE_CONTENT_TOKENS = 12;
742
+ function formatOmittedRun(start, end, counts) {
743
+ const ordered = [
744
+ ...OMITTED_ROLE_ORDER,
745
+ ...[...counts.keys()].filter((role) => !OMITTED_ROLE_ORDER.includes(role))
746
+ ];
747
+ const parts = ordered.filter((role) => (counts.get(role) ?? 0) > 0).map((role) => `${role} ${counts.get(role)}`);
748
+ const range = start === end ? `\u6D88\u606F ${start + 1}` : `\u6D88\u606F ${start + 1}\u2013${end + 1}`;
749
+ return `[... ${range} \u5DF2\u7701\u7565\uFF1A${parts.join("\u3001")} ...]`;
750
+ }
751
+ var SUMMARY_HEAD_SHARE = 0.4;
752
+ var DECLARATION_RESERVE = 40;
753
+ var USER_MESSAGE_MAX_DEMAND = 600;
754
+ var SUMMARY_USER_SHARE = 0.2;
755
+ var DECLARATION_SPLIT_COST = 20;
756
+ function buildBoundedCompactionRequest(args) {
757
+ const { msgsToCompress: msgs, previousSummary, contextWindow } = args;
758
+ const windowValid = Number.isFinite(contextWindow) && contextWindow > 0;
759
+ const window = windowValid ? Math.floor(contextWindow) : 0;
760
+ const outputTokenBudget = windowValid ? Math.min(8192, Math.max(1, Math.floor(window / 4))) : 0;
761
+ const cap = windowValid ? Math.min(computeSummaryInputTokenCap(contextWindow), window - outputTokenBudget) : 0;
762
+ const blocked = (reason, extra = {}) => ({
763
+ status: "blocked",
764
+ reason,
765
+ diagnostics: {
766
+ contextWindow: window,
767
+ cap,
768
+ outputTokenBudget,
769
+ previousSummaryTokens: estimateTokenCount(previousSummary ?? ""),
770
+ messageCount: msgs.length,
771
+ ...extra
772
+ }
773
+ });
774
+ if (!windowValid) return blocked("invalid-window");
775
+ if (!msgs.length) return blocked("empty-input");
776
+ const systemTokens = estimateTokenCount(COMPACTION_SUMMARY_SYSTEM_PROMPT);
777
+ for (let i = 0; i < msgs.length; ) {
778
+ const msg = msgs[i];
779
+ if (msg.role === "tool") return blocked("no-safe-group");
780
+ const calls = msg.role === "assistant" && Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
781
+ if (!calls.length) {
782
+ i++;
783
+ continue;
784
+ }
785
+ const ids = calls.map((call) => call.id);
786
+ const hasIds = ids.every((id) => typeof id === "string" && id.length > 0);
787
+ if (!hasIds && ids.some((id) => id !== void 0) || hasIds && new Set(ids).size !== ids.length) {
788
+ return blocked("no-safe-group");
789
+ }
790
+ const remaining = new Set(ids);
791
+ let count = 0;
792
+ i++;
793
+ while (i < msgs.length && msgs[i].role === "tool") {
794
+ const id = msgs[i].tool_call_id;
795
+ if (hasIds ? !id || !remaining.delete(id) : id !== void 0) {
796
+ return blocked("no-safe-group");
797
+ }
798
+ count++;
799
+ i++;
800
+ }
801
+ if (count !== calls.length || hasIds && remaining.size) return blocked("no-safe-group");
802
+ }
803
+ const canonicalize = args.canonicalizeToolName ?? ((name) => name);
804
+ const operations = /* @__PURE__ */ new Map();
805
+ for (const msg of msgs) {
806
+ if (!Array.isArray(msg.tool_calls)) continue;
807
+ for (const op of extractFileOperationsFromCalls(msg.tool_calls, canonicalize)) {
808
+ operations.set(JSON.stringify([op.type, op.path]), op);
809
+ }
810
+ }
811
+ const labelsByOperation = { read: "\u8BFB\u53D6", write: "\u5199\u5165", edit: "\u7F16\u8F91" };
812
+ const fileOpsText = [...operations.values()].map((op) => `- ${labelsByOperation[op.type]}: ${op.path}`).join("\n") || "\u65E0";
813
+ const note = "\u4EE5\u4E0B\u662F\u6709\u635F\u6295\u5F71\uFF1A\u90E8\u5206\u6D88\u606F\u88AB\u622A\u53D6\uFF0C\u8FDE\u7EED\u7701\u7565\u7684\u533A\u95F4\u5408\u5E76\u4E3A\u4E00\u884C [...] \u58F0\u660E\uFF1B\u539F\u6587\u4ECD\u5B58\u5386\u53F2\u3002";
814
+ const omitted = "[... \u5185\u5BB9\u5DF2\u622A\u53D6 ...]";
815
+ const contents = msgs.map((msg) => serializeMessageContent(msg.content) || formatMessageContentFallback(msg));
816
+ const excerpts = contents.map((content) => makeBoundedExcerpt(content));
817
+ const raw = contents.map((content, i) => msgs[i].role === "tool" ? excerpts[i](TOOL_RESULT_TRUNCATE_CHARS) : content);
818
+ const promptFor = (messagesText) => buildCompactionUserContent({
819
+ previousSummary,
820
+ fileOpsText,
821
+ outputTokenBudget,
822
+ messagesText
823
+ });
824
+ const demands = raw.map((text) => estimateTokenCount(text));
825
+ const lineOverheads = msgs.map((msg) => estimateTokenCount(`${msg.role}: `) + 1);
826
+ const fixedTokens = systemTokens + estimateTokenCount(promptFor(`${note}
827
+ `));
828
+ const availableTokens = cap - fixedTokens;
829
+ const diagnosticsOf = (expandedMessages, omittedMessages) => {
830
+ const previousSummaryTokens = estimateTokenCount(previousSummary ?? "");
831
+ const baseTokens = systemTokens + estimateTokenCount(promptFor(""));
832
+ return {
833
+ contextWindow: window,
834
+ cap,
835
+ outputTokenBudget,
836
+ previousSummaryTokens,
837
+ messageCount: msgs.length,
838
+ systemTokens,
839
+ templateTokens: fixedTokens - systemTokens - previousSummaryTokens,
840
+ availableTokens,
841
+ expandedMessages,
842
+ omittedMessages,
843
+ baseTokens,
844
+ fileOpsCount: operations.size
845
+ };
846
+ };
847
+ if (availableTokens <= 0) {
848
+ return blocked("no-budget", diagnosticsOf(0, msgs.length));
849
+ }
850
+ const projectContent = (i, allowance) => {
851
+ if (demands[i] <= allowance) return raw[i];
852
+ let lo = 0;
853
+ let hi = Math.min(contents[i].length, msgs[i].role === "tool" ? TOOL_RESULT_TRUNCATE_CHARS : contents[i].length);
854
+ let best = omitted;
855
+ while (lo <= hi) {
856
+ const mid = Math.floor((lo + hi) / 2);
857
+ const candidate = excerpts[i](mid);
858
+ if (estimateTokenCount(candidate) <= allowance) {
859
+ best = candidate;
860
+ lo = mid + 1;
861
+ } else {
862
+ hi = mid - 1;
863
+ }
864
+ }
865
+ return best;
866
+ };
867
+ const selectRegions = (budget2) => {
868
+ const expanded = msgs.map(() => false);
869
+ const allowances = msgs.map(() => 0);
870
+ let used = 0;
871
+ const declarationReserve = Math.min(DECLARATION_RESERVE, Math.max(4, Math.floor(budget2 / 4)));
872
+ const room = () => budget2 - used - declarationReserve;
873
+ const takeFull = (i) => {
874
+ expanded[i] = true;
875
+ allowances[i] = demands[i];
876
+ used += lineOverheads[i] + demands[i];
877
+ };
878
+ const drop = (i) => {
879
+ if (!expanded[i]) return;
880
+ expanded[i] = false;
881
+ used -= lineOverheads[i] + allowances[i];
882
+ allowances[i] = 0;
883
+ };
884
+ const headBudget = Math.floor(budget2 * SUMMARY_HEAD_SHARE);
885
+ let headEnd = -1;
886
+ let headUsed = 0;
887
+ for (let i = 0; i < msgs.length; i++) {
888
+ const cost = lineOverheads[i] + demands[i];
889
+ const limit = i === 0 ? Math.max(headBudget, room()) : headBudget - headUsed;
890
+ if (cost > limit) break;
891
+ takeFull(i);
892
+ headUsed += cost;
893
+ headEnd = i;
894
+ }
895
+ const userBudget = Math.floor(budget2 * SUMMARY_USER_SHARE);
896
+ let userSpend = 0;
897
+ for (let i = msgs.length - 1; i > headEnd; i--) {
898
+ if (expanded[i] || msgs[i].role !== "user") continue;
899
+ if (demands[i] > USER_MESSAGE_MAX_DEMAND) continue;
900
+ const cost = lineOverheads[i] + demands[i] + DECLARATION_SPLIT_COST;
901
+ if (userSpend + cost > userBudget || cost > room()) continue;
902
+ takeFull(i);
903
+ userSpend += cost;
904
+ }
905
+ let tailStart = msgs.length;
906
+ for (let i = msgs.length - 1; i > headEnd; i--) {
907
+ if (expanded[i]) {
908
+ tailStart = i;
909
+ continue;
910
+ }
911
+ if (lineOverheads[i] + demands[i] > room()) break;
912
+ takeFull(i);
913
+ tailStart = i;
914
+ }
915
+ const boundaryCap = Math.floor(room() * 0.5);
916
+ const takeBoundary = (i) => {
917
+ const inline = Math.min(room(), boundaryCap) - lineOverheads[i];
918
+ if (inline < MIN_INLINE_CONTENT_TOKENS) return false;
919
+ expanded[i] = true;
920
+ allowances[i] = inline;
921
+ used += lineOverheads[i] + inline;
922
+ return true;
923
+ };
924
+ if (tailStart - 1 > headEnd && !expanded[tailStart - 1] && takeBoundary(tailStart - 1)) tailStart--;
925
+ if (headEnd + 1 < tailStart && !expanded[headEnd + 1] && takeBoundary(headEnd + 1)) headEnd++;
926
+ let grew = true;
927
+ while (grew) {
928
+ grew = false;
929
+ for (let i = tailStart - 1; i > headEnd; i--) {
930
+ if (expanded[i]) {
931
+ tailStart = i;
932
+ continue;
933
+ }
934
+ if (lineOverheads[i] + demands[i] > room()) break;
935
+ takeFull(i);
936
+ tailStart = i;
937
+ grew = true;
938
+ break;
939
+ }
940
+ for (let i = headEnd + 1; i < tailStart; i++) {
941
+ if (expanded[i]) {
942
+ headEnd = i;
943
+ continue;
944
+ }
945
+ if (lineOverheads[i] + demands[i] > room()) break;
946
+ takeFull(i);
947
+ headEnd = i;
948
+ grew = true;
949
+ break;
950
+ }
951
+ }
952
+ const callOfResult = /* @__PURE__ */ new Map();
953
+ const resultsOfCall = /* @__PURE__ */ new Map();
954
+ for (let i = 0; i < msgs.length; i++) {
955
+ const msg = msgs[i];
956
+ const calls = msg.role === "assistant" && Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
957
+ if (!calls.length) continue;
958
+ const ids = calls.map((call) => call.id);
959
+ const byId = ids.every((id) => typeof id === "string" && id.length > 0);
960
+ const results = [];
961
+ for (let j = i + 1; j < msgs.length && msgs[j].role === "tool"; j++) {
962
+ const id = msgs[j].tool_call_id;
963
+ if (!(byId ? typeof id === "string" && ids.includes(id) : id === void 0)) break;
964
+ results.push(j);
965
+ callOfResult.set(j, i);
966
+ }
967
+ resultsOfCall.set(i, results);
968
+ }
969
+ for (const [callIndex, results] of resultsOfCall) {
970
+ if (!expanded[callIndex] || !results.length) continue;
971
+ if (results.every((j) => expanded[j])) continue;
972
+ drop(callIndex);
973
+ }
974
+ for (let i = 0; i < msgs.length; i++) {
975
+ if (!expanded[i] || msgs[i].role !== "tool") continue;
976
+ const callIndex = callOfResult.get(i);
977
+ if (callIndex === void 0 || !expanded[callIndex]) drop(i);
978
+ }
979
+ return { expanded, allowances };
980
+ };
981
+ const render = (budget2) => {
982
+ const { expanded, allowances } = selectRegions(budget2);
983
+ const pieces = [];
984
+ let runStart = -1;
985
+ let runCounts = /* @__PURE__ */ new Map();
986
+ const flushRun = (end) => {
987
+ if (runStart < 0) return;
988
+ pieces.push(formatOmittedRun(runStart, end, runCounts));
989
+ runStart = -1;
990
+ runCounts = /* @__PURE__ */ new Map();
991
+ };
992
+ let expandedCount = 0;
993
+ for (let i = 0; i < msgs.length; i++) {
994
+ if (!expanded[i]) {
995
+ if (runStart < 0) runStart = i;
996
+ runCounts.set(msgs[i].role, (runCounts.get(msgs[i].role) ?? 0) + 1);
997
+ continue;
998
+ }
999
+ flushRun(i - 1);
1000
+ expandedCount++;
1001
+ pieces.push(`${msgs[i].role}: ${projectContent(i, allowances[i])}`);
1002
+ }
1003
+ flushRun(msgs.length - 1);
1004
+ const promptContent = promptFor(`${note}
1005
+ ${pieces.join("\n")}`);
1006
+ return {
1007
+ promptContent,
1008
+ inputTokens: systemTokens + estimateTokenCount(promptContent),
1009
+ expandedCount,
1010
+ omittedCount: msgs.length - expandedCount
1011
+ };
1012
+ };
1013
+ let budget = availableTokens;
1014
+ let last = render(budget);
1015
+ for (let attempt = 0; attempt < 12 && last.inputTokens > cap; attempt++) {
1016
+ const overflow = last.inputTokens - cap;
1017
+ budget = Math.max(0, Math.floor(budget - Math.max(overflow, Math.ceil(budget * 0.15))));
1018
+ last = render(budget);
1019
+ }
1020
+ if (last.inputTokens > cap || last.expandedCount === 0) {
1021
+ return blocked("no-budget", diagnosticsOf(last.expandedCount, last.omittedCount));
1022
+ }
1023
+ return {
1024
+ status: "ready",
1025
+ promptContent: last.promptContent,
1026
+ coveredMessages: msgs.slice(),
1027
+ summarizedBeforeId: msgs[msgs.length - 1].id,
1028
+ inputTokens: last.inputTokens,
1029
+ outputTokenBudget,
1030
+ partial: false,
1031
+ capTokens: cap,
1032
+ expandedMessages: last.expandedCount,
1033
+ omittedMessages: last.omittedCount
1034
+ };
1035
+ }
1036
+ var TOOL_RESULT_TRUNCATE_CHARS = 4e3;
1037
+ var SUMMARY_INPUT_MAX_TOKENS = 3e4;
1038
+ function computeSummaryInputTokenCap(contextWindow) {
1039
+ const halfWindow = typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow * 0.5) : SUMMARY_INPUT_MAX_TOKENS;
1040
+ return Math.max(1, Math.min(SUMMARY_INPUT_MAX_TOKENS, halfWindow));
1041
+ }
1042
+ var EVIDENCE_LINE_PATTERNS = [
1043
+ // commit sha:必须带 git 语境(commit/sha/HEAD/merge/push 输出 a..b)且含字母+数字
1044
+ /\b(?:commit|sha|HEAD|merge|revert|cherry-pick)\b[^\n]{0,24}\b(?=[0-9a-f]*[a-f])(?=[0-9a-f]*\d)[0-9a-f]{7,40}\b/i,
1045
+ /\b(?=[0-9a-f]*[a-f])(?=[0-9a-f]*\d)[0-9a-f]{7,40}\.\.(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/,
1046
+ // 测试结论:带计数的 pass/fail,或 bun/jest 风格的 (pass)/(fail) 行首
1047
+ /\b\d+\s+(?:pass|passed|fail|failed|tests?)\b/i,
1048
+ /^\s*\((?:pass|fail)\)/i,
1049
+ /^\s*(?:FAIL|PASS|ERROR)\b[:\s]/,
1050
+ // 退出码 / HTTP 状态:必须带键名
1051
+ /\bexit(?:\s*code|Code|_code)?\s*[=:]\s*\d+/i,
1052
+ /\bHTTP\/[\d.]+\s+[1-5]\d{2}\b/,
1053
+ /\b(?:status|statusCode|http_code|code)\s*[=:]\s*[1-5]\d{2}\b/i,
1054
+ // 错误:行首的 XxxError:/Exception:,或 error: 前缀;超时带 timeout 关键结构
1055
+ /^\s*(?:Uncaught\s+)?[A-Z]\w*(?:Error|Exception)\b\s*:/,
1056
+ /^\s*(?:error|fatal|panic)\s*:/i,
1057
+ /\bTimeout\s+\d+\s*ms\s+exceeded\b/i,
1058
+ // 堆栈帧
1059
+ /^\s*at\s+\S+.*:\d+(?::\d+)?\)?\s*$/
1060
+ ];
1061
+ function isEvidenceLine(line) {
1062
+ if (!line) return false;
1063
+ return EVIDENCE_LINE_PATTERNS.some((re) => re.test(line));
1064
+ }
1065
+ function selectEvidenceLines(lines) {
1066
+ return lines.filter(isEvidenceLine);
1067
+ }
1068
+ function buildCompactionMetrics(args) {
1069
+ const {
1070
+ reason,
1071
+ previousSummary,
1072
+ msgsToCompress,
1073
+ msgsToKeep,
1074
+ newSummary,
1075
+ summaryUsage,
1076
+ estimateTokens,
1077
+ estimateMessageTokens
1078
+ } = args;
1079
+ const previousSummaryTokens = estimateTokens(previousSummary || "");
1080
+ const compressedTokens = msgsToCompress.reduce((s, m) => s + estimateMessageTokens(m), 0);
1081
+ const newSummaryTokens = estimateTokens(newSummary || "");
1082
+ const summaryInput = args.summaryInput;
1083
+ return {
1084
+ reason,
1085
+ previousSummaryTokens,
1086
+ compressedTokens,
1087
+ retainedTokens: msgsToKeep.reduce((s, m) => s + estimateMessageTokens(m), 0),
1088
+ newSummaryTokens,
1089
+ compressedCount: msgsToCompress.length,
1090
+ retainedCount: msgsToKeep.length,
1091
+ summaryUsage,
1092
+ hadPreviousSummary: previousSummary.trim().length > 0,
1093
+ residentReductionTokens: previousSummaryTokens + compressedTokens - newSummaryTokens,
1094
+ ...summaryInput ? {
1095
+ summaryInputTokens: summaryInput.inputTokens,
1096
+ ...summaryInput.capTokens !== void 0 ? { summaryInputCapTokens: summaryInput.capTokens } : {},
1097
+ ...summaryInput.expandedMessages !== void 0 ? { summaryExpandedMessages: summaryInput.expandedMessages } : {},
1098
+ ...summaryInput.omittedMessages !== void 0 ? { summaryOmittedMessages: summaryInput.omittedMessages } : {}
1099
+ } : {},
1100
+ ...args.planCounts?.pendingMessageCount !== void 0 ? { pendingMessageCount: args.planCounts.pendingMessageCount } : {},
1101
+ ...args.planCounts?.plannedCompressCount !== void 0 ? { plannedCompressCount: args.planCounts.plannedCompressCount } : {}
1102
+ };
1103
+ }
1104
+ function buildCompactionMetricsFromPlan(args) {
1105
+ return buildCompactionMetrics({
1106
+ reason: args.reason,
1107
+ previousSummary: args.previousSummary,
1108
+ msgsToCompress: args.plan.msgsToCompress,
1109
+ msgsToKeep: args.plan.msgsToKeep,
1110
+ newSummary: args.newSummary,
1111
+ summaryUsage: args.summaryUsage,
1112
+ ...args.summaryInput ? { summaryInput: args.summaryInput } : {},
1113
+ ...args.planCounts ? { planCounts: args.planCounts } : {},
1114
+ estimateTokens: estimateTokenCount,
1115
+ estimateMessageTokens: getMessageTokenCount
1116
+ });
1117
+ }
1118
+ function formatCompactionMetricsLog(metrics) {
1119
+ const totalBefore = metrics.previousSummaryTokens + metrics.compressedTokens;
1120
+ const totalAfter = metrics.newSummaryTokens + metrics.retainedTokens;
1121
+ const ratio = totalBefore > 0 ? (totalAfter / totalBefore).toFixed(2) : "N/A";
1122
+ const llmInfo = metrics.summaryUsage ? `, summary_llm_in=${metrics.summaryUsage.input_tokens ?? "?"} out=${metrics.summaryUsage.output_tokens ?? "?"}` : "";
1123
+ const netInfo = `, net=${metrics.residentReductionTokens}`;
1124
+ const omittedTotal = (metrics.summaryExpandedMessages ?? 0) + (metrics.summaryOmittedMessages ?? 0);
1125
+ const capSuffix = metrics.summaryInputCapTokens !== void 0 ? `/${metrics.summaryInputCapTokens}` : "";
1126
+ const omittedSuffix = metrics.summaryOmittedMessages !== void 0 ? ` omitted=${metrics.summaryOmittedMessages}/${omittedTotal}` : "";
1127
+ const projectionInfo = metrics.summaryInputTokens !== void 0 ? `, summary_in=${metrics.summaryInputTokens}${capSuffix}${omittedSuffix}` : "";
1128
+ const planInfo = metrics.pendingMessageCount !== void 0 ? `, pending=${metrics.pendingMessageCount}${metrics.plannedCompressCount !== void 0 ? ` fold=${metrics.plannedCompressCount}/${metrics.pendingMessageCount}` : ""}` : "";
1129
+ return `[Compaction] reason=${metrics.reason} compressed=${metrics.compressedCount}->${metrics.retainedCount} msgs, tokens=${totalBefore}->${totalAfter} (ratio=${ratio})${llmInfo}${netInfo}${projectionInfo}${planInfo}`;
1130
+ }
1131
+ function computeSummarySourceMetadata(messagesWithIds, summarizedBeforeId) {
1132
+ if (!summarizedBeforeId) return void 0;
1133
+ const found = messagesWithIds.findIndex((m) => m.id === summarizedBeforeId);
1134
+ if (found === -1) return void 0;
1135
+ const slice = messagesWithIds.slice(0, found + 1).map((m, index) => ({
1136
+ id: `local-${index}`,
1137
+ role: m.role,
1138
+ content: m.content ?? "",
1139
+ ...Array.isArray(m.tool_calls) ? { tool_calls: m.tool_calls } : {}
1140
+ }));
1141
+ const sourceHash = sha256Hex(JSON.stringify(slice));
1142
+ return {
1143
+ sourceHash,
1144
+ sourceCount: found + 1,
1145
+ schemaVersion: COMPACTION_SUMMARY_SCHEMA_VERSION
1146
+ };
1147
+ }
1148
+
1149
+ // packages/ai/llm/getModelContextWindow.ts
1150
+ var DEFAULT_CONTEXT_WINDOW = 256e3;
1151
+ var QWEN_3_6_CONTEXT_WINDOW = 262144;
1152
+ var GLM_5_2_CONTEXT_WINDOW = 1e6;
1153
+ var GPT_6_1_SOL_CONTEXT_WINDOW = 5e5;
1154
+ var GPT_6_1_SOL_PATTERN = /(^|\/)gpt-6\.1[- ]sol(?![a-z])/;
1155
+ var GPT_6_1_PINNED_PATTERN = /(^|\/)gpt-6\.1[- ](sol|terra)(?![a-z0-9])/;
1156
+ var GPT_272K_PINNED_PATTERN = /(^|\/)(gpt-6[- ](astra|luna|sol)|gpt-5\.6[- ](sol|terra|luna))(?![a-z0-9])/;
1157
+ var GPT_272K_CONTEXT_WINDOW = 272e3;
1158
+ function channelPinnedContextWindow(normalizedName) {
1159
+ if (GPT_6_1_PINNED_PATTERN.test(normalizedName)) return GPT_6_1_SOL_CONTEXT_WINDOW;
1160
+ if (GPT_272K_PINNED_PATTERN.test(normalizedName)) return GPT_272K_CONTEXT_WINDOW;
1161
+ return void 0;
1162
+ }
1163
+ var ANTIGRAVITY_EFFORT_SUFFIXES = [
1164
+ "-tiered",
1165
+ "-extra-low",
1166
+ "-low",
1167
+ "-medium",
1168
+ "-high"
1169
+ ];
1170
+ function stripEffortSuffix(model) {
1171
+ for (const suffix of ANTIGRAVITY_EFFORT_SUFFIXES) {
1172
+ if (model.endsWith(suffix) && model.length > suffix.length) {
1173
+ return model.slice(0, -suffix.length);
1174
+ }
1175
+ }
1176
+ return model;
1177
+ }
1178
+ function stripPreviewSuffix(model) {
1179
+ const suffix = "-preview";
1180
+ if (model.endsWith(suffix) && model.length > suffix.length) {
1181
+ return model.slice(0, -suffix.length);
1182
+ }
1183
+ return model;
1184
+ }
1185
+ function stripModelTag(model) {
1186
+ const colonIndex = model.indexOf(":");
1187
+ if (colonIndex > 0) {
1188
+ return model.slice(0, colonIndex);
1189
+ }
1190
+ return model;
1191
+ }
1192
+ var fullModelMap = null;
1193
+ var getFullModelMap = () => {
1194
+ if (!fullModelMap) {
1195
+ fullModelMap = /* @__PURE__ */ new Map();
1196
+ for (const [provider, models] of Object.entries(MODEL_LOOKUP_MAP)) {
1197
+ for (const model of models) {
1198
+ const entry = { ...model, provider };
1199
+ fullModelMap.set(model.name, entry);
1200
+ if (model.displayName) {
1201
+ fullModelMap.set(model.displayName.toLowerCase(), entry);
1202
+ }
1203
+ }
1204
+ }
1205
+ }
1206
+ return fullModelMap;
1207
+ };
1208
+ var legacyModelMap = null;
1209
+ var getLegacyModelMap = () => {
1210
+ if (!legacyModelMap) {
1211
+ legacyModelMap = /* @__PURE__ */ new Map();
1212
+ for (const model of ALL_MODELS) {
1213
+ legacyModelMap.set(model.name, model);
1214
+ if (model.displayName) {
1215
+ legacyModelMap.set(model.displayName.toLowerCase(), model);
1216
+ }
1217
+ }
1218
+ }
1219
+ return legacyModelMap;
1220
+ };
1221
+ function fuzzyContextWindow(normalizedName) {
1222
+ const bareModelName = (normalizedName.includes("/") ? normalizedName.slice(normalizedName.lastIndexOf("/") + 1) : normalizedName).replace(/:.*$/, "");
1223
+ if (normalizedName.includes("qwen-long") || normalizedName.includes("qwen3-long")) return 10485760;
1224
+ if (normalizedName.includes("qwen-coder") || normalizedName.includes("qwen3-coder")) return 1048576;
1225
+ if (normalizedName.includes("qwen3.8") || normalizedName.includes("qwen3p8")) return 1e6;
1226
+ if (normalizedName.includes("minimax-m3") || normalizedName.includes("minimax_m3")) return 1e6;
1227
+ if (bareModelName === "mimo-v2.6-pro" || normalizedName === "mimo v2.6 pro") return 1048576;
1228
+ if (normalizedName.includes("glm-5.3") || normalizedName.includes("glm5.3")) return 105e4;
1229
+ if (normalizedName.includes("glm-5.2") || normalizedName.includes("glm5.2")) return GLM_5_2_CONTEXT_WINDOW;
1230
+ if (normalizedName.includes("deepseek")) return 1e6;
1231
+ if (GPT_6_1_SOL_PATTERN.test(normalizedName)) return GPT_6_1_SOL_CONTEXT_WINDOW;
1232
+ const channelPinned = channelPinnedContextWindow(normalizedName);
1233
+ if (channelPinned !== void 0) return channelPinned;
1234
+ if (normalizedName.includes("gpt-5") || normalizedName.includes("gpt-4.1")) return 1047576;
1235
+ if (normalizedName.startsWith("cursor-grok-4.5")) return 1e6;
1236
+ if (normalizedName.includes("claude-4.6")) return 1e6;
1237
+ if (normalizedName.includes("gemini-3.1")) return 1e6;
1238
+ if (normalizedName.includes("gemini")) return 1048576;
1239
+ if (normalizedName.includes("qwen3.6") || normalizedName.includes("qwen3p6")) return QWEN_3_6_CONTEXT_WINDOW;
1240
+ if (normalizedName.includes("qwen3.7") || normalizedName.includes("qwen3p7")) return 262144;
1241
+ if (/minimax[-_ ]m2(?![\d.])/.test(normalizedName)) return 262144;
1242
+ const MISTRAL_LARGE_4 = /mistral[-_ ]large[-_ ]4/;
1243
+ const large4 = MISTRAL_LARGE_4.exec(normalizedName);
1244
+ if (large4) {
1245
+ const rest = normalizedName.slice(large4.index + large4[0].length);
1246
+ if (rest === "" || /^[-:_@/\s]/.test(rest)) return 524288;
1247
+ }
1248
+ if (normalizedName.includes("mistral-vibe-cli") || normalizedName.includes("mistral-medium-3.5") || normalizedName.includes("mistral-medium-3-5") || normalizedName.includes("mistral-medium-latest") || normalizedName.includes("mistral-medium-2604") || normalizedName.includes("mistral-large-latest") || normalizedName.includes("mistral-large-2512") || normalizedName.includes("mistral-small-latest") || normalizedName.includes("mistral-small-2603") || normalizedName.includes("magistral-medium-latest") || normalizedName.includes("magistral-small-latest") || // 展示名(TUI 传 displayName 的路径;Mistral 不在 MODEL_LOOKUP_MAP,无法走精确表):
1249
+ normalizedName.includes("mistral vibe cli") || normalizedName.includes("mistral medium 3.5") || normalizedName.includes("mistral large (latest)")) {
1250
+ return 262144;
1251
+ }
1252
+ if (bareModelName === "mistral-medium" || bareModelName === "mistral-medium-3") return 262144;
1253
+ if (normalizedName.includes("mistral-embed") || normalizedName.includes("codestral-embed")) return 8192;
1254
+ if (normalizedName.includes("mistral-ocr")) return 16384;
1255
+ if (normalizedName.includes("mistral-moderation")) return 131072;
1256
+ if (normalizedName.includes("codestral") || normalizedName.includes("mistral-code")) return 256e3;
1257
+ if (normalizedName.includes("claude")) return 2e5;
1258
+ if (normalizedName.includes("llama3.1") || normalizedName.includes("llama-3.1") || normalizedName.includes("llama3.2") || normalizedName.includes("llama-3.2") || normalizedName.includes("llama3.3") || normalizedName.includes("llama-3.3") || normalizedName.includes("qwen2.5") || normalizedName.includes("qwen-2.5") || normalizedName.includes("mistral-nemo") || normalizedName.includes("phi3.5") || normalizedName.includes("phi-3.5") || normalizedName.includes("phi4") || normalizedName.includes("phi-4")) {
1259
+ return 131072;
1260
+ }
1261
+ if (normalizedName.includes("qwen2") || normalizedName.includes("qwen-2") || normalizedName.includes("mistral") || normalizedName.includes("mixtral")) {
1262
+ return 32768;
1263
+ }
1264
+ if (normalizedName.includes("codellama") || normalizedName.includes("starcoder") || normalizedName.includes("phi3") || normalizedName.includes("phi-3")) {
1265
+ return 16384;
1266
+ }
1267
+ if (normalizedName.includes("llama3") || normalizedName.includes("llama-3") || normalizedName.includes("gemma2") || normalizedName.includes("gemma-2") || normalizedName.includes("gemma")) {
1268
+ return 8192;
1269
+ }
1270
+ if (/(^|[^a-z])llama/.test(normalizedName)) {
1271
+ return 4096;
1272
+ }
1273
+ return void 0;
1274
+ }
1275
+ var findCodexOAuthPinnedContextWindow = (modelName, provider) => {
1276
+ if (!modelName) return void 0;
1277
+ if (isPlatformManagedProvider(provider, modelName)) return void 0;
1278
+ return channelPinnedContextWindow(modelName.toLowerCase());
1279
+ };
1280
+ var findModelContextWindow = (modelName, provider) => findModelContextWindowImpl(modelName, provider, false);
1281
+ var findModelContextWindowImpl = (modelName, provider, allowHyphenRetry) => {
1282
+ if (!modelName) return void 0;
1283
+ const onPlatformChannel = isPlatformManagedProvider(provider, modelName);
1284
+ const normalizedName = modelName.toLowerCase();
1285
+ const map = getFullModelMap();
1286
+ const rawCandidates = [modelName, normalizedName];
1287
+ const strippedTag = stripModelTag(modelName);
1288
+ if (strippedTag !== modelName) {
1289
+ rawCandidates.push(strippedTag, strippedTag.toLowerCase());
1290
+ }
1291
+ const candidates = [];
1292
+ for (const base of rawCandidates) {
1293
+ candidates.push(base);
1294
+ const strippedEffort = stripEffortSuffix(base);
1295
+ if (strippedEffort !== base) {
1296
+ candidates.push(strippedEffort, strippedEffort.toLowerCase());
1297
+ }
1298
+ const strippedPreview = stripPreviewSuffix(base);
1299
+ if (strippedPreview !== base) {
1300
+ candidates.push(strippedPreview, strippedPreview.toLowerCase());
1301
+ }
1302
+ if (strippedEffort !== base) {
1303
+ const strippedBoth = stripPreviewSuffix(strippedEffort);
1304
+ if (strippedBoth !== strippedEffort) {
1305
+ candidates.push(strippedBoth, strippedBoth.toLowerCase());
1306
+ }
1307
+ }
1308
+ }
1309
+ for (const candidate of candidates) {
1310
+ const model = map.get(candidate);
1311
+ if (model?.contextWindow) {
1312
+ if (!onPlatformChannel && (channelPinnedContextWindow(model.name.toLowerCase()) !== void 0 || channelPinnedContextWindow(candidate.toLowerCase()) !== void 0)) {
1313
+ continue;
1314
+ }
1315
+ return typeof model.contextWindow === "number" ? model.contextWindow : void 0;
1316
+ }
1317
+ }
1318
+ if (onPlatformChannel) {
1319
+ const effective = resolvePlatformEffectiveModel(normalizedName);
1320
+ if (effective && effective !== normalizedName) {
1321
+ const aliased = map.get(effective);
1322
+ if (aliased?.contextWindow) {
1323
+ return typeof aliased.contextWindow === "number" ? aliased.contextWindow : void 0;
1324
+ }
1325
+ }
1326
+ }
1327
+ if (!onPlatformChannel) {
1328
+ for (const candidate of candidates) {
1329
+ const pinned = channelPinnedContextWindow(candidate.toLowerCase());
1330
+ if (pinned !== void 0) return pinned;
1331
+ }
1332
+ }
1333
+ const fuzzy = fuzzyContextWindow(normalizedName);
1334
+ if (fuzzy !== void 0) return fuzzy;
1335
+ if (!allowHyphenRetry) {
1336
+ const canonical = normalizeSeparators(modelName);
1337
+ if (canonical.toLowerCase() !== normalizedName) {
1338
+ return findModelContextWindowImpl(canonical, provider, true);
1339
+ }
1340
+ }
1341
+ return void 0;
1342
+ };
1343
+ function normalizeSeparators(raw) {
1344
+ return raw.replace(/\s+/g, "-").replace(/(?<=[a-z0-9])_(?=[a-z0-9])/g, "-");
1345
+ }
1346
+ var getModelContextWindow = (modelName, provider) => findModelContextWindow(modelName, provider) ?? DEFAULT_CONTEXT_WINDOW;
1347
+ var getModelInfo = (modelName) => {
1348
+ if (!modelName) return null;
1349
+ const map = getLegacyModelMap();
1350
+ return map.get(modelName) || map.get(modelName.toLowerCase()) || null;
1351
+ };
1352
+
1353
+ export {
1354
+ readCacheReadInputTokens,
1355
+ readCacheReadInputTokensOrNull,
1356
+ readCacheCreationInputTokens,
1357
+ normalizeUsage,
1358
+ serializeMessageContent,
1359
+ resolveCompressionTriggerRatio,
1360
+ truncateToolOutputForContext,
1361
+ getMessageTokenCount,
1362
+ resolveEffectiveCompactionBudgets,
1363
+ planCompression,
1364
+ DEFAULT_CONTEXT_WINDOW,
1365
+ findCodexOAuthPinnedContextWindow,
1366
+ findModelContextWindow,
1367
+ getModelContextWindow,
1368
+ getModelInfo,
1369
+ createSummaryBudget,
1370
+ classifySummaryError,
1371
+ isTruncatedCompletion,
1372
+ summaryCompletionTokens,
1373
+ selectSummaryRoute,
1374
+ runSummaryWithContract,
1375
+ sha256Hex,
1376
+ COMPACTION_SUMMARY_SCHEMA_VERSION,
1377
+ COMPACTION_SUMMARY_SYSTEM_PROMPT,
1378
+ buildBoundedCompactionRequest,
1379
+ buildCompactionMetricsFromPlan,
1380
+ formatCompactionMetricsLog,
1381
+ computeSummarySourceMetadata
1382
+ };