gerege-cli 0.26.5 → 0.26.7

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 (237) hide show
  1. package/README.md +8 -8
  2. package/chunks/{MaxSizedBox-VMVLMS4X.js → MaxSizedBox-LSNOJEKM.js} +1 -1
  3. package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
  4. package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
  5. package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-3DTOHTDM.js} +3 -3
  6. package/chunks/{advisor-ANUGICJ5.js → advisor-7JGQPS7X.js} +1 -1
  7. package/chunks/{agent-GNCQDICJ.js → agent-PNKQJGDO.js} +1 -1
  8. package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-7D33X7QQ.js} +1 -1
  9. package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-3R2MAUVE.js} +1 -1
  10. package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-2D7DECAE.js} +1 -1
  11. package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
  12. package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-OIHHZSPQ.js} +1 -1
  13. package/chunks/{batch-V2NJT3M5.js → batch-6UDAMPAA.js} +1 -1
  14. package/chunks/{bridge-BJQ627CX.js → bridge-QXVXPNJ6.js} +1 -1
  15. package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-P4W4R5SJ.js} +1 -1
  16. package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
  17. package/chunks/{chunk-ISGF3BVD.js → chunk-2J2BQ3PL.js} +2 -2
  18. package/chunks/{chunk-TQTIEK2W.js → chunk-2LMSDH6P.js} +1 -1
  19. package/chunks/{chunk-EIILQ6KT.js → chunk-3EZ5GCUT.js} +1 -1
  20. package/chunks/{chunk-UY2ET2AL.js → chunk-3ICJI5KW.js} +1 -1
  21. package/chunks/{chunk-VDRE7U3P.js → chunk-4A663FE6.js} +5 -5
  22. package/chunks/{chunk-2IGE2K5V.js → chunk-4AKTP4MM.js} +1 -1
  23. package/chunks/{chunk-NO26JN24.js → chunk-4LC4INFI.js} +1 -1
  24. package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
  25. package/chunks/{chunk-3XBJYUWP.js → chunk-4QOVM2LL.js} +1 -1
  26. package/chunks/{chunk-ZYTG6R7S.js → chunk-4VR4DUUD.js} +1 -1
  27. package/chunks/{chunk-DE53B2R7.js → chunk-4W27Z3OL.js} +1 -1
  28. package/chunks/{chunk-QOYRDEXR.js → chunk-53IB4U4E.js} +1 -1
  29. package/chunks/{chunk-CCOUFBOY.js → chunk-5R2JIZID.js} +1 -1
  30. package/chunks/{chunk-MPAR4JBP.js → chunk-5TWAP4OG.js} +1 -1
  31. package/chunks/{chunk-3NQESE5K.js → chunk-6JAXAFX7.js} +1 -1
  32. package/chunks/{chunk-POA4NX4N.js → chunk-6WV5RKYB.js} +1 -1
  33. package/chunks/{chunk-KN27BFXM.js → chunk-6YFNUVJR.js} +1 -1
  34. package/chunks/{chunk-2X3UF2CF.js → chunk-7HFFTOAD.js} +1 -1
  35. package/chunks/{chunk-KDYUZBZC.js → chunk-ATTJQLQV.js} +1 -1
  36. package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
  37. package/chunks/{chunk-X4BFEDWU.js → chunk-BIPPD7W6.js} +1 -1
  38. package/chunks/{chunk-DEMXCA3K.js → chunk-BVV7UXES.js} +1 -1
  39. package/chunks/{chunk-2VCDJ6UF.js → chunk-BY46PCWY.js} +1 -1
  40. package/chunks/{chunk-CXGGC4NO.js → chunk-CDKBM72V.js} +1 -1
  41. package/chunks/{chunk-5WLKN3GD.js → chunk-CK3OKTTL.js} +1 -1
  42. package/chunks/{chunk-FHBGTZ4K.js → chunk-DEJ47KJE.js} +1 -1
  43. package/chunks/{chunk-DTTC4ZKY.js → chunk-DQQN2HOP.js} +1 -1
  44. package/chunks/{chunk-PN62SUYK.js → chunk-DTX2OVQW.js} +1 -1
  45. package/chunks/{chunk-IBYFSHBB.js → chunk-DVUKYOCJ.js} +1 -1
  46. package/chunks/{chunk-Q5E5SOY2.js → chunk-E3KWSRJN.js} +1 -1
  47. package/chunks/{chunk-IDUGQMTP.js → chunk-EEPNACXJ.js} +1 -1
  48. package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
  49. package/chunks/{chunk-HSYBIGMS.js → chunk-F5SLLEJY.js} +1 -1
  50. package/chunks/{chunk-5ZQWQ3RK.js → chunk-F7622ZRQ.js} +1 -1
  51. package/chunks/{chunk-KKBOCRPF.js → chunk-FKUDVIME.js} +1 -1
  52. package/chunks/{chunk-62NLMVVT.js → chunk-FRVXSKL4.js} +1 -1
  53. package/chunks/{chunk-FIM7MM25.js → chunk-FTF2NFLB.js} +1 -1
  54. package/chunks/{chunk-OHXQYU6S.js → chunk-G4MWPXNY.js} +1 -1
  55. package/chunks/{chunk-SELRSZFK.js → chunk-GA35LMSX.js} +1 -1
  56. package/chunks/{chunk-SMYBY353.js → chunk-H34KVVI4.js} +1 -1
  57. package/chunks/{chunk-NGOIJH7K.js → chunk-H5EXNXGW.js} +1 -1
  58. package/chunks/{chunk-UBXLQ6TP.js → chunk-HJLRKM3W.js} +1 -1
  59. package/chunks/{chunk-CAPG7UVH.js → chunk-HVP4UF2Q.js} +1 -1
  60. package/chunks/{chunk-H57IX45A.js → chunk-HXTYFGSQ.js} +1 -1
  61. package/chunks/{chunk-55RVKT4O.js → chunk-IIHUDJX7.js} +1 -1
  62. package/chunks/{chunk-XFLLE2J3.js → chunk-IQMKQKKD.js} +2 -2
  63. package/chunks/{chunk-SQQORHMS.js → chunk-ISQMHOCC.js} +1 -1
  64. package/chunks/{chunk-YLAI26PX.js → chunk-IY7M5HKF.js} +1 -1
  65. package/chunks/{chunk-FDUXQAGW.js → chunk-IZXHCHJD.js} +1 -1
  66. package/chunks/{chunk-ZOBX6C7E.js → chunk-JHC22BZH.js} +1 -1
  67. package/chunks/{chunk-26ISBUM7.js → chunk-K7GN4CMV.js} +6 -6
  68. package/chunks/{chunk-4GC5HJZO.js → chunk-L7LO3YRT.js} +1 -1
  69. package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
  70. package/chunks/{chunk-2PY7R7GG.js → chunk-LY4XTBL4.js} +1 -1
  71. package/chunks/{chunk-7IERHQ63.js → chunk-LYFRGP42.js} +1 -1
  72. package/chunks/{chunk-FPZPCZFS.js → chunk-MDCA4I63.js} +1 -1
  73. package/chunks/{chunk-2LLPGSUK.js → chunk-MS2XCBPP.js} +1 -1
  74. package/chunks/{chunk-3Y6LSWEW.js → chunk-MXZXQUVP.js} +1 -1
  75. package/chunks/{chunk-IH2PFVWO.js → chunk-N4ZQC5HB.js} +1 -1
  76. package/chunks/{chunk-MTW3A3KT.js → chunk-N6EFYQ7M.js} +1 -1
  77. package/chunks/{chunk-AQWHCRKY.js → chunk-NHPKD7LY.js} +1 -1
  78. package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
  79. package/chunks/{chunk-CNFA5UUM.js → chunk-NPAENNRO.js} +1 -1
  80. package/chunks/{chunk-IA4K4PGK.js → chunk-NYBYDW6R.js} +1 -1
  81. package/chunks/{chunk-FNB3DPQZ.js → chunk-O3TUZQP4.js} +1 -1
  82. package/chunks/{chunk-RVJJFDF3.js → chunk-OZFZBGZG.js} +1 -1
  83. package/chunks/{chunk-B6D3KTUK.js → chunk-P2MZZMCS.js} +1 -1
  84. package/chunks/{chunk-GSOBASYW.js → chunk-PMBI46K4.js} +1 -1
  85. package/chunks/{chunk-WI4UMN3Q.js → chunk-Q5RRVBTY.js} +1 -1
  86. package/chunks/{chunk-5UZT4SXG.js → chunk-QHYSRPQR.js} +1 -1
  87. package/chunks/{chunk-2NOMOJWE.js → chunk-QONPET6Y.js} +2 -2
  88. package/chunks/{chunk-MOPJNP5I.js → chunk-QSPXKBUX.js} +1 -1
  89. package/chunks/{chunk-C56YJIEI.js → chunk-QTKPC24L.js} +1 -1
  90. package/chunks/{chunk-6X73W4TL.js → chunk-QTVSPQZQ.js} +1 -1
  91. package/chunks/{chunk-ADZI3OFT.js → chunk-QVHDM6N7.js} +1 -1
  92. package/chunks/{chunk-NVSKOSFG.js → chunk-RT6J7PV4.js} +1 -1
  93. package/chunks/{chunk-7MTBINFX.js → chunk-RULGA7WE.js} +2 -2
  94. package/chunks/{chunk-AMTFJVDD.js → chunk-SAVYMUU3.js} +1 -1
  95. package/chunks/{chunk-Z5XENA4A.js → chunk-T3CQ72HC.js} +8 -7
  96. package/chunks/{chunk-OPYGNTZP.js → chunk-U5YOAOU3.js} +1 -1
  97. package/chunks/{chunk-HFV6CQWE.js → chunk-ULLW2AYD.js} +1 -1
  98. package/chunks/{chunk-KGJ47CI5.js → chunk-UM5KBBYP.js} +1 -1
  99. package/chunks/{chunk-F26LTWDZ.js → chunk-UVMLWDRU.js} +1 -1
  100. package/chunks/{chunk-BRPJ5EHA.js → chunk-VK7LOUOJ.js} +1 -1
  101. package/chunks/{chunk-4EQWJTJR.js → chunk-VUNHJ74J.js} +1 -1
  102. package/chunks/{chunk-WB34KMOT.js → chunk-W2CV36HT.js} +1 -1
  103. package/chunks/{chunk-ADTFKUH2.js → chunk-WCI33URB.js} +1 -1
  104. package/chunks/{chunk-4TYTJQWR.js → chunk-WEPC42YR.js} +1 -1
  105. package/chunks/{chunk-YGHM5CDT.js → chunk-WF7Q3ZSQ.js} +1 -1
  106. package/chunks/{chunk-UJYOILZR.js → chunk-WK666FGZ.js} +3 -3
  107. package/chunks/{chunk-3WQPUP5U.js → chunk-WMLYHZZX.js} +1 -1
  108. package/chunks/{chunk-OCBJCZC2.js → chunk-WSI4G7XC.js} +1 -1
  109. package/chunks/{chunk-Q6QS5JTK.js → chunk-WXK7Z45R.js} +1 -1
  110. package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
  111. package/chunks/{chunk-BBOJUFMW.js → chunk-YWK3E4WJ.js} +1 -1
  112. package/chunks/{chunk-FNXO5KWB.js → chunk-YY4GWNTU.js} +2 -2
  113. package/chunks/{chunk-FLJLUMQF.js → chunk-ZFOEVHWG.js} +1 -1
  114. package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
  115. package/chunks/{config-utils-DLOK7OLM.js → config-utils-6B5FHBSF.js} +1 -1
  116. package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-FGRDE3GA.js} +1 -1
  117. package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-OFEHSKDB.js} +1 -1
  118. package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-D2KEWVHQ.js} +1 -1
  119. package/chunks/{cron-create-C6JOFIU4.js → cron-create-RFGGKTL7.js} +1 -1
  120. package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
  121. package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-GHQBRDMC.js} +1 -1
  122. package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
  123. package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
  124. package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
  125. package/chunks/{edit-3HMQPCHN.js → edit-XCECLEH3.js} +1 -1
  126. package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-SEN2PMRM.js} +1 -1
  127. package/chunks/{environment-NGIBJWOT.js → environment-CCPQJYKS.js} +1 -1
  128. package/chunks/{errors-MSTGCVGJ.js → errors-Y6HHUTGK.js} +1 -1
  129. package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-HADWGMIG.js} +1 -1
  130. package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-GZS7WOQL.js} +1 -1
  131. package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-76B5HDLT.js} +1 -1
  132. package/chunks/{fast-path-II433ZDP.js → fast-path-OEV7LQYV.js} +1 -1
  133. package/chunks/{glob-4Q6DCT3F.js → glob-NLWCQRMS.js} +1 -1
  134. package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-43XV33BT.js} +1 -1
  135. package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
  136. package/chunks/{i18n-L5URVOBB.js → i18n-JW6BVEGF.js} +1 -1
  137. package/chunks/{initializer-NQ2NECYP.js → initializer-UT6JLZ3O.js} +1 -1
  138. package/chunks/{installationInfo-BCTXASUM.js → installationInfo-LKWDV3S2.js} +1 -1
  139. package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-2KWKYVPC.js} +1 -1
  140. package/chunks/{list-7TE5TUZJ.js → list-BKINK3S2.js} +1 -1
  141. package/chunks/{llm-BWWKUBBZ.js → llm-3RWXAVM2.js} +4 -4
  142. package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-MDRBSH73.js} +1 -1
  143. package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
  144. package/chunks/{local-7BTAGV4J.js → local-TT4FLCTR.js} +1 -1
  145. package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OBA6VWYL.js} +1 -1
  146. package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
  147. package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-4MSRX3DY.js} +1 -1
  148. package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-PX5PZJKZ.js} +1 -1
  149. package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
  150. package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-X7REHGB4.js} +1 -1
  151. package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-6HUVAJH7.js} +1 -1
  152. package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
  153. package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
  154. package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
  155. package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
  156. package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-MYOYTUM2.js} +1 -1
  157. package/chunks/{mcp-YMG4RVMC.js → mcp-5OTEMZ7P.js} +1 -1
  158. package/chunks/{memory-7STURUXK.js → memory-TNW7RSAV.js} +1 -1
  159. package/chunks/mn-JMS6SWTO.js +8 -0
  160. package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-KNTWFZQS.js} +1 -1
  161. package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-U5C5P5UQ.js} +1 -1
  162. package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-R4KFI2WK.js} +1 -1
  163. package/chunks/{monitor-U5E33JO6.js → monitor-RD2PFK42.js} +1 -1
  164. package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
  165. package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
  166. package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-YLRN3UZT.js} +1 -1
  167. package/chunks/{omni-I5YECZBW.js → omni-CUJ52EW5.js} +1 -1
  168. package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-6B5MAU54.js} +1 -1
  169. package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
  170. package/chunks/{pidfile-UOGUNUTK.js → pidfile-P2HIGAUA.js} +1 -1
  171. package/chunks/{processUtils-QGQGZHBA.js → processUtils-JSKN5UGS.js} +1 -1
  172. package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
  173. package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-IEDZONWG.js} +1 -1
  174. package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-FYZBJCF6.js} +1 -1
  175. package/chunks/{read-file-63ZLWMOW.js → read-file-VNZNSD6X.js} +1 -1
  176. package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
  177. package/chunks/{review-AT6OWVDO.js → review-TBJRZWTD.js} +1 -1
  178. package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-4W5B5FOE.js} +1 -1
  179. package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-44X262G5.js} +1 -1
  180. package/chunks/{runtime-R3QIGB7U.js → runtime-6H6LKD73.js} +1 -1
  181. package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-SQXDRGVN.js} +1 -1
  182. package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-62IZKHJG.js} +1 -1
  183. package/chunks/{scheduler-KTPM226B.js → scheduler-QUCXJYRL.js} +1 -1
  184. package/chunks/{search-memory-7I5MGDNV.js → search-memory-TC2Z34QN.js} +1 -1
  185. package/chunks/{send-message-J526AEBI.js → send-message-TFZX7KI7.js} +1 -1
  186. package/chunks/{serve-KLTMPK4W.js → serve-WSICDFGG.js} +1 -1
  187. package/chunks/{server-VLRNY6KG.js → server-GYYVTNGY.js} +3 -3
  188. package/chunks/{session-2EB57NXY.js → session-KF3O23ZJ.js} +1 -1
  189. package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-7HFUSONH.js} +1 -1
  190. package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
  191. package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-3KDFTDEV.js} +1 -1
  192. package/chunks/{sessionService-YRW2IFPR.js → sessionService-XRTFLPDW.js} +1 -1
  193. package/chunks/{settings-KO2Q47JP.js → settings-QPPK6WXE.js} +1 -1
  194. package/chunks/{shell-OLZVNTQZ.js → shell-WYQDZWL7.js} +1 -1
  195. package/chunks/{skill-XW2AQS7M.js → skill-FYPT6AU7.js} +1 -1
  196. package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-OGFI5KZF.js} +1 -1
  197. package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-ANOOVPG7.js} +1 -1
  198. package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-45WTDY4E.js} +1 -1
  199. package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-TL5WK33V.js} +1 -1
  200. package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-N2IREVBM.js} +1 -1
  201. package/chunks/{team-create-S5ZY2UMF.js → team-create-R77PRZ5U.js} +1 -1
  202. package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-6DCRKB5I.js} +1 -1
  203. package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
  204. package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-RQDXJGVR.js} +1 -1
  205. package/chunks/{tool-call-UK56SWCT.js → tool-call-LVB4NCDT.js} +1 -1
  206. package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-LRBB2KS6.js} +1 -1
  207. package/chunks/{tool-search-OWPFLVV5.js → tool-search-OG73QAQZ.js} +1 -1
  208. package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-A4CUF6AD.js} +1 -1
  209. package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-LSGOYTU2.js} +1 -1
  210. package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-OGC6BZO7.js} +1 -1
  211. package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-7J3GXTER.js} +1 -1
  212. package/chunks/{upload-config-OWLL4SRQ.js → upload-config-ML5XEJIF.js} +1 -1
  213. package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
  214. package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
  215. package/chunks/{version-C26S7UAW.js → version-7JN2YXL2.js} +1 -1
  216. package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-42ZR4FEZ.js} +1 -1
  217. package/chunks/{web-search-DAREKD3Z.js → web-search-74NLPMZJ.js} +1 -1
  218. package/chunks/{workflow-WBGPKVO6.js → workflow-WNPHX42I.js} +1 -1
  219. package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
  220. package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-3YFBFAK3.js} +1 -1
  221. package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-EPJI6KRV.js} +1 -1
  222. package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
  223. package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-VEXYBDMA.js} +1 -1
  224. package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-NRZYTP2X.js} +1 -1
  225. package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
  226. package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-USATWO56.js} +1 -1
  227. package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-M5JTSFDL.js} +1 -1
  228. package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
  229. package/chunks/{write-file-EJNMAHQD.js → write-file-UMJVKE4S.js} +1 -1
  230. package/chunks/{zoom-image-S3OARMYP.js → zoom-image-76XYHQ3Z.js} +1 -1
  231. package/cli.js +2 -2
  232. package/execution-worker.js +1 -1
  233. package/export-transcript-document.js +1 -1
  234. package/gerege.mjs +64 -15
  235. package/locales/mn.js +2702 -3774
  236. package/package.json +3 -3
  237. package/chunks/mn-YH2OTBWJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-BC4C6F32.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-WSOEJTOC.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-Z5XENA4A.js";import{sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
