@qwen-code/qwen-code 0.25.4-preview.0 → 0.25.4-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/bundled/browser-use/runtime/native-host.js +0 -0
  2. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
  3. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
  4. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
  5. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
  6. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
  7. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
  8. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
  9. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
  10. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
  11. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
  12. package/bundled/browser-use/runtime/node_modules/playwright-core/cli.js +0 -0
  13. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  14. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/xdg-open +0 -0
  15. package/bundled/browser-use/runtime/scripts/native-host-setup.js +0 -0
  16. package/chunks/{MaxSizedBox-M27H235V.js → MaxSizedBox-E4RKSA7W.js} +1 -1
  17. package/chunks/{StandaloneSessionPicker-LWWDDYOW.js → StandaloneSessionPicker-2D3UKLVS.js} +1 -1
  18. package/chunks/{acp-subagent-executor-NUV52JVS.js → acp-subagent-executor-UQYUN6AB.js} +1 -1
  19. package/chunks/{acpAgent-IUJDXLZM.js → acpAgent-P7WGK2BP.js} +3 -3
  20. package/chunks/{advisor-MSOUBMJ6.js → advisor-GCH2MBXT.js} +1 -1
  21. package/chunks/{agent-H7XIWYWQ.js → agent-57T4YAYP.js} +1 -1
  22. package/chunks/{agent-headless-XDN3D3S3.js → agent-headless-IBON3A7N.js} +1 -1
  23. package/chunks/{agent-host-client-AZP3PZXS.js → agent-host-client-LE7P72FR.js} +1 -1
  24. package/chunks/{agent-host-connections-JRVX7I6I.js → agent-host-connections-4DM57L26.js} +1 -1
  25. package/chunks/{anthropicContentGenerator-N7TV53LD.js → anthropicContentGenerator-C4TPFXUK.js} +1 -1
  26. package/chunks/{batch-MKSJFJUH.js → batch-YJJGMJWO.js} +1 -1
  27. package/chunks/{bridge-GNMKKHQ4.js → bridge-FIO2ENBG.js} +1 -1
  28. package/chunks/{channel-settings-store-Y4YCS7JX.js → channel-settings-store-TEBCLK2B.js} +1 -1
  29. package/chunks/{chunk-GPOUP5OK.js → chunk-27MTSS3T.js} +1 -1
  30. package/chunks/{chunk-C4ANA47H.js → chunk-2MGCRPM3.js} +1 -1
  31. package/chunks/{chunk-6DQNNRRC.js → chunk-2WBKWPSO.js} +1 -1
  32. package/chunks/{chunk-CATL2PQS.js → chunk-34WLYVDK.js} +5 -5
  33. package/chunks/{chunk-B7CXPNCV.js → chunk-3J2YNEHG.js} +1 -1
  34. package/chunks/{chunk-VTNHPXNL.js → chunk-3TBFTELA.js} +1 -1
  35. package/chunks/{chunk-7JT34VGK.js → chunk-46I6JBVL.js} +1 -1
  36. package/chunks/{chunk-FEMWELCV.js → chunk-4ZKFLOEH.js} +1 -1
  37. package/chunks/{chunk-7AYXAVTZ.js → chunk-5DUJIOOX.js} +3 -3
  38. package/chunks/{chunk-6QLHJSVW.js → chunk-6PWOLWTH.js} +1 -1
  39. package/chunks/{chunk-OW4QBRSR.js → chunk-6UZ65Z2P.js} +1 -1
  40. package/chunks/{chunk-V2JZO5MS.js → chunk-7DSJE3CL.js} +1 -1
  41. package/chunks/{chunk-TJMHIEYI.js → chunk-7LCY7GGX.js} +1 -1
  42. package/chunks/{chunk-TLJHBK3A.js → chunk-7RNTXEWH.js} +1 -1
  43. package/chunks/{chunk-YZ7OO4AQ.js → chunk-A3IF6IOB.js} +1 -1
  44. package/chunks/{chunk-VTF6AVZB.js → chunk-A6OQSOUO.js} +1 -1
  45. package/chunks/{chunk-Y7YDHCON.js → chunk-AJ6JUUP7.js} +1 -1
  46. package/chunks/{chunk-QTMHQGWQ.js → chunk-AOMEBVFW.js} +1 -1
  47. package/chunks/{chunk-KVTG2ZNH.js → chunk-AUNAS7AS.js} +1 -1
  48. package/chunks/{chunk-BOFD4CN3.js → chunk-AVIDPC5K.js} +1 -1
  49. package/chunks/{chunk-ETYTRKB2.js → chunk-BOLPBPWC.js} +1 -1
  50. package/chunks/{chunk-OAPA66DR.js → chunk-BQQBFDBY.js} +1 -1
  51. package/chunks/{chunk-NOS2CNOI.js → chunk-CN22ATWU.js} +1 -1
  52. package/chunks/{chunk-XYBEQRSZ.js → chunk-DIHJELGW.js} +1 -1
  53. package/chunks/{chunk-XCEL3EDX.js → chunk-DJFCI7TU.js} +1 -1
  54. package/chunks/{chunk-VKEL2XTM.js → chunk-DQPDMFS3.js} +1 -1
  55. package/chunks/{chunk-DJRFEZBY.js → chunk-DSYKB77N.js} +1 -1
  56. package/chunks/{chunk-UEW7Q26E.js → chunk-EDNOGHMN.js} +2 -2
  57. package/chunks/{chunk-RXNGYG64.js → chunk-EE36D2EV.js} +1 -1
  58. package/chunks/{chunk-NZKX7HYL.js → chunk-EGQDN3FJ.js} +1 -1
  59. package/chunks/{chunk-DFRSQK5Q.js → chunk-FHFBCG6N.js} +1 -1
  60. package/chunks/{chunk-PECV2VVZ.js → chunk-GI6T3RBV.js} +1 -1
  61. package/chunks/{chunk-37BNHIUB.js → chunk-GOLT5JXA.js} +1 -1
  62. package/chunks/{chunk-KITFF4GL.js → chunk-IDGXHMNL.js} +1 -1
  63. package/chunks/{chunk-6HIOSLUM.js → chunk-IIZWK7ZP.js} +1 -1
  64. package/chunks/{chunk-MPGEAX4K.js → chunk-IJC6ZH2S.js} +1 -1
  65. package/chunks/{chunk-TLYJVB5H.js → chunk-IO6LSEPV.js} +1 -1
  66. package/chunks/{chunk-QIJKEZZR.js → chunk-IYVNCBMS.js} +1 -1
  67. package/chunks/{chunk-S4GOHFRN.js → chunk-JHGOWK7M.js} +1 -1
  68. package/chunks/{chunk-GHRD2MMC.js → chunk-JRJY343T.js} +1 -1
  69. package/chunks/{chunk-WCYZSCG7.js → chunk-JVUXQU3W.js} +1 -1
  70. package/chunks/{chunk-DMCTJUIJ.js → chunk-K2K2YYWO.js} +1 -1
  71. package/chunks/{chunk-37OHWQHB.js → chunk-KF6HU732.js} +2 -2
  72. package/chunks/{chunk-5LSV73BG.js → chunk-KVWUOBH7.js} +1 -1
  73. package/chunks/{chunk-7V4BAHFT.js → chunk-LBWBGFHD.js} +1 -1
  74. package/chunks/{chunk-RKPHDO42.js → chunk-LDXZT3SG.js} +5 -5
  75. package/chunks/{chunk-BGFA2SAQ.js → chunk-LFOZ6AIH.js} +1 -1
  76. package/chunks/{chunk-4322TZID.js → chunk-LGQHT42X.js} +2 -2
  77. package/chunks/{chunk-PDXZ2CUO.js → chunk-M3O2XDHA.js} +1 -1
  78. package/chunks/{chunk-47K2NMP6.js → chunk-M3UC46LS.js} +1 -1
  79. package/chunks/{chunk-UFRY7WND.js → chunk-M7JLPTQI.js} +1 -1
  80. package/chunks/{chunk-SATEKHQP.js → chunk-MBUXP3IS.js} +1 -1
  81. package/chunks/{chunk-RN6JS263.js → chunk-MEZA3VVH.js} +1 -1
  82. package/chunks/{chunk-OBFKP7RI.js → chunk-MWN6TR36.js} +1 -1
  83. package/chunks/{chunk-VHJ43ZYJ.js → chunk-O7XRQWCG.js} +1 -1
  84. package/chunks/{chunk-H224LNV3.js → chunk-OYFRLT5E.js} +1 -1
  85. package/chunks/{chunk-3NWFV2YF.js → chunk-PMBGV76N.js} +1 -1
  86. package/chunks/{chunk-YFAPACDE.js → chunk-PVM4IVFL.js} +6 -6
  87. package/chunks/{chunk-7WS2EYMQ.js → chunk-PWHD4NK3.js} +1 -1
  88. package/chunks/{chunk-JZIQSEFO.js → chunk-Q54NROBX.js} +1 -1
  89. package/chunks/{chunk-FCLAPJ22.js → chunk-QE7R4DPT.js} +1 -1
  90. package/chunks/{chunk-J6TW7GNF.js → chunk-QIUTQICH.js} +1 -1
  91. package/chunks/{chunk-TWDCN5H2.js → chunk-QK63EULE.js} +1 -1
  92. package/chunks/{chunk-HZZT75LI.js → chunk-QTAC4W7J.js} +1 -1
  93. package/chunks/{chunk-P7DIAJNX.js → chunk-R7HBR4QQ.js} +1 -1
  94. package/chunks/{chunk-U2FJSKS3.js → chunk-RHEMFKMX.js} +1 -1
  95. package/chunks/{chunk-TRRY3QMM.js → chunk-RL57IU47.js} +1 -1
  96. package/chunks/{chunk-SPWDYRDH.js → chunk-S2OOQRLJ.js} +1 -1
  97. package/chunks/{chunk-QBRADQ7L.js → chunk-SWTMWNTZ.js} +1 -1
  98. package/chunks/{chunk-AZUDF52L.js → chunk-SXTKQHFZ.js} +1 -1
  99. package/chunks/{chunk-5RQRSPPD.js → chunk-T5S3MJIK.js} +1 -1
  100. package/chunks/{chunk-I3ORWQ2U.js → chunk-UDGDEIBB.js} +1 -1
  101. package/chunks/{chunk-EMDEBV33.js → chunk-UIFBF3E7.js} +1 -1
  102. package/chunks/{chunk-BGEMWNES.js → chunk-UQDPWI7D.js} +1 -1
  103. package/chunks/{chunk-I5LKOTZT.js → chunk-VON4MVIM.js} +1 -1
  104. package/chunks/{chunk-HJPO6MEW.js → chunk-W5D2T2JK.js} +1 -1
  105. package/chunks/{chunk-F6YYDRMH.js → chunk-WNGYYU67.js} +1 -1
  106. package/chunks/{chunk-S2GKUZZZ.js → chunk-WO3F62ZD.js} +1 -1
  107. package/chunks/{chunk-K7KW3ZJQ.js → chunk-WVY5Q6YY.js} +1 -1
  108. package/chunks/{chunk-GH6DPLWU.js → chunk-Y4Q667BW.js} +1 -1
  109. package/chunks/{chunk-FH74N7Y7.js → chunk-YJLMFUCS.js} +2 -2
  110. package/chunks/{chunk-C3Y2S5AM.js → chunk-YKHRCSKP.js} +1 -1
  111. package/chunks/{chunk-P4UJ7CXJ.js → chunk-YLIS36QA.js} +1 -1
  112. package/chunks/{chunk-4QIFOIBS.js → chunk-YVZ4XZRB.js} +1 -1
  113. package/chunks/{chunk-KGRD6G5J.js → chunk-Z27JJPKN.js} +1 -1
  114. package/chunks/{chunk-KOHHDB2L.js → chunk-ZCIS6MJZ.js} +1 -1
  115. package/chunks/{chunk-QNNDZYVW.js → chunk-ZHLQ222N.js} +1 -1
  116. package/chunks/{chunk-KWRZ3WJO.js → chunk-ZP7MTWMR.js} +1 -1
  117. package/chunks/{codex-subagent-executor-H44VDB5E.js → codex-subagent-executor-6OJVGF2S.js} +1 -1
  118. package/chunks/{config-utils-4X4SV4RL.js → config-utils-FI3A4QAN.js} +1 -1
  119. package/chunks/{contextCommand-4KVOHTAJ.js → contextCommand-YEBZQHG4.js} +1 -1
  120. package/chunks/{core-runtime-4RARI4NX.js → core-runtime-CFMHUAS7.js} +1 -1
  121. package/chunks/{create-sub-session-CNSRJFYG.js → create-sub-session-G26337FT.js} +1 -1
  122. package/chunks/{daemon-git-worktree-guard-6XQQPP2H.js → daemon-git-worktree-guard-ITU6NQIV.js} +1 -1
  123. package/chunks/{daemon-status-provider-PRTEQT5T.js → daemon-status-provider-CSWRGMRX.js} +1 -1
  124. package/chunks/{daemon-trust-policy-GXKJVZDU.js → daemon-trust-policy-IYD7NOGK.js} +1 -1
  125. package/chunks/{daemon-trust-policy-monitor-L2ORKHMM.js → daemon-trust-policy-monitor-OWUP5SYB.js} +1 -1
  126. package/chunks/{deferred-core-runtime-RZQFUSPX.js → deferred-core-runtime-CVCQU7O4.js} +1 -1
  127. package/chunks/{edit-W44XQCIS.js → edit-7YBQLILC.js} +1 -1
  128. package/chunks/{enterPlanMode-B456A2XO.js → enterPlanMode-L3PVSD2P.js} +1 -1
  129. package/chunks/{environment-DSGQSQFS.js → environment-BVEOYQHO.js} +1 -1
  130. package/chunks/{errors-KL725247.js → errors-VQWBGR6D.js} +1 -1
  131. package/chunks/{execution-tool-KT3EBWHG.js → execution-tool-P7CBXSGZ.js} +1 -1
  132. package/chunks/{execution-worker-LPQ4HMN4.js → execution-worker-RZXNYK4B.js} +1 -1
  133. package/chunks/{exitPlanMode-JLKS76IA.js → exitPlanMode-MBUTM3NW.js} +1 -1
  134. package/chunks/{fast-path-5UD52IHH.js → fast-path-T2FDUSHV.js} +1 -1
  135. package/chunks/{glob-LYA2H6X3.js → glob-RH7XXSYE.js} +1 -1
  136. package/chunks/{goal-tools-SHSIDLZX.js → goal-tools-K6XBCE5E.js} +1 -1
  137. package/chunks/{handleAutoUpdate-T4RE6CZN.js → handleAutoUpdate-PG7R3KPH.js} +1 -1
  138. package/chunks/{i18n-5DK327WA.js → i18n-EGTBMA3N.js} +1 -1
  139. package/chunks/{initializer-TJGE4OJA.js → initializer-RIKH4PCP.js} +1 -1
  140. package/chunks/{installationInfo-MZ62GDIC.js → installationInfo-BBADHZLD.js} +1 -1
  141. package/chunks/{interactive-mod-session-YCUBQ6RM.js → interactive-mod-session-7RDKAHZ4.js} +1 -1
  142. package/chunks/{list-4L3LYDQM.js → list-YEGWEHJX.js} +1 -1
  143. package/chunks/{llm-3JQWBZXV.js → llm-D3LHPY27.js} +4 -4
  144. package/chunks/{llm-content-generator-6UPJWPOM.js → llm-content-generator-BLTBMV66.js} +1 -1
  145. package/chunks/{loadedSettingsAdapter-STPKAFJG.js → loadedSettingsAdapter-PLGMKMFO.js} +1 -1
  146. package/chunks/{local-execution-environment-IE5BOI7Y.js → local-execution-environment-4LDKFNC4.js} +1 -1
  147. package/chunks/{loggingContentGenerator-4KKWPZJA.js → loggingContentGenerator-376R7DRI.js} +1 -1
  148. package/chunks/{manage-memory-CRV5SXZZ.js → manage-memory-2ZTIVKNU.js} +1 -1
  149. package/chunks/{managed-execution-engine-FHLEWVND.js → managed-execution-engine-5LOM3MXG.js} +1 -1
  150. package/chunks/{managed-npm-update-BRHPOKDU.js → managed-npm-update-2C5JYEXW.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-GIQKZ5BH.js → managed-runtime-attestation-worker-R2FECMZK.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-P72BT46H.js → managed-runtime-bootstrap-KPLGH4UE.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-IYCJDB5K.js → managed-runtime-session-worker-EVKNPK3V.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-ONT4V5ZG.js → managed-runtime-ssh-worker-IA4HZ3PD.js} +1 -1
  155. package/chunks/{mcp-NXCQVE2Y.js → mcp-S67IJLI6.js} +1 -1
  156. package/chunks/{model-call-collection-3DNL45M5.js → model-call-collection-6OGPDTPG.js} +1 -1
  157. package/chunks/{model-configuration-6HRNYBWV.js → model-configuration-6RWVBOQS.js} +1 -1
  158. package/chunks/{modelConfigUtils-SKBN64ZW.js → modelConfigUtils-M3TVVYAO.js} +1 -1
  159. package/chunks/{monitor-7I7Q73UR.js → monitor-ZHOFTN7N.js} +1 -1
  160. package/chunks/{nonInteractiveCli-YLYRJUBE.js → nonInteractiveCli-6SUGPTJ4.js} +1 -1
  161. package/chunks/{nonInteractiveToolExecutor-U2ASWT63.js → nonInteractiveToolExecutor-SAHBGO3A.js} +1 -1
  162. package/chunks/{notebook-edit-WAD7IQCF.js → notebook-edit-ETUOQH6G.js} +1 -1
  163. package/chunks/{omni-POUUDVU3.js → omni-HV2UBGMZ.js} +1 -1
  164. package/chunks/{openaiContentGenerator-L7X6IVPL.js → openaiContentGenerator-RZCG7E4M.js} +1 -1
  165. package/chunks/{openaiResponsesContentGenerator-7XCMFI6P.js → openaiResponsesContentGenerator-X23L5JV3.js} +1 -1
  166. package/chunks/{pidfile-MQQT2ZDA.js → pidfile-26WXQCHG.js} +1 -1
  167. package/chunks/{processUtils-OZLF72NC.js → processUtils-WXLFGNBT.js} +1 -1
  168. package/chunks/{prompt-terminal-ledger-IYUF6SUU.js → prompt-terminal-ledger-EIZZHF4A.js} +1 -1
  169. package/chunks/{qwenContentGenerator-DKH3ILUO.js → qwenContentGenerator-GOY7Y6KH.js} +1 -1
  170. package/chunks/{reactive-degrade-KSNGHMBN.js → reactive-degrade-MNMTTHO5.js} +1 -1
  171. package/chunks/{read-file-VEELW4OQ.js → read-file-OJNGPNTQ.js} +1 -1
  172. package/chunks/{resumeHistoryUtils-4SFDTBXU.js → resumeHistoryUtils-QWOWF4VY.js} +1 -1
  173. package/chunks/{review-QA6HRLVU.js → review-5S24HP2V.js} +1 -1
  174. package/chunks/{ripGrep-4J6ASSE3.js → ripGrep-Y4PY2MQF.js} +1 -1
  175. package/chunks/{run-qwen-serve-EJ67LA5O.js → run-qwen-serve-EOUUDZUK.js} +2 -2
  176. package/chunks/{runtime-6E2FSB5U.js → runtime-ZBPOQX6E.js} +1 -1
  177. package/chunks/{sandboxConfig-4VE4LNRI.js → sandboxConfig-R7KDS3P5.js} +1 -1
  178. package/chunks/{scheduled-tasks-GM5EJMK7.js → scheduled-tasks-Q6V7D6K6.js} +1 -1
  179. package/chunks/{scheduler-HOSVIIOE.js → scheduler-EBQY6BOK.js} +1 -1
  180. package/chunks/{search-memory-HEAQCHIK.js → search-memory-HX6E23JC.js} +1 -1
  181. package/chunks/{send-message-FAQ7XEZ5.js → send-message-OZCCCH2F.js} +1 -1
  182. package/chunks/{serve-VNKPOWSW.js → serve-CMGCI4BK.js} +1 -1
  183. package/chunks/{server-U2XBJLOV.js → server-7LOAKPDN.js} +3 -3
  184. package/chunks/{session-AZGROSFX.js → session-LVQYZSJE.js} +1 -1
  185. package/chunks/{session-attachments-root-6M2ECUNK.js → session-attachments-root-NWG7JOMN.js} +1 -1
  186. package/chunks/{session-execution-engine-selector-PYDVOSJF.js → session-execution-engine-selector-PHH47ZMA.js} +1 -1
  187. package/chunks/{session-pr-refresh-3IS7DLEV.js → session-pr-refresh-5IACZPCY.js} +1 -1
  188. package/chunks/{sessionService-3FWNA4ZB.js → sessionService-7PFAWLHC.js} +1 -1
  189. package/chunks/{settings-VHKT7JJC.js → settings-CPZBOHN5.js} +1 -1
  190. package/chunks/{shell-TYOPVB7H.js → shell-A7NLPS2W.js} +1 -1
  191. package/chunks/{skill-GJQIE5AX.js → skill-VGANGVOD.js} +1 -1
  192. package/chunks/{skill-settings-76NI6SF3.js → skill-settings-TSZO3X6N.js} +1 -1
  193. package/chunks/{spawnChannel-FMSYLDKB.js → spawnChannel-2JQYNQKT.js} +1 -1
  194. package/chunks/{standalone-update-BPZQDQHD.js → standalone-update-QXC3RM6I.js} +1 -1
  195. package/chunks/{start-opentui-ui-X7XYV5N3.js → start-opentui-ui-BKJ4JHVK.js} +1 -1
  196. package/chunks/{startInteractiveUI-UZDF4JUB.js → startInteractiveUI-4QIPR7ZY.js} +1 -1
  197. package/chunks/{team-create-RFZNEF76.js → team-create-5MU6BGXX.js} +1 -1
  198. package/chunks/{team-plan-approval-MGW3JGSC.js → team-plan-approval-NZUJ6FSA.js} +1 -1
  199. package/chunks/{terminal-image-renderer-3UED5GZV.js → terminal-image-renderer-CTMJULJ2.js} +1 -1
  200. package/chunks/{theme-manager-SF6FSSZW.js → theme-manager-6H7GA6QR.js} +1 -1
  201. package/chunks/{tool-call-W2CJR74U.js → tool-call-XG4CAD5X.js} +1 -1
  202. package/chunks/{tool-result-media-XSFON2ZQ.js → tool-result-media-RJ5ONO7R.js} +1 -1
  203. package/chunks/{tool-search-7GY5YTOU.js → tool-search-KBINGEWV.js} +1 -1
  204. package/chunks/{total-session-admission-OATGW6M5.js → total-session-admission-XNWYCO7G.js} +1 -1
  205. package/chunks/{trustedFolders-AM4PSGUB.js → trustedFolders-JT5MOB3A.js} +1 -1
  206. package/chunks/{update-relaunch-YKY52XUT.js → update-relaunch-HXMQI3HO.js} +1 -1
  207. package/chunks/{updateCheck-RKQ5CPZM.js → updateCheck-XWE3TWL5.js} +1 -1
  208. package/chunks/{upload-config-CBT7ARZY.js → upload-config-ET7NRHU7.js} +1 -1
  209. package/chunks/{useAutoAcceptIndicator-Z3YWPUNO.js → useAutoAcceptIndicator-TPMYKNJX.js} +1 -1
  210. package/chunks/{validateNonInterActiveAuth-7CQHU2RF.js → validateNonInterActiveAuth-U52KMEDS.js} +1 -1
  211. package/chunks/{version-N2OB6KWP.js → version-CW4RTJ3H.js} +1 -1
  212. package/chunks/{web-fetch-L5XCBCBA.js → web-fetch-UPMJ3XIZ.js} +1 -1
  213. package/chunks/{web-search-4EHUA3LJ.js → web-search-PXABWQVC.js} +1 -1
  214. package/chunks/{workflow-FGAUAYIP.js → workflow-UQ4V3NBZ.js} +1 -1
  215. package/chunks/{workflow-ancestor-trust-F7RRN6I3.js → workflow-ancestor-trust-QII5KTUJ.js} +1 -1
  216. package/chunks/{workspace-agents-QW4TKC52.js → workspace-agents-Q3KKMDX2.js} +1 -1
  217. package/chunks/{workspace-providers-status-MFSZT3YA.js → workspace-providers-status-3ASB64FB.js} +1 -1
  218. package/chunks/{workspace-registration-store-WQRDSIEI.js → workspace-registration-store-2NPD6U3B.js} +1 -1
  219. package/chunks/{workspace-registry-FXZFRSCH.js → workspace-registry-6QJKRCDR.js} +1 -1
  220. package/chunks/{workspace-runtime-coordinator-LJ5YAT3A.js → workspace-runtime-coordinator-ZXUWDQIB.js} +1 -1
  221. package/chunks/{workspace-service-U632SUWU.js → workspace-service-YPYTYYUN.js} +1 -1
  222. package/chunks/{workspace-skills-status-M7YXM3LF.js → workspace-skills-status-VTFHQ6R7.js} +1 -1
  223. package/chunks/{workspace-trust-reconciler-NLJGGI4K.js → workspace-trust-reconciler-52CZVPKH.js} +1 -1
  224. package/chunks/{write-file-BJCKSXX7.js → write-file-FDBR76G5.js} +1 -1
  225. package/chunks/{zoom-image-TLJPD4DB.js → zoom-image-MYKWCCXO.js} +1 -1
  226. package/cli.js +2 -2
  227. package/execution-worker.js +1 -1
  228. package/export-transcript-document.js +1 -1
  229. package/package.json +4 -4
  230. package/vendor/landlock-run/arm64-linux/qwen-landlock-run +0 -0
  231. package/vendor/landlock-run/x64-linux/qwen-landlock-run +0 -0
  232. package/vendor/ripgrep/arm64-darwin/rg +0 -0
  233. package/vendor/ripgrep/arm64-linux/rg +0 -0
  234. package/vendor/ripgrep/x64-darwin/rg +0 -0
  235. package/vendor/ripgrep/x64-linux/rg +0 -0
  236. package/vendor/tree-sitter/tree-sitter-bash.wasm +0 -0
  237. package/vendor/tree-sitter/tree-sitter.wasm +0 -0
  238. package/web-shell/assets/{PierreFilePreview-D9tbdFw8.js → PierreFilePreview-DGTp45Z4.js} +1 -1
  239. package/web-shell/assets/{SpreadsheetPreview-CeFAk2s-.js → SpreadsheetPreview-DVC_YVei.js} +1 -1
  240. package/web-shell/assets/{WorkspaceFileBrowser-iaURw8SR.js → WorkspaceFileBrowser-DaQNpS06.js} +1 -1
  241. package/web-shell/assets/{abnfDiagram-VCTEODGH-Z4CT1NCF.js → abnfDiagram-VCTEODGH-wJbiOoPK.js} +1 -1
  242. package/web-shell/assets/{agents-route-B7o2Rq-a.js → agents-route-DUhhA1KI.js} +1 -1
  243. package/web-shell/assets/{arc-DcHBdUJQ.js → arc-CvpNMy1d.js} +1 -1
  244. package/web-shell/assets/{architectureDiagram-5GKGNRK7-DRDhEC81.js → architectureDiagram-5GKGNRK7-DIhi3dIz.js} +1 -1
  245. package/web-shell/assets/{blockDiagram-NRAW4CY4-CYRE6WIc.js → blockDiagram-NRAW4CY4-CoeyTlVJ.js} +1 -1
  246. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CIM8N_Sj.js → c4Diagram-UCG6FXSJ-BYoK_I9M.js} +1 -1
  247. package/web-shell/assets/channel-DvtGOCg6.js +1 -0
  248. package/web-shell/assets/{chunk-2Q5K7J3B-Bbfka9Fe.js → chunk-2Q5K7J3B-BeD4GwPg.js} +1 -1
  249. package/web-shell/assets/{chunk-5VM5RSS4-C02zF3RY.js → chunk-5VM5RSS4-BpkJsB_y.js} +1 -1
  250. package/web-shell/assets/{chunk-F27PBJKO-Dn0wRD2F.js → chunk-F27PBJKO-BROEWQ1J.js} +1 -1
  251. package/web-shell/assets/{chunk-G27WJ6UU-Dwpl3l0W.js → chunk-G27WJ6UU-DA8Wtppt.js} +1 -1
  252. package/web-shell/assets/{chunk-JWPE2WC7-sQbzSoTR.js → chunk-JWPE2WC7-GqB-QFh5.js} +1 -1
  253. package/web-shell/assets/{chunk-LCL6LL3I-DNlNDtfr.js → chunk-LCL6LL3I-DIPUwYsX.js} +1 -1
  254. package/web-shell/assets/{chunk-POPQ4Y6H-BOgf1Dl3.js → chunk-POPQ4Y6H-DbnU-jxX.js} +1 -1
  255. package/web-shell/assets/{chunk-SVP7TREG-DOofWP00.js → chunk-SVP7TREG-DvH7bQ-w.js} +1 -1
  256. package/web-shell/assets/{chunk-XXDRQBXY-Bj9FxhWU.js → chunk-XXDRQBXY-DdVWVo3U.js} +1 -1
  257. package/web-shell/assets/classDiagram-DTDB5LWJ-9NR5W1rE.js +1 -0
  258. package/web-shell/assets/classDiagram-v2-JRS7N3AN-9NR5W1rE.js +1 -0
  259. package/web-shell/assets/{cose-bilkent-JH36ORCC-CUlPjyww.js → cose-bilkent-JH36ORCC-JgMKxP9H.js} +1 -1
  260. package/web-shell/assets/{cynefin-OW5HDTMX-5noArzI7.js → cynefin-OW5HDTMX-BVUpNgVm.js} +1 -1
  261. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-DELvTqmf.js → cynefinDiagram-5FMLGOSQ-CxAdk-iS.js} +1 -1
  262. package/web-shell/assets/{dagre-3AP2YEHR-CAL6Z3hL.js → dagre-3AP2YEHR-CvXWkM86.js} +1 -1
  263. package/web-shell/assets/{diagram-S7CK7UJ4-DQC2gaIi.js → diagram-S7CK7UJ4-DD_PS4nm.js} +1 -1
  264. package/web-shell/assets/{diagram-UQ7AKVKN-CkU6M-3R.js → diagram-UQ7AKVKN-EVZkTODD.js} +1 -1
  265. package/web-shell/assets/{diagram-VSXAHHWV-CvHpHwVx.js → diagram-VSXAHHWV-CGZc1pZU.js} +1 -1
  266. package/web-shell/assets/{diagram-VX7I27RA-D9l5F9iB.js → diagram-VX7I27RA-DjNql499.js} +1 -1
  267. package/web-shell/assets/{diagram-Z3DM3KII-DW-VFvYx.js → diagram-Z3DM3KII-CCa0WtmR.js} +1 -1
  268. package/web-shell/assets/{docx-preview-8MQfOGQh.js → docx-preview-DpVElxvj.js} +1 -1
  269. package/web-shell/assets/{ebnfDiagram-PWID7BFC-C0Q71wC_.js → ebnfDiagram-PWID7BFC-W2hoOJZF.js} +1 -1
  270. package/web-shell/assets/{erDiagram-SSCWMZ5O-DWDLRh1S.js → erDiagram-SSCWMZ5O-Dz5NxxEb.js} +1 -1
  271. package/web-shell/assets/{flowDiagram-A5DVABFB-CVzJnl1P.js → flowDiagram-A5DVABFB-BTMAn8b5.js} +1 -1
  272. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-B320pcgR.js → ganttDiagram-EL5Y4UJY-BaFrd5ZY.js} +1 -1
  273. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Di4uZh-J.js → gitGraphDiagram-WWUBYQGX-IlmdUqRk.js} +1 -1
  274. package/web-shell/assets/{index-Csr8Hx_O.js → index-C2ez0ZjE.js} +1 -1
  275. package/web-shell/assets/{index-C9BecA_H.js → index-Cs-XBNmB.js} +101 -101
  276. package/web-shell/assets/{infoDiagram-RXCK75RN-CbafhxET.js → infoDiagram-RXCK75RN-BHs9kpar.js} +1 -1
  277. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-DrQuIDeR.js → ishikawaDiagram-5VMMS53U-DWCEQ85v.js} +1 -1
  278. package/web-shell/assets/{journeyDiagram-EYS64GPL-BschmjBj.js → journeyDiagram-EYS64GPL-RTDAw9yc.js} +1 -1
  279. package/web-shell/assets/{kanban-definition-3QL26DDD-B7x9BU9N.js → kanban-definition-3QL26DDD-B7Nl9bq6.js} +1 -1
  280. package/web-shell/assets/{layout-BewPaOyO.js → layout-BabjFEb1.js} +1 -1
  281. package/web-shell/assets/{linear-CnLILCVp.js → linear-CZuGjuQd.js} +1 -1
  282. package/web-shell/assets/{mermaid.core-Csj9KPfJ.js → mermaid.core-CK78bIGt.js} +6 -6
  283. package/web-shell/assets/{mindmap-definition-FBJOCRG2-CIGTi5gg.js → mindmap-definition-FBJOCRG2-BbcCi_jP.js} +1 -1
  284. package/web-shell/assets/{pegDiagram-XKGWAZYB-CuWBRQzb.js → pegDiagram-XKGWAZYB-DpLQ7u8i.js} +1 -1
  285. package/web-shell/assets/{pieDiagram-E7YTZNPT-Co5ukXCE.js → pieDiagram-E7YTZNPT-BpWFVtM0.js} +1 -1
  286. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-B0hzjh6o.js → quadrantDiagram-AXDQQJYC-CGzYlaN1.js} +1 -1
  287. package/web-shell/assets/{railroadDiagram-O6MQD6OU-nhkJB0xD.js → railroadDiagram-O6MQD6OU-BNQYW-Zi.js} +1 -1
  288. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-C7NpxjVR.js → requirementDiagram-EFPCY7ZU-C4fCdIDW.js} +1 -1
  289. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CUWlnhZC.js → sankeyDiagram-P5KCCOFB-BvbbAnMA.js} +1 -1
  290. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BoykH0_J.js → sequenceDiagram-WJ2MYXX4-DGXNc6E1.js} +1 -1
  291. package/web-shell/assets/{sizeCapture-X5ZJPWSS-aF-PkSe5.js → sizeCapture-X5ZJPWSS-C4W45Xf5.js} +1 -1
  292. package/web-shell/assets/{stateDiagram-HBIQ2CUA-g5q0b922.js → stateDiagram-HBIQ2CUA-D3q0fen-.js} +1 -1
  293. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-XKoYIi05.js +1 -0
  294. package/web-shell/assets/{swimlanes-XN3QIQJK-BbASszfe.js → swimlanes-XN3QIQJK-D8n-ResR.js} +1 -1
  295. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-C7qJMSzs.js +8 -0
  296. package/web-shell/assets/{timeline-definition-24CTP7MA-AXIV0TJJ.js → timeline-definition-24CTP7MA-Cio4y1mM.js} +1 -1
  297. package/web-shell/assets/{vennDiagram-4TSXK5OY-B-E0rj1h.js → vennDiagram-4TSXK5OY-DVlg0xnc.js} +1 -1
  298. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DiOOYJ2D.js → wardleyDiagram-VM6X3IG4-CgeIsimQ.js} +1 -1
  299. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-De_z7HkS.js → xychartDiagram-S5SC5T6Z-UXjyTLnU.js} +1 -1
  300. package/web-shell/index.html +1 -1
  301. package/web-shell/sw.js +1 -1
  302. package/web-shell/assets/channel-Bwr9aS_E.js +0 -1
  303. package/web-shell/assets/classDiagram-DTDB5LWJ-BmY8Mmyo.js +0 -1
  304. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BmY8Mmyo.js +0 -1
  305. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CTOjUMow.js +0 -1
  306. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bz6ia3oL.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{BaseJsonOutputAdapter}from"./chunk-TLJHBK3A.js";import{observeHeadlessJsonToolResultWire}from"./chunk-YFAPACDE.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