3
+ import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-BC4C6F32.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-WSOEJTOC.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-T3CQ72HC.js";import{sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{CoreToolScheduler,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,goalToolResultProvenance,isReplayOfHandledToolCall,markDuplicateProviderToolCallResponseSent,recordHandledToolCall}from"./chunk-Z5XENA4A.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function runAgentLoop(options){const{client,config,signal,host={}}=options;const duplicates=options.duplicates??{handled:new Map(client.getHistoryToolCallFingerprints()),responded:new Set};const executor=options.executor??createSchedulerExecutor(config,options.scheduler,options.runtimeView);let round=options.first;for(let index=0;;index++){const rounds=index+1;host.onRoundStart?.(index,round.promptId);const{turn,calls,stop}=await runModelRound(client,round,signal,host);host.onRoundEnd?.(index);if(stop)return{reason:stop,rounds,turn};if(calls.length===0)return{reason:"completed",rounds,turn};const batch=await runToolBatch(calls,{config,client,signal,toolSignal:options.toolSignal,host,duplicates,executor});if(batch.stop){return{reason:batch.stop,rounds,turn,parts:batch.parts}}if(options.maxRounds!==void 0&&rounds>=options.maxRounds){return{reason:"next_round",rounds,turn,parts:batch.parts}}round=host.nextRound?.(rounds,batch.parts)??{parts:batch.parts,promptId:round.promptId,options:{type:"toolResult"}}}}__name(runAgentLoop,"runAgentLoop");var STOP_EVENTS={["user_cancelled"]:"cancelled",["loop_detected"]:"loop_detected",["max_session_turns"]:"max_session_turns",["session_token_limit_exceeded"]:"session_token_limit",["user_prompt_submit_blocked"]:"user_prompt_blocked"};async function runModelRound(client,round,signal,host){const calls=[];let stop;const stream=client.sendMessageStream(round.parts,signal,round.promptId,round.options);let finished=false;try{for(;;){const next=await stream.next();if(next.done){finished=true;return{turn:next.value,calls,stop}}const event=next.value;let discardedCalls=[];if(event.type==="retry"||event.type==="model_fallback"){discardedCalls=calls.splice(0)}else if(event.type==="tool_call_request"){calls.push(event.value)}else if(event.type!=="user_cancelled"||signal.aborted){stop??=STOP_EVENTS[event.type]}await host.onModelEvent?.(event,discardedCalls)}}finally{if(!finished)await stream.return(void 0)}}__name(runModelRound,"runModelRound");async function runToolBatch(calls,options){const{config,client,signal,duplicates,executor}=options;const host=options.host??{};const toolSignal=options.toolSignal??signal;const providerKey=__name(request=>request.providerCallId??(request.callId||void 0),"providerKey");const isReplay=__name(request=>{const key=providerKey(request);return key?isReplayOfHandledToolCall(duplicates.handled,key,getCachedToolCallFingerprint(request,request.name,request.args)):false},"isReplay");const seenCallIds=new Set;const unique=[];const repeated=[];for(const request of calls){if(request.callId&&seenCallIds.has(request.callId)){repeated.push(request);continue}if(request.callId)seenCallIds.add(request.callId);unique.push(request)}if(findRepeatedDuplicateProviderToolCall([...unique,...repeated],providerKey,isReplay,duplicates.responded)){return{parts:[],stop:"duplicate_provider_call"}}const results=new Map;let ended=false;const deliver=__name(result=>{results.set(result.request,result);if(host.onToolResult?.(result)===true)ended=true},"deliver");const answer=__name((request,response,origin)=>deliver({request,executionRequest:request,response,status:response.error?"error":"success",origin}),"answer");const executable=[];for(const request of unique){const key=providerKey(request);if(key&&isReplay(request)){markDuplicateProviderToolCallResponseSent(key,duplicates.responded);answer(request,createDuplicateProviderToolCallResponse(request),"replayed");continue}if(key){recordHandledToolCall(duplicates.handled,key,getCachedToolCallFingerprint(request,request.name,request.args))}executable.push(request)}const selected=new Set(host.selectCalls?.(executable,calls)??executable);const toRun=executable.filter(request=>selected.has(request));const outputHandlers=new Map;for(const request of toRun){const handler=host.outputHandler?.(request);if(handler)outputHandlers.set(request.callId,handler)}const launches=new Map;let offered=0;const offerUntil=__name((end,settled)=>{for(;offered<end;offered++){const request=toRun[offered];launches.set(request.callId,host.beforeToolLaunch?.(request,settled)??true)}},"offerUntil");const completed=toRun.length===0?[]:await executor.run(toRun,toolSignal,{beforeLaunch:__name((request,settled)=>{offerUntil(toRun.findIndex(({callId})=>callId===request.callId)+1,settled);return launches.get(request.callId)===true},"beforeLaunch"),output:__name((callId,chunk)=>outputHandlers.get(callId)?.(callId,chunk),"output")});offerUntil(toRun.length,completed);const completedByCallId=new Map(completed.map(call=>[call.request.callId,call]));const aborted=signal.aborted;const planModeEntry=findPlanModeEntryBatchBoundaryIndex(toRun.map(({name})=>name));let terminateTurn=false;for(const[index,request]of toRun.entries()){const call=completedByCallId.get(request.callId);if(!call||!launches.get(request.callId))continue;terminateTurn||=call.response.terminateTurn===true;if(planModeEntry===void 0||index===planModeEntry){client.recordCompletedToolCall(call.request.name,call.request.args)}deliver(executedResult(request,call))}if(aborted&&!ended&&!options.keepCancelledResults){return{parts:[],stop:"cancelled"}}for(const request of executable){if(results.has(request))continue;answer(request,skippedResponse(request,host.skippedOutput?.(request)??""),"skipped")}for(const request of repeated){const key=providerKey(request);if(!key)continue;markDuplicateProviderToolCallResponseSent(key,duplicates.responded);answer(request,createDuplicateProviderToolCallResponse(request),"duplicate")}const ordered=calls.flatMap(request=>{const result=results.get(request);return result?[result]:[]});const finalized=await finalizeToolResponses(config,ordered.map(({request,response,executionRequest})=>({callId:request.callId,toolName:executionRequest.name,responseParts:response.responseParts,persistedOutputFiles:response.persistedOutputFiles,artifacts:response.artifacts})),new Map(ordered.map(({request})=>[request.callId,request.prompt_id])));const recorder=config.getChatRecordingService?.();const parts=[];ordered.forEach(({request,executionRequest,response,status},index)=>{const responseParts=finalized[index].responseParts;parts.push(...responseParts);const provenance=goalToolResultProvenance(executionRequest,responseParts);recorder?.recordToolResult?.(responseParts,{callId:request.callId,status,resultDisplay:response.resultDisplay,persistedOutputFiles:finalized[index].persistedOutputFiles,artifacts:finalized[index].artifacts,error:response.error,errorType:response.errorType,executionStatus:response.executionStatus},...provenance?[provenance]:[])});if(aborted&&!ended)return{parts,stop:"cancelled"};if(ended)return{parts,stop:"surface_ended"};if(terminateTurn&&(host.endsOnTerminateTurn?.()??true)){return{parts,stop:"tool_ended_turn"}}return{parts}}__name(runToolBatch,"runToolBatch");function executedResult(request,call){return{request,executionRequest:call.request,response:call.response,status:call.status,origin:"executed"}}__name(executedResult,"executedResult");function skippedResponse(request,output){return{callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{output}}}],resultDisplay:output,error:void 0,errorType:void 0,executionStatus:"not_started"}}__name(skippedResponse,"skippedResponse");function createSchedulerExecutor(config,options={},runtimeView){return{run:__name((requests,signal,hooks)=>new Promise((resolve,reject)=>{const batch=new Set(requests.map(({callId})=>callId));const settled=new Map;const parents=new Map;const scheduler=new CoreToolScheduler({getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose"),...options,config,outputUpdateHandler:__name((callId,chunk)=>{options.outputUpdateHandler?.(callId,chunk);hooks.output(parents.get(callId)??callId,chunk)},"outputUpdateHandler"),onToolCallsUpdate:__name(toolCalls=>{for(const call of toolCalls){const{callId,parentCallId}=call.request;if(!batch.has(callId)){if(parentCallId)parents.set(callId,parentCallId)}else if(call.status==="success"||call.status==="error"||call.status==="cancelled"){settled.set(callId,call)}}options.onToolCallsUpdate?.(toolCalls)},"onToolCallsUpdate"),beforeToolLaunch:__name(call=>hooks.beforeLaunch(call.request,[...settled.values()]),"beforeToolLaunch"),onAllToolCallsComplete:__name(async completedCalls=>{await options.onAllToolCallsComplete?.(completedCalls);resolve(completedCalls)},"onAllToolCallsComplete")});scheduler.schedule(requests,signal,runtimeView).catch(reject)}),"run")}}__name(createSchedulerExecutor,"createSchedulerExecutor");export{runAgentLoop,runModelRound,runToolBatch,createSchedulerExecutor};
3
+ import{CoreToolScheduler,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,goalToolResultProvenance,isReplayOfHandledToolCall,markDuplicateProviderToolCallResponseSent,recordHandledToolCall}from"./chunk-T3CQ72HC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function runAgentLoop(options){const{client,config,signal,host={}}=options;const duplicates=options.duplicates??{handled:new Map(client.getHistoryToolCallFingerprints()),responded:new Set};const executor=options.executor??createSchedulerExecutor(config,options.scheduler,options.runtimeView);let round=options.first;for(let index=0;;index++){const rounds=index+1;host.onRoundStart?.(index,round.promptId);const{turn,calls,stop}=await runModelRound(client,round,signal,host);host.onRoundEnd?.(index);if(stop)return{reason:stop,rounds,turn};if(calls.length===0)return{reason:"completed",rounds,turn};const batch=await runToolBatch(calls,{config,client,signal,toolSignal:options.toolSignal,host,duplicates,executor});if(batch.stop){return{reason:batch.stop,rounds,turn,parts:batch.parts}}if(options.maxRounds!==void 0&&rounds>=options.maxRounds){return{reason:"next_round",rounds,turn,parts:batch.parts}}round=host.nextRound?.(rounds,batch.parts)??{parts:batch.parts,promptId:round.promptId,options:{type:"toolResult"}}}}__name(runAgentLoop,"runAgentLoop");var STOP_EVENTS={["user_cancelled"]:"cancelled",["loop_detected"]:"loop_detected",["max_session_turns"]:"max_session_turns",["session_token_limit_exceeded"]:"session_token_limit",["user_prompt_submit_blocked"]:"user_prompt_blocked"};async function runModelRound(client,round,signal,host){const calls=[];let stop;const stream=client.sendMessageStream(round.parts,signal,round.promptId,round.options);let finished=false;try{for(;;){const next=await stream.next();if(next.done){finished=true;return{turn:next.value,calls,stop}}const event=next.value;let discardedCalls=[];if(event.type==="retry"||event.type==="model_fallback"){discardedCalls=calls.splice(0)}else if(event.type==="tool_call_request"){calls.push(event.value)}else if(event.type!=="user_cancelled"||signal.aborted){stop??=STOP_EVENTS[event.type]}await host.onModelEvent?.(event,discardedCalls)}}finally{if(!finished)await stream.return(void 0)}}__name(runModelRound,"runModelRound");async function runToolBatch(calls,options){const{config,client,signal,duplicates,executor}=options;const host=options.host??{};const toolSignal=options.toolSignal??signal;const providerKey=__name(request=>request.providerCallId??(request.callId||void 0),"providerKey");const isReplay=__name(request=>{const key=providerKey(request);return key?isReplayOfHandledToolCall(duplicates.handled,key,getCachedToolCallFingerprint(request,request.name,request.args)):false},"isReplay");const seenCallIds=new Set;const unique=[];const repeated=[];for(const request of calls){if(request.callId&&seenCallIds.has(request.callId)){repeated.push(request);continue}if(request.callId)seenCallIds.add(request.callId);unique.push(request)}if(findRepeatedDuplicateProviderToolCall([...unique,...repeated],providerKey,isReplay,duplicates.responded)){return{parts:[],stop:"duplicate_provider_call"}}const results=new Map;let ended=false;const deliver=__name(result=>{results.set(result.request,result);if(host.onToolResult?.(result)===true)ended=true},"deliver");const answer=__name((request,response,origin)=>deliver({request,executionRequest:request,response,status:response.error?"error":"success",origin}),"answer");const executable=[];for(const request of unique){const key=providerKey(request);if(key&&isReplay(request)){markDuplicateProviderToolCallResponseSent(key,duplicates.responded);answer(request,createDuplicateProviderToolCallResponse(request),"replayed");continue}if(key){recordHandledToolCall(duplicates.handled,key,getCachedToolCallFingerprint(request,request.name,request.args))}executable.push(request)}const selected=new Set(host.selectCalls?.(executable,calls)??executable);const toRun=executable.filter(request=>selected.has(request));const outputHandlers=new Map;for(const request of toRun){const handler=host.outputHandler?.(request);if(handler)outputHandlers.set(request.callId,handler)}const launches=new Map;let offered=0;const offerUntil=__name((end,settled)=>{for(;offered<end;offered++){const request=toRun[offered];launches.set(request.callId,host.beforeToolLaunch?.(request,settled)??true)}},"offerUntil");const completed=toRun.length===0?[]:await executor.run(toRun,toolSignal,{beforeLaunch:__name((request,settled)=>{offerUntil(toRun.findIndex(({callId})=>callId===request.callId)+1,settled);return launches.get(request.callId)===true},"beforeLaunch"),output:__name((callId,chunk)=>outputHandlers.get(callId)?.(callId,chunk),"output")});offerUntil(toRun.length,completed);const completedByCallId=new Map(completed.map(call=>[call.request.callId,call]));const aborted=signal.aborted;const planModeEntry=findPlanModeEntryBatchBoundaryIndex(toRun.map(({name})=>name));let terminateTurn=false;for(const[index,request]of toRun.entries()){const call=completedByCallId.get(request.callId);if(!call||!launches.get(request.callId))continue;terminateTurn||=call.response.terminateTurn===true;if(planModeEntry===void 0||index===planModeEntry){client.recordCompletedToolCall(call.request.name,call.request.args)}deliver(executedResult(request,call))}if(aborted&&!ended&&!options.keepCancelledResults){return{parts:[],stop:"cancelled"}}for(const request of executable){if(results.has(request))continue;answer(request,skippedResponse(request,host.skippedOutput?.(request)??""),"skipped")}for(const request of repeated){const key=providerKey(request);if(!key)continue;markDuplicateProviderToolCallResponseSent(key,duplicates.responded);answer(request,createDuplicateProviderToolCallResponse(request),"duplicate")}const ordered=calls.flatMap(request=>{const result=results.get(request);return result?[result]:[]});const finalized=await finalizeToolResponses(config,ordered.map(({request,response,executionRequest})=>({callId:request.callId,toolName:executionRequest.name,responseParts:response.responseParts,persistedOutputFiles:response.persistedOutputFiles,artifacts:response.artifacts})),new Map(ordered.map(({request})=>[request.callId,request.prompt_id])));const recorder=config.getChatRecordingService?.();const parts=[];ordered.forEach(({request,executionRequest,response,status},index)=>{const responseParts=finalized[index].responseParts;parts.push(...responseParts);const provenance=goalToolResultProvenance(executionRequest,responseParts);recorder?.recordToolResult?.(responseParts,{callId:request.callId,status,resultDisplay:response.resultDisplay,persistedOutputFiles:finalized[index].persistedOutputFiles,artifacts:finalized[index].artifacts,error:response.error,errorType:response.errorType,executionStatus:response.executionStatus},...provenance?[provenance]:[])});if(aborted&&!ended)return{parts,stop:"cancelled"};if(ended)return{parts,stop:"surface_ended"};if(terminateTurn&&(host.endsOnTerminateTurn?.()??true)){return{parts,stop:"tool_ended_turn"}}return{parts}}__name(runToolBatch,"runToolBatch");function executedResult(request,call){return{request,executionRequest:call.request,response:call.response,status:call.status,origin:"executed"}}__name(executedResult,"executedResult");function skippedResponse(request,output){return{callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{output}}}],resultDisplay:output,error:void 0,errorType:void 0,executionStatus:"not_started"}}__name(skippedResponse,"skippedResponse");function createSchedulerExecutor(config,options={},runtimeView){return{run:__name((requests,signal,hooks)=>new Promise((resolve,reject)=>{const batch=new Set(requests.map(({callId})=>callId));const settled=new Map;const parents=new Map;const scheduler=new CoreToolScheduler({getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose"),...options,config,outputUpdateHandler:__name((callId,chunk)=>{options.outputUpdateHandler?.(callId,chunk);hooks.output(parents.get(callId)??callId,chunk)},"outputUpdateHandler"),onToolCallsUpdate:__name(toolCalls=>{for(const call of toolCalls){const{callId,parentCallId}=call.request;if(!batch.has(callId)){if(parentCallId)parents.set(callId,parentCallId)}else if(call.status==="success"||call.status==="error"||call.status==="cancelled"){settled.set(callId,call)}}options.onToolCallsUpdate?.(toolCalls)},"onToolCallsUpdate"),beforeToolLaunch:__name(call=>hooks.beforeLaunch(call.request,[...settled.values()]),"beforeToolLaunch"),onAllToolCallsComplete:__name(async completedCalls=>{await options.onAllToolCallsComplete?.(completedCalls);resolve(completedCalls)},"onAllToolCallsComplete")});scheduler.schedule(requests,signal,runtimeView).catch(reject)}),"run")}}__name(createSchedulerExecutor,"createSchedulerExecutor");export{runAgentLoop,runModelRound,runToolBatch,createSchedulerExecutor};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-NO26JN24.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,renameSync,rmdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve(repositoryRoot);rmSync(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
3
+ import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-4LC4INFI.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,renameSync,rmdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve(repositoryRoot);rmSync(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
4
4
  `)}catch(error){debugLogger.debug(`Failed to record the merge base in ${path}:`,error)}}__name(recordReviewWorktreeLeaseMergeBase,"recordReviewWorktreeLeaseMergeBase");function atomicWriteLease(path,data){const tmp=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,path)}catch(error){try{rmSync(tmp,{force:true})}catch{}throw error}}__name(atomicWriteLease,"atomicWriteLease");function reclaimBaseTreeTrust(root,target){const dir=join(leaseDirectory(root),"base-tree",target);let entries;try{entries=readdirSync(dir)}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to reclaim base-tree trust state for ${target}:`,error)}return}for(const name of entries){if(name.endsWith(".lock"))continue;try{rmSync(join(dir,name),{recursive:true,force:true})}catch(error){debugLogger.debug(`Failed to reclaim base-tree trust state ${name} for ${target}:`,error)}}try{rmdirSync(dir)}catch{}}__name(reclaimBaseTreeTrust,"reclaimBaseTreeTrust");function restoreReviewWorktreeLeaseMergeBase(repositoryRoot,target,sessionId){if(!validTarget(target)||!sessionId)return;const path=leasePath(resolve(repositoryRoot),target);const existing=readLease(path);if(!existing||existing.sessionId!==sessionId)return;if(existing.mergeBaseSha!==void 0)return;if(existing.priorMergeBaseResumable!==true)return;const next={...existing,mergeBaseSha:existing.priorMergeBaseSha,mergeBaseStale:existing.priorMergeBaseStale===true,priorMergeBaseCurrent:true};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
5
5
  `)}catch(error){debugLogger.debug(`Failed to restore the merge base in ${path}:`,error)}}__name(restoreReviewWorktreeLeaseMergeBase,"restoreReviewWorktreeLeaseMergeBase");function createReviewWorktreeLease(params){if(!params.sessionId||!params.promptId||!validTarget(params.target)){return}const repositoryRoot=resolve(params.repositoryRoot);const path=leasePath(repositoryRoot,params.target);const leaseFor=__name((identity,prior)=>{const lease={sessionId:params.sessionId,promptId:params.promptId,target:params.target,repositoryRoot,worktreePath:resolve(repositoryRoot,params.worktreePath),branch:params.branch,identity,...prior===void 0?{}:{priorMergeBaseSha:prior.sha,priorMergeBaseStale:prior.stale,priorMergeBaseResumable:prior.resumable}};return`${JSON.stringify(lease,null,2)}
6
6
  `},"leaseFor");let data=leaseFor(mintIdentity());mkdirSync(leaseDirectory(repositoryRoot),{recursive:true,mode:448});const legacy=legacyLeasePath(repositoryRoot,params.target);try{writeFileSync(path,data,{encoding:"utf8",flag:"wx"})}catch(error){if(error.code!=="EEXIST")throw error;const existing=readLease(path);if(existing&&existing.sessionId!==params.sessionId){throw new Error(`review worktree lease for ${params.target} is held by another session (session ${existing.sessionId}) at ${path}; it was acquired between the gate read and the lease write \u2014 retry`)}if(existing){data=leaseFor(typeof existing.identity==="number"&&Number.isFinite(existing.identity)?existing.identity:mintIdentity(),existing.mergeBaseSha!==void 0?{sha:existing.mergeBaseSha,stale:existing.mergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:existing.priorMergeBaseSha!==void 0?{sha:existing.priorMergeBaseSha,stale:existing.priorMergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:void 0)}atomicWriteLease(path,data)}mirrorLeaseAtLegacyPath(legacy,data,params.sessionId,params.target)}__name(createReviewWorktreeLease,"createReviewWorktreeLease");function mirrorLeaseAtLegacyPath(legacy,data,sessionId,target){try{mkdirSync(dirname(legacy),{recursive:true});writeFileSync(legacy,data,{encoding:"utf8",flag:"wx"});return}catch(error){if(error.code!=="EEXIST"){warnMirrorSkipped(legacy,error);return}}const displaced=readLease(legacy);const tmp=`${legacy}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,legacy)}catch(error){try{rmSync(tmp,{force:true})}catch{}warnMirrorSkipped(legacy,error);return}if(displaced&&displaced.sessionId!==sessionId){writeStderrLineSafe(`warning: replaced the pre-move review lease for ${target} at ${legacy} (recorded session ${inertSessionId(displaced.sessionId)}) \u2014 if a pre-move build is still reviewing ${target} on this machine, its worktree is no longer protected; otherwise this was residue or a plant, and it is gone.`)}}__name(mirrorLeaseAtLegacyPath,"mirrorLeaseAtLegacyPath");function inertSessionId(id){const inert=inertPath(id);return inert.length>120?`${inert.slice(0,120)}\u2026`:inert}__name(inertSessionId,"inertSessionId");function warnMirrorSkipped(legacy,error){writeStderrLineSafe(`warning: could not mirror the review worktree lease to the pre-move path ${legacy} (${error.code??error}); the acquisition stands on the new-path lease, but builds from before the lease move will not see this lock.`)}__name(warnMirrorSkipped,"warnMirrorSkipped");function readLease(path){try{if(!lstatSync(path).isFile()){rmSync(path,{force:true,recursive:true});return null}}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to inspect review lease ${path}:`,error)}return null}try{const value=JSON.parse(readFileSync(path,"utf8"));if(typeof value.sessionId!=="string"||typeof value.promptId!=="string"||typeof value.target!=="string"||typeof value.repositoryRoot!=="string"||typeof value.worktreePath!=="string"||typeof value.branch!=="string"||value.identity!==void 0&&(typeof value.identity!=="number"||!Number.isFinite(value.identity))||value.mergeBaseSha!==void 0&&typeof value.mergeBaseSha!=="string"||value.priorMergeBaseSha!==void 0&&typeof value.priorMergeBaseSha!=="string"||value.mergeBaseStale!==void 0&&typeof value.mergeBaseStale!=="boolean"||value.priorMergeBaseStale!==void 0&&typeof value.priorMergeBaseStale!=="boolean"||value.priorMergeBaseCurrent!==void 0&&typeof value.priorMergeBaseCurrent!=="boolean"||value.priorMergeBaseResumable!==void 0&&typeof value.priorMergeBaseResumable!=="boolean"){return null}return value}catch(error){debugLogger.debug(`Failed to read review lease ${path}:`,error);return null}}__name(readLease,"readLease");function readReviewWorktreeLease(repositoryRoot,target){return readReviewWorktreeLeaseAt(repositoryRoot,target)?.lease??null}__name(readReviewWorktreeLease,"readReviewWorktreeLease");function readReviewWorktreeLeaseAt(repositoryRoot,target){if(!validTarget(target))return null;const root=resolve(repositoryRoot);const current=leasePath(root,target);const lease=readLease(current);return lease?{lease,path:current}:null}__name(readReviewWorktreeLeaseAt,"readReviewWorktreeLeaseAt");function reviewLeaseHeldByAnotherSession(lease){if(!lease)return false;const sessionId=process.env["QWEN_CODE_SESSION_ID"]?.trim();return!sessionId||lease.sessionId!==sessionId}__name(reviewLeaseHeldByAnotherSession,"reviewLeaseHeldByAnotherSession");function sameLease(a,b){return b!==null&&a.sessionId===b.sessionId&&a.promptId===b.promptId&&a.target===b.target&&a.repositoryRoot===b.repositoryRoot&&a.worktreePath===b.worktreePath&&a.branch===b.branch}__name(sameLease,"sameLease");function removeLeaseWorktree(lease,gitTimeout){const prMatch=/^pr-(\d+)$/.exec(lease.target);if(!prMatch||lease.branch!==reviewBranch(prMatch[1])){debugLogger.debug(`Rejected invalid review lease ${lease.target}`);return false}const repositoryRoot=resolve(lease.repositoryRoot);const worktreePath=resolve(lease.worktreePath);const reviewTmpRoot=resolve(repositoryRoot,REVIEW_TMP_DIR);const worktreeRelative=relative(reviewTmpRoot,worktreePath);if(worktreeRelative===""||worktreeRelative.startsWith("..")||isAbsolute(worktreeRelative)){debugLogger.debug(`Rejected review lease outside ${REVIEW_TMP_DIR}: ${worktreePath}`);return false}try{execFileSync("git",["-C",repositoryRoot,"worktree","remove",worktreePath,"--force"],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Git failed to remove review worktree ${lease.target}:`,error);try{rmSync(worktreePath,{recursive:true,force:true});execFileSync("git",["-C",repositoryRoot,"worktree","prune"],gitOptions(gitTimeout))}catch(fallbackError){debugLogger.debug(`Fallback failed to remove review worktree ${lease.target}:`,fallbackError);return false}}let branchExists=true;try{execFileSync("git",["-C",repositoryRoot,"show-ref","--verify","--quiet",`refs/heads/${lease.branch}`],gitOptions(gitTimeout))}catch(error){if(error.status!==1){debugLogger.debug(`Failed to inspect review branch ${lease.branch}:`,error);return false}branchExists=false}if(branchExists){try{execFileSync("git",["-C",repositoryRoot,"branch","-D",lease.branch],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Failed to delete review branch ${lease.branch}:`,error);return false}}return!existsSync(worktreePath)}__name(removeLeaseWorktree,"removeLeaseWorktree");function cleanupReviewWorktreeLeases(params){try{const repositoryRoot=resolve(params.repositoryRoot);const newLeaseDirectory=leaseDirectory(repositoryRoot);if(!existsSync(newLeaseDirectory))return;let entries;try{entries=readdirSync(newLeaseDirectory)}catch(error){debugLogger.debug(`Failed to list ${newLeaseDirectory} for lease cleanup:`,error);return}for(const entry of entries){if(!isReviewLeaseFile(entry))continue;const path=join(newLeaseDirectory,basename(entry));const lease=readLease(path);if(!lease||lease.sessionId!==params.sessionId||lease.promptId!==params.promptId||resolve(lease.repositoryRoot)!==repositoryRoot){continue}if(!removeLeaseWorktree(lease,params.gitTimeout??GIT_TIMEOUT_MS)){continue}rmSync(path,{force:true});reclaimBaseTreeTrust(repositoryRoot,lease.target);const twin=join(repositoryRoot,REVIEW_TMP_DIR,basename(entry));try{if(sameLease(lease,readLease(twin))){rmSync(twin,{force:true})}}catch(error){debugLogger.debug(`Failed to remove legacy lease twin ${twin}:`,error)}}}catch(error){debugLogger.debug("Failed to clean up review worktree leases:",error)}}__name(cleanupReviewWorktreeLeases,"cleanupReviewWorktreeLeases");export{isReviewLeaseFile,clearReviewWorktreeLease,clearReviewWorktreeLeaseIfOwned,recordReviewWorktreeLeaseMergeBase,restoreReviewWorktreeLeaseMergeBase,createReviewWorktreeLease,readReviewWorktreeLease,readReviewWorktreeLeaseAt,reviewLeaseHeldByAnotherSession,cleanupReviewWorktreeLeases};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{readConfigFile}from"./chunk-WI4UMN3Q.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-DOLUT3XC.js";import{normalizeClaudeMcpServer}from"./chunk-Z5XENA4A.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
3
+ import{readConfigFile}from"./chunk-Q5RRVBTY.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-DOLUT3XC.js";import{normalizeClaudeMcpServer}from"./chunk-T3CQ72HC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{t}from"./chunk-ABJGFEES.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-Z5XENA4A.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{getAllMemoryFilenames}from"./chunk-Y6HHV4LC.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-GOR7FFVE.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-B3ZFUGTC.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[‎‏؜⁦⁧⁨⁩‪‫‬‭‮]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
3
+ import{t}from"./chunk-NO7VTKRL.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-T3CQ72HC.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{getAllMemoryFilenames}from"./chunk-Y6HHV4LC.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-GOR7FFVE.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-B3ZFUGTC.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[‎‏؜⁦⁧⁨⁩‪‫‬‭‮]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
4
4
 
5
5
  ${cappedContent}`;remainingBudget-=cappedContent.length}return{text:contextText,remainingBudget}}__name(buildExtensionMentionContext,"buildExtensionMentionContext");function currentTier(tokens,thresholds){if(tokens>=thresholds.hard)return"hard";if(tokens>=thresholds.auto)return"auto";if(tokens>=thresholds.warn)return"warn";return"safe"}__name(currentTier,"currentTier");function extensionContextFileOwners(config,workingDir){const owners=new Map;for(const extension of config.getActiveExtensions?.()??[]){const displayName=getSanitizedExtensionDisplayName(extension);for(const contextFile of extension.contextFiles??[]){const absolutePath=path.resolve(workingDir,contextFile);const fileLabel=formatContextFileDisplayPath(absolutePath,extension.path);owners.set(absolutePath,`${t("Extension")}: ${displayName} \xB7 ${fileLabel}`)}}return owners}__name(extensionContextFileOwners,"extensionContextFileOwners");function parseMemoryFiles(memoryContent,workingDir,extensionOwners=new Map,admissionRoot=workingDir){if(!memoryContent||memoryContent.trim().length===0)return[];const results=[];const root=path.resolve(admissionRoot);const globalDir=path.resolve(Storage.getGlobalQwenDir());const memoryFilenames=new Set(getAllMemoryFilenames());const openablePath=__name(absolutePath=>isSubpath(root,absolutePath)||path.resolve(path.dirname(absolutePath))===globalDir&&memoryFilenames.has(path.basename(absolutePath))?absolutePath:void 0,"openablePath");const regex=/--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g;let match;while((match=regex.exec(memoryContent))!==null){const filePath=match[1];const content=match[2];const absolutePath=path.resolve(workingDir,filePath);const owner=extensionOwners.get(absolutePath);const openPath=openablePath(absolutePath);results.push({path:owner??formatContextFileDisplayPath(absolutePath,workingDir),tokens:estimateContextTextTokens(content),...openPath!==void 0?{absolutePath:openPath}:{}})}if(results.length===0&&memoryContent.trim().length>0){results.push({path:t("memory"),tokens:estimateContextTextTokens(memoryContent)})}return results}__name(parseMemoryFiles,"parseMemoryFiles");function unescapeXml(text){return text.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&")}__name(unescapeXml,"unescapeXml");var SKILL_LISTING_ENTRY=/<skill>\n<name>\n([\s\S]*?)\n<\/name>[\s\S]*?<\/skill>/g;function measureSkillListing(text){const byName=new Map;for(const match of text.matchAll(SKILL_LISTING_ENTRY)){const name=unescapeXml(match[1]);byName.set(name.toLowerCase(),{name,tokens:estimateContextTextTokens(match[0])})}return{tokens:estimateContextTextTokens(text),byName}}__name(measureSkillListing,"measureSkillListing");function mergeSkillListing(into,from){into.tokens+=from.tokens;for(const[name,entry]of from.byName){into.byName.set(name,entry)}}__name(mergeSkillListing,"mergeSkillListing");function measureTailSkillListings(conversation){const listing={tokens:0,byName:new Map};const billedTexts=new Set;for(const content of conversation){for(const part of content.parts??[]){const text=part.text;if(typeof text!=="string"||!isSkillListingReminder(text))continue;const measured=measureSkillListing(text);if(measured.byName.size===0)continue;mergeSkillListing(listing,measured);billedTexts.add(text)}}return{listing,billedTexts}}__name(measureTailSkillListings,"measureTailSkillListings");function measureStartupPrelude(prelude){const skillListing={tokens:0,byName:new Map};let startupContextTokens=0;for(const content of prelude){for(const part of content.parts??[]){if(typeof part.text!=="string")continue;if(isSkillListingReminder(part.text)){mergeSkillListing(skillListing,measureSkillListing(part.text))}else{startupContextTokens+=estimateContextTextTokens(part.text)}}}return{skillListing,startupContextTokens}}__name(measureStartupPrelude,"measureStartupPrelude");function estimateFunctionResponseTokens(part,imageTokenEstimate){const response=part.functionResponse;let tokens=estimateContextTextTokens(JSON.stringify({id:response.id,name:response.name,response:response.response}));const nested=response.parts;if(Array.isArray(nested)){for(const inner of nested){if(inner.inlineData||inner.fileData){tokens+=imageTokenEstimate}else if(typeof inner.text==="string"){tokens+=estimateContextTextTokens(inner.text)}}}return tokens}__name(estimateFunctionResponseTokens,"estimateFunctionResponseTokens");function consumeBilledSkillBody(part,billedSkillBodies){if(billedSkillBodies.size===0)return false;const output=part.functionResponse?.response?.output;if(typeof output!=="string")return false;if(billedSkillBodies.delete(output))return true;for(const body of billedSkillBodies){if(output.startsWith(`${body}
6
6
  `)){billedSkillBodies.delete(body);return true}}return false}__name(consumeBilledSkillBody,"consumeBilledSkillBody");function estimateConversationTokens(conversation,billing){let tokens=0;const remainingSkillBodies=new Set(billing.billedSkillBodies);for(const content of conversation){for(const part of content.parts??[]){if(typeof part.text==="string"){if(billing.billedListingTexts.has(part.text))continue;tokens+=estimateContextTextTokens(part.text)}else if(part.inlineData||part.fileData){tokens+=billing.imageTokenEstimate}else if(part.functionCall){tokens+=estimateContextTextTokens(JSON.stringify(part.functionCall))}else if(part.functionResponse){if(part.functionResponse.name===ToolNames.SKILL&&consumeBilledSkillBody(part,remainingSkillBodies)){continue}tokens+=estimateFunctionResponseTokens(part,billing.imageTokenEstimate)}}}return tokens}__name(estimateConversationTokens,"estimateConversationTokens");async function collectContextData(config,showDetails){const modelName=config.getModel()||"unknown";const contentGeneratorConfig=config.getContentGeneratorConfig();const contextWindowSize=contentGeneratorConfig.contextWindowSize??DEFAULT_TOKEN_LIMIT;const llmClient=config.getLlmClient?.();const activeChat=llmClient?.isInitialized?.()?llmClient.getChat():void 0;const apiTotalTokens=activeChat?activeChat.getLastPromptTokenCount():uiTelemetryService.getLastPromptTokenCount();const apiCachedTokens=activeChat?.getLastCachedContentTokenCount?.()??uiTelemetryService.getLastCachedContentTokenCount();const history=activeChat?.getHistoryShallow?.()??activeChat?.getHistory?.()??[];const preludeLength=getStartupContextLength(history);const prelude=measureStartupPrelude(withoutAutoMemorySnapshots(history.slice(0,preludeLength)));const conversationHistory=withoutAutoMemorySnapshots(history.slice(preludeLength));const tailSkillListings=measureTailSkillListings(conversationHistory);let conversationTokens=0;const systemPromptText=getMainSessionBaseSystemPrompt(config);const systemPromptTokens=estimateContextTextTokens(systemPromptText);const toolRegistry=config.getToolRegistry();const allTools=toolRegistry?toolRegistry.getAllTools():[];const toolDeclarations=toolRegistry?toolRegistry.getFunctionDeclarations():[];const toolsJsonStr=JSON.stringify(toolDeclarations);const allToolsTokens=estimateContextTextTokens(toolsJsonStr);const builtinTools=[];const mcpTools=[];for(const tool of allTools){if(toolRegistry?.isDeferredAndHidden(tool.name)){continue}if(isMediaPolicyToolHiddenFromModel(config,tool)){continue}const toolJsonStr=JSON.stringify(tool.schema);const tokens=estimateContextTextTokens(toolJsonStr);if(tool instanceof DiscoveredMCPTool){mcpTools.push({name:`${tool.serverName}__${tool.serverToolName||tool.name}`,tokens})}else if(tool.name!==ToolNames.SKILL){builtinTools.push({name:tool.name,tokens})}}const memoryContent=config.getUserMemory();const instructionFiles=parseMemoryFiles(memoryContent,config.getWorkingDir(),extensionContextFileOwners(config,config.getWorkingDir()),config.storage.getProjectRoot());const memoryFiles=[];const instructionFilesTokens=instructionFiles.reduce((sum,f)=>sum+f.tokens,0);const catalog=config.getAutoMemoryContext?.()??"";const snapshots=catalog?history.flatMap(content=>(content.parts??[]).filter(part=>part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true)):[];const pendingSnapshot=getAutoMemorySnapshot(history,catalog);if(pendingSnapshot)snapshots.push(pendingSnapshot);const autoMemoryTokens=estimateContextTextTokens(config.getAutoMemoryPrompt())+snapshots.reduce((sum,part)=>sum+estimateContextTextTokens(part.text??""),0);if(autoMemoryTokens>0){memoryFiles.push({path:t("auto memory"),tokens:autoMemoryTokens})}const memoryFilesTokens=memoryFiles.reduce((sum,f)=>sum+f.tokens,0);const skillTool=allTools.find(tool=>tool.name===ToolNames.SKILL);const skillToolDefinitionTokens=skillTool?estimateContextTextTokens(JSON.stringify(skillTool.schema)):0;const loadedContentNames=skillTool&&"getLoadedSkillContentNames"in skillTool?skillTool.getLoadedSkillContentNames():new Map;const bodyTokensByName=new Map;for(const[content,name]of loadedContentNames){bodyTokensByName.set(name,(bodyTokensByName.get(name)??0)+estimateContextTextTokens(content))}const loadedBodiesTokens=[...bodyTokensByName.values()].reduce((sum,tokens)=>sum+tokens,0);const skillManager=config.getSkillManager();const skillConfigs=skillManager?await skillManager.listSkills():[];const enabledSkillNames=new Set(skillConfigs.filter(skill=>config.isSkillEnabled(skill)).map(skill=>skill.name.toLowerCase()));let skillListing=prelude.skillListing;if(!activeChat){const reminder=await buildAvailableSkillsReminder(config);if(reminder){skillListing=measureSkillListing(reminder.reminder)}}mergeSkillListing(skillListing,tailSkillListings.listing);const billedSkillBodies=new Set(loadedContentNames.keys());const skills=skillConfigs.map(skill=>{const listingTokens=skillListing.byName.get(skill.name.toLowerCase())?.tokens??0;const bodyTokens=bodyTokensByName.get(skill.name);const isLoaded=bodyTokens!==void 0;return{name:skill.name,tokens:listingTokens,loaded:isLoaded,bodyTokens}});const discoveredNames=new Set(skillConfigs.map(skill=>skill.name));for(const[name,bodyTokens]of bodyTokensByName){if(!discoveredNames.has(name)){skills.push({name,tokens:skillListing.byName.get(name.toLowerCase())?.tokens??0,loaded:true,bodyTokens})}}const rowedNames=new Set(skills.map(s=>s.name.toLowerCase()));for(const[key,entry]of skillListing.byName){enabledSkillNames.add(key);if(rowedNames.has(key))continue;rowedNames.add(key);skills.push({name:entry.name,tokens:entry.tokens,loaded:false})}conversationTokens=estimateConversationTokens(conversationHistory,{imageTokenEstimate:resolveSlimmingConfig(config.getChatCompression?.()).imageTokenEstimate,billedSkillBodies,billedListingTexts:tailSkillListings.billedTexts});const skillsTokens=skillToolDefinitionTokens+skillListing.tokens+loadedBodiesTokens;const startupContextTokens=prelude.startupContextTokens;const thresholds=computeThresholds(contextWindowSize,config.getAutoCompactThreshold());const autocompactBuffer=Math.max(0,Math.round(contextWindowSize-thresholds.auto));const rawOverhead=systemPromptTokens+allToolsTokens+instructionFilesTokens+memoryFilesTokens+skillListing.tokens+loadedBodiesTokens+startupContextTokens;const rawContent=rawOverhead+conversationTokens;const hasTokenCount=apiTotalTokens>0;const isEstimated=!hasTokenCount||activeChat?.isLastPromptTokenCountEstimated()===true;const mcpToolsTotalTokens=mcpTools.reduce((sum,tool)=>sum+tool.tokens,0);let totalTokens;let displaySystemPrompt;let displayBuiltinTools;let displayMcpTools;let displayInstructionFiles;let displayMemoryFiles;let displaySkills;let displayStartupContext;let messagesTokens;let unattributedTokens=0;let freeSpace;let detailBuiltinTools;let detailMcpTools;let detailInstructionFiles;let detailMemoryFiles;let detailSkills;const clampDeficit=Math.max(0,skillToolDefinitionTokens+mcpToolsTotalTokens-allToolsTokens);const clampedMcpTools=Math.max(0,mcpToolsTotalTokens-clampDeficit);const clampedSkills=skillsTokens-Math.max(0,clampDeficit-mcpToolsTotalTokens);const clampedBuiltinTools=Math.max(0,allToolsTokens-skillToolDefinitionTokens-clampedMcpTools);const mcpDetailShare=mcpToolsTotalTokens>0?clampedMcpTools/mcpToolsTotalTokens:1;const scaleTokens=__name((items,factor)=>factor<1?items.map(item=>({...item,tokens:Math.round(item.tokens*factor)})):items,"scaleTokens");if(!hasTokenCount){totalTokens=0;displaySystemPrompt=systemPromptTokens;displaySkills=clampedSkills;displayStartupContext=startupContextTokens;displayBuiltinTools=clampedBuiltinTools;displayMcpTools=clampedMcpTools;displayInstructionFiles=instructionFilesTokens;displayMemoryFiles=memoryFilesTokens;messagesTokens=conversationTokens;freeSpace=Math.max(0,contextWindowSize-rawContent-autocompactBuffer);detailBuiltinTools=builtinTools;detailMcpTools=scaleTokens(mcpTools,mcpDetailShare);detailInstructionFiles=instructionFiles;detailMemoryFiles=memoryFiles;detailSkills=skills}else{totalTokens=apiTotalTokens;const scale=rawOverhead>totalTokens?totalTokens/rawOverhead:1;displaySystemPrompt=Math.floor(systemPromptTokens*scale);displayBuiltinTools=Math.floor(clampedBuiltinTools*scale);displayMcpTools=Math.floor(clampedMcpTools*scale);displayInstructionFiles=Math.floor(instructionFilesTokens*scale);displayMemoryFiles=Math.floor(memoryFilesTokens*scale);displaySkills=Math.floor(clampedSkills*scale);displayStartupContext=Math.floor(startupContextTokens*scale);const attributedOverhead=displaySystemPrompt+displayBuiltinTools+displayMcpTools+displayInstructionFiles+displayMemoryFiles+displaySkills+displayStartupContext;if(scale<1){messagesTokens=Math.max(0,totalTokens-attributedOverhead)}else{messagesTokens=Math.min(conversationTokens,Math.max(0,totalTokens-attributedOverhead));unattributedTokens=Math.max(0,totalTokens-attributedOverhead-messagesTokens)}freeSpace=Math.max(0,contextWindowSize-totalTokens-autocompactBuffer);detailBuiltinTools=scaleTokens(builtinTools,scale);detailMcpTools=scaleTokens(mcpTools,scale*mcpDetailShare);detailInstructionFiles=scaleTokens(instructionFiles,scale);detailMemoryFiles=scaleTokens(memoryFiles,scale);detailSkills=scale<1?skills.map(item=>({...item,tokens:Math.round(item.tokens*scale),bodyTokens:item.bodyTokens?Math.round(item.bodyTokens*scale):void 0})):skills}const tierTokens=hasTokenCount?apiTotalTokens:rawContent;const breakdown={systemPrompt:displaySystemPrompt,builtinTools:displayBuiltinTools,mcpTools:displayMcpTools,instructionFiles:displayInstructionFiles,memoryFiles:displayMemoryFiles,skills:displaySkills,startupContext:displayStartupContext,messages:messagesTokens,unattributed:unattributedTokens,cachedTokens:hasTokenCount?apiCachedTokens:0,freeSpace,autocompactBuffer,thresholds,currentTier:currentTier(tierTokens,thresholds)};return{type:"context_usage",modelName,totalTokens,contextWindowSize,breakdown,builtinTools:showDetails?detailBuiltinTools:[],mcpTools:showDetails?detailMcpTools:[],instructionFiles:showDetails?detailInstructionFiles:[],memoryFiles:showDetails?detailMemoryFiles:[],skills:showDetails?detailSkills.filter(skill=>skill.loaded||enabledSkillNames.has(skill.name.toLowerCase())):[],isEstimated,showDetails}}__name(collectContextData,"collectContextData");function fmtTokens(tokens){if(tokens>=999950){return`${(tokens/1e6).toFixed(1)}m`}if(tokens>=1e3){return`${(tokens/1e3).toFixed(1)}k`}return`${tokens}`}__name(fmtTokens,"fmtTokens");function fmtCategoryRow(label,tokens,contextWindowSize,indent=" "){const percentage=contextWindowSize>0?(tokens/contextWindowSize*100).toFixed(1):"0.0";const right=`${fmtTokens(tokens)} tokens (${percentage}%)`;const leftPart=`${indent}${label}`;const totalWidth=56;const dots=Math.max(1,totalWidth-leftPart.length-right.length);return`${leftPart}${" ".repeat(dots)}${right}`}__name(fmtCategoryRow,"fmtCategoryRow");function formatNum(n){return Math.round(n).toLocaleString("en-US")}__name(formatNum,"formatNum");function formatContextUsageText(data){const{modelName,totalTokens,contextWindowSize,breakdown,builtinTools,mcpTools,instructionFiles=[],memoryFiles,skills,isEstimated,showDetails}=data;const hasTokenCount=totalTokens>0;const memoryLabel=breakdown.instructionFiles===void 0?"Memory files":"Auto memory";const lines=[];lines.push("## Context Usage");lines.push("");if(!hasTokenCount){const includesConversation=breakdown.messages>0;lines.push(includesConversation?"*No provider usage yet. These are local estimates, including the conversation.*":"*No API response yet. Send a message to see actual usage.*");lines.push("");lines.push(includesConversation?"**Estimated usage, including the conversation**":"**Estimated pre-conversation overhead**");lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("")}else{lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("");if(isEstimated){lines.push("*Token usage is estimated until provider usage is received.*");lines.push("")}lines.push(fmtCategoryRow("Used",totalTokens,contextWindowSize));if((breakdown.cachedTokens??0)>0){lines.push(fmtCategoryRow("Cached prefix",breakdown.cachedTokens,contextWindowSize," \u2514 "))}lines.push(fmtCategoryRow("Free",breakdown.freeSpace,contextWindowSize));lines.push("");lines.push("**Compaction thresholds**");lines.push(` Effective window: ${formatNum(breakdown.thresholds.effectiveWindow)} (window \u2212 ${formatNum(contextWindowSize-breakdown.thresholds.effectiveWindow)} reserve)`);lines.push(` Warn threshold: ${formatNum(breakdown.thresholds.warn)}`);lines.push(` Auto threshold: ${formatNum(breakdown.thresholds.auto)}`);lines.push(` Hard threshold: ${formatNum(breakdown.thresholds.hard)}`);lines.push(` Current tier: ${breakdown.currentTier}`);lines.push("");lines.push("**Usage by category**")}lines.push(fmtCategoryRow("System prompt",breakdown.systemPrompt,contextWindowSize));lines.push(fmtCategoryRow("Built-in tools",breakdown.builtinTools,contextWindowSize));if(breakdown.mcpTools>0){lines.push(fmtCategoryRow("MCP tools",breakdown.mcpTools,contextWindowSize))}if(breakdown.instructionFiles!==void 0){lines.push(fmtCategoryRow("Instruction files",breakdown.instructionFiles,contextWindowSize))}lines.push(fmtCategoryRow(memoryLabel,breakdown.memoryFiles,contextWindowSize));lines.push(fmtCategoryRow("Skills",breakdown.skills,contextWindowSize));if((breakdown.startupContext??0)>0){lines.push(fmtCategoryRow("Startup context",breakdown.startupContext,contextWindowSize))}if(hasTokenCount||breakdown.messages>0){lines.push(fmtCategoryRow("Messages",breakdown.messages,contextWindowSize));if((breakdown.unattributed??0)>0){lines.push(fmtCategoryRow("Unattributed",breakdown.unattributed,contextWindowSize))}}if(showDetails){const sortedBuiltin=[...builtinTools].sort((a,b)=>b.tokens-a.tokens);const sortedMcp=[...mcpTools].sort((a,b)=>b.tokens-a.tokens);const sortedMemory=[...memoryFiles].sort((a,b)=>b.tokens-a.tokens);const sortedSkills=[...skills].sort((a,b)=>{if(!a.loaded!==!b.loaded)return a.loaded?-1:1;return b.tokens+(b.bodyTokens??0)-(a.tokens+(a.bodyTokens??0))});if(sortedBuiltin.length>0){lines.push("");lines.push("**Built-in tools**");for(const tool of sortedBuiltin){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(sortedMcp.length>0){lines.push("");lines.push("**MCP tools**");for(const tool of sortedMcp){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(instructionFiles.length>0){lines.push("","**Instruction files**");for(const file of[...instructionFiles].sort((a,b)=>b.tokens-a.tokens)){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedMemory.length>0){lines.push("");lines.push("**"+memoryLabel+"**");for(const file of sortedMemory){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedSkills.length>0){lines.push("");lines.push("**Skills**");for(const skill of sortedSkills){lines.push(fmtCategoryRow(skill.name,skill.tokens,contextWindowSize," \u2514 "));if(skill.loaded&&skill.bodyTokens&&skill.bodyTokens>0){lines.push(fmtCategoryRow("body loaded",skill.bodyTokens,contextWindowSize," \u2514 "))}}}}else{lines.push("");lines.push("*Run /context detail for per-item breakdown.*")}return lines.join("\n")}__name(formatContextUsageText,"formatContextUsageText");var contextCommand={name:"context",get description(){return t('Show context window usage breakdown. Use "/context detail" for per-item breakdown.')},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,args)=>{const normalizedArgs=args?.trim().toLowerCase();const showDetails=normalizedArgs==="detail"||normalizedArgs==="-d";const executionMode=context.executionMode??"interactive";const{config}=context.services;if(!config){if(executionMode==="interactive"){context.ui.addItem({type:"error",text:t("Config not loaded.")},Date.now());return}return{type:"message",messageType:"error",content:t("Config not loaded.")}}const contextUsageItem=await collectContextData(config,showDetails);if(executionMode==="interactive"){context.ui.addItem(contextUsageItem,Date.now());return}return{type:"message",messageType:"info",content:formatContextUsageText(contextUsageItem)}},"action"),subCommands:[{name:"detail",get description(){return t("Show per-item context usage breakdown.")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{await contextCommand.action(context,"detail")},"action")}]};export{EXTENSION_CONTEXT_BUDGET,parseExtensionRef,buildExtensionRef,matchExtensionByRef,sanitizeDisplayText,getSanitizedExtensionDisplayName,buildExtensionMentionContext,collectContextData,formatContextUsageText,contextCommand};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{HistoryReplayer,observeAcpToolResultProjection}from"./chunk-26ISBUM7.js";import{JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,truncateJsonStringPayload}from"./chunk-WQUA4G2X.js";import{isA2uiToolMeta}from"./chunk-CAPG7UVH.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-Z5XENA4A.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-HW6AWS7W.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var MAX_REMEMBER_ERROR_DETAILS_CHARS=1e3;var MAX_REMEMBER_ERROR_CAUSE_DEPTH=50;var REMEMBER_ERROR_FORMAT_RE=new RegExp("[\\p{Cf}]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_SPACE_SEPARATOR_RE=/[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE=new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE=new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])","giu");var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)","giu");var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+","gu");var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE=new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+","gu");var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","giu");var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","gu");var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE=new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@","giu");var REMEMBER_ERROR_CONTROL_RE=/[\x00-\x1f\x7f-\x9f]/g;var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES=new Set(["managed_memory_unavailable"]);function createWorkspaceMemoryExtractionErrorLogger(logger){return(target,err)=>{logger.warn(`Failed to extract workspace memory error ${target}:`,{extractionError:err instanceof Error?err.message:String(err)})}}__name(createWorkspaceMemoryExtractionErrorLogger,"createWorkspaceMemoryExtractionErrorLogger");function reportRememberErrorExtractionFailure(onExtractionError,target,err){try{onExtractionError?.(target,err)}catch{}}__name(reportRememberErrorExtractionFailure,"reportRememberErrorExtractionFailure");function errorCodeFromRecord(record){if(typeof record["code"]==="string")return record["code"];const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;if(typeof dataRecord["errorKind"]==="string"){return dataRecord["errorKind"]}if(typeof dataRecord["code"]==="string")return dataRecord["code"]}return void 0}__name(errorCodeFromRecord,"errorCodeFromRecord");function rawRememberErrorCode(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);const record=err;const direct=errorCodeFromRecord(record);if(direct)return direct;const cause=record["cause"];if(cause!=null){return rawRememberErrorCode(cause,seen,depth+1)}return void 0}__name(rawRememberErrorCode,"rawRememberErrorCode");function extractRememberErrorCode(err,fallback="remember_failed"){return rawRememberErrorCode(err,new WeakSet,0)??fallback}__name(extractRememberErrorCode,"extractRememberErrorCode");function workspaceMemoryFailureCode(err,fallback="remember_failed",onExtractionError){try{return extractRememberErrorCode(err,fallback)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"code",extractionErr);return fallback}}__name(workspaceMemoryFailureCode,"workspaceMemoryFailureCode");function detailFromRecord(record,seen,depth){const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;const details=dataRecord["details"];if(typeof details==="string"&&details.length>0)return details;const message2=dataRecord["message"];if(typeof message2==="string"&&message2.length>0)return message2}const message=record["message"];if(typeof message==="string"&&message.length>0)return message;if(typeof data==="string"&&data.length>0)return data;const cause=record["cause"];if(cause!=null){return rawRememberErrorDetails(cause,seen,depth+1)}return void 0}__name(detailFromRecord,"detailFromRecord");function rawRememberErrorDetails(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(typeof err==="string"&&err.length>0)return err;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);return detailFromRecord(err,seen,depth)}__name(rawRememberErrorDetails,"rawRememberErrorDetails");function replaceControlChars(details){return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE," ")}__name(replaceControlChars,"replaceControlChars");function replaceStackControlChars(stack){return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE,char=>char==="\n"||char==="\r"||char===" "?char:" ")}__name(replaceStackControlChars,"replaceStackControlChars");function collapseCredentialSeparators(text){return text.replace(REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,(_match,scheme,userinfo)=>`${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}@`).replace(REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,(_match,scheme,token)=>`${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`)}__name(collapseCredentialSeparators,"collapseCredentialSeparators");function collapseCredentialSeparatorsByStackLine(stack){return stack.split(/(\r\n|\n|\r)/).map(part=>part==="\r\n"||part==="\n"||part==="\r"?part:collapseCredentialSeparators(part)).join("")}__name(collapseCredentialSeparatorsByStackLine,"collapseCredentialSeparatorsByStackLine");function isHighSurrogate(codeUnit){return codeUnit>=55296&&codeUnit<=56319}__name(isHighSurrogate,"isHighSurrogate");function isLowSurrogate(codeUnit){return codeUnit>=56320&&codeUnit<=57343}__name(isLowSurrogate,"isLowSurrogate");function truncateBeforeDanglingSurrogate(details,cutPoint){const beforeCut=details.charCodeAt(cutPoint-1);const atCut=details.charCodeAt(cutPoint);if(isHighSurrogate(beforeCut)&&isLowSurrogate(atCut)){return cutPoint-1}return cutPoint}__name(truncateBeforeDanglingSurrogate,"truncateBeforeDanglingSurrogate");function capRememberErrorText(redacted){if(redacted.length<=MAX_REMEMBER_ERROR_DETAILS_CHARS)return redacted;const truncationSuffix="... [truncated]";const cutPoint=truncateBeforeDanglingSurrogate(redacted,MAX_REMEMBER_ERROR_DETAILS_CHARS-truncationSuffix.length);return`${redacted.slice(0,cutPoint)}${truncationSuffix}`}__name(capRememberErrorText,"capRememberErrorText");function redactAndCapRememberErrorText(normalized){const redacted=redactLogCredentials(normalized).trim();if(!redacted)return void 0;return capRememberErrorText(redacted)}__name(redactAndCapRememberErrorText,"redactAndCapRememberErrorText");function sanitizeRememberErrorDetails(details){return redactAndCapRememberErrorText(replaceControlChars(collapseCredentialSeparators(details)))}__name(sanitizeRememberErrorDetails,"sanitizeRememberErrorDetails");function sanitizeRememberErrorStack(stack){return redactAndCapRememberErrorText(replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack)))}__name(sanitizeRememberErrorStack,"sanitizeRememberErrorStack");function extractRememberErrorDetails(err){const raw=rawRememberErrorDetails(err,new WeakSet,0);if(!raw)return void 0;return sanitizeRememberErrorDetails(raw)}__name(extractRememberErrorDetails,"extractRememberErrorDetails");function extractRememberErrorStack(err){if(!(err instanceof Error)||!err.stack)return void 0;return sanitizeRememberErrorStack(err.stack)}__name(extractRememberErrorStack,"extractRememberErrorStack");function shouldSuppressRememberErrorDetails(code){return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code)}__name(shouldSuppressRememberErrorDetails,"shouldSuppressRememberErrorDetails");function workspaceMemoryFailureDiagnostics(err,onExtractionError){let details;let stack;try{details=extractRememberErrorDetails(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"details",extractionErr);details=void 0}try{stack=extractRememberErrorStack(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"stack",extractionErr);stack=void 0}return{...details?{details}:{},debugDetails:details??"<details unavailable>",...stack?{stack}:{}}}__name(workspaceMemoryFailureDiagnostics,"workspaceMemoryFailureDiagnostics");init_esbuild_shims();var MAX_REMEMBER_CONTENT_BYTES=64*1024;init_esbuild_shims();function formatWorkspaceMemoryForgetSummary(removedEntryCount){return removedEntryCount>0?`Forgot ${removedEntryCount} memory entr${removedEntryCount===1?"y":"ies"}.`:"No managed auto-memory entries matched."}__name(formatWorkspaceMemoryForgetSummary,"formatWorkspaceMemoryForgetSummary");function formatWorkspaceMemoryDreamSummary(touchedTopicCount){return touchedTopicCount>0?"Managed auto-memory dream completed.":"No managed auto-memory topics changed."}__name(formatWorkspaceMemoryDreamSummary,"formatWorkspaceMemoryDreamSummary");init_esbuild_shims();var VALID_SERVER_NAME=/^[A-Za-z0-9_-]+$/;var RESERVED_SERVER_NAMES=new Set(["__proto__","constructor","prototype"]);function isValidServerName(name){return typeof name==="string"&&name.length>0&&name.length<=256&&VALID_SERVER_NAME.test(name)&&!RESERVED_SERVER_NAMES.has(name)}__name(isValidServerName,"isValidServerName");init_esbuild_shims();var GENERATION_MAX_PROMPT_BYTES=32*1024;var GENERATION_TIMEOUT_MS=6e4;async function executeGeneration(config,requestId,prompt,signal,emit){const fastModel=config.getFastModel();const mainModel=config.getModel();const client=config.getBaseLlmClient();let modelSource=fastModel?"fast":"main";let resolved;if(fastModel){try{resolved=await client.resolveForModel(fastModel,{failClosed:true})}catch{modelSource="main"}}resolved??=await client.resolveForModel(mainModel,{failClosed:true});const{contentGenerator,model}=resolved;await emit({type:"started",model,modelSource});const stream=await contentGenerator.generateContentStream({model,contents:[{role:"user",parts:[{text:prompt}]}],config:{abortSignal:signal,tools:[],thinkingConfig:{thinkingBudget:0,includeThoughts:false},temperature:.2}},`generation:${requestId}`);let seq=0;let thinkingEmitted=false;let usage;for await(const chunk of stream){if(!thinkingEmitted&&chunk.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.thought===true))){thinkingEmitted=true;await emit({type:"thinking"})}const text=getResponseText(chunk)??"";if(text){await emit({type:"delta",seq:seq++,text})}if(chunk.usageMetadata)usage=chunk.usageMetadata}return{model,modelSource,...usage?.promptTokenCount!==void 0?{inputTokens:usage.promptTokenCount}:{},...usage?.candidatesTokenCount!==void 0?{outputTokens:usage.candidatesTokenCount}:{}}}__name(executeGeneration,"executeGeneration");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";init_esbuild_shims();import{Buffer}from"node:buffer";import{isDeepStrictEqual}from"node:util";var ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for ACP transport ...]\n";var EMPTY_CONTENT_ARRAY_JSON_BYTES=Buffer.byteLength("[]","utf8");var EMPTY_TEXT_BLOCK_JSON_BYTES=Buffer.byteLength(JSON.stringify(createTextBlock("")),"utf8");var JSON_ARRAY_SEPARATOR_BYTES=1;var TRUNCATION_MARKER_PAYLOAD_BYTES=jsonStringJsonByteLength(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)-JSON_STRING_DELIMITER_BYTES;var MAX_CANONICAL_TEXT_BLOCKS=Math.floor((ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-EMPTY_CONTENT_ARRAY_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES)/(EMPTY_TEXT_BLOCK_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES));function createTextBlock(text){return{type:"content",content:{type:"text",text}}}__name(createTextBlock,"createTextBlock");function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord,"isObjectRecord");function hasExactKeys(value,first,second){const keys=Object.keys(value);return keys.length===2&&Object.hasOwn(value,first)&&Object.hasOwn(value,second)}__name(hasExactKeys,"hasExactKeys");function canonicalTextBlocks(value){if(!Array.isArray(value))return void 0;for(const block of value){if(!isObjectRecord(block)||!hasExactKeys(block,"type","content")||block["type"]!=="content"||!isObjectRecord(block["content"])||!hasExactKeys(block["content"],"type","text")||block["content"]["type"]!=="text"||typeof block["content"]["text"]!=="string"){return void 0}}return value}__name(canonicalTextBlocks,"canonicalTextBlocks");function contentSkeletonBytes(blockCount){if(blockCount===0)return EMPTY_CONTENT_ARRAY_JSON_BYTES;return EMPTY_CONTENT_ARRAY_JSON_BYTES+blockCount*EMPTY_TEXT_BLOCK_JSON_BYTES+(blockCount-1)*JSON_ARRAY_SEPARATOR_BYTES}__name(contentSkeletonBytes,"contentSkeletonBytes");function fallbackContent(){return[createTextBlock(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)]}__name(fallbackContent,"fallbackContent");function jsonByteLength(value){return Buffer.byteLength(JSON.stringify(value),"utf8")}__name(jsonByteLength,"jsonByteLength");function allocatePayloadBudgets(payloadBytes,availableBytes){const base=payloadBytes.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));let remaining=availableBytes-base.reduce((sum,bytes)=>sum+bytes,0);if(remaining<0)return void 0;const capacities=payloadBytes.map((bytes,index)=>({index,capacity:bytes-base[index]}));const sorted=capacities.filter(({capacity})=>capacity>0).sort((left,right)=>left.capacity===right.capacity?left.index-right.index:left.capacity-right.capacity);let active=sorted.length;let position=0;let level=0;let remainder=0;while(position<sorted.length&&active>0&&remaining>0){const nextLevel=sorted[position].capacity;const cost=(nextLevel-level)*active;if(cost>remaining){level+=Math.floor(remaining/active);remainder=remaining%active;remaining=0;break}level=nextLevel;remaining-=cost;while(position<sorted.length&&sorted[position].capacity===nextLevel){position++;active--}}const allocations=base.map((bytes,index)=>bytes+Math.min(capacities[index].capacity,level));if(remainder>0){for(const{index,capacity}of capacities){if(remainder===0)break;if(capacity>level){allocations[index]++;remainder--}}}return allocations}__name(allocatePayloadBudgets,"allocatePayloadBudgets");function projectContent(original){if(original.length>MAX_CANONICAL_TEXT_BLOCKS)return fallbackContent();const skeletonBytes=contentSkeletonBytes(original.length);const availablePayloadBytes=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-skeletonBytes;let remainingPayloadBytes=availablePayloadBytes;let needsProjection=false;for(const block of original){const payloadBytes2=jsonStringPayloadByteLength(block.content.text,remainingPayloadBytes);if(payloadBytes2>remainingPayloadBytes){needsProjection=true;break}remainingPayloadBytes-=payloadBytes2}if(!needsProjection)return original;const baseScans=original.map(block=>jsonStringPayloadByteLength(block.content.text,TRUNCATION_MARKER_PAYLOAD_BYTES));const basePayloadBytes=baseScans.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));const baseTotal=basePayloadBytes.reduce((sum,bytes)=>sum+bytes,0);if(baseTotal>availablePayloadBytes)return fallbackContent();const payloadBytes=original.map((block,index)=>{if(baseScans[index]<=TRUNCATION_MARKER_PAYLOAD_BYTES){return baseScans[index]}const maximumAllocation=availablePayloadBytes-baseTotal+basePayloadBytes[index];const bytes=jsonStringPayloadByteLength(block.content.text,maximumAllocation);return bytes<=maximumAllocation?bytes:maximumAllocation+1});const allocations=allocatePayloadBudgets(payloadBytes,availablePayloadBytes);if(!allocations)return fallbackContent();const projected=original.map((block,index)=>{if(payloadBytes[index]<=allocations[index])return block;return createTextBlock(truncateJsonStringPayload(block.content.text,payloadBytes[index],allocations[index],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))});return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:fallbackContent()}__name(projectContent,"projectContent");function projectRawOutput(value){const payloadBudget=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-JSON_STRING_DELIMITER_BYTES;const payloadBytes=jsonStringPayloadByteLength(value,payloadBudget);if(payloadBytes<=payloadBudget)return value;const projected=truncateJsonStringPayload(value,payloadBytes,payloadBudget,ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER);return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER}__name(projectRawOutput,"projectRawOutput");function a2uiMeta(meta){if(!meta)return void 0;const toolName=typeof meta["toolName"]==="string"?meta["toolName"]:void 0;const serverId=typeof meta["serverId"]==="string"?meta["serverId"]:void 0;return toolName===void 0&&serverId===void 0?void 0:{...toolName===void 0?{}:{toolName},...serverId===void 0?{}:{serverId}}}__name(a2uiMeta,"a2uiMeta");function projectAcpToolResultUpdate(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return update;const meta=isObjectRecord(record["_meta"])?record["_meta"]:void 0;if(isA2uiToolMeta(a2uiMeta(meta)))return update;const content=canonicalTextBlocks(record["content"]);const rawOutput=record["rawOutput"];if(content?.length===1&&typeof rawOutput==="string"&&rawOutput===content[0].content.text){const projectedContent2=projectContent(content);if(projectedContent2===content)return update;const projectedText=projectedContent2[0].content.text;return{...record,content:projectedContent2,rawOutput:projectedText}}const projectedContent=content?projectContent(content):void 0;let projectedRawOutput=typeof rawOutput==="string"?projectRawOutput(rawOutput):void 0;if(isShellResultDisplay(rawOutput)){const structured=mapShellResultText(rawOutput,text=>text);projectedRawOutput=isDeepStrictEqual(structured,rawOutput)?rawOutput:structured;if(Buffer.byteLength(JSON.stringify(structured),"utf8")>ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET){const payloadBytes=[];const skeleton=mapShellResultText(structured,text=>{payloadBytes.push(jsonStringPayloadByteLength(text));return""});const budgets=allocatePayloadBudgets(payloadBytes,ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-Buffer.byteLength(JSON.stringify(skeleton),"utf8"));let index=0;projectedRawOutput=mapShellResultText(structured,text=>truncateJsonStringPayload(text,jsonStringPayloadByteLength(text),budgets[index++],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))}}const contentChanged=projectedContent!==void 0&&projectedContent!==content;const rawOutputChanged=projectedRawOutput!==void 0&&projectedRawOutput!==rawOutput;if(!contentChanged&&!rawOutputChanged)return update;return{...record,...contentChanged?{content:projectedContent}:{},...rawOutputChanged?{rawOutput:projectedRawOutput}:{}}}__name(projectAcpToolResultUpdate,"projectAcpToolResultUpdate");var HistoryReplayLimitError=class extends Error{constructor(sessionId,reason,observed,limit){super(`Transcript replay for session ${sessionId} exceeds the ${reason} limit (${observed}, max ${limit})`);this.sessionId=sessionId;this.reason=reason;this.observed=observed;this.limit=limit;this.name="HistoryReplayLimitError"}static{__name(this,"HistoryReplayLimitError")}};function createReplayCumulativeUsage(){return{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}}__name(createReplayCumulativeUsage,"createReplayCumulativeUsage");function copyCumulativeUsage(target,source){target.promptTokens=source.promptTokens;target.cachedTokens=source.cachedTokens;target.candidateTokens=source.candidateTokens;target.apiTimeMs=source.apiTimeMs}__name(copyCumulativeUsage,"copyCumulativeUsage");function isObjectRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord2,"isObjectRecord");function isCumulativeUsage(value){if(!isObjectRecord2(value))return false;return typeof value["promptTokens"]==="number"&&Number.isFinite(value["promptTokens"])&&typeof value["cachedTokens"]==="number"&&Number.isFinite(value["cachedTokens"])&&typeof value["candidateTokens"]==="number"&&Number.isFinite(value["candidateTokens"])&&typeof value["apiTimeMs"]==="number"&&Number.isFinite(value["apiTimeMs"])}__name(isCumulativeUsage,"isCumulativeUsage");function isPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&(value["timestamp"]===void 0||typeof value["timestamp"]==="string")&&typeof value["recordId"]==="string"}__name(isPendingReplayToolCall,"isPendingReplayToolCall");function isCurrentPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&typeof value["sourceRecordId"]==="string"&&(value["sourceTimestamp"]===void 0||typeof value["sourceTimestamp"]==="string")}__name(isCurrentPendingReplayToolCall,"isCurrentPendingReplayToolCall");function parseTranscriptReplayState(replay,logger){if(!isObjectRecord2(replay)){return{pendingToolCalls:[],cumulativeUsage:createReplayCumulativeUsage()}}if("v"in replay&&replay["v"]!==1){throw new TypeError("Unsupported transcript replay state version.")}const rawPending=replay["pendingToolCalls"];const pendingToolCalls=Array.isArray(rawPending)?rawPending.flatMap(pending=>{if(isPendingReplayToolCall(pending))return[pending];if(isCurrentPendingReplayToolCall(pending)){return[{callId:pending.callId,toolName:pending.toolName,...pending.resolvedToolName?{resolvedToolName:pending.resolvedToolName}:{},recordId:pending.sourceRecordId,...pending.sourceTimestamp?{timestamp:pending.sourceTimestamp}:{},...pending.rawCallId?{rawCallId:pending.rawCallId}:{},...pending.timingMatched?{timingMatched:true}:{}}]}return[]}):[];if(logger&&Array.isArray(rawPending)&&pendingToolCalls.length!==rawPending.length){const dropped=rawPending.length-pendingToolCalls.length;logger.warn(`[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`)}const cumulativeUsage=isCumulativeUsage(replay["cumulativeUsage"])?{...replay["cumulativeUsage"]}:createReplayCumulativeUsage();const rawGoalState=replay["goalState"];const goalState=rawGoalState===void 0?void 0:parseGoalSnapshotV2(rawGoalState);if(logger&&rawGoalState!==void 0&&!goalState){logger.warn("[transcript] replay state dropped a malformed Goal state")}const rawGoalCause=replay["goalCause"];const goalCause=rawGoalCause===void 0?void 0:parseGoalStateCause(rawGoalCause);if(logger&&rawGoalCause!==void 0&&!goalCause){logger.warn("[transcript] replay state dropped a malformed Goal cause")}return{pendingToolCalls,cumulativeUsage,...goalState?{goalState}:{},...goalCause?{goalCause}:{}}}__name(parseTranscriptReplayState,"parseTranscriptReplayState");function blankReplayedMcpAppHtml(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return void 0;const rawOutput=record["rawOutput"];if(!isObjectRecord2(rawOutput)||rawOutput["type"]!=="mcp_app"||typeof rawOutput["html"]!=="string"||rawOutput["html"]===""){return void 0}const blanked={...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}};if(Buffer2.byteLength(JSON.stringify(blanked),"utf8")>=Buffer2.byteLength(JSON.stringify(record),"utf8")){return void 0}return blanked}__name(blankReplayedMcpAppHtml,"blankReplayedMcpAppHtml");function degradeReplayEnvelopeAppHtml(envelope,maxBytes){let pageBytes=Buffer2.byteLength(JSON.stringify(envelope),"utf8");for(let i=0;i<envelope.updates.length&&pageBytes>maxBytes;i++){const update=envelope.updates[i];const blanked=blankReplayedMcpAppHtml(update);if(blanked===void 0)continue;pageBytes+=Buffer2.byteLength(JSON.stringify(blanked),"utf8")-Buffer2.byteLength(JSON.stringify(update),"utf8");envelope.updates[i]=blanked}}__name(degradeReplayEnvelopeAppHtml,"degradeReplayEnvelopeAppHtml");function replayContext(sessionId,updates,cumulativeUsage,config,limits){let activeRecordId=null;let serializedUpdateBytes=2;return{sessionId,sendUpdate:__name(async update=>{const projectedUpdate=projectAcpToolResultUpdate(update);const updateWithRecordId=(()=>{if(activeRecordId===null)return projectedUpdate;const record=projectedUpdate;const meta=isObjectRecord2(record["_meta"])?record["_meta"]:{};return{...record,_meta:{...meta,"qwen.session.recordId":activeRecordId}}})();let deliveredUpdate=liftSessionUpdateTimestamp(updateWithRecordId);observeAcpToolResultProjection(update,projectedUpdate,sessionId,deliveredUpdate);if(limits){const updateCount=updates.length+1;if(updateCount>limits.maxUpdates){throw new HistoryReplayLimitError(sessionId,"updates",updateCount,limits.maxUpdates)}let updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(deliveredUpdate),"utf8");if(serializedUpdateBytes+updateBytes>limits.maxBytes){for(let i=0;i<updates.length&&serializedUpdateBytes+updateBytes>limits.maxBytes;i++){const blanked=blankReplayedMcpAppHtml(updates[i]);if(blanked===void 0)continue;serializedUpdateBytes-=Buffer2.byteLength(JSON.stringify(updates[i]),"utf8")-Buffer2.byteLength(JSON.stringify(blanked),"utf8");updates[i]=blanked}if(serializedUpdateBytes+updateBytes>limits.maxBytes){const blanked=blankReplayedMcpAppHtml(deliveredUpdate);if(blanked!==void 0){deliveredUpdate=blanked;updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(blanked),"utf8")}}}serializedUpdateBytes+=updateBytes;if(serializedUpdateBytes>limits.maxBytes){throw new HistoryReplayLimitError(sessionId,"bytes",serializedUpdateBytes,limits.maxBytes)}}updates.push(deliveredUpdate)},"sendUpdate"),setActiveRecordId:__name(recordId=>{activeRecordId=recordId},"setActiveRecordId"),cumulativeUsage,...config?{config}:{}}}__name(replayContext,"replayContext");async function collectHistoryReplayUpdates({sessionId,config,records,gaps,cumulativeUsage,logger,replayState,goalBootstrap,limits,suppressRestoreAskUserQuestion,finalizeDangling,branchPointsByAssistantUuid}){const updates=[];let replayError;try{const initial=parseTranscriptReplayState(replayState,logger);let skipFinalizeCallIds;if(suppressRestoreAskUserQuestion!==true&&config?.getRestoreAskUserQuestion?.()===true){const replayClient=config.getLlmClient?.();const lastHistoryContent=replayClient?.isInitialized?.()===true?replayClient.getChat?.()?.peekLastHistoryEntry?.()??lastHistoryContentFromRecords(records):lastHistoryContentFromRecords(records);skipFinalizeCallIds=restorableAskUserQuestionCallIds(lastHistoryContent)}await new HistoryReplayer(replayContext(sessionId,updates,cumulativeUsage,config,limits)).replay(records,gaps,{...initial.goalState?{initialGoalState:initial.goalState}:{},...initial.goalCause?{initialGoalCause:initial.goalCause}:{},...goalBootstrap?{goalBootstrap}:{},...skipFinalizeCallIds?{skipFinalizeCallIds}:{},...finalizeDangling===void 0?{}:{finalizeDangling}})}catch(error){if(error instanceof HistoryReplayLimitError)throw error;replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error)}if(branchPointsByAssistantUuid){stampBranchPoints(updates,branchPointsByAssistantUuid)}return replayError===void 0?{updates}:{updates,replayError}}__name(collectHistoryReplayUpdates,"collectHistoryReplayUpdates");function liftSessionUpdateTimestamp(update){const record=update;const meta=record["_meta"];const timestamp=isObjectRecord2(meta)?meta["timestamp"]:void 0;return typeof timestamp==="number"||typeof timestamp==="string"?{...record,timestamp}:update}__name(liftSessionUpdateTimestamp,"liftSessionUpdateTimestamp");function readTranscriptSourceRecordIds(update){const value=update;const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;const sourceRecordIds=transcript?.["sourceRecordIds"];if(!Array.isArray(sourceRecordIds))return void 0;return sourceRecordIds.filter(id=>typeof id==="string")}__name(readTranscriptSourceRecordIds,"readTranscriptSourceRecordIds");function stampBranchPoints(updates,branchPoints){const lastChunkIndexByRecordId=new Map;updates.forEach((update,index)=>{if(update.sessionUpdate!=="agent_message_chunk")return;const text=update.content?.text;if(typeof text!=="string"||text.length===0)return;for(const recordId of readTranscriptSourceRecordIds(update)??[]){if(Object.hasOwn(branchPoints,recordId)){lastChunkIndexByRecordId.set(recordId,index)}}});const decoratedIndexes=new Set;for(const[recordId,index]of lastChunkIndexByRecordId){if(decoratedIndexes.has(index))continue;decoratedIndexes.add(index);const value=updates[index];const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;value["_meta"]={...meta,qwenTranscript:{...transcript,branchRecordId:branchPoints[recordId]}}}}__name(stampBranchPoints,"stampBranchPoints");async function replayTranscriptRecordPage({sessionId,page,config,encodeCursor,logger,finalizeDangling=true}){const state=parseTranscriptReplayState(page.replay,logger);const updates=[];const replayer=new HistoryReplayer(replayContext(sessionId,updates,state.cumulativeUsage,config));let replayState;let replayError;try{const replayPageState=await replayer.replayPage(page.records,{pendingToolCalls:page.direction==="backward"?[]:state.pendingToolCalls,finalizeDangling:finalizeDangling&&(page.direction==="backward"||!page.hasMore),gaps:page.gaps,includeTiming:true,...state.goalState?{goalState:state.goalState}:{},...state.goalCause?{goalCause:state.goalCause}:{}});replayState=replayPageState.replay}catch(error){logger?.warn("[historyReplay] Paged history replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);replayState=replayer.getReplayState();replayError="Replay conversion failed for this page"}if(page.branchPointsByAssistantUuid){stampBranchPoints(updates,page.branchPointsByAssistantUuid)}const nextCursor=page.nextCursorState&&replayError===void 0?encodeCursor({...page.nextCursorState,...page.direction==="backward"?{}:{replay:replayState}}):void 0;return{updates,...nextCursor?{nextCursor}:{},hasMore:replayError===void 0&&page.hasMore,startTime:page.startTime,lastUpdated:page.lastUpdated,...replayError?{partial:true,replayError}:{}}}__name(replayTranscriptRecordPage,"replayTranscriptRecordPage");export{createWorkspaceMemoryExtractionErrorLogger,extractRememberErrorCode,workspaceMemoryFailureCode,shouldSuppressRememberErrorDetails,workspaceMemoryFailureDiagnostics,MAX_REMEMBER_CONTENT_BYTES,formatWorkspaceMemoryForgetSummary,formatWorkspaceMemoryDreamSummary,isValidServerName,GENERATION_MAX_PROMPT_BYTES,GENERATION_TIMEOUT_MS,executeGeneration,projectAcpToolResultUpdate,HistoryReplayLimitError,createReplayCumulativeUsage,copyCumulativeUsage,degradeReplayEnvelopeAppHtml,collectHistoryReplayUpdates,replayTranscriptRecordPage};
3
+ import{HistoryReplayer,observeAcpToolResultProjection}from"./chunk-K7GN4CMV.js";import{JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,truncateJsonStringPayload}from"./chunk-WQUA4G2X.js";import{isA2uiToolMeta}from"./chunk-HVP4UF2Q.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-T3CQ72HC.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-HW6AWS7W.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var MAX_REMEMBER_ERROR_DETAILS_CHARS=1e3;var MAX_REMEMBER_ERROR_CAUSE_DEPTH=50;var REMEMBER_ERROR_FORMAT_RE=new RegExp("[\\p{Cf}]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_SPACE_SEPARATOR_RE=/[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE=new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE=new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])","giu");var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)","giu");var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+","gu");var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE=new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+","gu");var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","giu");var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","gu");var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE=new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@","giu");var REMEMBER_ERROR_CONTROL_RE=/[\x00-\x1f\x7f-\x9f]/g;var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES=new Set(["managed_memory_unavailable"]);function createWorkspaceMemoryExtractionErrorLogger(logger){return(target,err)=>{logger.warn(`Failed to extract workspace memory error ${target}:`,{extractionError:err instanceof Error?err.message:String(err)})}}__name(createWorkspaceMemoryExtractionErrorLogger,"createWorkspaceMemoryExtractionErrorLogger");function reportRememberErrorExtractionFailure(onExtractionError,target,err){try{onExtractionError?.(target,err)}catch{}}__name(reportRememberErrorExtractionFailure,"reportRememberErrorExtractionFailure");function errorCodeFromRecord(record){if(typeof record["code"]==="string")return record["code"];const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;if(typeof dataRecord["errorKind"]==="string"){return dataRecord["errorKind"]}if(typeof dataRecord["code"]==="string")return dataRecord["code"]}return void 0}__name(errorCodeFromRecord,"errorCodeFromRecord");function rawRememberErrorCode(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);const record=err;const direct=errorCodeFromRecord(record);if(direct)return direct;const cause=record["cause"];if(cause!=null){return rawRememberErrorCode(cause,seen,depth+1)}return void 0}__name(rawRememberErrorCode,"rawRememberErrorCode");function extractRememberErrorCode(err,fallback="remember_failed"){return rawRememberErrorCode(err,new WeakSet,0)??fallback}__name(extractRememberErrorCode,"extractRememberErrorCode");function workspaceMemoryFailureCode(err,fallback="remember_failed",onExtractionError){try{return extractRememberErrorCode(err,fallback)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"code",extractionErr);return fallback}}__name(workspaceMemoryFailureCode,"workspaceMemoryFailureCode");function detailFromRecord(record,seen,depth){const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;const details=dataRecord["details"];if(typeof details==="string"&&details.length>0)return details;const message2=dataRecord["message"];if(typeof message2==="string"&&message2.length>0)return message2}const message=record["message"];if(typeof message==="string"&&message.length>0)return message;if(typeof data==="string"&&data.length>0)return data;const cause=record["cause"];if(cause!=null){return rawRememberErrorDetails(cause,seen,depth+1)}return void 0}__name(detailFromRecord,"detailFromRecord");function rawRememberErrorDetails(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(typeof err==="string"&&err.length>0)return err;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);return detailFromRecord(err,seen,depth)}__name(rawRememberErrorDetails,"rawRememberErrorDetails");function replaceControlChars(details){return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE," ")}__name(replaceControlChars,"replaceControlChars");function replaceStackControlChars(stack){return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE,char=>char==="\n"||char==="\r"||char===" "?char:" ")}__name(replaceStackControlChars,"replaceStackControlChars");function collapseCredentialSeparators(text){return text.replace(REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,(_match,scheme,userinfo)=>`${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}@`).replace(REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,(_match,scheme,token)=>`${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`)}__name(collapseCredentialSeparators,"collapseCredentialSeparators");function collapseCredentialSeparatorsByStackLine(stack){return stack.split(/(\r\n|\n|\r)/).map(part=>part==="\r\n"||part==="\n"||part==="\r"?part:collapseCredentialSeparators(part)).join("")}__name(collapseCredentialSeparatorsByStackLine,"collapseCredentialSeparatorsByStackLine");function isHighSurrogate(codeUnit){return codeUnit>=55296&&codeUnit<=56319}__name(isHighSurrogate,"isHighSurrogate");function isLowSurrogate(codeUnit){return codeUnit>=56320&&codeUnit<=57343}__name(isLowSurrogate,"isLowSurrogate");function truncateBeforeDanglingSurrogate(details,cutPoint){const beforeCut=details.charCodeAt(cutPoint-1);const atCut=details.charCodeAt(cutPoint);if(isHighSurrogate(beforeCut)&&isLowSurrogate(atCut)){return cutPoint-1}return cutPoint}__name(truncateBeforeDanglingSurrogate,"truncateBeforeDanglingSurrogate");function capRememberErrorText(redacted){if(redacted.length<=MAX_REMEMBER_ERROR_DETAILS_CHARS)return redacted;const truncationSuffix="... [truncated]";const cutPoint=truncateBeforeDanglingSurrogate(redacted,MAX_REMEMBER_ERROR_DETAILS_CHARS-truncationSuffix.length);return`${redacted.slice(0,cutPoint)}${truncationSuffix}`}__name(capRememberErrorText,"capRememberErrorText");function redactAndCapRememberErrorText(normalized){const redacted=redactLogCredentials(normalized).trim();if(!redacted)return void 0;return capRememberErrorText(redacted)}__name(redactAndCapRememberErrorText,"redactAndCapRememberErrorText");function sanitizeRememberErrorDetails(details){return redactAndCapRememberErrorText(replaceControlChars(collapseCredentialSeparators(details)))}__name(sanitizeRememberErrorDetails,"sanitizeRememberErrorDetails");function sanitizeRememberErrorStack(stack){return redactAndCapRememberErrorText(replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack)))}__name(sanitizeRememberErrorStack,"sanitizeRememberErrorStack");function extractRememberErrorDetails(err){const raw=rawRememberErrorDetails(err,new WeakSet,0);if(!raw)return void 0;return sanitizeRememberErrorDetails(raw)}__name(extractRememberErrorDetails,"extractRememberErrorDetails");function extractRememberErrorStack(err){if(!(err instanceof Error)||!err.stack)return void 0;return sanitizeRememberErrorStack(err.stack)}__name(extractRememberErrorStack,"extractRememberErrorStack");function shouldSuppressRememberErrorDetails(code){return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code)}__name(shouldSuppressRememberErrorDetails,"shouldSuppressRememberErrorDetails");function workspaceMemoryFailureDiagnostics(err,onExtractionError){let details;let stack;try{details=extractRememberErrorDetails(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"details",extractionErr);details=void 0}try{stack=extractRememberErrorStack(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"stack",extractionErr);stack=void 0}return{...details?{details}:{},debugDetails:details??"<details unavailable>",...stack?{stack}:{}}}__name(workspaceMemoryFailureDiagnostics,"workspaceMemoryFailureDiagnostics");init_esbuild_shims();var MAX_REMEMBER_CONTENT_BYTES=64*1024;init_esbuild_shims();function formatWorkspaceMemoryForgetSummary(removedEntryCount){return removedEntryCount>0?`Forgot ${removedEntryCount} memory entr${removedEntryCount===1?"y":"ies"}.`:"No managed auto-memory entries matched."}__name(formatWorkspaceMemoryForgetSummary,"formatWorkspaceMemoryForgetSummary");function formatWorkspaceMemoryDreamSummary(touchedTopicCount){return touchedTopicCount>0?"Managed auto-memory dream completed.":"No managed auto-memory topics changed."}__name(formatWorkspaceMemoryDreamSummary,"formatWorkspaceMemoryDreamSummary");init_esbuild_shims();var VALID_SERVER_NAME=/^[A-Za-z0-9_-]+$/;var RESERVED_SERVER_NAMES=new Set(["__proto__","constructor","prototype"]);function isValidServerName(name){return typeof name==="string"&&name.length>0&&name.length<=256&&VALID_SERVER_NAME.test(name)&&!RESERVED_SERVER_NAMES.has(name)}__name(isValidServerName,"isValidServerName");init_esbuild_shims();var GENERATION_MAX_PROMPT_BYTES=32*1024;var GENERATION_TIMEOUT_MS=6e4;async function executeGeneration(config,requestId,prompt,signal,emit){const fastModel=config.getFastModel();const mainModel=config.getModel();const client=config.getBaseLlmClient();let modelSource=fastModel?"fast":"main";let resolved;if(fastModel){try{resolved=await client.resolveForModel(fastModel,{failClosed:true})}catch{modelSource="main"}}resolved??=await client.resolveForModel(mainModel,{failClosed:true});const{contentGenerator,model}=resolved;await emit({type:"started",model,modelSource});const stream=await contentGenerator.generateContentStream({model,contents:[{role:"user",parts:[{text:prompt}]}],config:{abortSignal:signal,tools:[],thinkingConfig:{thinkingBudget:0,includeThoughts:false},temperature:.2}},`generation:${requestId}`);let seq=0;let thinkingEmitted=false;let usage;for await(const chunk of stream){if(!thinkingEmitted&&chunk.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.thought===true))){thinkingEmitted=true;await emit({type:"thinking"})}const text=getResponseText(chunk)??"";if(text){await emit({type:"delta",seq:seq++,text})}if(chunk.usageMetadata)usage=chunk.usageMetadata}return{model,modelSource,...usage?.promptTokenCount!==void 0?{inputTokens:usage.promptTokenCount}:{},...usage?.candidatesTokenCount!==void 0?{outputTokens:usage.candidatesTokenCount}:{}}}__name(executeGeneration,"executeGeneration");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";init_esbuild_shims();import{Buffer}from"node:buffer";import{isDeepStrictEqual}from"node:util";var ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for ACP transport ...]\n";var EMPTY_CONTENT_ARRAY_JSON_BYTES=Buffer.byteLength("[]","utf8");var EMPTY_TEXT_BLOCK_JSON_BYTES=Buffer.byteLength(JSON.stringify(createTextBlock("")),"utf8");var JSON_ARRAY_SEPARATOR_BYTES=1;var TRUNCATION_MARKER_PAYLOAD_BYTES=jsonStringJsonByteLength(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)-JSON_STRING_DELIMITER_BYTES;var MAX_CANONICAL_TEXT_BLOCKS=Math.floor((ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-EMPTY_CONTENT_ARRAY_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES)/(EMPTY_TEXT_BLOCK_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES));function createTextBlock(text){return{type:"content",content:{type:"text",text}}}__name(createTextBlock,"createTextBlock");function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord,"isObjectRecord");function hasExactKeys(value,first,second){const keys=Object.keys(value);return keys.length===2&&Object.hasOwn(value,first)&&Object.hasOwn(value,second)}__name(hasExactKeys,"hasExactKeys");function canonicalTextBlocks(value){if(!Array.isArray(value))return void 0;for(const block of value){if(!isObjectRecord(block)||!hasExactKeys(block,"type","content")||block["type"]!=="content"||!isObjectRecord(block["content"])||!hasExactKeys(block["content"],"type","text")||block["content"]["type"]!=="text"||typeof block["content"]["text"]!=="string"){return void 0}}return value}__name(canonicalTextBlocks,"canonicalTextBlocks");function contentSkeletonBytes(blockCount){if(blockCount===0)return EMPTY_CONTENT_ARRAY_JSON_BYTES;return EMPTY_CONTENT_ARRAY_JSON_BYTES+blockCount*EMPTY_TEXT_BLOCK_JSON_BYTES+(blockCount-1)*JSON_ARRAY_SEPARATOR_BYTES}__name(contentSkeletonBytes,"contentSkeletonBytes");function fallbackContent(){return[createTextBlock(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)]}__name(fallbackContent,"fallbackContent");function jsonByteLength(value){return Buffer.byteLength(JSON.stringify(value),"utf8")}__name(jsonByteLength,"jsonByteLength");function allocatePayloadBudgets(payloadBytes,availableBytes){const base=payloadBytes.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));let remaining=availableBytes-base.reduce((sum,bytes)=>sum+bytes,0);if(remaining<0)return void 0;const capacities=payloadBytes.map((bytes,index)=>({index,capacity:bytes-base[index]}));const sorted=capacities.filter(({capacity})=>capacity>0).sort((left,right)=>left.capacity===right.capacity?left.index-right.index:left.capacity-right.capacity);let active=sorted.length;let position=0;let level=0;let remainder=0;while(position<sorted.length&&active>0&&remaining>0){const nextLevel=sorted[position].capacity;const cost=(nextLevel-level)*active;if(cost>remaining){level+=Math.floor(remaining/active);remainder=remaining%active;remaining=0;break}level=nextLevel;remaining-=cost;while(position<sorted.length&&sorted[position].capacity===nextLevel){position++;active--}}const allocations=base.map((bytes,index)=>bytes+Math.min(capacities[index].capacity,level));if(remainder>0){for(const{index,capacity}of capacities){if(remainder===0)break;if(capacity>level){allocations[index]++;remainder--}}}return allocations}__name(allocatePayloadBudgets,"allocatePayloadBudgets");function projectContent(original){if(original.length>MAX_CANONICAL_TEXT_BLOCKS)return fallbackContent();const skeletonBytes=contentSkeletonBytes(original.length);const availablePayloadBytes=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-skeletonBytes;let remainingPayloadBytes=availablePayloadBytes;let needsProjection=false;for(const block of original){const payloadBytes2=jsonStringPayloadByteLength(block.content.text,remainingPayloadBytes);if(payloadBytes2>remainingPayloadBytes){needsProjection=true;break}remainingPayloadBytes-=payloadBytes2}if(!needsProjection)return original;const baseScans=original.map(block=>jsonStringPayloadByteLength(block.content.text,TRUNCATION_MARKER_PAYLOAD_BYTES));const basePayloadBytes=baseScans.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));const baseTotal=basePayloadBytes.reduce((sum,bytes)=>sum+bytes,0);if(baseTotal>availablePayloadBytes)return fallbackContent();const payloadBytes=original.map((block,index)=>{if(baseScans[index]<=TRUNCATION_MARKER_PAYLOAD_BYTES){return baseScans[index]}const maximumAllocation=availablePayloadBytes-baseTotal+basePayloadBytes[index];const bytes=jsonStringPayloadByteLength(block.content.text,maximumAllocation);return bytes<=maximumAllocation?bytes:maximumAllocation+1});const allocations=allocatePayloadBudgets(payloadBytes,availablePayloadBytes);if(!allocations)return fallbackContent();const projected=original.map((block,index)=>{if(payloadBytes[index]<=allocations[index])return block;return createTextBlock(truncateJsonStringPayload(block.content.text,payloadBytes[index],allocations[index],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))});return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:fallbackContent()}__name(projectContent,"projectContent");function projectRawOutput(value){const payloadBudget=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-JSON_STRING_DELIMITER_BYTES;const payloadBytes=jsonStringPayloadByteLength(value,payloadBudget);if(payloadBytes<=payloadBudget)return value;const projected=truncateJsonStringPayload(value,payloadBytes,payloadBudget,ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER);return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER}__name(projectRawOutput,"projectRawOutput");function a2uiMeta(meta){if(!meta)return void 0;const toolName=typeof meta["toolName"]==="string"?meta["toolName"]:void 0;const serverId=typeof meta["serverId"]==="string"?meta["serverId"]:void 0;return toolName===void 0&&serverId===void 0?void 0:{...toolName===void 0?{}:{toolName},...serverId===void 0?{}:{serverId}}}__name(a2uiMeta,"a2uiMeta");function projectAcpToolResultUpdate(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return update;const meta=isObjectRecord(record["_meta"])?record["_meta"]:void 0;if(isA2uiToolMeta(a2uiMeta(meta)))return update;const content=canonicalTextBlocks(record["content"]);const rawOutput=record["rawOutput"];if(content?.length===1&&typeof rawOutput==="string"&&rawOutput===content[0].content.text){const projectedContent2=projectContent(content);if(projectedContent2===content)return update;const projectedText=projectedContent2[0].content.text;return{...record,content:projectedContent2,rawOutput:projectedText}}const projectedContent=content?projectContent(content):void 0;let projectedRawOutput=typeof rawOutput==="string"?projectRawOutput(rawOutput):void 0;if(isShellResultDisplay(rawOutput)){const structured=mapShellResultText(rawOutput,text=>text);projectedRawOutput=isDeepStrictEqual(structured,rawOutput)?rawOutput:structured;if(Buffer.byteLength(JSON.stringify(structured),"utf8")>ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET){const payloadBytes=[];const skeleton=mapShellResultText(structured,text=>{payloadBytes.push(jsonStringPayloadByteLength(text));return""});const budgets=allocatePayloadBudgets(payloadBytes,ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-Buffer.byteLength(JSON.stringify(skeleton),"utf8"));let index=0;projectedRawOutput=mapShellResultText(structured,text=>truncateJsonStringPayload(text,jsonStringPayloadByteLength(text),budgets[index++],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))}}const contentChanged=projectedContent!==void 0&&projectedContent!==content;const rawOutputChanged=projectedRawOutput!==void 0&&projectedRawOutput!==rawOutput;if(!contentChanged&&!rawOutputChanged)return update;return{...record,...contentChanged?{content:projectedContent}:{},...rawOutputChanged?{rawOutput:projectedRawOutput}:{}}}__name(projectAcpToolResultUpdate,"projectAcpToolResultUpdate");var HistoryReplayLimitError=class extends Error{constructor(sessionId,reason,observed,limit){super(`Transcript replay for session ${sessionId} exceeds the ${reason} limit (${observed}, max ${limit})`);this.sessionId=sessionId;this.reason=reason;this.observed=observed;this.limit=limit;this.name="HistoryReplayLimitError"}static{__name(this,"HistoryReplayLimitError")}};function createReplayCumulativeUsage(){return{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}}__name(createReplayCumulativeUsage,"createReplayCumulativeUsage");function copyCumulativeUsage(target,source){target.promptTokens=source.promptTokens;target.cachedTokens=source.cachedTokens;target.candidateTokens=source.candidateTokens;target.apiTimeMs=source.apiTimeMs}__name(copyCumulativeUsage,"copyCumulativeUsage");function isObjectRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord2,"isObjectRecord");function isCumulativeUsage(value){if(!isObjectRecord2(value))return false;return typeof value["promptTokens"]==="number"&&Number.isFinite(value["promptTokens"])&&typeof value["cachedTokens"]==="number"&&Number.isFinite(value["cachedTokens"])&&typeof value["candidateTokens"]==="number"&&Number.isFinite(value["candidateTokens"])&&typeof value["apiTimeMs"]==="number"&&Number.isFinite(value["apiTimeMs"])}__name(isCumulativeUsage,"isCumulativeUsage");function isPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&(value["timestamp"]===void 0||typeof value["timestamp"]==="string")&&typeof value["recordId"]==="string"}__name(isPendingReplayToolCall,"isPendingReplayToolCall");function isCurrentPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&typeof value["sourceRecordId"]==="string"&&(value["sourceTimestamp"]===void 0||typeof value["sourceTimestamp"]==="string")}__name(isCurrentPendingReplayToolCall,"isCurrentPendingReplayToolCall");function parseTranscriptReplayState(replay,logger){if(!isObjectRecord2(replay)){return{pendingToolCalls:[],cumulativeUsage:createReplayCumulativeUsage()}}if("v"in replay&&replay["v"]!==1){throw new TypeError("Unsupported transcript replay state version.")}const rawPending=replay["pendingToolCalls"];const pendingToolCalls=Array.isArray(rawPending)?rawPending.flatMap(pending=>{if(isPendingReplayToolCall(pending))return[pending];if(isCurrentPendingReplayToolCall(pending)){return[{callId:pending.callId,toolName:pending.toolName,...pending.resolvedToolName?{resolvedToolName:pending.resolvedToolName}:{},recordId:pending.sourceRecordId,...pending.sourceTimestamp?{timestamp:pending.sourceTimestamp}:{},...pending.rawCallId?{rawCallId:pending.rawCallId}:{},...pending.timingMatched?{timingMatched:true}:{}}]}return[]}):[];if(logger&&Array.isArray(rawPending)&&pendingToolCalls.length!==rawPending.length){const dropped=rawPending.length-pendingToolCalls.length;logger.warn(`[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`)}const cumulativeUsage=isCumulativeUsage(replay["cumulativeUsage"])?{...replay["cumulativeUsage"]}:createReplayCumulativeUsage();const rawGoalState=replay["goalState"];const goalState=rawGoalState===void 0?void 0:parseGoalSnapshotV2(rawGoalState);if(logger&&rawGoalState!==void 0&&!goalState){logger.warn("[transcript] replay state dropped a malformed Goal state")}const rawGoalCause=replay["goalCause"];const goalCause=rawGoalCause===void 0?void 0:parseGoalStateCause(rawGoalCause);if(logger&&rawGoalCause!==void 0&&!goalCause){logger.warn("[transcript] replay state dropped a malformed Goal cause")}return{pendingToolCalls,cumulativeUsage,...goalState?{goalState}:{},...goalCause?{goalCause}:{}}}__name(parseTranscriptReplayState,"parseTranscriptReplayState");function blankReplayedMcpAppHtml(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return void 0;const rawOutput=record["rawOutput"];if(!isObjectRecord2(rawOutput)||rawOutput["type"]!=="mcp_app"||typeof rawOutput["html"]!=="string"||rawOutput["html"]===""){return void 0}const blanked={...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}};if(Buffer2.byteLength(JSON.stringify(blanked),"utf8")>=Buffer2.byteLength(JSON.stringify(record),"utf8")){return void 0}return blanked}__name(blankReplayedMcpAppHtml,"blankReplayedMcpAppHtml");function degradeReplayEnvelopeAppHtml(envelope,maxBytes){let pageBytes=Buffer2.byteLength(JSON.stringify(envelope),"utf8");for(let i=0;i<envelope.updates.length&&pageBytes>maxBytes;i++){const update=envelope.updates[i];const blanked=blankReplayedMcpAppHtml(update);if(blanked===void 0)continue;pageBytes+=Buffer2.byteLength(JSON.stringify(blanked),"utf8")-Buffer2.byteLength(JSON.stringify(update),"utf8");envelope.updates[i]=blanked}}__name(degradeReplayEnvelopeAppHtml,"degradeReplayEnvelopeAppHtml");function replayContext(sessionId,updates,cumulativeUsage,config,limits){let activeRecordId=null;let serializedUpdateBytes=2;return{sessionId,sendUpdate:__name(async update=>{const projectedUpdate=projectAcpToolResultUpdate(update);const updateWithRecordId=(()=>{if(activeRecordId===null)return projectedUpdate;const record=projectedUpdate;const meta=isObjectRecord2(record["_meta"])?record["_meta"]:{};return{...record,_meta:{...meta,"qwen.session.recordId":activeRecordId}}})();let deliveredUpdate=liftSessionUpdateTimestamp(updateWithRecordId);observeAcpToolResultProjection(update,projectedUpdate,sessionId,deliveredUpdate);if(limits){const updateCount=updates.length+1;if(updateCount>limits.maxUpdates){throw new HistoryReplayLimitError(sessionId,"updates",updateCount,limits.maxUpdates)}let updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(deliveredUpdate),"utf8");if(serializedUpdateBytes+updateBytes>limits.maxBytes){for(let i=0;i<updates.length&&serializedUpdateBytes+updateBytes>limits.maxBytes;i++){const blanked=blankReplayedMcpAppHtml(updates[i]);if(blanked===void 0)continue;serializedUpdateBytes-=Buffer2.byteLength(JSON.stringify(updates[i]),"utf8")-Buffer2.byteLength(JSON.stringify(blanked),"utf8");updates[i]=blanked}if(serializedUpdateBytes+updateBytes>limits.maxBytes){const blanked=blankReplayedMcpAppHtml(deliveredUpdate);if(blanked!==void 0){deliveredUpdate=blanked;updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(blanked),"utf8")}}}serializedUpdateBytes+=updateBytes;if(serializedUpdateBytes>limits.maxBytes){throw new HistoryReplayLimitError(sessionId,"bytes",serializedUpdateBytes,limits.maxBytes)}}updates.push(deliveredUpdate)},"sendUpdate"),setActiveRecordId:__name(recordId=>{activeRecordId=recordId},"setActiveRecordId"),cumulativeUsage,...config?{config}:{}}}__name(replayContext,"replayContext");async function collectHistoryReplayUpdates({sessionId,config,records,gaps,cumulativeUsage,logger,replayState,goalBootstrap,limits,suppressRestoreAskUserQuestion,finalizeDangling,branchPointsByAssistantUuid}){const updates=[];let replayError;try{const initial=parseTranscriptReplayState(replayState,logger);let skipFinalizeCallIds;if(suppressRestoreAskUserQuestion!==true&&config?.getRestoreAskUserQuestion?.()===true){const replayClient=config.getLlmClient?.();const lastHistoryContent=replayClient?.isInitialized?.()===true?replayClient.getChat?.()?.peekLastHistoryEntry?.()??lastHistoryContentFromRecords(records):lastHistoryContentFromRecords(records);skipFinalizeCallIds=restorableAskUserQuestionCallIds(lastHistoryContent)}await new HistoryReplayer(replayContext(sessionId,updates,cumulativeUsage,config,limits)).replay(records,gaps,{...initial.goalState?{initialGoalState:initial.goalState}:{},...initial.goalCause?{initialGoalCause:initial.goalCause}:{},...goalBootstrap?{goalBootstrap}:{},...skipFinalizeCallIds?{skipFinalizeCallIds}:{},...finalizeDangling===void 0?{}:{finalizeDangling}})}catch(error){if(error instanceof HistoryReplayLimitError)throw error;replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error)}if(branchPointsByAssistantUuid){stampBranchPoints(updates,branchPointsByAssistantUuid)}return replayError===void 0?{updates}:{updates,replayError}}__name(collectHistoryReplayUpdates,"collectHistoryReplayUpdates");function liftSessionUpdateTimestamp(update){const record=update;const meta=record["_meta"];const timestamp=isObjectRecord2(meta)?meta["timestamp"]:void 0;return typeof timestamp==="number"||typeof timestamp==="string"?{...record,timestamp}:update}__name(liftSessionUpdateTimestamp,"liftSessionUpdateTimestamp");function readTranscriptSourceRecordIds(update){const value=update;const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;const sourceRecordIds=transcript?.["sourceRecordIds"];if(!Array.isArray(sourceRecordIds))return void 0;return sourceRecordIds.filter(id=>typeof id==="string")}__name(readTranscriptSourceRecordIds,"readTranscriptSourceRecordIds");function stampBranchPoints(updates,branchPoints){const lastChunkIndexByRecordId=new Map;updates.forEach((update,index)=>{if(update.sessionUpdate!=="agent_message_chunk")return;const text=update.content?.text;if(typeof text!=="string"||text.length===0)return;for(const recordId of readTranscriptSourceRecordIds(update)??[]){if(Object.hasOwn(branchPoints,recordId)){lastChunkIndexByRecordId.set(recordId,index)}}});const decoratedIndexes=new Set;for(const[recordId,index]of lastChunkIndexByRecordId){if(decoratedIndexes.has(index))continue;decoratedIndexes.add(index);const value=updates[index];const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;value["_meta"]={...meta,qwenTranscript:{...transcript,branchRecordId:branchPoints[recordId]}}}}__name(stampBranchPoints,"stampBranchPoints");async function replayTranscriptRecordPage({sessionId,page,config,encodeCursor,logger,finalizeDangling=true}){const state=parseTranscriptReplayState(page.replay,logger);const updates=[];const replayer=new HistoryReplayer(replayContext(sessionId,updates,state.cumulativeUsage,config));let replayState;let replayError;try{const replayPageState=await replayer.replayPage(page.records,{pendingToolCalls:page.direction==="backward"?[]:state.pendingToolCalls,finalizeDangling:finalizeDangling&&(page.direction==="backward"||!page.hasMore),gaps:page.gaps,includeTiming:true,...state.goalState?{goalState:state.goalState}:{},...state.goalCause?{goalCause:state.goalCause}:{}});replayState=replayPageState.replay}catch(error){logger?.warn("[historyReplay] Paged history replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);replayState=replayer.getReplayState();replayError="Replay conversion failed for this page"}if(page.branchPointsByAssistantUuid){stampBranchPoints(updates,page.branchPointsByAssistantUuid)}const nextCursor=page.nextCursorState&&replayError===void 0?encodeCursor({...page.nextCursorState,...page.direction==="backward"?{}:{replay:replayState}}):void 0;return{updates,...nextCursor?{nextCursor}:{},hasMore:replayError===void 0&&page.hasMore,startTime:page.startTime,lastUpdated:page.lastUpdated,...replayError?{partial:true,replayError}:{}}}__name(replayTranscriptRecordPage,"replayTranscriptRecordPage");export{createWorkspaceMemoryExtractionErrorLogger,extractRememberErrorCode,workspaceMemoryFailureCode,shouldSuppressRememberErrorDetails,workspaceMemoryFailureDiagnostics,MAX_REMEMBER_CONTENT_BYTES,formatWorkspaceMemoryForgetSummary,formatWorkspaceMemoryDreamSummary,isValidServerName,GENERATION_MAX_PROMPT_BYTES,GENERATION_TIMEOUT_MS,executeGeneration,projectAcpToolResultUpdate,HistoryReplayLimitError,createReplayCumulativeUsage,copyCumulativeUsage,degradeReplayEnvelopeAppHtml,collectHistoryReplayUpdates,replayTranscriptRecordPage};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{t}from"./chunk-ABJGFEES.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var LOOP_DETECTED_FALLBACK_MESSAGE="A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.";var LOOP_TYPE_LABELS={["consecutive_identical_tool_calls"]:"the model repeated the same tool call with identical arguments",["chanting_identical_sentences"]:"the model repeated the same sentence in its output or reasoning",["repetitive_thoughts"]:"the model repeated the same reasoning thought",["read_file_loop"]:"the model spent too many consecutive calls reading files without making progress",["action_stagnation"]:"the model kept calling the same tool without making progress",["shell_command_stagnation"]:"the model repeated similar shell inspection commands without making progress",["global_tool_call_duplicate"]:"the model repeated the same tool call across the turn, even when not back-to-back",["alternating_tool_call_pattern"]:"the model alternated between the same two tool calls in a repeating pattern",["turn_tool_call_cap"]:"the turn reached the per-turn tool-call limit",["invalid_tool_params_stagnation"]:"the model repeatedly sent invalid tool parameters without correcting them",["repeated_tool_execution_failure"]:"the same tool execution failure continued after a corrective reminder"};var ALWAYS_ON_HINT=" This is an always-on guard and cannot be disabled via `model.skipLoopDetection`.";var GOVERNED_HINT=' Set `model.loopProtection` to "warn" to remind the model instead of stopping, or to "off" to disable this guard.';var HEURISTIC_HINT=' Set `model.loopProtection` to "warn" to remind the model instead of stopping, or `model.skipLoopDetection` to true to disable this check.';var SKIP_HINT=" Set the `model.skipLoopDetection` setting to true to disable.";function reasonLabel(stop){const limit=stop.toolCallLimit;switch(stop.loopReason){case"explicit_cap":return`the turn reached the per-turn tool-call limit set by \`model.maxToolCallsPerTurn\`${limit!==void 0?` (${limit})`:""}`;case"backstop":return limit!==void 0?`the turn reached the ${limit}-call backstop of the adaptive per-turn cap`:"the turn reached the backstop of the adaptive per-turn cap";case"stuck_repetition":return limit!==void 0?`past ${limit} tool calls the model kept repeating the same tool call`:"past the per-turn soft cap the model kept repeating the same tool call";case"provider_duplicate_id":return"the provider replayed a tool call id that had already run";default:return void 0}}__name(reasonLabel,"reasonLabel");function hint(stop){switch(stop.loopReason){case"explicit_cap":return" Raise `model.maxToolCallsPerTurn`, or set it to 0 to disable the cap.";case"backstop":return" Set `model.maxToolCallsPerTurn` to choose a fixed cap instead (0 disables it).";case"stuck_repetition":return' Give the model a more specific instruction, or set `model.loopProtection` to "warn" to remind it instead of stopping. An explicit `model.maxToolCallsPerTurn` replaces this repetition check with a fixed cap (0 disables it).';case"repeated_call":return HEURISTIC_HINT;case"provider_duplicate_id":return ALWAYS_ON_HINT;default:break}switch(stop.loopType){case"turn_tool_call_cap":return" A per-turn tool-call cap was reached. The default is adaptive (allows up to 1000 diverse calls, halting only on repeated calls); an explicitly set `model.maxToolCallsPerTurn` is a hard cap. If the model was repeating the same call, investigate the repetition; otherwise unset the value to use the adaptive default, or raise it (set 0 to disable).";case"consecutive_identical_tool_calls":case"shell_command_stagnation":case"invalid_tool_params_stagnation":return GOVERNED_HINT;case"repeated_tool_execution_failure":return ALWAYS_ON_HINT;case"chanting_identical_sentences":case"repetitive_thoughts":case void 0:return SKIP_HINT;default:return HEURISTIC_HINT}}__name(hint,"hint");function describeLoopStop(stop){if(!stop?.loopType)return void 0;return reasonLabel(stop)??LOOP_TYPE_LABELS[stop.loopType]}__name(describeLoopStop,"describeLoopStop");function formatLoopDetectedMessage(stop){const cause=describeLoopStop(stop);const detail=cause?` (${stop?.loopType}: ${cause})`:"";return`Loop detection halted the run${detail}.${hint(stop??{})}`}__name(formatLoopDetectedMessage,"formatLoopDetectedMessage");function formatInteractiveLoopDetectedMessage(stop){return stop?.loopType?formatLoopDetectedMessage(stop):LOOP_DETECTED_FALLBACK_MESSAGE}__name(formatInteractiveLoopDetectedMessage,"formatInteractiveLoopDetectedMessage");init_esbuild_shims();import{randomUUID}from"node:crypto";var CHAT_RECORDING_FAILURE_MESSAGE="Session recording stopped after a write failure. New messages for the affected session will not be saved. Check disk space and permissions, then start a new session to resume recording. See the debug log for details.";var TUI_CHAT_RECORDING_FAILURE_MESSAGE="Session recording stopped after a write failure. New messages for the affected session will not be saved. Check disk space and permissions, then run `/clear` to start a new recorded session. See the debug log for details.";var CHAT_RECORDING_SETTLE_TIMEOUT_MS=2e3;var debugLogger=createDebugLogger("CHAT_RECORDING");function createChatRecordingFailureSystemMessage(event){return{type:"system",subtype:"session_recording_degraded",uuid:randomUUID(),session_id:event.sessionId,parent_tool_use_id:null,data:{session_id:event.sessionId,reason:"write_failed",message:CHAT_RECORDING_FAILURE_MESSAGE}}}__name(createChatRecordingFailureSystemMessage,"createChatRecordingFailureSystemMessage");function reportChatRecordingFailureToAdapter(adapter,event){adapter.emitMessage(createChatRecordingFailureSystemMessage(event))}__name(reportChatRecordingFailureToAdapter,"reportChatRecordingFailureToAdapter");function subscribeToHeadlessChatRecordingFailures(config,adapter){if(typeof config.onChatRecordingFailure!=="function")return()=>{};return config.onChatRecordingFailure(event=>{if(config.getOutputFormat()==="text"){writeStderrLine(`Warning: ${t(CHAT_RECORDING_FAILURE_MESSAGE)}`);return}reportChatRecordingFailureToAdapter(adapter,event)})}__name(subscribeToHeadlessChatRecordingFailures,"subscribeToHeadlessChatRecordingFailures");async function settleChatRecording(config,options){if(typeof config.getChatRecordingService!=="function")return"settled";const recorder=config.getChatRecordingService();if(!recorder)return"settled";if(options.finalize)recorder.finalize();let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>{debugLogger.debug("Timed out waiting for chat recording to flush");resolve("timeout")},CHAT_RECORDING_SETTLE_TIMEOUT_MS)});const settled=recorder.flush().then(()=>"settled",()=>"settled");try{return await Promise.race([settled,timeout])}finally{if(timer)clearTimeout(timer)}}__name(settleChatRecording,"settleChatRecording");export{describeLoopStop,formatLoopDetectedMessage,formatInteractiveLoopDetectedMessage,TUI_CHAT_RECORDING_FAILURE_MESSAGE,reportChatRecordingFailureToAdapter,subscribeToHeadlessChatRecordingFailures,settleChatRecording};
3
+ import{t}from"./chunk-NO7VTKRL.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var LOOP_DETECTED_FALLBACK_MESSAGE="A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.";var LOOP_TYPE_LABELS={["consecutive_identical_tool_calls"]:"the model repeated the same tool call with identical arguments",["chanting_identical_sentences"]:"the model repeated the same sentence in its output or reasoning",["repetitive_thoughts"]:"the model repeated the same reasoning thought",["read_file_loop"]:"the model spent too many consecutive calls reading files without making progress",["action_stagnation"]:"the model kept calling the same tool without making progress",["shell_command_stagnation"]:"the model repeated similar shell inspection commands without making progress",["global_tool_call_duplicate"]:"the model repeated the same tool call across the turn, even when not back-to-back",["alternating_tool_call_pattern"]:"the model alternated between the same two tool calls in a repeating pattern",["turn_tool_call_cap"]:"the turn reached the per-turn tool-call limit",["invalid_tool_params_stagnation"]:"the model repeatedly sent invalid tool parameters without correcting them",["repeated_tool_execution_failure"]:"the same tool execution failure continued after a corrective reminder"};var ALWAYS_ON_HINT=" This is an always-on guard and cannot be disabled via `model.skipLoopDetection`.";var GOVERNED_HINT=' Set `model.loopProtection` to "warn" to remind the model instead of stopping, or to "off" to disable this guard.';var HEURISTIC_HINT=' Set `model.loopProtection` to "warn" to remind the model instead of stopping, or `model.skipLoopDetection` to true to disable this check.';var SKIP_HINT=" Set the `model.skipLoopDetection` setting to true to disable.";function reasonLabel(stop){const limit=stop.toolCallLimit;switch(stop.loopReason){case"explicit_cap":return`the turn reached the per-turn tool-call limit set by \`model.maxToolCallsPerTurn\`${limit!==void 0?` (${limit})`:""}`;case"backstop":return limit!==void 0?`the turn reached the ${limit}-call backstop of the adaptive per-turn cap`:"the turn reached the backstop of the adaptive per-turn cap";case"stuck_repetition":return limit!==void 0?`past ${limit} tool calls the model kept repeating the same tool call`:"past the per-turn soft cap the model kept repeating the same tool call";case"provider_duplicate_id":return"the provider replayed a tool call id that had already run";default:return void 0}}__name(reasonLabel,"reasonLabel");function hint(stop){switch(stop.loopReason){case"explicit_cap":return" Raise `model.maxToolCallsPerTurn`, or set it to 0 to disable the cap.";case"backstop":return" Set `model.maxToolCallsPerTurn` to choose a fixed cap instead (0 disables it).";case"stuck_repetition":return' Give the model a more specific instruction, or set `model.loopProtection` to "warn" to remind it instead of stopping. An explicit `model.maxToolCallsPerTurn` replaces this repetition check with a fixed cap (0 disables it).';case"repeated_call":return HEURISTIC_HINT;case"provider_duplicate_id":return ALWAYS_ON_HINT;default:break}switch(stop.loopType){case"turn_tool_call_cap":return" A per-turn tool-call cap was reached. The default is adaptive (allows up to 1000 diverse calls, halting only on repeated calls); an explicitly set `model.maxToolCallsPerTurn` is a hard cap. If the model was repeating the same call, investigate the repetition; otherwise unset the value to use the adaptive default, or raise it (set 0 to disable).";case"consecutive_identical_tool_calls":case"shell_command_stagnation":case"invalid_tool_params_stagnation":return GOVERNED_HINT;case"repeated_tool_execution_failure":return ALWAYS_ON_HINT;case"chanting_identical_sentences":case"repetitive_thoughts":case void 0:return SKIP_HINT;default:return HEURISTIC_HINT}}__name(hint,"hint");function describeLoopStop(stop){if(!stop?.loopType)return void 0;return reasonLabel(stop)??LOOP_TYPE_LABELS[stop.loopType]}__name(describeLoopStop,"describeLoopStop");function formatLoopDetectedMessage(stop){const cause=describeLoopStop(stop);const detail=cause?` (${stop?.loopType}: ${cause})`:"";return`Loop detection halted the run${detail}.${hint(stop??{})}`}__name(formatLoopDetectedMessage,"formatLoopDetectedMessage");function formatInteractiveLoopDetectedMessage(stop){return stop?.loopType?formatLoopDetectedMessage(stop):LOOP_DETECTED_FALLBACK_MESSAGE}__name(formatInteractiveLoopDetectedMessage,"formatInteractiveLoopDetectedMessage");init_esbuild_shims();import{randomUUID}from"node:crypto";var CHAT_RECORDING_FAILURE_MESSAGE="Session recording stopped after a write failure. New messages for the affected session will not be saved. Check disk space and permissions, then start a new session to resume recording. See the debug log for details.";var TUI_CHAT_RECORDING_FAILURE_MESSAGE="Session recording stopped after a write failure. New messages for the affected session will not be saved. Check disk space and permissions, then run `/clear` to start a new recorded session. See the debug log for details.";var CHAT_RECORDING_SETTLE_TIMEOUT_MS=2e3;var debugLogger=createDebugLogger("CHAT_RECORDING");function createChatRecordingFailureSystemMessage(event){return{type:"system",subtype:"session_recording_degraded",uuid:randomUUID(),session_id:event.sessionId,parent_tool_use_id:null,data:{session_id:event.sessionId,reason:"write_failed",message:CHAT_RECORDING_FAILURE_MESSAGE}}}__name(createChatRecordingFailureSystemMessage,"createChatRecordingFailureSystemMessage");function reportChatRecordingFailureToAdapter(adapter,event){adapter.emitMessage(createChatRecordingFailureSystemMessage(event))}__name(reportChatRecordingFailureToAdapter,"reportChatRecordingFailureToAdapter");function subscribeToHeadlessChatRecordingFailures(config,adapter){if(typeof config.onChatRecordingFailure!=="function")return()=>{};return config.onChatRecordingFailure(event=>{if(config.getOutputFormat()==="text"){writeStderrLine(`Warning: ${t(CHAT_RECORDING_FAILURE_MESSAGE)}`);return}reportChatRecordingFailureToAdapter(adapter,event)})}__name(subscribeToHeadlessChatRecordingFailures,"subscribeToHeadlessChatRecordingFailures");async function settleChatRecording(config,options){if(typeof config.getChatRecordingService!=="function")return"settled";const recorder=config.getChatRecordingService();if(!recorder)return"settled";if(options.finalize)recorder.finalize();let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>{debugLogger.debug("Timed out waiting for chat recording to flush");resolve("timeout")},CHAT_RECORDING_SETTLE_TIMEOUT_MS)});const settled=recorder.flush().then(()=>"settled",()=>"settled");try{return await Promise.race([settled,timeout])}finally{if(timer)clearTimeout(timer)}}__name(settleChatRecording,"settleChatRecording");export{describeLoopStop,formatLoopDetectedMessage,formatInteractiveLoopDetectedMessage,TUI_CHAT_RECORDING_FAILURE_MESSAGE,reportChatRecordingFailureToAdapter,subscribeToHeadlessChatRecordingFailures,settleChatRecording};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team