3
+ import{BaseJsonOutputAdapter}from"./chunk-7RNTXEWH.js";import{observeHeadlessJsonToolResultWire}from"./chunk-PVM4IVFL.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
4
4
  `)}else{process.stdout.write(`${resultMessage.result}
5
5
  `)}}else{const json=JSON.stringify(this.messages);const frame=`${json}
6
6
  `;observeHeadlessJsonToolResultWire(this.messages,frame);process.stdout.write(frame)}}emitMessage(message){this.messages.push(message)}};export{JsonOutputAdapter};
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-PECV2VVZ.js";import{t}from"./chunk-H45OX4VY.js";import{SessionReferenceService,readManyFiles}from"./chunk-BOFD4CN3.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-RKPHDO42.js";import{shouldRunVisionBridge}from"./chunk-DR3HLUJ5.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-POUUDVU3.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-POUUDVU3.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
4
- ${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-POUUDVU3.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
3
+ import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-GI6T3RBV.js";import{t}from"./chunk-H45OX4VY.js";import{SessionReferenceService,readManyFiles}from"./chunk-AVIDPC5K.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-LDXZT3SG.js";import{shouldRunVisionBridge}from"./chunk-DR3HLUJ5.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-HV2UBGMZ.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-HV2UBGMZ.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
4
+ ${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-HV2UBGMZ.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{HistoryReplayer,JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,observeAcpToolResultProjection,truncateJsonStringPayload}from"./chunk-YFAPACDE.js";import{isA2uiToolMeta}from"./chunk-4QIFOIBS.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-RKPHDO42.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-F63ESLTI.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}return{...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}}}__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}){const updates=[];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;const replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);return{updates,replayError}}return{updates}}__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");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){const branchPoints=page.branchPointsByAssistantUuid;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]}}}}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,JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,observeAcpToolResultProjection,truncateJsonStringPayload}from"./chunk-PVM4IVFL.js";import{isA2uiToolMeta}from"./chunk-YVZ4XZRB.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-LDXZT3SG.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-F63ESLTI.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}return{...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}}}__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}){const updates=[];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;const replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);return{updates,replayError}}return{updates}}__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");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){const branchPoints=page.branchPointsByAssistantUuid;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]}}}}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{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PRIVATE_RELAUNCH_ENV_PROVENANCE,PROJECT_ENV_HARDCODED_EXCLUSIONS,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-CVMMNPLX.js";import{isWorkspaceTrusted}from"./chunk-HJPO6MEW.js";import{require_main}from"./chunk-OGI5HG6N.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{QWEN_DIR}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"QWEN_SERVER_TOKEN","LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if(parsed[key]&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
3
+ import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PRIVATE_RELAUNCH_ENV_PROVENANCE,PROJECT_ENV_HARDCODED_EXCLUSIONS,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-CVMMNPLX.js";import{isWorkspaceTrusted}from"./chunk-W5D2T2JK.js";import{require_main}from"./chunk-OGI5HG6N.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{QWEN_DIR}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"QWEN_SERVER_TOKEN","LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if(parsed[key]&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{encodeTextFileContentAsync}from"./chunk-RKPHDO42.js";import{executeSandbox}from"./chunk-BQTFBDPK.js";import{assertShellSandboxCwd}from"./chunk-PPHCG6Q5.js";import{sandboxAsset}from"./chunk-3X7DP5W3.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
3
+ import{encodeTextFileContentAsync}from"./chunk-LDXZT3SG.js";import{executeSandbox}from"./chunk-BQTFBDPK.js";import{assertShellSandboxCwd}from"./chunk-PPHCG6Q5.js";import{sandboxAsset}from"./chunk-3X7DP5W3.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
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{registerCleanup}from"./chunk-V2JZO5MS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
3
+ import{registerCleanup}from"./chunk-7DSJE3CL.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
4
4
  `)}}});const enabled=process.env["QWEN_CODE_CPU_PROFILE"]==="1";if(!enabled)return;void startCpuProfile().then(result=>{if(!result.ok){process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
5
5
  `)}})}__name(initCpuProfiler,"initCpuProfiler");async function startCpuProfile(opts){if(state!=="idle"){return{ok:false,error:state==="recording"?"CPU profiling is already in progress.":"CPU profiler is currently stopping. Please wait a moment and try again."}}state="recording";try{const inspectorSession=await getOrCreateSession();await inspectorSession.post("Profiler.enable");await inspectorSession.post("Profiler.setSamplingInterval",{interval:opts?.samplingInterval??DEFAULT_SAMPLING_INTERVAL_US});await inspectorSession.post("Profiler.start");return{ok:true}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(startCpuProfile,"startCpuProfile");async function stopCpuProfile(options){if(state!=="recording"){return{ok:false,error:state==="idle"?"CPU profiler is not recording.":"CPU profiler is already stopping."}}const outputDir=options?.outputDir??defaultOutputDir();const now=options?.now??new Date;const rateLimitMs=options?.rateLimitMs??RATE_LIMIT_MS;const maxProfiles=options?.maxProfiles??MAX_PROFILES;try{enforceRateLimit(outputDir,now,rateLimitMs)}catch(error){state="idle";if(session){session.post("Profiler.stop").catch(()=>{});session.post("Profiler.disable").catch(()=>{})}disconnectSession();return{ok:false,error:formatError(error)}}state="stopping";try{if(!session){throw new Error("Inspector session lost unexpectedly during Profiler.stop; the profile data could not be retrieved.")}const result=await session.post("Profiler.stop");if(!result.profile){throw new Error("V8 Profiler.stop returned an empty profile; recording may have been interrupted.")}await session.post("Profiler.disable");fs.mkdirSync(outputDir,{recursive:true,mode:448});try{fs.chmodSync(outputDir,448)}catch{}checkDiskSpace(outputDir);const filePath=path.join(outputDir,`qwen-code-cpu-${process.pid}-${formatTimestamp(now)}.cpuprofile`);try{fs.writeFileSync(filePath,JSON.stringify(result.profile),{mode:384})}catch(writeError){try{fs.rmSync(filePath,{force:true})}catch{}throw writeError}recordWrite(outputDir,now);cleanupOldProfiles(outputDir,maxProfiles);state="idle";return{ok:true,filePath}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(stopCpuProfile,"stopCpuProfile");function isCpuProfileRecording(){return state==="recording"}__name(isCpuProfileRecording,"isCpuProfileRecording");function registerSignalHandler(){if(signalHandlerRegistered)return;if(process.platform==="win32")return;signalHandlerRegistered=true;process.on("SIGUSR1",handleSigusr1)}__name(registerSignalHandler,"registerSignalHandler");function defaultOutputDir(){return path.join(os.homedir(),".qwen","cpu-profiles")}__name(defaultOutputDir,"defaultOutputDir");function formatTimestamp(now){return now.toISOString().replace(/[:.]/g,"-")}__name(formatTimestamp,"formatTimestamp");function formatError(error){return error instanceof Error?error.message:String(error)}__name(formatError,"formatError");var sessionFactory=null;async function getOrCreateSession(){if(session)return session;if(sessionFactory){session=await sessionFactory();return session}const inspectorModule=await import("node:inspector/promises");const newSession=new inspectorModule.Session;newSession.connect();session=newSession;return session}__name(getOrCreateSession,"getOrCreateSession");function disconnectSession(){if(session){try{session.disconnect()}catch{}session=null}}__name(disconnectSession,"disconnectSession");function handleSigusr1(){if(state==="idle"){void startCpuProfile().then(result=>{if(result.ok){process.stderr.write(`[cpu-profiler] Recording started (PID ${process.pid}). Send SIGUSR1 again to stop.
6
6
  `)}else{process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}