@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{fireSessionDeleteHook}from"./chunk-F64AWDLW.js";import{reportChatRecordingFailureToAdapter}from"./chunk-RYKFI4N2.js";import{MAX_SUGGESTIONS_TO_SHOW,SESSION_MENTION_PREFIX,buildMcpResourceRef,buildMcpServerRef,buildSessionRef,getExtensionSuggestions,matchMcpServerPrefix,normalizeDescription}from"./chunk-4322TZID.js";import{StreamJsonOutputAdapter}from"./chunk-TLJHBK3A.js";import{getTranslatedSourceDisplayMap}from"./chunk-7AYXAVTZ.js";import{BaseSelectionList,Colors,RadioButtonSelect,RowMouseController,TextInput,dist_default,findElementAtMouseEvent,useMouseEvents,useTerminalSize}from"./chunk-RN6JS263.js";import{ICON,SHELL_COMMAND_NAME}from"./chunk-HZZT75LI.js";import{useKeypress}from"./chunk-3ULVEPFO.js";import{getInteractiveModSession}from"./chunk-Y7YDHCON.js";import{theme}from"./chunk-OWCYARAS.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{Box_default,Text}from"./chunk-XZQH4UBR.js";import{require_react}from"./chunk-5QKDV4CD.js";import{themeManager}from"./chunk-W3YCOEIP.js";import{appEvents}from"./chunk-CATL2PQS.js";import{getCachedStringWidth,toCodePoints}from"./chunk-MOH67CDU.js";import{AGENT_HOST_SESSION_SOURCE_TYPE,AGENT_SESSION_SOURCE_TYPE}from"./chunk-DHYCGKLG.js";import{createLoadedSettingsAdapter}from"./chunk-QBRADQ7L.js";import{loadMcpApprovals}from"./chunk-DMCTJUIJ.js";import{SettingScope,settingExistsInScope}from"./chunk-DFRSQK5Q.js";import{getCurrentLanguage,t,ta}from"./chunk-H45OX4VY.js";import{FileSearchFactory,INITIAL_FOLLOWUP_STATE,Logger,createFollowupController,discoverProviderModels,generateSessionRecap,preserveModelProviderPlaceholders}from"./chunk-BOFD4CN3.js";import{executeModTool,modToolRequest}from"./chunk-5RQRSPPD.js";import{CoreToolScheduler,SessionService,allowEditorTypeInSandbox,checkHasEditorType,compactToolResultDisplayForHistory,didWriteProjectContextFile,executeRuntimeShell,isGatedMcpScope,refreshMemoryAfterManagedWrite,refreshMemoryInstruction}from"./chunk-RKPHDO42.js";import{TERMINAL_CSI_REGEX,TERMINAL_OSC_REGEX,TERMINAL_SHIFT_DCS_REGEX,stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{resolveBranchName,watchRepoBranch}from"./chunk-LLX4BCWK.js";import{isSignalTermination}from"./chunk-3X7DP5W3.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-7J2TOJMG.js";import{qwenOAuth2Events,sanitizeForOsc}from"./chunk-I5TFTKQS.js";import{applyProviderInstallPlan,buildInstallPlan,getDefaultBaseUrlForProtocol,getDefaultModelIds,getModelsForProviderProtocol,resolveBaseUrl,shouldShowStep}from"./chunk-XYBEQRSZ.js";import{AuthEvent,PromptSuggestionEvent,logAuth,logPromptSuggestion}from"./chunk-DR3HLUJ5.js";import{REASONING_EFFORT_TIERS}from"./chunk-TAAJ7TDB.js";import{isBinary}from"./chunk-4YLXNRRH.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{escapePath}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 DEFAULT_WINDOW_TITLE="qwen";var MULTIPLEXER_ENV_KEYS=["TMUX","STY","ZELLIJ","DVTM"];function sanitizeWindowTitle(title){return sanitizeForOsc(title)}__name(sanitizeWindowTitle,"sanitizeWindowTitle");function computeWindowTitle(folderName){return sanitizeWindowTitle(process.env["CLI_TITLE"]||`Qwen - ${folderName||DEFAULT_WINDOW_TITLE}`)}__name(computeWindowTitle,"computeWindowTitle");function writeTerminalTitle(write,title){const clean=sanitizeWindowTitle(title);if(process.platform==="win32"){process.title=clean}const inMultiplexer=MULTIPLEXER_ENV_KEYS.some(k=>!!process.env[k]);if(clean.length===0){if(inMultiplexer){write("\x1B]2;\x07")}else{write("\x1B]0;\x07\x1B]2;\x07")}return}if(inMultiplexer){write(`\x1B]2;${clean}\x07`)}else{const padded=clean.substring(0,80).padEnd(80," ");write(`\x1B]0;${padded}\x07\x1B]2;${padded}\x07`)}}__name(writeTerminalTitle,"writeTerminalTitle");function formatSessionWindowTitle(sessionName,folderName,statusPrefix=""){const base=sessionName?sanitizeWindowTitle(sessionName):computeWindowTitle(folderName);return sanitizeWindowTitle(statusPrefix+base)}__name(formatSessionWindowTitle,"formatSessionWindowTitle");function titleStatusPrefix(streamingState){switch(streamingState){case"responding":return`${ICON.CIRCLE_LEFT_HALF} `;case"waiting_for_confirmation":return`${ICON.SPARKLE} `;default:return""}}__name(titleStatusPrefix,"titleStatusPrefix");init_esbuild_shims();var import_react=__toESM(require_react(),1);var useLogger=__name((storage,sessionId)=>{const[logger2,setLogger]=(0,import_react.useState)(null);(0,import_react.useEffect)(()=>{if(!sessionId){return}let cancelled=false;const newLogger=new Logger(sessionId,storage);newLogger.initialize().then(()=>{if(!cancelled){setLogger(newLogger)}}).catch(()=>{});return()=>{cancelled=true}},[storage,sessionId]);return logger2},"useLogger");init_esbuild_shims();var import_react2=__toESM(require_react(),1);var DEFAULT_AWAY_THRESHOLD_MINUTES=5;var MIN_USER_MESSAGES_TO_FIRE=3;var MIN_USER_MESSAGES_SINCE_LAST_RECAP=2;function shouldFireRecap(history){let userMessageCount=0;let lastRecapIndex=-1;for(let i=0;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userMessageCount++;if(item.type==="away_recap")lastRecapIndex=i}if(userMessageCount<MIN_USER_MESSAGES_TO_FIRE)return false;if(lastRecapIndex===-1)return true;let userSinceLast=0;for(let i=lastRecapIndex+1;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userSinceLast++}return userSinceLast>=MIN_USER_MESSAGES_SINCE_LAST_RECAP}__name(shouldFireRecap,"shouldFireRecap");function useAwaySummary(options){const{enabled,config,isFocused,isIdle,addItem,history,awayThresholdMinutes}=options;const blurredAtRef=(0,import_react2.useRef)(null);const recapPendingRef=(0,import_react2.useRef)(false);const inFlightRef=(0,import_react2.useRef)(null);const isIdleRef=(0,import_react2.useRef)(isIdle);isIdleRef.current=isIdle;const historyRef=(0,import_react2.useRef)(history);historyRef.current=history;const thresholdMs=(awayThresholdMinutes&&awayThresholdMinutes>0?awayThresholdMinutes:DEFAULT_AWAY_THRESHOLD_MINUTES)*60*1e3;(0,import_react2.useEffect)(()=>{if(!enabled||!config){inFlightRef.current?.abort();inFlightRef.current=null;blurredAtRef.current=null;return}if(!isFocused){if(blurredAtRef.current===null){blurredAtRef.current=Date.now()}return}const blurredAt=blurredAtRef.current;if(blurredAt===null)return;if(Date.now()-blurredAt<thresholdMs){blurredAtRef.current=null;return}if(recapPendingRef.current)return;if(!isIdleRef.current)return;if(!shouldFireRecap(historyRef.current)){blurredAtRef.current=null;return}blurredAtRef.current=null;recapPendingRef.current=true;const controller=new AbortController;inFlightRef.current=controller;const mods=getInteractiveModSession(config);const recap=mods?mods.ready.then(()=>controller.signal.aborted||!isIdleRef.current?null:generateSessionRecap(config,controller.signal)).catch(()=>null):generateSessionRecap(config,controller.signal);void recap.then(recap2=>{if(controller.signal.aborted||!recap2)return;if(!isIdleRef.current)return;const item={type:"away_recap",text:recap2};addItem(item,Date.now());try{config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/recap",outputHistoryItems:[{...item}]})}catch{}}).finally(()=>{if(inFlightRef.current===controller){inFlightRef.current=null}recapPendingRef.current=false})},[enabled,config,isFocused,isIdle,addItem,thresholdMs]);(0,import_react2.useEffect)(()=>()=>{inFlightRef.current?.abort()},[])}__name(useAwaySummary,"useAwaySummary");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var BRANCH_POLL_INTERVAL_MS=5e3;var primedBranchNames=new Map;async function primeGitBranchName(cwd){primedBranchNames.set(cwd,await resolveBranchName(cwd))}__name(primeGitBranchName,"primeGitBranchName");function useGitBranchName(cwd){const[branchName,setBranchName]=(0,import_react3.useState)(()=>primedBranchNames.get(cwd));const branchNameRef=(0,import_react3.useRef)(branchName);branchNameRef.current=branchName;(0,import_react3.useEffect)(()=>{let cancelled=false;let dispose;let pollTimer;let refreshGeneration=0;const refresh=__name(async()=>{const generation=++refreshGeneration;const name=await resolveBranchName(cwd);if(!cancelled&&generation===refreshGeneration&&name!==branchNameRef.current){setBranchName(name)}},"refresh");const init=__name(async()=>{await refresh();if(cancelled)return;const disposer=await watchRepoBranch(cwd,()=>{void refresh().catch(()=>{})});if(cancelled){disposer()}else{dispose=disposer}if(!cancelled){pollTimer=setInterval(()=>{void refresh().catch(()=>{})},BRANCH_POLL_INTERVAL_MS);pollTimer.unref?.()}},"init");void init().catch(()=>{});return()=>{cancelled=true;dispose?.();if(pollTimer)clearInterval(pollTimer)}},[cwd]);return branchName}__name(useGitBranchName,"useGitBranchName");init_esbuild_shims();import{createWriteStream,fstatSync,openSync,constants}from"node:fs";init_esbuild_shims();var debugLogger=createDebugLogger("DUAL_OUTPUT");var SUPPORTED_EVENTS=["system","user","assistant","stream_event","result","control_request","control_response"];var DUAL_OUTPUT_PROTOCOL_VERSION=2;var MAX_BUFFERED_BYTES=1024*1024;var DualOutputBridge=class{static{__name(this,"DualOutputBridge")}adapter;stream;sessionId;active=true;shutdownPromise=null;unsubscribeRecordingFailure;constructor(config,target,options={}){this.sessionId=config.getSessionId();if("fd"in target){if(target.fd<=2){throw new Error(`--json-fd ${target.fd}: file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) are reserved. Use fd 3 or higher.`)}try{fstatSync(target.fd)}catch{throw new Error(`--json-fd ${target.fd}: file descriptor is not open. The caller must provide this fd via spawn stdio configuration or shell redirection (e.g., 3>/tmp/events.jsonl).`)}this.stream=createWriteStream("",{fd:target.fd})}else{try{const fd=openSync(target.filePath,constants.O_WRONLY|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(err){const code=err.code;if(code==="ENXIO"){try{const fd=openSync(target.filePath,constants.O_RDWR|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(retryErr){if(retryErr.code==="EACCES"){throw new Error(`--json-file "${target.filePath}": permission denied opening FIFO for read-write. Check read/write permissions on the file and its parent directories, or start a reader before launching Qwen Code.`)}throw retryErr}}else if(code==="ENOENT"){this.stream=createWriteStream(target.filePath,{flags:"w"})}else{throw err}}}this.stream.on("error",err=>{const code=err.code;if(code==="EPIPE"||code==="ERR_STREAM_DESTROYED"){debugLogger.warn("DualOutput: consumer disconnected, disabling")}else if(code==="ERR_SYSTEM_ERROR"){debugLogger.warn("DualOutput: system error on stream, disabling:",err.message)}else{debugLogger.error("DualOutput stream error:",err)}this.active=false});this.adapter=new StreamJsonOutputAdapter(config,true,this.stream);this.unsubscribeRecordingFailure=typeof config.onChatRecordingFailure==="function"?config.onChatRecordingFailure(event=>{this.emitRecordingFailure(event)}):()=>{};try{this.adapter.emitSystemMessage("session_start",{session_id:this.sessionId,cwd:process.cwd(),protocol_version:DUAL_OUTPUT_PROTOCOL_VERSION,version:options.version,supported_events:[...SUPPORTED_EVENTS]})}catch(err){debugLogger.error("DualOutput session_start error:",err);this.active=false}}processEvent(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.processEvent(event)}catch(err){debugLogger.error("DualOutput processEvent error:",err);this.active=false}}startAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.startAssistantMessage()}catch(err){debugLogger.error("DualOutput startAssistantMessage error:",err);this.active=false}}finalizeAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.finalizeAssistantMessage()}catch(err){debugLogger.error("DualOutput finalizeAssistantMessage error:",err);this.active=false}}emitUserMessage(parts){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitUserMessage(parts)}catch(err){debugLogger.error("DualOutput emitUserMessage error:",err);this.active=false}}emitToolResult(request,response){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitToolResult(request,response)}catch(err){debugLogger.error("DualOutput emitToolResult error:",err);this.active=false}}get isConnected(){return this.active}disableIfBufferOverflowed(){if(this.stream.writableLength>MAX_BUFFERED_BYTES){debugLogger.warn("DualOutput: buffered data exceeds limit, disabling (no consumer draining?)");this.active=false;this.stream.destroy()}}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath,permissionSuggestions)}catch(err){debugLogger.error("DualOutput emitPermissionRequest error:",err);this.active=false}}emitControlResponse(requestId,allowed){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlResponse(requestId,allowed)}catch(err){debugLogger.error("DualOutput emitControlResponse error:",err);this.active=false}}emitControlError(requestId,message){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlError(requestId,message)}catch(err){debugLogger.error("DualOutput emitControlError error:",err);this.active=false}}emitSystemMessage(subtype,data){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitSystemMessage(subtype,data)}catch(err){debugLogger.error("DualOutput emitSystemMessage error:",err);this.active=false}}emitRecordingFailure(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{reportChatRecordingFailureToAdapter(this.adapter,event)}catch(err){debugLogger.error("DualOutput recording failure output error:",err);this.active=false}}shutdown(){if(this.shutdownPromise)return this.shutdownPromise;this.unsubscribeRecordingFailure();if(this.active){try{this.adapter.emitSystemMessage("session_end",{session_id:this.sessionId})}catch{}}this.active=false;this.shutdownPromise=new Promise(resolve2=>{if(this.stream.closed||this.stream.destroyed){resolve2();return}const cleanup=__name(()=>{this.stream.off("close",onClose);this.stream.off("error",onError)},"cleanup");const onClose=__name(()=>{cleanup();resolve2()},"onClose");const onError=__name(err=>{debugLogger.debug("DualOutput: stream error during shutdown:",err)},"onError");this.stream.once("close",onClose);this.stream.once("error",onError);try{this.stream.end()}catch(err){cleanup();debugLogger.debug("DualOutput: stream end error during shutdown:",err);resolve2()}});return this.shutdownPromise}};init_esbuild_shims();import{createHash}from"node:crypto";import{closeSync,createReadStream,openSync as openSync2,readSync,statSync,unwatchFile,watchFile}from"node:fs";import{createInterface}from"node:readline";var debugLogger2=createDebugLogger("REMOTE_INPUT");var RemoteInputWatcher=class{static{__name(this,"RemoteInputWatcher")}submitFn=null;confirmationHandler=null;queue=[];processing=false;active=true;bytesRead=0;consumedPrefixHash=null;reading=false;filePath;retryTimer=null;pollIntervalMs;constructor(filePath,options){this.filePath=filePath;this.pollIntervalMs=options?.pollIntervalMs??500;this.startWatching()}setSubmitFn(fn){this.submitFn=fn;this.processQueue()}setConfirmationHandler(fn){this.confirmationHandler=fn}notifyIdle(){if(this.queue.length>0&&!this.processing){this.processQueue()}}startWatching(){try{const stat=statSync(this.filePath);this.bytesRead=stat.size;this.consumedPrefixHash=this.hashFilePrefix(this.bytesRead)}catch{this.bytesRead=0;this.consumedPrefixHash=null}watchFile(this.filePath,{interval:this.pollIntervalMs},()=>{if(!this.active)return;this.readNewLines()});debugLogger2.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let currentSize;try{const stat=statSync(this.filePath);currentSize=stat.size}catch{return Promise.resolve()}if(currentSize<this.bytesRead){debugLogger2.debug("RemoteInput: input file shrank, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}else if(this.hasConsumedPrefixChanged()){debugLogger2.debug("RemoteInput: input file prefix changed, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}if(currentSize<=this.bytesRead)return Promise.resolve();const consumeUntil=this.findLastCompleteRecordEnd(this.bytesRead,currentSize);if(consumeUntil===null){return Promise.resolve()}const nextConsumedPrefixHash=this.hashFilePrefix(consumeUntil);this.reading=true;const stream=createReadStream(this.filePath,{start:this.bytesRead,end:consumeUntil-1,encoding:"utf-8"});const rl=createInterface({input:stream,crlfDelay:Infinity});rl.on("line",line=>{const trimmed=line.trim();if(!trimmed)return;try{const cmd=JSON.parse(trimmed);if(cmd&&cmd.type==="confirmation_response"&&typeof cmd.request_id==="string"&&typeof cmd.allowed==="boolean"){debugLogger2.debug(`RemoteInput: confirmation_response for ${cmd.request_id} (allowed=${cmd.allowed})`);this.confirmationHandler?.(cmd.request_id,cmd.allowed)}else if(cmd&&cmd.type==="submit"&&typeof cmd.text==="string"){debugLogger2.debug(`RemoteInput: queued command: ${cmd.text.slice(0,50)}...`);this.queue.push(cmd)}else{debugLogger2.warn(`RemoteInput: unknown command type: ${String(cmd?.type)}`)}}catch(_err){debugLogger2.warn(`RemoteInput: failed to parse line: ${trimmed}`)}});return new Promise(resolve2=>{rl.on("close",()=>{this.bytesRead=consumeUntil;if(nextConsumedPrefixHash!==null){this.consumedPrefixHash=nextConsumedPrefixHash}this.reading=false;this.processQueue();resolve2()})})}findLastCompleteRecordEnd(start,end){if(end<=start)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const buffer=Buffer.allocUnsafe(Math.min(64*1024,end-start));let remaining=end-start;let position=start;let lastLineBreak=-1;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)break;for(let i=0;i<bytesRead;i++){if(buffer[i]===10){lastLineBreak=position+i}}remaining-=bytesRead;position+=bytesRead}return lastLineBreak>=start?lastLineBreak+1:null}catch(err){debugLogger2.warn("RemoteInput: failed to scan complete records:",err);return null}finally{if(fd!==null){closeSync(fd)}}}hasConsumedPrefixChanged(){if(this.bytesRead===0){return false}if(this.consumedPrefixHash===null){debugLogger2.warn("RemoteInput: missing consumed prefix hash, resetting read offset");return true}const currentHash=this.hashFilePrefix(this.bytesRead);if(currentHash===null){debugLogger2.warn("RemoteInput: failed to hash consumed prefix, resetting read offset");return true}return currentHash!==this.consumedPrefixHash}hashFilePrefix(size){if(size<=0)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const hash=createHash("sha256");const buffer=Buffer.allocUnsafe(Math.min(64*1024,size));let remaining=size;let position=0;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)return null;hash.update(buffer.subarray(0,bytesRead));remaining-=bytesRead;position+=bytesRead}return hash.digest("base64")}catch(err){debugLogger2.warn("RemoteInput: failed to hash file prefix:",err);return null}finally{if(fd!==null){closeSync(fd)}}}async processQueue(){if(this.processing||!this.submitFn||this.queue.length===0)return;this.processing=true;if(this.retryTimer){clearTimeout(this.retryTimer);this.retryTimer=null}try{while(this.queue.length>0&&this.active){if(!this.submitFn)break;const cmd=this.queue[0];debugLogger2.debug(`RemoteInput: submitting: ${cmd.text.slice(0,50)}...`);try{const result=await this.submitFn(cmd.text);if(result===false){debugLogger2.debug("RemoteInput: TUI busy, will retry on idle");this.scheduleRetry();break}this.queue.shift()}catch(err){debugLogger2.error("RemoteInput: submit failed:",err);this.queue.shift()}if(this.queue.length>0){await new Promise(r=>setTimeout(r,500))}}}finally{this.processing=false}}scheduleRetry(){if(this.retryTimer)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null;if(this.queue.length>0&&!this.processing){this.processQueue()}},2e3)}shutdown(){this.active=false;unwatchFile(this.filePath);if(this.retryTimer)clearTimeout(this.retryTimer);this.queue.length=0;debugLogger2.debug("RemoteInput: shut down")}};init_esbuild_shims();async function observeInteractiveModTool(config,call,refreshContextFilesOnWrite){if(call.request.isClientInitiated)return;const succeeded=call.response.executionStatus==="success";if(call.status!=="cancelled"||succeeded){config.getLlmClient()?.recordCompletedToolCall(call.request.name,call.request.args)}const candidates=[{toolName:call.request.name,args:call.request.args,status:succeeded?"success":"error"}];const refreshed=await refreshMemoryAfterManagedWrite(config,candidates,{logContext:"interactive Mod native attempt"});if(!refreshed&&succeeded&&(call.request.name==="save_memory"||refreshContextFilesOnWrite&&didWriteProjectContextFile(candidates,config.getProjectRoot()))){await refreshMemoryInstruction(config,{logContext:"interactive Mod native attempt"})}}__name(observeInteractiveModTool,"observeInteractiveModTool");init_esbuild_shims();function logicalCompletion(request,response,completed){if(completed?.status==="cancelled")return{...completed,request,response,nativeAttemptsObserved:true};if(response.error)return{...completed,status:"error",request,response,nativeAttemptsObserved:true};return{...completed,status:"success",request,response,nativeAttemptsObserved:true}}__name(logicalCompletion,"logicalCompletion");var logger=createDebugLogger("INTERACTIVE_MOD_TOOLS");var InteractiveModToolScheduler=class{constructor(options){this.options=options;this.native=new CoreToolScheduler(options)}static{__name(this,"InteractiveModToolScheduler")}native;tail=Promise.resolve();displayOwner;schedule(request,signal,runtimeView){const session=getInteractiveModSession(this.options.config);const requests=Array.isArray(request)?request:[request];if(!session||requests.every(item=>item.isClientInitiated)){return this.native.schedule(request,signal,runtimeView)}const owner=captureHookExecutionOwner(this.options.config);const sessionSignal=session.captureToolSignal();const active=AbortSignal.any([signal,sessionSignal]);const displayOwner={};const clearDisplay=__name(()=>{if(this.displayOwner!==displayOwner)return;this.displayOwner=void 0;this.options.onToolCallsUpdate?.([])},"clearDisplay");sessionSignal.addEventListener("abort",clearDisplay,{once:true});let delivered=false;const task=this.tail.then(()=>runWithHookExecutionOwner(owner,async()=>{await new Promise((resolve2,reject)=>{const cancel=__name(()=>reject(active.reason),"cancel");if(active.aborted)return cancel();active.addEventListener("abort",cancel,{once:true});void session.ready.then(()=>{active.removeEventListener("abort",cancel);resolve2()},error=>{active.removeEventListener("abort",cancel);reject(error)})});active.throwIfAborted();const middleware=session.toolCall();if(!middleware)return this.native.schedule(request,active,runtimeView);const calls=requests.map(item=>({status:"scheduled",request:item,nativeAttemptsObserved:true}));const attemptUpdates=new Map;const publish=__name(()=>{if(!sessionSignal.aborted){this.displayOwner=displayOwner;this.options.onToolCallsUpdate?.(calls.flatMap((call,index)=>attemptUpdates.get(index)??[call]))}},"publish");publish();for(let index=0;index<requests.length;index++){const original=requests[index];let last;const execute=__name((nativeRequest,nativeSignal,check)=>new Promise((resolve2,reject)=>{nativeSignal.throwIfAborted();active.throwIfAborted();const attemptSignal=AbortSignal.any([active,nativeSignal]);attemptUpdates.delete(index);publish();const scheduler=new CoreToolScheduler({...this.options,chatRecordingService:void 0,modToolCheck:check,outputUpdateHandler:__name((id,chunk)=>{if(!attemptSignal.aborted)this.options.outputUpdateHandler?.(id,chunk)},"outputUpdateHandler"),onToolCallsUpdate:__name(updates=>{if(attemptSignal.aborted||!updates.length)return;attemptUpdates.set(index,updates.map(current=>{if(current.request.callId!==nativeRequest.callId)return current;if(current.status==="success"||current.status==="error"||current.status==="cancelled"){return{status:"scheduled",request:original,nativeAttemptsObserved:true}}return{...current,nativeAttemptsObserved:true}}));publish()},"onToolCallsUpdate"),onAllToolCallsComplete:__name(async completed=>{last=completed[0];attemptUpdates.delete(index);publish();try{if(!sessionSignal.aborted)await this.options.onNativeAttempt?.(last);resolve2(last)}catch(error){logger.warn(`Native tool observation failed: ${String(error)}`);resolve2(last)}},"onAllToolCallsComplete")});void runWithHookExecutionOwner(owner,()=>scheduler.schedule(nativeRequest,attemptSignal,runtimeView)).catch(reject)}),"execute");try{active.throwIfAborted();const execution=!original.isClientInitiated&&await modToolRequest(this.options.config,original);const result=execution?await executeModTool(original,execution,middleware,execute,active):{completed:await execute(original,active),response:void 0};const response=result.response??result.completed.response;const completed=result.completed;calls[index]=logicalCompletion(original,response,completed)}catch(error){const message=active.aborted?"Tool call cancelled.":`Mod tool scheduling failed: ${String(error)}`;calls[index]={...last,status:active.aborted?"cancelled":"error",request:original,response:{callId:original.callId,responseParts:[{functionResponse:{id:original.callId,name:original.name,response:{error:message}}}],error:new Error(message),errorType:void 0,resultDisplay:message,executionStatus:last?.response.executionStatus??"not_started",contentLength:message.length},nativeAttemptsObserved:true}}publish()}sessionSignal.throwIfAborted();clearDisplay();delivered=true;await this.options.onAllToolCallsComplete(calls.filter(call=>call.status==="success"||call.status==="error"||call.status==="cancelled"))}));const settled=task.catch(async error=>{if(delivered||sessionSignal.aborted)throw error;clearDisplay();delivered=true;await this.options.onAllToolCallsComplete(requests.map(item=>({status:active.aborted?"cancelled":"error",request:item,nativeAttemptsObserved:true,response:{callId:item.callId,error:new Error(String(error)),errorType:void 0,executionStatus:"not_started",resultDisplay:String(error),responseParts:[{functionResponse:{id:item.callId,name:item.name,response:{error:String(error)}}}]}})))});const drained=settled.finally(()=>{sessionSignal.removeEventListener("abort",clearDisplay)});this.tail=drained.catch(()=>{});return drained}};init_esbuild_shims();var calculatePromptWidths=__name(terminalWidth=>{const widthFraction=.9;const FRAME_PADDING_AND_BORDER=4;const PROMPT_PREFIX_WIDTH=2;const MIN_CONTENT_WIDTH=2;const innerContentWidth=Math.floor(terminalWidth*widthFraction)-FRAME_PADDING_AND_BORDER-PROMPT_PREFIX_WIDTH;const inputWidth=Math.max(MIN_CONTENT_WIDTH,innerContentWidth);const FRAME_OVERHEAD=FRAME_PADDING_AND_BORDER+PROMPT_PREFIX_WIDTH;const containerWidth=inputWidth+FRAME_OVERHEAD;const suggestionsWidth=Math.max(20,Math.floor(terminalWidth*1));return{inputWidth,containerWidth,suggestionsWidth,frameOverhead:FRAME_OVERHEAD}},"calculatePromptWidths");var MAIN_CONTENT_HEIGHT_RESERVATION=2;var STATIC_EXTRA_HEIGHT=3;var clampDialogHeight=__name(height=>height===void 0?void 0:Math.max(1,Math.floor(height)),"clampDialogHeight");var getDialogMaxHeight=__name((terminalHeight,staticExtraHeight)=>Math.max(1,terminalHeight-staticExtraHeight-MAIN_CONTENT_HEIGHT_RESERVATION),"getDialogMaxHeight");init_esbuild_shims();var import_react5=__toESM(require_react(),1);init_esbuild_shims();var import_react4=__toESM(require_react(),1);var useQwenAuth=__name((pendingAuthType,isAuthenticating)=>{const[qwenAuthState,setQwenAuthState]=(0,import_react4.useState)({deviceAuth:null,authStatus:"idle",authMessage:null});const isQwenAuth=pendingAuthType==="qwen-oauth";(0,import_react4.useEffect)(()=>{if(!isQwenAuth||!isAuthenticating){setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null});return}setQwenAuthState(prev=>({...prev,authStatus:"idle"}));const handleDeviceAuth=__name(deviceAuth=>{setQwenAuthState(prev=>({...prev,deviceAuth:{verification_uri:deviceAuth.verification_uri,verification_uri_complete:deviceAuth.verification_uri_complete,user_code:deviceAuth.user_code,expires_in:deviceAuth.expires_in,device_code:deviceAuth.device_code},authStatus:"polling"}))},"handleDeviceAuth");const handleAuthProgress=__name((status,message)=>{setQwenAuthState(prev=>({...prev,authStatus:status,authMessage:message||null}))},"handleAuthProgress");qwenOAuth2Events.on("auth-uri",handleDeviceAuth);qwenOAuth2Events.on("auth-progress",handleAuthProgress);return()=>{qwenOAuth2Events.off("auth-uri",handleDeviceAuth);qwenOAuth2Events.off("auth-progress",handleAuthProgress)}},[isQwenAuth,isAuthenticating]);const cancelQwenAuth=(0,import_react4.useCallback)(()=>{qwenOAuth2Events.emit("auth-cancel");setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null})},[]);return{qwenAuthState,cancelQwenAuth}},"useQwenAuth");function normalizeModelIds(modelIdsInput){return modelIdsInput.split(",").map(id=>id.trim()).filter((id,index,array)=>id.length>0&&array.indexOf(id)===index)}__name(normalizeModelIds,"normalizeModelIds");function maskApiKey(apiKey){const trimmed=apiKey.trim();if(trimmed.length===0)return"(not set)";if(trimmed.length<=6)return"***";return`${trimmed.slice(0,3)}...${trimmed.slice(-4)}`}__name(maskApiKey,"maskApiKey");var useAuthCommand=__name((settings,config,addItem,onAuthChange)=>{const unAuthenticated=config.getAuthType()===void 0;const[authState,setAuthState]=(0,import_react5.useState)(unAuthenticated?"updating":"unauthenticated");const[authError,setAuthError]=(0,import_react5.useState)(null);const[isAuthenticating,setIsAuthenticating]=(0,import_react5.useState)(false);const[isAuthDialogOpen,setIsAuthDialogOpen]=(0,import_react5.useState)(unAuthenticated);const[pendingAuthType,setPendingAuthType]=(0,import_react5.useState)(void 0);const[externalAuthState,setExternalAuthState]=(0,import_react5.useState)(null);const{qwenAuthState,cancelQwenAuth}=useQwenAuth(pendingAuthType,isAuthenticating);const openedViaCommandRef=(0,import_react5.useRef)(false);const onAuthError=(0,import_react5.useCallback)(error=>{setAuthError(error);if(error){setAuthState("updating");setIsAuthDialogOpen(true)}},[setAuthError,setAuthState]);const handleAuthFailure=(0,import_react5.useCallback)((error,protocolForTelemetry)=>{setIsAuthenticating(false);setExternalAuthState(null);const msg=t("Failed to authenticate. Message: {{message}}",{message:getErrorMessage(error)});onAuthError(msg);const effectiveProtocol=protocolForTelemetry??pendingAuthType;if(effectiveProtocol){logAuth(config,new AuthEvent(effectiveProtocol,"manual","error",msg))}},[onAuthError,pendingAuthType,config]);const completeAuthentication=(0,import_react5.useCallback)(()=>{setAuthError(null);setAuthState("authenticated");setPendingAuthType(void 0);setIsAuthDialogOpen(false);setIsAuthenticating(false);onAuthChange?.()},[onAuthChange]);const handleProviderSubmit=(0,import_react5.useCallback)(async(providerConfig,inputs)=>{let protocol=inputs.protocol??providerConfig.protocol;try{setPendingAuthType(protocol);setIsAuthenticating(true);setAuthError(null);const plan=buildInstallPlan(providerConfig,inputs,getModelsForProviderProtocol(settings.merged.modelProviders,inputs.protocol??providerConfig.protocol,settings.merged.providerProtocol),{authType:settings.merged.security?.auth?.selectedType,id:settings.merged.model?.name,baseUrl:settings.merged.model?.baseUrl});protocol=plan.authType;setPendingAuthType(protocol);await applyProviderInstallPlan(plan,{settings:createLoadedSettingsAdapter(settings),reloadModelProviders:__name(mp=>config.reloadModelProvidersConfig(mp),"reloadModelProviders"),syncAuthState:__name((authType,modelId,baseUrl)=>config.syncModelSelection(authType,modelId,baseUrl),"syncAuthState"),refreshAuth:__name(authType=>config.refreshAuth(authType),"refreshAuth")});if(!plan.modelSelection&&!config.getAuthType()){setIsAuthenticating(false);setPendingAuthType(void 0);onAuthError(t("Service models saved. Configure a conversation model to start chatting."));return}completeAuthentication();const feedbackItem={type:"info",text:!plan.modelSelection?t("Service models saved."):t("Successfully configured {{provider}}. Use /model to switch models.",{provider:providerConfig.label})};addItem(feedbackItem,Date.now());if(openedViaCommandRef.current){openedViaCommandRef.current=false;config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/auth",outputHistoryItems:[feedbackItem]})}if(plan.modelSelection)logAuth(config,new AuthEvent(protocol,"manual","success"))}catch(error){handleAuthFailure(error,protocol)}},[settings,config,completeAuthentication,addItem,handleAuthFailure,onAuthError]);const openAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=true;setIsAuthDialogOpen(true)},[]);const closeAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=false;setIsAuthDialogOpen(false);setAuthError(null)},[]);const cancelAuthentication=(0,import_react5.useCallback)(()=>{if(isAuthenticating&&pendingAuthType==="qwen-oauth"){cancelQwenAuth()}if(isAuthenticating&&pendingAuthType){logAuth(config,new AuthEvent(pendingAuthType,"manual","cancelled"))}setIsAuthenticating(false);setExternalAuthState(null);setIsAuthDialogOpen(true);setAuthError(null)},[isAuthenticating,pendingAuthType,cancelQwenAuth,config]);(0,import_react5.useEffect)(()=>{const val=process.env["QWEN_DEFAULT_AUTH_TYPE"];const valid=["qwen-oauth","openai","openai-responses","anthropic","gemini","vertex-ai"];if(val&&!valid.includes(val)){onAuthError(t('Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}',{value:val,validValues:valid.join(", ")}))}},[onAuthError]);const state=(0,import_react5.useMemo)(()=>({authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState}),[authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState]);const actions=(0,import_react5.useMemo)(()=>({setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication}),[setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication]);return{authState,setAuthState,authError,onAuthError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication,state,actions}},"useAuthCommand");init_esbuild_shims();var import_react6=__toESM(require_react(),1);function useDeleteCommand(options){const[isDeleteDialogOpen,setIsDeleteDialogOpen]=(0,import_react6.useState)(false);const openDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(true)},[]);const closeDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(false)},[]);const{config,addItem,logger:logger2}=options??{};const isDeletingManyRef=(0,import_react6.useRef)(false);const purgeSessionLogs=(0,import_react6.useCallback)(sessionIds=>{if(sessionIds.length===0)return;void logger2?.removeSessionsMessages(sessionIds).catch(error=>{console.error("Failed to purge deleted sessions from log:",error)})},[logger2]);const handleDelete=(0,import_react6.useCallback)(async sessionId=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}closeDeleteDialog();if(sessionId===config.getSessionId()){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}try{const sessionService=config.getSessionService();const success=await sessionService.removeSession(sessionId);if(success){purgeSessionLogs([sessionId]);fireSessionDeleteHook(config,sessionId);addItem?.({type:"info",text:t("Session deleted successfully.")},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete session. Session not found.")},Date.now())}}catch(error){console.error("handleDelete failed:",error);addItem?.({type:"error",text:t("Failed to delete session.")},Date.now())}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);const handleDeleteMany=(0,import_react6.useCallback)(async sessionIds=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}try{closeDeleteDialog();isDeletingManyRef.current=true;const currentId=config.getSessionId();const filtered=sessionIds.filter(id=>id!==currentId);if(filtered.length===0){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}if(filtered.length<sessionIds.length){addItem?.({type:"info",text:t("Current active session skipped.")},Date.now())}addItem?.({type:"info",text:t("Deleting {{count}} session(s)...",{count:String(filtered.length)})},Date.now());const sessionService=config.getSessionService();const result=await sessionService.removeSessions(filtered);purgeSessionLogs(result.removed);for(const sessionId of result.removed){fireSessionDeleteHook(config,sessionId)}const removedCount=result.removed.length;const failedIds=[...result.notFound,...result.errors.map(e=>e.sessionId)];const failedCount=failedIds.length;const sampleIds=failedIds.slice(0,3).map(id=>id.slice(0,8)).join(", ");const overflow=failedCount>3?`, +${failedCount-3} more`:"";const firstError=result.errors[0]?.error.message;const reason=firstError?` \u2014 ${firstError}`:"";if(removedCount>0&&failedCount===0){addItem?.({type:"info",text:t("Deleted {{count}} session(s).",{count:String(removedCount)})},Date.now())}else if(removedCount>0&&failedCount>0){addItem?.({type:"error",text:t("Deleted {{removed}} session(s); {{failed}} could not be deleted ({{ids}}{{overflow}}){{reason}}.",{removed:String(removedCount),failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete {{failed}} session(s) ({{ids}}{{overflow}}){{reason}}.",{failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}}catch(error){console.error("handleDeleteMany failed:",error);const detail=error instanceof Error?error.message:String(error);addItem?.({type:"error",text:t("Failed to delete sessions: {{error}}",{error:detail})},Date.now())}finally{isDeletingManyRef.current=false}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);return{isDeleteDialogOpen,openDeleteDialog,closeDeleteDialog,handleDelete,handleDeleteMany}}__name(useDeleteCommand,"useDeleteCommand");init_esbuild_shims();var import_react7=__toESM(require_react(),1);function sourceLabel(scope){switch(scope){case"workspace":return".qwen/settings.json";case"project":default:return".mcp.json"}}__name(sourceLabel,"sourceLabel");function summarize(config){let summary;if(config.httpUrl){summary=`${config.httpUrl} (http)`}else if(config.url){summary=`${config.url} (sse)`}else if(config.command){summary=`${config.command} ${config.args?.join(" ")??""} (stdio)`.replace(/\s+\(/," (")}else{summary="(unknown transport)"}const details=[];if(config.env&&Object.keys(config.env).length>0){details.push(`env: ${Object.keys(config.env).join(", ")}`)}if(config.headers&&Object.keys(config.headers).length>0){details.push(`headers: ${Object.keys(config.headers).join(", ")}`)}return details.length>0?`${summary} [${details.join("; ")}]`:summary}__name(summarize,"summarize");var useMcpApproval=__name(config=>{const[queue,setQueue]=(0,import_react7.useState)([]);const computePending=(0,import_react7.useCallback)(()=>{if(config.getApprovalMode()==="yolo")return[];const servers=config.getMcpServers()??{};const approvals=loadMcpApprovals();const root=config.getWorkingDir();return Object.entries(servers).filter(([,c])=>isGatedMcpScope(c.scope)).filter(([name,c])=>approvals.getState(root,name,c)==="pending").map(([name,c])=>({name,config:c,summary:summarize(c),source:sourceLabel(c.scope)}))},[config]);(0,import_react7.useEffect)(()=>{setQueue(computePending())},[computePending]);(0,import_react7.useEffect)(()=>{const onPendingChanged=__name(()=>{setQueue(computePending())},"onPendingChanged");appEvents.on("mcp-pending-approval-changed",onPendingChanged);return()=>{appEvents.off("mcp-pending-approval-changed",onPendingChanged)}},[computePending]);const reconnect=(0,import_react7.useCallback)(name=>{config.approveMcpServerForSession(name);const registry=config.getToolRegistry();void registry?.discoverToolsForServer?.(name)?.catch?.(error=>{if(process.env["DEBUG"]){console.error(`MCP reconnect failed for ${name}:`,error)}})},[config]);const handleMcpApprovalSelect=(0,import_react7.useCallback)(async choice=>{const approvals=loadMcpApprovals();const root=config.getWorkingDir();const current=queue[0];if(!current){return}if(choice==="approve_all"){for(const server of queue){await approvals.setState(root,server.name,server.config,"approved");reconnect(server.name)}setQueue([]);return}if(choice==="approve"){await approvals.setState(root,current.name,current.config,"approved");reconnect(current.name)}else{await approvals.setState(root,current.name,current.config,"rejected")}setQueue(q=>q.slice(1))},[config,queue,reconnect]);return{isMcpApprovalDialogOpen:queue.length>0,currentMcpApproval:queue[0],pendingMcpApprovals:queue,mcpApprovalRemaining:Math.max(0,queue.length-1),handleMcpApprovalSelect}},"useMcpApproval");init_esbuild_shims();var import_react8=__toESM(require_react(),1);import crypto from"node:crypto";import path from"node:path";import os from"node:os";import fs from"node:fs";var OUTPUT_UPDATE_INTERVAL_MS=1e3;var MAX_OUTPUT_LENGTH=1e4;var debugLogger3=createDebugLogger("SHELL_COMMAND_PROCESSOR");function copyString(value){return value.split("").join("")}__name(copyString,"copyString");function addShellCommandToLlmHistory(llmClient,rawQuery,resultText){const modelContent=resultText.length>MAX_OUTPUT_LENGTH?copyString(resultText.substring(0,MAX_OUTPUT_LENGTH))+"\n... (truncated)":resultText;llmClient.addHistory({role:"user",parts:[{text:`I ran the following shell command:
3
+ import{fireSessionDeleteHook}from"./chunk-F64AWDLW.js";import{reportChatRecordingFailureToAdapter}from"./chunk-RYKFI4N2.js";import{MAX_SUGGESTIONS_TO_SHOW,SESSION_MENTION_PREFIX,buildMcpResourceRef,buildMcpServerRef,buildSessionRef,getExtensionSuggestions,matchMcpServerPrefix,normalizeDescription}from"./chunk-LGQHT42X.js";import{StreamJsonOutputAdapter}from"./chunk-7RNTXEWH.js";import{getTranslatedSourceDisplayMap}from"./chunk-5DUJIOOX.js";import{BaseSelectionList,Colors,RadioButtonSelect,RowMouseController,TextInput,dist_default,findElementAtMouseEvent,useMouseEvents,useTerminalSize}from"./chunk-MEZA3VVH.js";import{ICON,SHELL_COMMAND_NAME}from"./chunk-QTAC4W7J.js";import{useKeypress}from"./chunk-3ULVEPFO.js";import{getInteractiveModSession}from"./chunk-AJ6JUUP7.js";import{theme}from"./chunk-OWCYARAS.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{Box_default,Text}from"./chunk-XZQH4UBR.js";import{require_react}from"./chunk-5QKDV4CD.js";import{themeManager}from"./chunk-W3YCOEIP.js";import{appEvents}from"./chunk-34WLYVDK.js";import{getCachedStringWidth,toCodePoints}from"./chunk-MOH67CDU.js";import{AGENT_HOST_SESSION_SOURCE_TYPE,AGENT_SESSION_SOURCE_TYPE}from"./chunk-DHYCGKLG.js";import{createLoadedSettingsAdapter}from"./chunk-SWTMWNTZ.js";import{loadMcpApprovals}from"./chunk-K2K2YYWO.js";import{SettingScope,settingExistsInScope}from"./chunk-FHFBCG6N.js";import{getCurrentLanguage,t,ta}from"./chunk-H45OX4VY.js";import{FileSearchFactory,INITIAL_FOLLOWUP_STATE,Logger,createFollowupController,discoverProviderModels,generateSessionRecap,preserveModelProviderPlaceholders}from"./chunk-AVIDPC5K.js";import{executeModTool,modToolRequest}from"./chunk-T5S3MJIK.js";import{CoreToolScheduler,SessionService,allowEditorTypeInSandbox,checkHasEditorType,compactToolResultDisplayForHistory,didWriteProjectContextFile,executeRuntimeShell,isGatedMcpScope,refreshMemoryAfterManagedWrite,refreshMemoryInstruction}from"./chunk-LDXZT3SG.js";import{TERMINAL_CSI_REGEX,TERMINAL_OSC_REGEX,TERMINAL_SHIFT_DCS_REGEX,stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{resolveBranchName,watchRepoBranch}from"./chunk-LLX4BCWK.js";import{isSignalTermination}from"./chunk-3X7DP5W3.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-7J2TOJMG.js";import{qwenOAuth2Events,sanitizeForOsc}from"./chunk-I5TFTKQS.js";import{applyProviderInstallPlan,buildInstallPlan,getDefaultBaseUrlForProtocol,getDefaultModelIds,getModelsForProviderProtocol,resolveBaseUrl,shouldShowStep}from"./chunk-DIHJELGW.js";import{AuthEvent,PromptSuggestionEvent,logAuth,logPromptSuggestion}from"./chunk-DR3HLUJ5.js";import{REASONING_EFFORT_TIERS}from"./chunk-TAAJ7TDB.js";import{isBinary}from"./chunk-4YLXNRRH.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{escapePath}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 DEFAULT_WINDOW_TITLE="qwen";var MULTIPLEXER_ENV_KEYS=["TMUX","STY","ZELLIJ","DVTM"];function sanitizeWindowTitle(title){return sanitizeForOsc(title)}__name(sanitizeWindowTitle,"sanitizeWindowTitle");function computeWindowTitle(folderName){return sanitizeWindowTitle(process.env["CLI_TITLE"]||`Qwen - ${folderName||DEFAULT_WINDOW_TITLE}`)}__name(computeWindowTitle,"computeWindowTitle");function writeTerminalTitle(write,title){const clean=sanitizeWindowTitle(title);if(process.platform==="win32"){process.title=clean}const inMultiplexer=MULTIPLEXER_ENV_KEYS.some(k=>!!process.env[k]);if(clean.length===0){if(inMultiplexer){write("\x1B]2;\x07")}else{write("\x1B]0;\x07\x1B]2;\x07")}return}if(inMultiplexer){write(`\x1B]2;${clean}\x07`)}else{const padded=clean.substring(0,80).padEnd(80," ");write(`\x1B]0;${padded}\x07\x1B]2;${padded}\x07`)}}__name(writeTerminalTitle,"writeTerminalTitle");function formatSessionWindowTitle(sessionName,folderName,statusPrefix=""){const base=sessionName?sanitizeWindowTitle(sessionName):computeWindowTitle(folderName);return sanitizeWindowTitle(statusPrefix+base)}__name(formatSessionWindowTitle,"formatSessionWindowTitle");function titleStatusPrefix(streamingState){switch(streamingState){case"responding":return`${ICON.CIRCLE_LEFT_HALF} `;case"waiting_for_confirmation":return`${ICON.SPARKLE} `;default:return""}}__name(titleStatusPrefix,"titleStatusPrefix");init_esbuild_shims();var import_react=__toESM(require_react(),1);var useLogger=__name((storage,sessionId)=>{const[logger2,setLogger]=(0,import_react.useState)(null);(0,import_react.useEffect)(()=>{if(!sessionId){return}let cancelled=false;const newLogger=new Logger(sessionId,storage);newLogger.initialize().then(()=>{if(!cancelled){setLogger(newLogger)}}).catch(()=>{});return()=>{cancelled=true}},[storage,sessionId]);return logger2},"useLogger");init_esbuild_shims();var import_react2=__toESM(require_react(),1);var DEFAULT_AWAY_THRESHOLD_MINUTES=5;var MIN_USER_MESSAGES_TO_FIRE=3;var MIN_USER_MESSAGES_SINCE_LAST_RECAP=2;function shouldFireRecap(history){let userMessageCount=0;let lastRecapIndex=-1;for(let i=0;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userMessageCount++;if(item.type==="away_recap")lastRecapIndex=i}if(userMessageCount<MIN_USER_MESSAGES_TO_FIRE)return false;if(lastRecapIndex===-1)return true;let userSinceLast=0;for(let i=lastRecapIndex+1;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userSinceLast++}return userSinceLast>=MIN_USER_MESSAGES_SINCE_LAST_RECAP}__name(shouldFireRecap,"shouldFireRecap");function useAwaySummary(options){const{enabled,config,isFocused,isIdle,addItem,history,awayThresholdMinutes}=options;const blurredAtRef=(0,import_react2.useRef)(null);const recapPendingRef=(0,import_react2.useRef)(false);const inFlightRef=(0,import_react2.useRef)(null);const isIdleRef=(0,import_react2.useRef)(isIdle);isIdleRef.current=isIdle;const historyRef=(0,import_react2.useRef)(history);historyRef.current=history;const thresholdMs=(awayThresholdMinutes&&awayThresholdMinutes>0?awayThresholdMinutes:DEFAULT_AWAY_THRESHOLD_MINUTES)*60*1e3;(0,import_react2.useEffect)(()=>{if(!enabled||!config){inFlightRef.current?.abort();inFlightRef.current=null;blurredAtRef.current=null;return}if(!isFocused){if(blurredAtRef.current===null){blurredAtRef.current=Date.now()}return}const blurredAt=blurredAtRef.current;if(blurredAt===null)return;if(Date.now()-blurredAt<thresholdMs){blurredAtRef.current=null;return}if(recapPendingRef.current)return;if(!isIdleRef.current)return;if(!shouldFireRecap(historyRef.current)){blurredAtRef.current=null;return}blurredAtRef.current=null;recapPendingRef.current=true;const controller=new AbortController;inFlightRef.current=controller;const mods=getInteractiveModSession(config);const recap=mods?mods.ready.then(()=>controller.signal.aborted||!isIdleRef.current?null:generateSessionRecap(config,controller.signal)).catch(()=>null):generateSessionRecap(config,controller.signal);void recap.then(recap2=>{if(controller.signal.aborted||!recap2)return;if(!isIdleRef.current)return;const item={type:"away_recap",text:recap2};addItem(item,Date.now());try{config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/recap",outputHistoryItems:[{...item}]})}catch{}}).finally(()=>{if(inFlightRef.current===controller){inFlightRef.current=null}recapPendingRef.current=false})},[enabled,config,isFocused,isIdle,addItem,thresholdMs]);(0,import_react2.useEffect)(()=>()=>{inFlightRef.current?.abort()},[])}__name(useAwaySummary,"useAwaySummary");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var BRANCH_POLL_INTERVAL_MS=5e3;var primedBranchNames=new Map;async function primeGitBranchName(cwd){primedBranchNames.set(cwd,await resolveBranchName(cwd))}__name(primeGitBranchName,"primeGitBranchName");function useGitBranchName(cwd){const[branchName,setBranchName]=(0,import_react3.useState)(()=>primedBranchNames.get(cwd));const branchNameRef=(0,import_react3.useRef)(branchName);branchNameRef.current=branchName;(0,import_react3.useEffect)(()=>{let cancelled=false;let dispose;let pollTimer;let refreshGeneration=0;const refresh=__name(async()=>{const generation=++refreshGeneration;const name=await resolveBranchName(cwd);if(!cancelled&&generation===refreshGeneration&&name!==branchNameRef.current){setBranchName(name)}},"refresh");const init=__name(async()=>{await refresh();if(cancelled)return;const disposer=await watchRepoBranch(cwd,()=>{void refresh().catch(()=>{})});if(cancelled){disposer()}else{dispose=disposer}if(!cancelled){pollTimer=setInterval(()=>{void refresh().catch(()=>{})},BRANCH_POLL_INTERVAL_MS);pollTimer.unref?.()}},"init");void init().catch(()=>{});return()=>{cancelled=true;dispose?.();if(pollTimer)clearInterval(pollTimer)}},[cwd]);return branchName}__name(useGitBranchName,"useGitBranchName");init_esbuild_shims();import{createWriteStream,fstatSync,openSync,constants}from"node:fs";init_esbuild_shims();var debugLogger=createDebugLogger("DUAL_OUTPUT");var SUPPORTED_EVENTS=["system","user","assistant","stream_event","result","control_request","control_response"];var DUAL_OUTPUT_PROTOCOL_VERSION=2;var MAX_BUFFERED_BYTES=1024*1024;var DualOutputBridge=class{static{__name(this,"DualOutputBridge")}adapter;stream;sessionId;active=true;shutdownPromise=null;unsubscribeRecordingFailure;constructor(config,target,options={}){this.sessionId=config.getSessionId();if("fd"in target){if(target.fd<=2){throw new Error(`--json-fd ${target.fd}: file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) are reserved. Use fd 3 or higher.`)}try{fstatSync(target.fd)}catch{throw new Error(`--json-fd ${target.fd}: file descriptor is not open. The caller must provide this fd via spawn stdio configuration or shell redirection (e.g., 3>/tmp/events.jsonl).`)}this.stream=createWriteStream("",{fd:target.fd})}else{try{const fd=openSync(target.filePath,constants.O_WRONLY|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(err){const code=err.code;if(code==="ENXIO"){try{const fd=openSync(target.filePath,constants.O_RDWR|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(retryErr){if(retryErr.code==="EACCES"){throw new Error(`--json-file "${target.filePath}": permission denied opening FIFO for read-write. Check read/write permissions on the file and its parent directories, or start a reader before launching Qwen Code.`)}throw retryErr}}else if(code==="ENOENT"){this.stream=createWriteStream(target.filePath,{flags:"w"})}else{throw err}}}this.stream.on("error",err=>{const code=err.code;if(code==="EPIPE"||code==="ERR_STREAM_DESTROYED"){debugLogger.warn("DualOutput: consumer disconnected, disabling")}else if(code==="ERR_SYSTEM_ERROR"){debugLogger.warn("DualOutput: system error on stream, disabling:",err.message)}else{debugLogger.error("DualOutput stream error:",err)}this.active=false});this.adapter=new StreamJsonOutputAdapter(config,true,this.stream);this.unsubscribeRecordingFailure=typeof config.onChatRecordingFailure==="function"?config.onChatRecordingFailure(event=>{this.emitRecordingFailure(event)}):()=>{};try{this.adapter.emitSystemMessage("session_start",{session_id:this.sessionId,cwd:process.cwd(),protocol_version:DUAL_OUTPUT_PROTOCOL_VERSION,version:options.version,supported_events:[...SUPPORTED_EVENTS]})}catch(err){debugLogger.error("DualOutput session_start error:",err);this.active=false}}processEvent(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.processEvent(event)}catch(err){debugLogger.error("DualOutput processEvent error:",err);this.active=false}}startAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.startAssistantMessage()}catch(err){debugLogger.error("DualOutput startAssistantMessage error:",err);this.active=false}}finalizeAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.finalizeAssistantMessage()}catch(err){debugLogger.error("DualOutput finalizeAssistantMessage error:",err);this.active=false}}emitUserMessage(parts){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitUserMessage(parts)}catch(err){debugLogger.error("DualOutput emitUserMessage error:",err);this.active=false}}emitToolResult(request,response){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitToolResult(request,response)}catch(err){debugLogger.error("DualOutput emitToolResult error:",err);this.active=false}}get isConnected(){return this.active}disableIfBufferOverflowed(){if(this.stream.writableLength>MAX_BUFFERED_BYTES){debugLogger.warn("DualOutput: buffered data exceeds limit, disabling (no consumer draining?)");this.active=false;this.stream.destroy()}}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath,permissionSuggestions)}catch(err){debugLogger.error("DualOutput emitPermissionRequest error:",err);this.active=false}}emitControlResponse(requestId,allowed){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlResponse(requestId,allowed)}catch(err){debugLogger.error("DualOutput emitControlResponse error:",err);this.active=false}}emitControlError(requestId,message){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlError(requestId,message)}catch(err){debugLogger.error("DualOutput emitControlError error:",err);this.active=false}}emitSystemMessage(subtype,data){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitSystemMessage(subtype,data)}catch(err){debugLogger.error("DualOutput emitSystemMessage error:",err);this.active=false}}emitRecordingFailure(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{reportChatRecordingFailureToAdapter(this.adapter,event)}catch(err){debugLogger.error("DualOutput recording failure output error:",err);this.active=false}}shutdown(){if(this.shutdownPromise)return this.shutdownPromise;this.unsubscribeRecordingFailure();if(this.active){try{this.adapter.emitSystemMessage("session_end",{session_id:this.sessionId})}catch{}}this.active=false;this.shutdownPromise=new Promise(resolve2=>{if(this.stream.closed||this.stream.destroyed){resolve2();return}const cleanup=__name(()=>{this.stream.off("close",onClose);this.stream.off("error",onError)},"cleanup");const onClose=__name(()=>{cleanup();resolve2()},"onClose");const onError=__name(err=>{debugLogger.debug("DualOutput: stream error during shutdown:",err)},"onError");this.stream.once("close",onClose);this.stream.once("error",onError);try{this.stream.end()}catch(err){cleanup();debugLogger.debug("DualOutput: stream end error during shutdown:",err);resolve2()}});return this.shutdownPromise}};init_esbuild_shims();import{createHash}from"node:crypto";import{closeSync,createReadStream,openSync as openSync2,readSync,statSync,unwatchFile,watchFile}from"node:fs";import{createInterface}from"node:readline";var debugLogger2=createDebugLogger("REMOTE_INPUT");var RemoteInputWatcher=class{static{__name(this,"RemoteInputWatcher")}submitFn=null;confirmationHandler=null;queue=[];processing=false;active=true;bytesRead=0;consumedPrefixHash=null;reading=false;filePath;retryTimer=null;pollIntervalMs;constructor(filePath,options){this.filePath=filePath;this.pollIntervalMs=options?.pollIntervalMs??500;this.startWatching()}setSubmitFn(fn){this.submitFn=fn;this.processQueue()}setConfirmationHandler(fn){this.confirmationHandler=fn}notifyIdle(){if(this.queue.length>0&&!this.processing){this.processQueue()}}startWatching(){try{const stat=statSync(this.filePath);this.bytesRead=stat.size;this.consumedPrefixHash=this.hashFilePrefix(this.bytesRead)}catch{this.bytesRead=0;this.consumedPrefixHash=null}watchFile(this.filePath,{interval:this.pollIntervalMs},()=>{if(!this.active)return;this.readNewLines()});debugLogger2.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let currentSize;try{const stat=statSync(this.filePath);currentSize=stat.size}catch{return Promise.resolve()}if(currentSize<this.bytesRead){debugLogger2.debug("RemoteInput: input file shrank, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}else if(this.hasConsumedPrefixChanged()){debugLogger2.debug("RemoteInput: input file prefix changed, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}if(currentSize<=this.bytesRead)return Promise.resolve();const consumeUntil=this.findLastCompleteRecordEnd(this.bytesRead,currentSize);if(consumeUntil===null){return Promise.resolve()}const nextConsumedPrefixHash=this.hashFilePrefix(consumeUntil);this.reading=true;const stream=createReadStream(this.filePath,{start:this.bytesRead,end:consumeUntil-1,encoding:"utf-8"});const rl=createInterface({input:stream,crlfDelay:Infinity});rl.on("line",line=>{const trimmed=line.trim();if(!trimmed)return;try{const cmd=JSON.parse(trimmed);if(cmd&&cmd.type==="confirmation_response"&&typeof cmd.request_id==="string"&&typeof cmd.allowed==="boolean"){debugLogger2.debug(`RemoteInput: confirmation_response for ${cmd.request_id} (allowed=${cmd.allowed})`);this.confirmationHandler?.(cmd.request_id,cmd.allowed)}else if(cmd&&cmd.type==="submit"&&typeof cmd.text==="string"){debugLogger2.debug(`RemoteInput: queued command: ${cmd.text.slice(0,50)}...`);this.queue.push(cmd)}else{debugLogger2.warn(`RemoteInput: unknown command type: ${String(cmd?.type)}`)}}catch(_err){debugLogger2.warn(`RemoteInput: failed to parse line: ${trimmed}`)}});return new Promise(resolve2=>{rl.on("close",()=>{this.bytesRead=consumeUntil;if(nextConsumedPrefixHash!==null){this.consumedPrefixHash=nextConsumedPrefixHash}this.reading=false;this.processQueue();resolve2()})})}findLastCompleteRecordEnd(start,end){if(end<=start)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const buffer=Buffer.allocUnsafe(Math.min(64*1024,end-start));let remaining=end-start;let position=start;let lastLineBreak=-1;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)break;for(let i=0;i<bytesRead;i++){if(buffer[i]===10){lastLineBreak=position+i}}remaining-=bytesRead;position+=bytesRead}return lastLineBreak>=start?lastLineBreak+1:null}catch(err){debugLogger2.warn("RemoteInput: failed to scan complete records:",err);return null}finally{if(fd!==null){closeSync(fd)}}}hasConsumedPrefixChanged(){if(this.bytesRead===0){return false}if(this.consumedPrefixHash===null){debugLogger2.warn("RemoteInput: missing consumed prefix hash, resetting read offset");return true}const currentHash=this.hashFilePrefix(this.bytesRead);if(currentHash===null){debugLogger2.warn("RemoteInput: failed to hash consumed prefix, resetting read offset");return true}return currentHash!==this.consumedPrefixHash}hashFilePrefix(size){if(size<=0)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const hash=createHash("sha256");const buffer=Buffer.allocUnsafe(Math.min(64*1024,size));let remaining=size;let position=0;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)return null;hash.update(buffer.subarray(0,bytesRead));remaining-=bytesRead;position+=bytesRead}return hash.digest("base64")}catch(err){debugLogger2.warn("RemoteInput: failed to hash file prefix:",err);return null}finally{if(fd!==null){closeSync(fd)}}}async processQueue(){if(this.processing||!this.submitFn||this.queue.length===0)return;this.processing=true;if(this.retryTimer){clearTimeout(this.retryTimer);this.retryTimer=null}try{while(this.queue.length>0&&this.active){if(!this.submitFn)break;const cmd=this.queue[0];debugLogger2.debug(`RemoteInput: submitting: ${cmd.text.slice(0,50)}...`);try{const result=await this.submitFn(cmd.text);if(result===false){debugLogger2.debug("RemoteInput: TUI busy, will retry on idle");this.scheduleRetry();break}this.queue.shift()}catch(err){debugLogger2.error("RemoteInput: submit failed:",err);this.queue.shift()}if(this.queue.length>0){await new Promise(r=>setTimeout(r,500))}}}finally{this.processing=false}}scheduleRetry(){if(this.retryTimer)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null;if(this.queue.length>0&&!this.processing){this.processQueue()}},2e3)}shutdown(){this.active=false;unwatchFile(this.filePath);if(this.retryTimer)clearTimeout(this.retryTimer);this.queue.length=0;debugLogger2.debug("RemoteInput: shut down")}};init_esbuild_shims();async function observeInteractiveModTool(config,call,refreshContextFilesOnWrite){if(call.request.isClientInitiated)return;const succeeded=call.response.executionStatus==="success";if(call.status!=="cancelled"||succeeded){config.getLlmClient()?.recordCompletedToolCall(call.request.name,call.request.args)}const candidates=[{toolName:call.request.name,args:call.request.args,status:succeeded?"success":"error"}];const refreshed=await refreshMemoryAfterManagedWrite(config,candidates,{logContext:"interactive Mod native attempt"});if(!refreshed&&succeeded&&(call.request.name==="save_memory"||refreshContextFilesOnWrite&&didWriteProjectContextFile(candidates,config.getProjectRoot()))){await refreshMemoryInstruction(config,{logContext:"interactive Mod native attempt"})}}__name(observeInteractiveModTool,"observeInteractiveModTool");init_esbuild_shims();function logicalCompletion(request,response,completed){if(completed?.status==="cancelled")return{...completed,request,response,nativeAttemptsObserved:true};if(response.error)return{...completed,status:"error",request,response,nativeAttemptsObserved:true};return{...completed,status:"success",request,response,nativeAttemptsObserved:true}}__name(logicalCompletion,"logicalCompletion");var logger=createDebugLogger("INTERACTIVE_MOD_TOOLS");var InteractiveModToolScheduler=class{constructor(options){this.options=options;this.native=new CoreToolScheduler(options)}static{__name(this,"InteractiveModToolScheduler")}native;tail=Promise.resolve();displayOwner;schedule(request,signal,runtimeView){const session=getInteractiveModSession(this.options.config);const requests=Array.isArray(request)?request:[request];if(!session||requests.every(item=>item.isClientInitiated)){return this.native.schedule(request,signal,runtimeView)}const owner=captureHookExecutionOwner(this.options.config);const sessionSignal=session.captureToolSignal();const active=AbortSignal.any([signal,sessionSignal]);const displayOwner={};const clearDisplay=__name(()=>{if(this.displayOwner!==displayOwner)return;this.displayOwner=void 0;this.options.onToolCallsUpdate?.([])},"clearDisplay");sessionSignal.addEventListener("abort",clearDisplay,{once:true});let delivered=false;const task=this.tail.then(()=>runWithHookExecutionOwner(owner,async()=>{await new Promise((resolve2,reject)=>{const cancel=__name(()=>reject(active.reason),"cancel");if(active.aborted)return cancel();active.addEventListener("abort",cancel,{once:true});void session.ready.then(()=>{active.removeEventListener("abort",cancel);resolve2()},error=>{active.removeEventListener("abort",cancel);reject(error)})});active.throwIfAborted();const middleware=session.toolCall();if(!middleware)return this.native.schedule(request,active,runtimeView);const calls=requests.map(item=>({status:"scheduled",request:item,nativeAttemptsObserved:true}));const attemptUpdates=new Map;const publish=__name(()=>{if(!sessionSignal.aborted){this.displayOwner=displayOwner;this.options.onToolCallsUpdate?.(calls.flatMap((call,index)=>attemptUpdates.get(index)??[call]))}},"publish");publish();for(let index=0;index<requests.length;index++){const original=requests[index];let last;const execute=__name((nativeRequest,nativeSignal,check)=>new Promise((resolve2,reject)=>{nativeSignal.throwIfAborted();active.throwIfAborted();const attemptSignal=AbortSignal.any([active,nativeSignal]);attemptUpdates.delete(index);publish();const scheduler=new CoreToolScheduler({...this.options,chatRecordingService:void 0,modToolCheck:check,outputUpdateHandler:__name((id,chunk)=>{if(!attemptSignal.aborted)this.options.outputUpdateHandler?.(id,chunk)},"outputUpdateHandler"),onToolCallsUpdate:__name(updates=>{if(attemptSignal.aborted||!updates.length)return;attemptUpdates.set(index,updates.map(current=>{if(current.request.callId!==nativeRequest.callId)return current;if(current.status==="success"||current.status==="error"||current.status==="cancelled"){return{status:"scheduled",request:original,nativeAttemptsObserved:true}}return{...current,nativeAttemptsObserved:true}}));publish()},"onToolCallsUpdate"),onAllToolCallsComplete:__name(async completed=>{last=completed[0];attemptUpdates.delete(index);publish();try{if(!sessionSignal.aborted)await this.options.onNativeAttempt?.(last);resolve2(last)}catch(error){logger.warn(`Native tool observation failed: ${String(error)}`);resolve2(last)}},"onAllToolCallsComplete")});void runWithHookExecutionOwner(owner,()=>scheduler.schedule(nativeRequest,attemptSignal,runtimeView)).catch(reject)}),"execute");try{active.throwIfAborted();const execution=!original.isClientInitiated&&await modToolRequest(this.options.config,original);const result=execution?await executeModTool(original,execution,middleware,execute,active):{completed:await execute(original,active),response:void 0};const response=result.response??result.completed.response;const completed=result.completed;calls[index]=logicalCompletion(original,response,completed)}catch(error){const message=active.aborted?"Tool call cancelled.":`Mod tool scheduling failed: ${String(error)}`;calls[index]={...last,status:active.aborted?"cancelled":"error",request:original,response:{callId:original.callId,responseParts:[{functionResponse:{id:original.callId,name:original.name,response:{error:message}}}],error:new Error(message),errorType:void 0,resultDisplay:message,executionStatus:last?.response.executionStatus??"not_started",contentLength:message.length},nativeAttemptsObserved:true}}publish()}sessionSignal.throwIfAborted();clearDisplay();delivered=true;await this.options.onAllToolCallsComplete(calls.filter(call=>call.status==="success"||call.status==="error"||call.status==="cancelled"))}));const settled=task.catch(async error=>{if(delivered||sessionSignal.aborted)throw error;clearDisplay();delivered=true;await this.options.onAllToolCallsComplete(requests.map(item=>({status:active.aborted?"cancelled":"error",request:item,nativeAttemptsObserved:true,response:{callId:item.callId,error:new Error(String(error)),errorType:void 0,executionStatus:"not_started",resultDisplay:String(error),responseParts:[{functionResponse:{id:item.callId,name:item.name,response:{error:String(error)}}}]}})))});const drained=settled.finally(()=>{sessionSignal.removeEventListener("abort",clearDisplay)});this.tail=drained.catch(()=>{});return drained}};init_esbuild_shims();var calculatePromptWidths=__name(terminalWidth=>{const widthFraction=.9;const FRAME_PADDING_AND_BORDER=4;const PROMPT_PREFIX_WIDTH=2;const MIN_CONTENT_WIDTH=2;const innerContentWidth=Math.floor(terminalWidth*widthFraction)-FRAME_PADDING_AND_BORDER-PROMPT_PREFIX_WIDTH;const inputWidth=Math.max(MIN_CONTENT_WIDTH,innerContentWidth);const FRAME_OVERHEAD=FRAME_PADDING_AND_BORDER+PROMPT_PREFIX_WIDTH;const containerWidth=inputWidth+FRAME_OVERHEAD;const suggestionsWidth=Math.max(20,Math.floor(terminalWidth*1));return{inputWidth,containerWidth,suggestionsWidth,frameOverhead:FRAME_OVERHEAD}},"calculatePromptWidths");var MAIN_CONTENT_HEIGHT_RESERVATION=2;var STATIC_EXTRA_HEIGHT=3;var clampDialogHeight=__name(height=>height===void 0?void 0:Math.max(1,Math.floor(height)),"clampDialogHeight");var getDialogMaxHeight=__name((terminalHeight,staticExtraHeight)=>Math.max(1,terminalHeight-staticExtraHeight-MAIN_CONTENT_HEIGHT_RESERVATION),"getDialogMaxHeight");init_esbuild_shims();var import_react5=__toESM(require_react(),1);init_esbuild_shims();var import_react4=__toESM(require_react(),1);var useQwenAuth=__name((pendingAuthType,isAuthenticating)=>{const[qwenAuthState,setQwenAuthState]=(0,import_react4.useState)({deviceAuth:null,authStatus:"idle",authMessage:null});const isQwenAuth=pendingAuthType==="qwen-oauth";(0,import_react4.useEffect)(()=>{if(!isQwenAuth||!isAuthenticating){setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null});return}setQwenAuthState(prev=>({...prev,authStatus:"idle"}));const handleDeviceAuth=__name(deviceAuth=>{setQwenAuthState(prev=>({...prev,deviceAuth:{verification_uri:deviceAuth.verification_uri,verification_uri_complete:deviceAuth.verification_uri_complete,user_code:deviceAuth.user_code,expires_in:deviceAuth.expires_in,device_code:deviceAuth.device_code},authStatus:"polling"}))},"handleDeviceAuth");const handleAuthProgress=__name((status,message)=>{setQwenAuthState(prev=>({...prev,authStatus:status,authMessage:message||null}))},"handleAuthProgress");qwenOAuth2Events.on("auth-uri",handleDeviceAuth);qwenOAuth2Events.on("auth-progress",handleAuthProgress);return()=>{qwenOAuth2Events.off("auth-uri",handleDeviceAuth);qwenOAuth2Events.off("auth-progress",handleAuthProgress)}},[isQwenAuth,isAuthenticating]);const cancelQwenAuth=(0,import_react4.useCallback)(()=>{qwenOAuth2Events.emit("auth-cancel");setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null})},[]);return{qwenAuthState,cancelQwenAuth}},"useQwenAuth");function normalizeModelIds(modelIdsInput){return modelIdsInput.split(",").map(id=>id.trim()).filter((id,index,array)=>id.length>0&&array.indexOf(id)===index)}__name(normalizeModelIds,"normalizeModelIds");function maskApiKey(apiKey){const trimmed=apiKey.trim();if(trimmed.length===0)return"(not set)";if(trimmed.length<=6)return"***";return`${trimmed.slice(0,3)}...${trimmed.slice(-4)}`}__name(maskApiKey,"maskApiKey");var useAuthCommand=__name((settings,config,addItem,onAuthChange)=>{const unAuthenticated=config.getAuthType()===void 0;const[authState,setAuthState]=(0,import_react5.useState)(unAuthenticated?"updating":"unauthenticated");const[authError,setAuthError]=(0,import_react5.useState)(null);const[isAuthenticating,setIsAuthenticating]=(0,import_react5.useState)(false);const[isAuthDialogOpen,setIsAuthDialogOpen]=(0,import_react5.useState)(unAuthenticated);const[pendingAuthType,setPendingAuthType]=(0,import_react5.useState)(void 0);const[externalAuthState,setExternalAuthState]=(0,import_react5.useState)(null);const{qwenAuthState,cancelQwenAuth}=useQwenAuth(pendingAuthType,isAuthenticating);const openedViaCommandRef=(0,import_react5.useRef)(false);const onAuthError=(0,import_react5.useCallback)(error=>{setAuthError(error);if(error){setAuthState("updating");setIsAuthDialogOpen(true)}},[setAuthError,setAuthState]);const handleAuthFailure=(0,import_react5.useCallback)((error,protocolForTelemetry)=>{setIsAuthenticating(false);setExternalAuthState(null);const msg=t("Failed to authenticate. Message: {{message}}",{message:getErrorMessage(error)});onAuthError(msg);const effectiveProtocol=protocolForTelemetry??pendingAuthType;if(effectiveProtocol){logAuth(config,new AuthEvent(effectiveProtocol,"manual","error",msg))}},[onAuthError,pendingAuthType,config]);const completeAuthentication=(0,import_react5.useCallback)(()=>{setAuthError(null);setAuthState("authenticated");setPendingAuthType(void 0);setIsAuthDialogOpen(false);setIsAuthenticating(false);onAuthChange?.()},[onAuthChange]);const handleProviderSubmit=(0,import_react5.useCallback)(async(providerConfig,inputs)=>{let protocol=inputs.protocol??providerConfig.protocol;try{setPendingAuthType(protocol);setIsAuthenticating(true);setAuthError(null);const plan=buildInstallPlan(providerConfig,inputs,getModelsForProviderProtocol(settings.merged.modelProviders,inputs.protocol??providerConfig.protocol,settings.merged.providerProtocol),{authType:settings.merged.security?.auth?.selectedType,id:settings.merged.model?.name,baseUrl:settings.merged.model?.baseUrl});protocol=plan.authType;setPendingAuthType(protocol);await applyProviderInstallPlan(plan,{settings:createLoadedSettingsAdapter(settings),reloadModelProviders:__name(mp=>config.reloadModelProvidersConfig(mp),"reloadModelProviders"),syncAuthState:__name((authType,modelId,baseUrl)=>config.syncModelSelection(authType,modelId,baseUrl),"syncAuthState"),refreshAuth:__name(authType=>config.refreshAuth(authType),"refreshAuth")});if(!plan.modelSelection&&!config.getAuthType()){setIsAuthenticating(false);setPendingAuthType(void 0);onAuthError(t("Service models saved. Configure a conversation model to start chatting."));return}completeAuthentication();const feedbackItem={type:"info",text:!plan.modelSelection?t("Service models saved."):t("Successfully configured {{provider}}. Use /model to switch models.",{provider:providerConfig.label})};addItem(feedbackItem,Date.now());if(openedViaCommandRef.current){openedViaCommandRef.current=false;config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/auth",outputHistoryItems:[feedbackItem]})}if(plan.modelSelection)logAuth(config,new AuthEvent(protocol,"manual","success"))}catch(error){handleAuthFailure(error,protocol)}},[settings,config,completeAuthentication,addItem,handleAuthFailure,onAuthError]);const openAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=true;setIsAuthDialogOpen(true)},[]);const closeAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=false;setIsAuthDialogOpen(false);setAuthError(null)},[]);const cancelAuthentication=(0,import_react5.useCallback)(()=>{if(isAuthenticating&&pendingAuthType==="qwen-oauth"){cancelQwenAuth()}if(isAuthenticating&&pendingAuthType){logAuth(config,new AuthEvent(pendingAuthType,"manual","cancelled"))}setIsAuthenticating(false);setExternalAuthState(null);setIsAuthDialogOpen(true);setAuthError(null)},[isAuthenticating,pendingAuthType,cancelQwenAuth,config]);(0,import_react5.useEffect)(()=>{const val=process.env["QWEN_DEFAULT_AUTH_TYPE"];const valid=["qwen-oauth","openai","openai-responses","anthropic","gemini","vertex-ai"];if(val&&!valid.includes(val)){onAuthError(t('Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}',{value:val,validValues:valid.join(", ")}))}},[onAuthError]);const state=(0,import_react5.useMemo)(()=>({authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState}),[authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState]);const actions=(0,import_react5.useMemo)(()=>({setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication}),[setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication]);return{authState,setAuthState,authError,onAuthError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication,state,actions}},"useAuthCommand");init_esbuild_shims();var import_react6=__toESM(require_react(),1);function useDeleteCommand(options){const[isDeleteDialogOpen,setIsDeleteDialogOpen]=(0,import_react6.useState)(false);const openDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(true)},[]);const closeDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(false)},[]);const{config,addItem,logger:logger2}=options??{};const isDeletingManyRef=(0,import_react6.useRef)(false);const purgeSessionLogs=(0,import_react6.useCallback)(sessionIds=>{if(sessionIds.length===0)return;void logger2?.removeSessionsMessages(sessionIds).catch(error=>{console.error("Failed to purge deleted sessions from log:",error)})},[logger2]);const handleDelete=(0,import_react6.useCallback)(async sessionId=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}closeDeleteDialog();if(sessionId===config.getSessionId()){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}try{const sessionService=config.getSessionService();const success=await sessionService.removeSession(sessionId);if(success){purgeSessionLogs([sessionId]);fireSessionDeleteHook(config,sessionId);addItem?.({type:"info",text:t("Session deleted successfully.")},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete session. Session not found.")},Date.now())}}catch(error){console.error("handleDelete failed:",error);addItem?.({type:"error",text:t("Failed to delete session.")},Date.now())}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);const handleDeleteMany=(0,import_react6.useCallback)(async sessionIds=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}try{closeDeleteDialog();isDeletingManyRef.current=true;const currentId=config.getSessionId();const filtered=sessionIds.filter(id=>id!==currentId);if(filtered.length===0){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}if(filtered.length<sessionIds.length){addItem?.({type:"info",text:t("Current active session skipped.")},Date.now())}addItem?.({type:"info",text:t("Deleting {{count}} session(s)...",{count:String(filtered.length)})},Date.now());const sessionService=config.getSessionService();const result=await sessionService.removeSessions(filtered);purgeSessionLogs(result.removed);for(const sessionId of result.removed){fireSessionDeleteHook(config,sessionId)}const removedCount=result.removed.length;const failedIds=[...result.notFound,...result.errors.map(e=>e.sessionId)];const failedCount=failedIds.length;const sampleIds=failedIds.slice(0,3).map(id=>id.slice(0,8)).join(", ");const overflow=failedCount>3?`, +${failedCount-3} more`:"";const firstError=result.errors[0]?.error.message;const reason=firstError?` \u2014 ${firstError}`:"";if(removedCount>0&&failedCount===0){addItem?.({type:"info",text:t("Deleted {{count}} session(s).",{count:String(removedCount)})},Date.now())}else if(removedCount>0&&failedCount>0){addItem?.({type:"error",text:t("Deleted {{removed}} session(s); {{failed}} could not be deleted ({{ids}}{{overflow}}){{reason}}.",{removed:String(removedCount),failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete {{failed}} session(s) ({{ids}}{{overflow}}){{reason}}.",{failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}}catch(error){console.error("handleDeleteMany failed:",error);const detail=error instanceof Error?error.message:String(error);addItem?.({type:"error",text:t("Failed to delete sessions: {{error}}",{error:detail})},Date.now())}finally{isDeletingManyRef.current=false}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);return{isDeleteDialogOpen,openDeleteDialog,closeDeleteDialog,handleDelete,handleDeleteMany}}__name(useDeleteCommand,"useDeleteCommand");init_esbuild_shims();var import_react7=__toESM(require_react(),1);function sourceLabel(scope){switch(scope){case"workspace":return".qwen/settings.json";case"project":default:return".mcp.json"}}__name(sourceLabel,"sourceLabel");function summarize(config){let summary;if(config.httpUrl){summary=`${config.httpUrl} (http)`}else if(config.url){summary=`${config.url} (sse)`}else if(config.command){summary=`${config.command} ${config.args?.join(" ")??""} (stdio)`.replace(/\s+\(/," (")}else{summary="(unknown transport)"}const details=[];if(config.env&&Object.keys(config.env).length>0){details.push(`env: ${Object.keys(config.env).join(", ")}`)}if(config.headers&&Object.keys(config.headers).length>0){details.push(`headers: ${Object.keys(config.headers).join(", ")}`)}return details.length>0?`${summary} [${details.join("; ")}]`:summary}__name(summarize,"summarize");var useMcpApproval=__name(config=>{const[queue,setQueue]=(0,import_react7.useState)([]);const computePending=(0,import_react7.useCallback)(()=>{if(config.getApprovalMode()==="yolo")return[];const servers=config.getMcpServers()??{};const approvals=loadMcpApprovals();const root=config.getWorkingDir();return Object.entries(servers).filter(([,c])=>isGatedMcpScope(c.scope)).filter(([name,c])=>approvals.getState(root,name,c)==="pending").map(([name,c])=>({name,config:c,summary:summarize(c),source:sourceLabel(c.scope)}))},[config]);(0,import_react7.useEffect)(()=>{setQueue(computePending())},[computePending]);(0,import_react7.useEffect)(()=>{const onPendingChanged=__name(()=>{setQueue(computePending())},"onPendingChanged");appEvents.on("mcp-pending-approval-changed",onPendingChanged);return()=>{appEvents.off("mcp-pending-approval-changed",onPendingChanged)}},[computePending]);const reconnect=(0,import_react7.useCallback)(name=>{config.approveMcpServerForSession(name);const registry=config.getToolRegistry();void registry?.discoverToolsForServer?.(name)?.catch?.(error=>{if(process.env["DEBUG"]){console.error(`MCP reconnect failed for ${name}:`,error)}})},[config]);const handleMcpApprovalSelect=(0,import_react7.useCallback)(async choice=>{const approvals=loadMcpApprovals();const root=config.getWorkingDir();const current=queue[0];if(!current){return}if(choice==="approve_all"){for(const server of queue){await approvals.setState(root,server.name,server.config,"approved");reconnect(server.name)}setQueue([]);return}if(choice==="approve"){await approvals.setState(root,current.name,current.config,"approved");reconnect(current.name)}else{await approvals.setState(root,current.name,current.config,"rejected")}setQueue(q=>q.slice(1))},[config,queue,reconnect]);return{isMcpApprovalDialogOpen:queue.length>0,currentMcpApproval:queue[0],pendingMcpApprovals:queue,mcpApprovalRemaining:Math.max(0,queue.length-1),handleMcpApprovalSelect}},"useMcpApproval");init_esbuild_shims();var import_react8=__toESM(require_react(),1);import crypto from"node:crypto";import path from"node:path";import os from"node:os";import fs from"node:fs";var OUTPUT_UPDATE_INTERVAL_MS=1e3;var MAX_OUTPUT_LENGTH=1e4;var debugLogger3=createDebugLogger("SHELL_COMMAND_PROCESSOR");function copyString(value){return value.split("").join("")}__name(copyString,"copyString");function addShellCommandToLlmHistory(llmClient,rawQuery,resultText){const modelContent=resultText.length>MAX_OUTPUT_LENGTH?copyString(resultText.substring(0,MAX_OUTPUT_LENGTH))+"\n... (truncated)":resultText;llmClient.addHistory({role:"user",parts:[{text:`I ran the following shell command:
4
4
  \`\`\`sh
5
5
  ${rawQuery}
6
6
  \`\`\`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{OpenAIContentConverter,TaggedThinkingParser,corroborateTruncationFromCompletionTokens,openaiRequestCaptureContext}from"./chunk-SHR6GNT4.js";import{applyOfficialOpenAIPromptCaching,isOfficialOpenAIEndpoint,markToolCallArgumentsIncomplete}from"./chunk-T2F7KYYR.js";import{DashScopeOpenAICompatibleProvider,DefaultOpenAICompatibleProvider}from"./chunk-U2FJSKS3.js";import{getCurrentAgentId}from"./chunk-7J2TOJMG.js";import{extractTextFromContents}from"./chunk-SLYWXBG7.js";import{StreamInactivityTimeoutError,StreamLifetimeExceededError,parseToolCallArguments,resolveStreamIdleTimeoutMs,resolveStreamMaxLifetimeMs,withStreamGuards}from"./chunk-S2GKUZZZ.js";import{runtimeDiagnostics}from"./chunk-VFB6Q74I.js";import{reportOpenAiChunk,reportOpenAiRequest,reportOpenAiResponse}from"./chunk-YTKRKP2I.js";import{InvalidStreamError,getToolCallPreparations,markFlushedToolCallPark,trailingReattachPartCount}from"./chunk-V3XYE727.js";import{safeJsonParse}from"./chunk-CJZJ36VK.js";import{applyDeepSeekReasoningEffort,getBuiltinDeepSeekReasoning,getEffectiveReasoning,getRequestModel,isOpenRouterHostname,resolveReasoningForModel}from"./chunk-XYBEQRSZ.js";import{getRateLimitErrorDetails,getTransportCode}from"./chunk-WZDBBDRD.js";import{createChildAbortController}from"./chunk-476F6QIM.js";import{ProtocolTagSanitizedEvent,logProtocolTagSanitized}from"./chunk-DR3HLUJ5.js";import{REASONING_EFFORT_TIERS,getGptReasoningCapabilities,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,reconcileMaxTokens}from"./chunk-TAAJ7TDB.js";import{redactProxyError}from"./chunk-ZZZAYAJW.js";import{FinishReason,GenerateContentResponse}from"./chunk-QKX6AI4W.js";import{isInForkExecution}from"./chunk-65UCR6OZ.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{getErrorMessage,getErrorStatus,getErrorType,isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();var ModelScopeOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"ModelScopeOpenAICompatibleProvider")}static isModelScopeProvider(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="modelscope.cn"||hostname.endsWith(".modelscope.cn")}catch{return false}}buildRequest(request,userPromptId){const newRequest=super.buildRequest(request,userPromptId);if(!newRequest.stream){delete newRequest.stream_options}return newRequest}};init_esbuild_shims();init_esbuild_shims();function ensureReasoningContentOnAssistantMessage(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content==="string"){return message}return{...assistant,reasoning_content:""}}__name(ensureReasoningContentOnAssistantMessage,"ensureReasoningContentOnAssistantMessage");function stripReasoningContent(message){if(!("reasoning_content"in message)){return message}const next={...message};delete next["reasoning_content"];return next}__name(stripReasoningContent,"stripReasoningContent");function isDeepSeekHostname(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="api.deepseek.com"||hostname.endsWith(".api.deepseek.com")}catch{return false}}__name(isDeepSeekHostname,"isDeepSeekHostname");function isDeepSeekProvider(contentGeneratorConfig){if(isDeepSeekHostname(contentGeneratorConfig))return true;const model=contentGeneratorConfig.model??"";return model.toLowerCase().includes("deepseek")}__name(isDeepSeekProvider,"isDeepSeekProvider");var DeepSeekOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"DeepSeekOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDeepSeekProvider=isDeepSeekProvider;static isDeepSeekHostname=isDeepSeekHostname;supportedReasoningEffortsFor(model){return!this.getReasoningCapabilities(model)?.profile&&isDeepSeekHostname(this.contentGeneratorConfig)?REASONING_EFFORT_TIERS:super.supportedReasoningEffortsFor(model)}buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);const profile=this.getReasoningCapabilities(baseRequest.model)?.profile;const reshaped=(!profile||profile==="deepseek-openai")&&isDeepSeekHostname(this.contentGeneratorConfig)?applyDeepSeekReasoningEffort(baseRequest,this.contentGeneratorConfig.baseUrl):baseRequest;if(!reshaped.messages?.length){return reshaped}const messages=reshaped.messages.map(message=>{const content=this.contentGeneratorConfig.modalities?.image?message:flattenContentParts(message);return isDeepSeekHostname(this.contentGeneratorConfig)||!profile||profile==="deepseek-openai"?ensureReasoningContentOnAssistantMessage(content):content});return{...reshaped,messages}}getDefaultGenerationConfig(){return{}}};function flattenContentParts(message){if(!("content"in message)){return message}const{content}=message;if(typeof content==="string"||content===null||content===void 0){return message}if(!Array.isArray(content)){return message}const text=content.map(part=>{if(typeof part==="string"){return part}if(part.type==="text"){return part.text??""}return`[Unsupported content type: ${part.type}]`}).join("\n\n");return{...message,content:text}}__name(flattenContentParts,"flattenContentParts");init_esbuild_shims();var debugLogger=createDebugLogger("ZAI");function isZaiHostname(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl;if(!baseUrl){return false}try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="z.ai"||hostname.endsWith(".z.ai")||hostname==="bigmodel.cn"||hostname.endsWith(".bigmodel.cn")}catch{return false}}__name(isZaiHostname,"isZaiHostname");function isZaiProvider(contentGeneratorConfig){if(isZaiHostname(contentGeneratorConfig)){return true}const model=contentGeneratorConfig.model??"";return model.toLowerCase().startsWith("glm-")}__name(isZaiProvider,"isZaiProvider");function isGlmTieredEffortModel(model){if(!model){return false}const parsed=/^glm-(\d+)(?:\.(\d+))?/.exec(model.toLowerCase());if(!parsed){return false}const major=Number(parsed[1]);const minor=Number(parsed[2]??0);return major>5||major===5&&minor>=2}__name(isGlmTieredEffortModel,"isGlmTieredEffortModel");var ZaiOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"ZaiOpenAICompatibleProvider")}static isZaiProvider=isZaiProvider;static isZaiHostname=isZaiHostname;nonZaiHostnameFlattenWarned=false;supportedReasoningEffortsFor(model){return isZaiHostname(this.contentGeneratorConfig)&&isGlmTieredEffortModel(model??this.contentGeneratorConfig.model)?REASONING_EFFORT_TIERS:super.supportedReasoningEffortsFor(model)}buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);if(isZaiHostname(this.contentGeneratorConfig)){return flattenReasoningEffort(baseRequest)}const reasoning=baseRequest["reasoning"];if(reasoning?.effort&&!baseRequest["reasoning_effort"]&&!this.nonZaiHostnameFlattenWarned){debugLogger.warn(`GLM model '${this.contentGeneratorConfig.model??"unknown"}' on a non-Z.ai hostname; leaving nested reasoning.effort='${String(reasoning.effort)}' unflattened (reasoning_effort reshape is hostname-gated).`);this.nonZaiHostnameFlattenWarned=true}return baseRequest}};function flattenReasoningEffort(request){const r=request;const nested=r["reasoning"];const effort=nested?.effort;if(typeof effort!=="string"||!effort){return request}const next={...r};if(typeof next["reasoning_effort"]!=="string"||!next["reasoning_effort"]){next["reasoning_effort"]=effort}if(nested&&Object.keys(nested).length===1){delete next["reasoning"]}else if(nested){const{effort:_drop,...rest}=nested;next["reasoning"]=rest}return next}__name(flattenReasoningEffort,"flattenReasoningEffort");init_esbuild_shims();var MINIMAX_KNOWN_HOSTS=["api.minimaxi.com","api.minimax.io"];var MINIMAX_HOST_SUFFIXES=[".minimaxi.com",".minimax.io"];var MiniMaxOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"MiniMaxOpenAICompatibleProvider")}static isMiniMaxProvider(config){if(!config.baseUrl)return false;try{const hostname=new URL(config.baseUrl).hostname.toLowerCase();if(MINIMAX_KNOWN_HOSTS.includes(hostname)){return true}return MINIMAX_HOST_SUFFIXES.some(suffix=>hostname.endsWith(suffix))}catch{return false}}buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);baseRequest.tools=baseRequest.tools?.map(tool=>tool.function.parameters===void 0?{...tool,function:{...tool.function,parameters:{type:"object",properties:{}}}}:tool);return baseRequest}getResponseParsingOptions(){return{taggedThinkingTags:true}}};init_esbuild_shims();var MISTRAL_API_HOST="api.mistral.ai";var MISTRAL_MODEL_MARKERS=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function isMistralHostname(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname===MISTRAL_API_HOST||hostname.endsWith(`.${MISTRAL_API_HOST}`)}catch{return false}}__name(isMistralHostname,"isMistralHostname");function isMistralProvider(config){if(isMistralHostname(config))return true;const model=config.model?.toLowerCase()??"";return MISTRAL_MODEL_MARKERS.some(marker=>model.includes(marker))}__name(isMistralProvider,"isMistralProvider");var MistralOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"MistralOpenAICompatibleProvider")}static isMistralProvider=isMistralProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);if(!isMistralHostname(this.contentGeneratorConfig)&&this.getReasoningCapabilities(request.model)?.profile==="deepseek-openai")return baseRequest;return{...baseRequest,messages:baseRequest.messages.map(stripReasoningContent)}}};init_esbuild_shims();var CEREBRAS_API_HOST="api.cerebras.ai";function isCerebrasProvider(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname===CEREBRAS_API_HOST||hostname.endsWith(`.${CEREBRAS_API_HOST}`)}catch{return false}}__name(isCerebrasProvider,"isCerebrasProvider");var CerebrasOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"CerebrasOpenAICompatibleProvider")}static isCerebrasProvider=isCerebrasProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);return{...baseRequest,messages:baseRequest.messages.map(stripReasoningContent)}}};init_esbuild_shims();var FIREWORKS_API_HOST="api.fireworks.ai";function isFireworksProvider(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname===FIREWORKS_API_HOST||hostname.endsWith(`.${FIREWORKS_API_HOST}`)}catch{return false}}__name(isFireworksProvider,"isFireworksProvider");var FireworksOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"FireworksOpenAICompatibleProvider")}static isFireworksProvider=isFireworksProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);return{...baseRequest,messages:baseRequest.messages.map(unmirrorReasoningField)}}};function unmirrorReasoningField(message){if(message.role!=="assistant"){return message}const assistant=message;if(assistant.reasoning!==assistant.reasoning_content){return message}if(typeof assistant.reasoning!=="string"){return message}const{reasoning:_drop,...rest}=assistant;return rest}__name(unmirrorReasoningField,"unmirrorReasoningField");init_esbuild_shims();function isMiMoProvider(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl??"";if(baseUrl){try{const hostname=new URL(baseUrl).hostname.toLowerCase();if(hostname==="xiaomimimo.com"||hostname.endsWith(".xiaomimimo.com")){return true}}catch{}}const model=contentGeneratorConfig.model??"";return model.toLowerCase().startsWith("mimo-")}__name(isMiMoProvider,"isMiMoProvider");var MiMoOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"MiMoOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isMiMoProvider=isMiMoProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);if(this.getReasoningCapabilities(request.model)?.profile&&!isMiMoProvider({...this.contentGeneratorConfig,model:""})||!baseRequest.messages?.length){return baseRequest}return{...baseRequest,messages:baseRequest.messages.map(ensureReasoningContentOnAssistantMessage)}}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??true}}};init_esbuild_shims();init_esbuild_shims();var debugLogger2=createDebugLogger("STREAMING_TOOL_CALL_PARSER");var StreamingToolCallParser=class{static{__name(this,"StreamingToolCallParser")}buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;namelessToolCallIndices=new Set;idToIndexMap=new Map;pendingIndexRemaps=new Map;nextAvailableIndex=0;conflictingToolCallIdentity=false;invalidToolCallIndex=false;addChunk(index,chunk,id,name){const validName=name?.trim()||void 0;if(!Number.isSafeInteger(index)||index<0){this.conflictingToolCallIdentity=true;this.invalidToolCallIndex=true;return{complete:false,error:new Error(`Invalid tool call index: ${index}`)}}if(!id&&!validName&&!chunk.trim()){const depth2=this.depths.get(index)??0;const inString2=this.inStrings.get(index)??false;if(!this.buffers.has(index)||depth2===0&&!inString2){return{complete:false}}}let actualIndex=index;const isKnownId=Boolean(id&&this.idToIndexMap.has(id));const existingName=this.toolCallMeta.get(index)?.name;const isNameOnlyDelta=Boolean(validName&&chunk.length===0&&(!existingName||existingName===validName));if(id){if(this.idToIndexMap.has(id)){actualIndex=this.idToIndexMap.get(id)}else if(this.pendingIndexRemaps.has(index)&&!this.toolCallMeta.get(this.pendingIndexRemaps.get(index))?.id){actualIndex=this.pendingIndexRemaps.get(index);this.idToIndexMap.set(id,actualIndex)}else{if(this.buffers.has(index)){const existingBuffer=this.buffers.get(index);const existingDepth=this.depths.get(index);const existingMeta=this.toolCallMeta.get(index);if(existingMeta?.id&&existingMeta.id!==id){let existingComplete=existingDepth===0;if(existingComplete&&existingBuffer.trim()){try{JSON.parse(existingBuffer)}catch{existingComplete=false}}if(existingComplete){actualIndex=0;while(this.buffers.has(actualIndex))actualIndex+=1;if(!existingMeta.name){this.conflictingToolCallIdentity=true}}else{this.conflictingToolCallIdentity=true}}}this.idToIndexMap.set(id,actualIndex)}}else if(!isNameOnlyDelta){if(this.pendingIndexRemaps.has(index)){actualIndex=this.pendingIndexRemaps.get(index);const existingBuffer=this.buffers.get(actualIndex);const existingDepth=this.depths.get(actualIndex);if(existingDepth===0&&existingBuffer.trim()){try{JSON.parse(existingBuffer);actualIndex=this.findMostRecentIncompleteIndex()}catch{}}}else if(this.buffers.has(index)){const existingBuffer=this.buffers.get(index);const existingDepth=this.depths.get(index);if(existingDepth>0||!existingBuffer.trim()){actualIndex=index}else{try{JSON.parse(existingBuffer);actualIndex=this.findMostRecentIncompleteIndex()}catch{actualIndex=index}}}}if(!this.buffers.has(actualIndex)){this.buffers.set(actualIndex,"");this.depths.set(actualIndex,0);this.inStrings.set(actualIndex,false);this.escapes.set(actualIndex,false);this.toolCallMeta.set(actualIndex,{})}const currentBuffer=this.buffers.get(actualIndex);const currentDepth=this.depths.get(actualIndex);const meta=this.toolCallMeta.get(actualIndex);if(chunk.length===0&&(id||validName)){if(id)meta.id=id;if(validName&&!meta.name)meta.name=validName;if(!meta.name&&meta.id){this.namelessToolCallIndices.add(actualIndex)}else{this.namelessToolCallIndices.delete(actualIndex)}if(actualIndex!==index){this.pendingIndexRemaps.set(index,actualIndex)}return{actualIndex,complete:false}}if(isKnownId&&currentDepth===0){if(currentBuffer.trim()){try{JSON.parse(currentBuffer);debugLogger2.debug(`Ignoring replay chunk for completed toolCall id=${id}`);return{actualIndex,complete:false}}catch{}}}const identityChanged=Boolean(id&&meta.id&&meta.id!==id);if(id)meta.id=id;if(validName){if(!identityChanged&&meta.name&&meta.name!==validName){this.conflictingToolCallIdentity=true}else{meta.name=validName}}if(actualIndex!==index){this.pendingIndexRemaps.set(index,actualIndex)}const currentInString=this.inStrings.get(actualIndex);const currentEscape=this.escapes.get(actualIndex);const newBuffer=currentBuffer+chunk;this.buffers.set(actualIndex,newBuffer);if(!meta.name&&(meta.id||/\S/.test(newBuffer))){this.namelessToolCallIndices.add(actualIndex)}else{this.namelessToolCallIndices.delete(actualIndex)}let depth=currentDepth;let inString=currentInString;let escape=currentEscape;for(const char of chunk){if(!inString){if(char==="{"||char==="[")depth++;else if(char==="}"||char==="]")depth--}if(char==='"'&&!escape){inString=!inString}escape=char==="\\"&&!escape}this.depths.set(actualIndex,depth);this.inStrings.set(actualIndex,inString);this.escapes.set(actualIndex,escape);if(depth===0&&newBuffer.trim().length>0){try{const parsed=JSON.parse(newBuffer);return{actualIndex,complete:true,value:parsed}}catch(e){if(inString){try{const repaired=JSON.parse(newBuffer+'"');return{actualIndex,complete:true,value:repaired,repaired:true}}catch{}}return{actualIndex,complete:false,error:e instanceof Error?e:new Error(String(e))}}}return{actualIndex,complete:false}}getToolCallMeta(index){return this.toolCallMeta.get(index)||{}}hasNamelessToolCall(){return this.namelessToolCallIndices.size>0}hasConflictingToolCallIdentity(){return this.conflictingToolCallIdentity}hasInvalidToolCallIndex(){return this.invalidToolCallIndex}hasInvalidToolCallArguments(){for(const[index,buffer]of this.buffers.entries()){if(!this.toolCallMeta.get(index)?.name||buffer.length===0)continue;if(!parseToolCallArguments(buffer).ok)return true}return false}getCompletedToolCalls(){const completed=[];const emittedIds=new Set;for(const[index,buffer]of this.buffers.entries()){const meta=this.toolCallMeta.get(index);if(meta?.name){if(meta.id){if(emittedIds.has(meta.id)){continue}emittedIds.add(meta.id)}let args={};if(buffer.trim()){try{args=JSON.parse(buffer)}catch{const inString=this.inStrings.get(index);if(inString){try{args=JSON.parse(buffer+'"')}catch{args=safeJsonParse(buffer,{})}}else{args=safeJsonParse(buffer,{})}}if(typeof args!=="object"||args===null||Array.isArray(args)){debugLogger2.debug(`Collapsing non-object arguments for tool call ${meta.name} (id=${meta.id}) at index ${index}; buffer likely polluted by a misrouted fragment`);args={}}}else{debugLogger2.debug(`Emitting no-argument tool call ${meta.name} (id=${meta.id}) at index ${index} with empty buffer`)}completed.push({id:meta.id,name:meta.name,args,index})}}return completed}findNextAvailableIndex(){while(this.buffers.has(this.nextAvailableIndex)){const buffer=this.buffers.get(this.nextAvailableIndex);const depth=this.depths.get(this.nextAvailableIndex);const meta=this.toolCallMeta.get(this.nextAvailableIndex);if(!meta?.name||depth>0||!meta?.id){return this.nextAvailableIndex}if(buffer.trim()){try{JSON.parse(buffer)}catch{return this.nextAvailableIndex}}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let maxIndex=-1;for(const[index,buffer]of this.buffers.entries()){const depth=this.depths.get(index);const meta=this.toolCallMeta.get(index);if(meta?.id&&(depth>0||!buffer.trim()&&!meta?.name)){maxIndex=Math.max(maxIndex,index)}else if(buffer.trim()){try{JSON.parse(buffer)}catch{maxIndex=Math.max(maxIndex,index)}}}return maxIndex>=0?maxIndex:this.findNextAvailableIndex()}resetIndex(index){this.buffers.set(index,"");this.depths.set(index,0);this.inStrings.set(index,false);this.escapes.set(index,false);this.toolCallMeta.set(index,{});this.namelessToolCallIndices.delete(index);for(const[providerIndex,actualIndex]of this.pendingIndexRemaps){if(providerIndex===index||actualIndex===index){this.pendingIndexRemaps.delete(providerIndex)}}}reset(){this.buffers.clear();this.depths.clear();this.inStrings.clear();this.escapes.clear();this.toolCallMeta.clear();this.namelessToolCallIndices.clear();this.idToIndexMap.clear();this.pendingIndexRemaps.clear();this.nextAvailableIndex=0;this.conflictingToolCallIdentity=false;this.invalidToolCallIndex=false}getBuffer(index){return this.buffers.get(index)||""}getState(index){return{depth:this.depths.get(index)||0,inString:this.inStrings.get(index)||false,escape:this.escapes.get(index)||false}}hasIncompleteToolCalls(){for(const[index]of this.buffers.entries()){const meta=this.toolCallMeta.get(index);if(!meta?.name)continue;const depth=this.depths.get(index)||0;const inString=this.inStrings.get(index)||false;if(depth>0||inString){return true}}return false}};var debugLogger3=createDebugLogger("OPENAI_PIPELINE");var OPENAI_STRICT_SCHEMA_KEYS=new Set(["type","properties","required","additionalProperties","items","description","enum"]);var OPENAI_STRICT_UNSUPPORTED_SCHEMA_KEYS=new Set(["minLength","maxLength","minItems","maxItems","uniqueItems"]);function asObject(value){if(!value||typeof value!=="object"||Array.isArray(value)){return void 0}return value}__name(asObject,"asObject");function profileReasoning(profile,reasoning,disableField){if(reasoning===void 0)return{};const enabled=reasoning!==false;const effort=reasoning&&reasoning.effort;switch(profile){case"openai-reasoning":return{reasoning:enabled?reasoning:{enabled:false}};case"openai-effort":case"dashscope-effort":return effort||!enabled?{reasoning_effort:enabled?effort:"none"}:{};case"deepseek-openai":return{...disableField==="enable_thinking"?{enable_thinking:enabled}:{thinking:{type:enabled?"enabled":"disabled"}},...effort?{reasoning_effort:effort}:{}};case"dashscope-thinking":return{enable_thinking:enabled};case"qwen-chat-template":return{chat_template_kwargs:{enable_thinking:enabled}};default:return{}}}__name(profileReasoning,"profileReasoning");function applyConfiguredReasoningEffort(request,capabilities){if(capabilities?.profile){const loose2=request;const{reasoning:reasoning2,...rest2}=loose2;const{effort:_effort,...siblings}=asObject(reasoning2)??{};return{...Object.keys(siblings).length?{reasoning:siblings}:{},...profileReasoning(capabilities.profile,reasoning2,capabilities.disableField),...rest2}}if(!capabilities||capabilities.toggleOnly||!Array.isArray(capabilities.efforts)){return request}const loose=request;const reasoning=asObject(loose["reasoning"]);if(!reasoning||!("effort"in reasoning))return request;const effort=capabilities.efforts.find(candidate=>candidate===reasoning["effort"]);if(effort&&getGptReasoningCapabilities(loose["model"]))return request;const{effort:_drop,...rest}=reasoning;const next={...loose};if(Object.keys(rest).length>0)next["reasoning"]=rest;else delete next["reasoning"];if(effort&&next["reasoning_effort"]===void 0){next["reasoning_effort"]=effort}return next}__name(applyConfiguredReasoningEffort,"applyConfiguredReasoningEffort");function normalizeSchemaType(value){if(typeof value!=="string")return void 0;const normalized=value.toLowerCase();return["object","array","string","number","integer","boolean","null"].includes(normalized)?normalized:void 0}__name(normalizeSchemaType,"normalizeSchemaType");function normalizeOpenAIStrictSchema(schema){const source=asObject(schema);if(!source)return void 0;const type=normalizeSchemaType(source["type"]);if(!type)return void 0;const normalized={type};for(const[key,value]of Object.entries(source)){if(key==="type"||OPENAI_STRICT_UNSUPPORTED_SCHEMA_KEYS.has(key)||!OPENAI_STRICT_SCHEMA_KEYS.has(key)){continue}normalized[key]=value}if(type==="object"){const properties=asObject(source["properties"]);if(!properties)return void 0;const normalizedProperties={};for(const[key,value]of Object.entries(properties)){const property=normalizeOpenAIStrictSchema(value);if(!property)return void 0;normalizedProperties[key]=property}const propertyKeys=Object.keys(normalizedProperties);const required=source["required"];if(!Array.isArray(required)||!propertyKeys.every(key=>required.includes(key))||required.length!==propertyKeys.length){return void 0}normalized["properties"]=normalizedProperties;normalized["required"]=required;normalized["additionalProperties"]=false}if(type==="array"){const items=normalizeOpenAIStrictSchema(source["items"]);if(!items)return void 0;normalized["items"]=items}return normalized}__name(normalizeOpenAIStrictSchema,"normalizeOpenAIStrictSchema");function isRequiredThinkingError(error){if(getErrorStatus(error)!==400)return false;const providerMessage=getRateLimitErrorDetails(error).providerMessage;const message=`${getErrorMessage(error)} ${providerMessage??""}`;return message.includes("enable_thinking")&&/(?:restricted to|must be) true\b/i.test(message)}__name(isRequiredThinkingError,"isRequiredThinkingError");function wireRequestHasMediaContent(wireRequest){const messages=wireRequest?.["messages"];if(!Array.isArray(messages))return false;return messages.some(message=>{const content=message.content;return Array.isArray(content)&&content.some(part=>{const type=part.type;return type==="image_url"||type==="input_audio"||type==="video_url"||type==="file"})})}__name(wireRequestHasMediaContent,"wireRequestHasMediaContent");var StreamContentError=class extends Error{static{__name(this,"StreamContentError")}constructor(message){super(message);this.name="StreamContentError"}};var NON_SSE_BODY_PREFIX_LIMIT=512;function isSSECompatibleContentType(contentType){if(!contentType)return true;const mediaType=(contentType.split(";")[0]??"").trim().toLowerCase();return mediaType==="text/event-stream"||mediaType==="application/x-ndjson"||mediaType==="application/stream+json"}__name(isSSECompatibleContentType,"isSSECompatibleContentType");function hasNonThoughtCandidateParts(response){return Boolean(response.candidates?.some(candidate=>candidate.content?.parts?.some(part=>!part.thought)))}__name(hasNonThoughtCandidateParts,"hasNonThoughtCandidateParts");function flushTrailingThinkingTag(abortSignal,context,finishSeen,completed){if(abortSignal?.aborted===true||context.hasThinkingTagInReasoning||finishSeen||context.pendingUntrustedResponseParts!==void 0||context.taggedThinkingParser!==void 0){return{}}const filter=context.trailingThinkingTagFilter;const trailingText=filter?.parse("",true,completed);const sanitizedTagName=filter?.sanitizedTagName;if(filter){filter.sanitizedTagName=void 0}if(!trailingText)return{sanitizedTagName};const response=new GenerateContentResponse;response.candidates=[{content:{parts:[{text:trailingText}],role:"model"},index:0}];return{response,sanitizedTagName}}__name(flushTrailingThinkingTag,"flushTrailingThinkingTag");var NonSSEResponseError=class extends Error{constructor(contentType,httpStatus,bodyPrefix,requestId){const preview=bodyPrefix.length>0?` Body prefix: ${bodyPrefix}`:"";super(`Streaming request received a non-SSE response (HTTP ${httpStatus}, Content-Type: ${contentType||"unknown"}).${preview}`);this.contentType=contentType;this.httpStatus=httpStatus;this.bodyPrefix=bodyPrefix;this.requestId=requestId;this.name="NonSSEResponseError";this.status=httpStatus;this.request_id=requestId}static{__name(this,"NonSSEResponseError")}status;request_id};var PROVIDER_OUTPUT_BUDGET_KEYS=["max_completion_tokens","max_new_tokens"];function hasProviderOutputBudgetKey(samplingParams){return PROVIDER_OUTPUT_BUDGET_KEYS.some(key=>samplingParams[key]!==void 0)}__name(hasProviderOutputBudgetKey,"hasProviderOutputBudgetKey");function getWireOutputBudget(request){if(typeof request.max_tokens==="number"&&request.max_tokens>0){return request.max_tokens}const wire=request;for(const key of PROVIDER_OUTPUT_BUDGET_KEYS){const value=wire[key];if(typeof value==="number"&&value>0){return value}}return void 0}__name(getWireOutputBudget,"getWireOutputBudget");function clampProviderOutputBudgetKeys(samplingParams,requestMaxTokens){if(typeof requestMaxTokens!=="number")return samplingParams;for(const key of PROVIDER_OUTPUT_BUDGET_KEYS){const value=samplingParams[key];if(typeof value==="number"&&value>requestMaxTokens){samplingParams[key]=requestMaxTokens}}return samplingParams}__name(clampProviderOutputBudgetKeys,"clampProviderOutputBudgetKeys");var ContentGenerationPipeline=class{constructor(config){this.config=config;this.contentGeneratorConfig=config.contentGeneratorConfig;this.client=this.config.provider.buildClient();this.streamIdleTimeoutMs=resolveStreamIdleTimeoutMs(this.contentGeneratorConfig);this.streamMaxLifetimeMs=resolveStreamMaxLifetimeMs(this.contentGeneratorConfig)}static{__name(this,"ContentGenerationPipeline")}client;contentGeneratorConfig;requiredThinkingModels=new Set;streamIdleTimeoutMs;streamMaxLifetimeMs;async execute(request,userPromptId){return this.executeWithErrorHandling(request,userPromptId,false,async(openaiRequest,context,telemetryAttempt)=>{const parentSignal=request.config?.abortSignal;const perRequestAc=parentSignal?createChildAbortController(parentSignal):void 0;try{const openaiResponse=await this.client.chat.completions.create(openaiRequest,{signal:perRequestAc?.signal});reportOpenAiResponse(telemetryAttempt,openaiResponse);const llmResponse=OpenAIContentConverter.convertOpenAIResponseToLlm(openaiResponse,context);return llmResponse}finally{perRequestAc?.abort()}})}async executeStream(request,userPromptId){return this.executeWithErrorHandling(request,userPromptId,true,async(openaiRequest,context,telemetryAttempt)=>{const parentSignal=request.config?.abortSignal;const perRequestAc=createChildAbortController(parentSignal);let stream;try{const createPromise=this.client.chat.completions.create(openaiRequest,{signal:perRequestAc.signal});if(typeof createPromise.withResponse==="function"){const{data,response:httpResponse,request_id}=await createPromise.withResponse();stream=data;const contentType=httpResponse.headers.get("content-type")??null;if(!isSSECompatibleContentType(contentType)){let bodyPrefix="";try{if(httpResponse.body){const reader=httpResponse.body.getReader();const{value}=await reader.read();reader.releaseLock();if(value){bodyPrefix=new TextDecoder().decode(value).slice(0,NON_SSE_BODY_PREFIX_LIMIT)}}}catch{}throw new NonSSEResponseError(contentType,httpResponse.status,bodyPrefix,request_id)}}else{stream=await createPromise}}catch(e){perRequestAc.abort();throw e}const idleMs=this.streamIdleTimeoutMs;const maxLifetimeMs=this.streamMaxLifetimeMs;const guarded=idleMs>0||maxLifetimeMs>0?withStreamGuards(stream,idleMs,maxLifetimeMs,()=>perRequestAc.abort(),parentSignal):stream;const innerStream=this.processStreamWithLogging(guarded,context,request,openaiRequest,userPromptId,telemetryAttempt);async function*drainThenCleanup(){try{yield*innerStream}finally{perRequestAc.abort()}}__name(drainThenCleanup,"drainThenCleanup");return drainThenCleanup()})}async*processStreamWithLogging(stream,context,request,openaiRequest,userPromptId,telemetryAttempt){let pendingFinishResponse=null;let finishYielded=false;let finishSeen=false;let contentYielded=request.continuationInFlight===true;let pendingFinishProtocolTagSanitized;const logPendingProtocolTagSanitized=__name((response,sanitization)=>{if(!sanitization)return;const event=new ProtocolTagSanitizedEvent({model:context.model,promptId:userPromptId,responseId:response?.responseId,tagName:sanitization.tagName,toolCallCount:sanitization.toolCallCount});debugLogger3.warn("Sanitized a model protocol tag",{model:event.model,promptId:event.prompt_id,responseId:event.response_id,tagName:event.tag_name,toolCallCount:event.tool_call_count});logProtocolTagSanitized(this.config.cliConfig,event)},"logPendingProtocolTagSanitized");const logFlushedTrailingTag=__name(flushed=>{if(flushed.sanitizedTagName){logPendingProtocolTagSanitized(flushed.response,{tagName:flushed.sanitizedTagName,toolCallCount:0})}return flushed.response},"logFlushedTrailingTag");try{for await(const chunk of stream){reportOpenAiChunk(telemetryAttempt,chunk);if(chunk.choices?.[0]?.finish_reason==="error_finish"){const errorContent=chunk.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new StreamContentError(errorContent)}const response=OpenAIContentConverter.convertOpenAIChunkToLlm(chunk,context);const sanitization=context.protocolTagSanitized;if(sanitization){context.protocolTagSanitized=void 0}if((response.candidates?.[0]?.content?.parts?.length??0)===0&&!response.candidates?.[0]?.finishReason&&!response.usageMetadata&&getToolCallPreparations(response).length===0){continue}if(response.candidates?.[0]?.finishReason){finishSeen=true}if(pendingFinishProtocolTagSanitized&&pendingFinishResponse&&!response.candidates?.[0]?.finishReason&&response.candidates?.some(candidate=>(candidate.content?.parts?.length??0)>0)){throw new InvalidStreamError("Model response continued after a finish reason.","PROTOCOL_TAG_LEAK")}if(finishYielded){if(response.usageMetadata){const pending=pendingFinishResponse;if(pending){pending.usageMetadata=response.usageMetadata}}continue}if(!pendingFinishResponse&&response.candidates?.[0]?.finishReason&&sanitization){pendingFinishProtocolTagSanitized=sanitization}const shouldYield=this.handleChunkMerging(response,pendingFinishResponse,mergedResponse=>{pendingFinishResponse=mergedResponse});if(shouldYield){if(pendingFinishResponse){logPendingProtocolTagSanitized(pendingFinishResponse,pendingFinishProtocolTagSanitized);this.settleParkedTruncationOverride(pendingFinishResponse,context);finishYielded=true;yield pendingFinishResponse}else{contentYielded||=hasNonThoughtCandidateParts(response);logPendingProtocolTagSanitized(response,sanitization);yield response}}}if(context.pendingThinkingTagCandidate&&!context.pendingThinkingTagCandidate.closingTagName&&!/\S/.test(context.pendingThinkingTagCandidate.text)){const pendingParts=context.pendingUntrustedResponseParts;context.pendingThinkingTagCandidate=void 0;context.pendingUntrustedResponseParts=void 0;if(pendingParts?.length){const response=new GenerateContentResponse;response.candidates=[{content:{parts:pendingParts,role:"model"},index:0}];contentYielded||=hasNonThoughtCandidateParts(response);yield response}}else if(context.pendingThinkingTagCandidate||context.responseParsingOptions?.taggedThinkingTagsAfterReasoning&&context.taggedThinkingParser?.hasUnclosedThought()){throw new InvalidStreamError("Model response leaked thinking tags.","PROTOCOL_TAG_LEAK")}const flushedTail=logFlushedTrailingTag(flushTrailingThinkingTag(request.config?.abortSignal,context,finishSeen,true));if(flushedTail){contentYielded||=hasNonThoughtCandidateParts(flushedTail);yield flushedTail}if(pendingFinishResponse&&!finishYielded){logPendingProtocolTagSanitized(pendingFinishResponse,pendingFinishProtocolTagSanitized);this.settleParkedTruncationOverride(pendingFinishResponse,context);finishYielded=true;yield pendingFinishResponse}}catch(error){await this.invalidateOmniOssCacheOnError(openaiRequest,error);if(error instanceof InvalidStreamError){throw error}const flushedTail=logFlushedTrailingTag(flushTrailingThinkingTag(request.config?.abortSignal,context,finishSeen,false));if(flushedTail){contentYielded||=hasNonThoughtCandidateParts(flushedTail);yield flushedTail}const parked=pendingFinishResponse;const parkedHasToolCall=parked?.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall));if(pendingFinishResponse&&!finishYielded&&request.config?.abortSignal?.aborted!==true&&(!parkedHasToolCall||contentYielded)){logPendingProtocolTagSanitized(pendingFinishResponse,pendingFinishProtocolTagSanitized);if(parkedHasToolCall){markFlushedToolCallPark(pendingFinishResponse)}this.settleParkedTruncationOverride(pendingFinishResponse,context);yield pendingFinishResponse;finishYielded=true}if(error instanceof StreamContentError){throw redactProxyError(error)}if(error instanceof StreamInactivityTimeoutError||error instanceof StreamLifetimeExceededError){const isLifetime=error instanceof StreamLifetimeExceededError;debugLogger3.warn(isLifetime?"OpenAI stream lifetime cap exceeded":"OpenAI stream inactivity timeout",{chunksReceived:error.chunksReceived,wallClockMs:error.streamLifetimeMs,...isLifetime?{maxLifetimeMs:error.maxLifetimeMs}:{idleMs:error.idleMs}});throw redactProxyError(error)}if(context.pendingThinkingTagCandidate?.closingTagName&&request.config?.abortSignal?.aborted!==true){context.pendingThinkingTagCandidate=void 0;context.pendingUntrustedResponseParts=void 0;throw new InvalidStreamError("Model response leaked thinking tags.","PROTOCOL_TAG_LEAK")}await this.handleError(error,context,request)}}handleChunkMerging(response,pendingFinishResponse,setPendingFinish){const isFinishChunk=response.candidates?.[0]?.finishReason;if(isFinishChunk){if(pendingFinishResponse){if(response.usageMetadata){pendingFinishResponse.usageMetadata=response.usageMetadata}if(response.modelVersion){pendingFinishResponse.modelVersion=response.modelVersion}setPendingFinish(pendingFinishResponse)}else{setPendingFinish(response)}return false}else if(pendingFinishResponse){const mergedResponse=new GenerateContentResponse;mergedResponse.candidates=pendingFinishResponse.candidates;if(response.usageMetadata){mergedResponse.usageMetadata=response.usageMetadata}else{mergedResponse.usageMetadata=pendingFinishResponse.usageMetadata}mergedResponse.responseId=response.responseId||pendingFinishResponse.responseId;mergedResponse.createTime=response.createTime||pendingFinishResponse.createTime;mergedResponse.modelVersion=response.modelVersion||pendingFinishResponse.modelVersion;mergedResponse.promptFeedback=response.promptFeedback||pendingFinishResponse.promptFeedback;setPendingFinish(mergedResponse);return true}return true}settleParkedTruncationOverride(response,context){const parked=context.pendingTruncationOverride;if(!parked){return}context.pendingTruncationOverride=void 0;const candidate=response.candidates?.[0];if(!candidate||candidate.finishReason!==FinishReason.MAX_TOKENS){return}const verdict=corroborateTruncationFromCompletionTokens(response.usageMetadata?.candidatesTokenCount,context.maxOutputTokens);if(verdict==="disproved"){candidate.finishReason=parked.finishReason;markToolCallArgumentsIncomplete(candidate.content?.parts)}debugLogger3.debug("Settled a parked truncation override",{candidatesTokenCount:response.usageMetadata?.candidatesTokenCount??null,maxOutputTokens:context.maxOutputTokens??null,verdict,downgraded:verdict==="disproved",from:FinishReason.MAX_TOKENS,to:candidate.finishReason})}async buildRequest(request,userPromptId,context,isStreaming){const reasoningCapabilities=resolveReasoningForModel(this.config.cliConfig,this.contentGeneratorConfig,context.model);const convertedMessages=OpenAIContentConverter.convertLlmRequestToOpenAI(request,context);const messages=reasoningCapabilities?.profile==="deepseek-openai"?convertedMessages.map(ensureReasoningContentOnAssistantMessage):convertedMessages;let baseRequest={messages,...this.buildGenerateContentConfig({...request,model:context.model}),...this.buildResponseFormat(request),model:context.model};if(isStreaming){baseRequest.stream=true;baseRequest.stream_options={include_usage:true}}else{baseRequest.stream=false}const effectiveReasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model:context.model},reasoningCapabilities);if(reasoningCapabilities&&!("reasoning"in baseRequest)&&effectiveReasoning&&request.config?.thinkingConfig?.includeThoughts!==false){baseRequest={...baseRequest,reasoning:effectiveReasoning}}if(this.contentGeneratorConfig.samplingParams?.["reasoning"]===void 0&&(!reasoningCapabilities?.profile&&!getBuiltinDeepSeekReasoning({...this.contentGeneratorConfig,model:context.model})||this.contentGeneratorConfig.extra_body?.["reasoning"]===void 0)&&(reasoningCapabilities?.profile||!isOpenRouterHostname(this.contentGeneratorConfig))){baseRequest=applyConfiguredReasoningEffort(baseRequest,reasoningCapabilities)}if(request.config?.tools&&request.config.tools.length>0){baseRequest.tools=await OpenAIContentConverter.convertLlmToolsToOpenAI(request.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto");const fcMode=request.config?.toolConfig?.functionCallingConfig?.mode;if(fcMode==="ANY"){baseRequest["tool_choice"]="required"}else if(fcMode==="NONE"){baseRequest["tool_choice"]="none"}}let providerRequest=this.config.provider.buildRequest(baseRequest,userPromptId,trailingReattachPartCount(request.contents));if(this.contentGeneratorConfig.enableCacheControl!==false&&isOfficialOpenAIEndpoint(this.contentGeneratorConfig)){providerRequest=applyOfficialOpenAIPromptCaching(providerRequest,this.config.cliConfig.getSessionId?.(),request.promptCacheSharing===true,isInForkExecution()?void 0:getCurrentAgentId()??void 0)}const model=(context.model??"").toLowerCase();const isDashScope=DashScopeOpenAICompatibleProvider.isDashScopeProvider(this.contentGeneratorConfig);const explicitThinkingMandatory=reasoningCapabilities?.canDisable===false||this.requiresThinking(model);const profile=reasoningCapabilities?.profile;const thinkingMandatory=explicitThinkingMandatory||!profile&&getGptReasoningCapabilities(model)?.thinkingMandatory===true;const reasoningDisabled=request.config?.thinkingConfig?.includeThoughts===false||this.contentGeneratorConfig.reasoning===false;if((profile==="openai-effort"||profile==="dashscope-effort")&&isReasoningEffortPlaceholder(providerRequest.reasoning_effort)&&effectiveReasoning&&this.contentGeneratorConfig.samplingParams?.["reasoning"]===void 0&&this.contentGeneratorConfig.extra_body?.["reasoning"]===void 0)providerRequest.reasoning_effort=effectiveReasoning.effort;if(reasoningDisabled&&profile){const typed2=providerRequest;if(!thinkingMandatory||request.config?.thinkingConfig?.includeThoughts===false){delete typed2["reasoning"];delete typed2["reasoning_effort"]}if(!thinkingMandatory){if(isDashScope&&profile==="dashscope-effort"){delete typed2["thinking_budget"];delete typed2["enable_thinking"]}const template=asObject(typed2["chat_template_kwargs"]);Object.assign(typed2,profileReasoning(profile,false,reasoningCapabilities?.disableField));if(profile==="qwen-chat-template"){delete typed2["enable_thinking"];typed2["chat_template_kwargs"]={...template,enable_thinking:false}}else if(reasoningCapabilities?.disableField==="enable_thinking"){delete typed2["reasoning_effort"];typed2["enable_thinking"]=false}}}else if(reasoningDisabled){const typed2=providerRequest;if(!thinkingMandatory&&isQwenFamilyWireModel(model)){if(isDashScope){if(isTieredEffortWireModel(model)){delete typed2["enable_thinking"];delete typed2["thinking_budget"];typed2["reasoning_effort"]="none"}else{typed2["enable_thinking"]=false}}else{delete typed2["enable_thinking"];const existing=typed2["chat_template_kwargs"]??{};typed2["chat_template_kwargs"]={...existing,enable_thinking:false}}}if(!thinkingMandatory){if(reasoningCapabilities?.disableField==="reasoning_effort"){delete typed2["enable_thinking"];delete typed2["thinking_budget"];typed2["reasoning_effort"]="none"}else if(reasoningCapabilities?.disableField==="enable_thinking"){typed2["enable_thinking"]=false}}if("reasoning"in typed2){delete typed2["reasoning"]}if("reasoning_effort"in typed2&&typed2["reasoning_effort"]!=="none"){delete typed2["reasoning_effort"]}const gptReasoning=getGptReasoningCapabilities(model);if(gptReasoning&&!reasoningCapabilities&&!gptReasoning.thinkingMandatory&&!thinkingMandatory&&!isOpenRouterHostname(this.contentGeneratorConfig)){typed2["reasoning_effort"]="none"}if(isDeepSeekHostname(this.contentGeneratorConfig)||reasoningCapabilities?.disableField==="thinking"){typed2["thinking"]={type:"disabled"}}if(!thinkingMandatory&&isOpenRouterHostname(this.contentGeneratorConfig)){typed2["reasoning"]={enabled:false}}}if(thinkingMandatory){const typed2=providerRequest;if(typed2["enable_thinking"]===false){delete typed2["enable_thinking"]}if(typed2["reasoning_effort"]==="none"){delete typed2["reasoning_effort"]}const thinking=asObject(typed2["thinking"]);if(thinking?.["type"]==="disabled"){const remaining={...thinking};delete remaining["type"];if(Object.keys(remaining).length>0)typed2["thinking"]=remaining;else delete typed2["thinking"]}const chatTemplateKwargs=typed2["chat_template_kwargs"];if(chatTemplateKwargs?.["enable_thinking"]===false){const remaining={...chatTemplateKwargs};delete remaining["enable_thinking"];if(Object.keys(remaining).length>0){typed2["chat_template_kwargs"]=remaining}else{delete typed2["chat_template_kwargs"]}}}const typed=providerRequest;const reasoningEffort=typed["reasoning_effort"];const thinkingBudget=typed["thinking_budget"];if(isDashScope&&typed["tool_choice"]==="required"&&(explicitThinkingMandatory||isQwenFamilyWireModel(model)&&(typed["enable_thinking"]===true||thinkingBudget!=null&&typed["enable_thinking"]!==false||typeof reasoningEffort==="string"&&reasoningEffort!=="none"))){debugLogger3.debug("DashScope: dropping tool_choice=required while thinking is enabled",{model,reasoningEffort,thinkingBudget,explicitThinkingMandatory});delete typed["tool_choice"]}return providerRequest}buildResponseFormat(request){if(!isOfficialOpenAIEndpoint(this.contentGeneratorConfig))return{};if(request.config?.responseMimeType!=="application/json")return{};const schema=request.config.responseJsonSchema??request.config.responseSchema;if(!schema)return{response_format:{type:"json_object"}};const strictSchema=normalizeOpenAIStrictSchema(schema);if(!strictSchema)return{response_format:{type:"json_object"}};return{response_format:{type:"json_schema",json_schema:{name:"response",schema:strictSchema,strict:true}}}}requiresThinking(model){const normalizedModel=model.toLowerCase();return this.requiredThinkingModels.has(normalizedModel)||this.contentGeneratorConfig.thinkingMandatory===true&&normalizedModel===(this.contentGeneratorConfig.model??"").toLowerCase()}buildGenerateContentConfig(request){const defaultSamplingParams=this.config.provider.getDefaultGenerationConfig();const configSamplingParams=this.contentGeneratorConfig.samplingParams;const getParameterValue=__name((configKey,requestKey)=>{const configValue=configSamplingParams?.[configKey];const requestValue=requestKey?request.config?.[requestKey]:void 0;const defaultValue=requestKey?defaultSamplingParams[requestKey]:void 0;if(configValue!==void 0)return configValue;if(requestValue!==void 0)return requestValue;return defaultValue},"getParameterValue");const addParameterIfDefined=__name((key,configKey,requestKey)=>{const value=getParameterValue(configKey,requestKey);return value!==void 0?{[key]:value}:{}},"addParameterIfDefined");if(configSamplingParams!==void 0){const rawEffort={...configSamplingParams,...this.contentGeneratorConfig.extra_body}["reasoning_effort"];const samplingParams=getGptReasoningCapabilities(request.model||this.contentGeneratorConfig.model)&&configSamplingParams["reasoning"]===void 0&&(isReasoningEffortPlaceholder(configSamplingParams["reasoning_effort"])||isReasoningEffortPlaceholder(rawEffort))?{...this.buildReasoningConfig(request),...configSamplingParams}:configSamplingParams;const requestMaxTokens=request.config?.maxOutputTokens;const maxTokens=reconcileMaxTokens(configSamplingParams.max_tokens,requestMaxTokens)??configSamplingParams.max_tokens??(hasProviderOutputBudgetKey(configSamplingParams)?void 0:requestMaxTokens);return clampProviderOutputBudgetKeys(maxTokens!==void 0?{...samplingParams,max_tokens:maxTokens}:{...samplingParams},requestMaxTokens)}const params={...addParameterIfDefined("temperature","temperature","temperature"),...addParameterIfDefined("top_p","top_p","topP"),...addParameterIfDefined("max_tokens","max_tokens","maxOutputTokens"),...addParameterIfDefined("top_k","top_k","topK"),...addParameterIfDefined("repetition_penalty","repetition_penalty"),...addParameterIfDefined("presence_penalty","presence_penalty","presencePenalty"),...addParameterIfDefined("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(request)};return params}buildReasoningConfig(request){if(request.config?.thinkingConfig?.includeThoughts===false){return{}}const reasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model:request.model||this.contentGeneratorConfig.model},resolveReasoningForModel(this.config.cliConfig,this.contentGeneratorConfig,request.model));if(reasoning===false||reasoning===void 0){return{}}return{reasoning}}async executeWithErrorHandling(request,userPromptId,isStreaming,executor){const context=this.createRequestContext(request,isStreaming);let openaiRequest;const executeAttempt=__name(async(attemptContext=context)=>{openaiRequest=await this.buildRequest(request,userPromptId,attemptContext,isStreaming);attemptContext.maxOutputTokens=getWireOutputBudget(openaiRequest);openaiRequestCaptureContext.getStore()?.(openaiRequest);runtimeDiagnostics.recordOpenAIWireRequest(openaiRequest);const telemetryAttempt=reportOpenAiRequest(openaiRequest);return executor(openaiRequest,attemptContext,telemetryAttempt)},"executeAttempt");try{return await executeAttempt()}catch(error){await this.invalidateOmniOssCacheOnError(openaiRequest,error);const model=context.model.toLowerCase();const wireRequest=openaiRequest;const chatTemplateKwargs=wireRequest?.["chat_template_kwargs"];if((wireRequest?.["enable_thinking"]===false||chatTemplateKwargs?.["enable_thinking"]===false||wireRequest?.["reasoning_effort"]==="none")&&request.config?.abortSignal?.aborted!==true&&isRequiredThinkingError(error)){this.requiredThinkingModels.add(model);debugLogger3.warn("Retrying with required thinking enabled",{model,originalError:getErrorMessage(error)});try{return await executeAttempt()}catch(retryError){return await this.handleError(retryError,context,request)}}if(request.config?.abortSignal?.aborted!==true&&getErrorStatus(error)===400&&wireRequestHasMediaContent(wireRequest)){debugLogger3.warn("Media-bearing request rejected with 400; retrying once with media degraded to placeholders",{model,originalError:getErrorMessage(error)});try{return await executeAttempt({...context,modalities:{}})}catch(retryError){return await this.handleError(retryError,context,request)}}return await this.handleError(error,context,request)}}async invalidateOmniOssCacheOnError(openaiRequest,error){try{if(!this.config.cliConfig.isOmniEnabled?.())return;if(getErrorStatus(error)===429)return;const message=getErrorMessage(error);if(!/oss:\/\//i.test(message)&&!(/download/i.test(message)&&/resource|media/i.test(message))){return}const urls=new Set;for(const m of openaiRequest?.messages??[]){const content=m.content;if(!Array.isArray(content))continue;for(const part of content){const p=part;for(const u of[p.image_url?.url,p.video_url?.url,p.input_audio?.data]){if(typeof u==="string"&&u.startsWith("oss://"))urls.add(u)}}}if(urls.size===0)return;const{OmniUploadCache}=await import("./upload-cache-2R5KHOGA.js");const{OmniObjectStore}=await import("./storage-JMQT2RMJ.js");const store=new OmniObjectStore(this.config.cliConfig.storage.getQwenDir());const cache=new OmniUploadCache(store.getOmniRootDir());for(const u of urls)await cache.invalidateByUrl(u)}catch{}}async handleError(error,context,request){this.config.errorHandler.handle(redactProxyError(error),context,request)}createRequestContext(request,isStreaming){const effectiveModel=getRequestModel(this.contentGeneratorConfig,request.model||this.contentGeneratorConfig.model);const providerOverrides=this.config.provider.getRequestContextOverrides?.()??{};const toolCallParser=isStreaming?new StreamingToolCallParser:void 0;const responseParsingOptions=this.config.provider.getResponseParsingOptions?.(effectiveModel);const taggedThinkingParser=isStreaming&&responseParsingOptions?.taggedThinkingTags?new TaggedThinkingParser:void 0;return{model:effectiveModel,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:providerOverrides.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??true,toolResultContentFormat:providerOverrides.toolResultContentFormat??this.contentGeneratorConfig.toolResultContentFormat??"parts",...toolCallParser?{toolCallParser}:{},...responseParsingOptions?{responseParsingOptions}:{},...taggedThinkingParser?{taggedThinkingParser}:{}}}};init_esbuild_shims();var debugLogger4=createDebugLogger("OPENAI_ERROR");var EnhancedErrorHandler=class{constructor(shouldSuppressLogging=()=>false){this.shouldSuppressLogging=shouldSuppressLogging}static{__name(this,"EnhancedErrorHandler")}handle(error,context,request){const redactedError=redactProxyError(error);const isTimeoutError=this.isTimeoutError(redactedError);const errorMessage=this.buildErrorMessage(redactedError,context,isTimeoutError);if(!this.shouldSuppressErrorLogging(redactedError,request)){debugLogger4.error("OpenAI API Error:",errorMessage,this.buildDiagnostics(redactedError,context))}if(isTimeoutError){const timeoutError=new Error(`${errorMessage}
3
+ import{OpenAIContentConverter,TaggedThinkingParser,corroborateTruncationFromCompletionTokens,openaiRequestCaptureContext}from"./chunk-SHR6GNT4.js";import{applyOfficialOpenAIPromptCaching,isOfficialOpenAIEndpoint,markToolCallArgumentsIncomplete}from"./chunk-T2F7KYYR.js";import{DashScopeOpenAICompatibleProvider,DefaultOpenAICompatibleProvider}from"./chunk-RHEMFKMX.js";import{getCurrentAgentId}from"./chunk-7J2TOJMG.js";import{extractTextFromContents}from"./chunk-SLYWXBG7.js";import{StreamInactivityTimeoutError,StreamLifetimeExceededError,parseToolCallArguments,resolveStreamIdleTimeoutMs,resolveStreamMaxLifetimeMs,withStreamGuards}from"./chunk-WO3F62ZD.js";import{runtimeDiagnostics}from"./chunk-VFB6Q74I.js";import{reportOpenAiChunk,reportOpenAiRequest,reportOpenAiResponse}from"./chunk-YTKRKP2I.js";import{InvalidStreamError,getToolCallPreparations,markFlushedToolCallPark,trailingReattachPartCount}from"./chunk-V3XYE727.js";import{safeJsonParse}from"./chunk-CJZJ36VK.js";import{applyDeepSeekReasoningEffort,getBuiltinDeepSeekReasoning,getEffectiveReasoning,getRequestModel,isOpenRouterHostname,resolveReasoningForModel}from"./chunk-DIHJELGW.js";import{getRateLimitErrorDetails,getTransportCode}from"./chunk-WZDBBDRD.js";import{createChildAbortController}from"./chunk-476F6QIM.js";import{ProtocolTagSanitizedEvent,logProtocolTagSanitized}from"./chunk-DR3HLUJ5.js";import{REASONING_EFFORT_TIERS,getGptReasoningCapabilities,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,reconcileMaxTokens}from"./chunk-TAAJ7TDB.js";import{redactProxyError}from"./chunk-ZZZAYAJW.js";import{FinishReason,GenerateContentResponse}from"./chunk-QKX6AI4W.js";import{isInForkExecution}from"./chunk-65UCR6OZ.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{getErrorMessage,getErrorStatus,getErrorType,isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();var ModelScopeOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"ModelScopeOpenAICompatibleProvider")}static isModelScopeProvider(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="modelscope.cn"||hostname.endsWith(".modelscope.cn")}catch{return false}}buildRequest(request,userPromptId){const newRequest=super.buildRequest(request,userPromptId);if(!newRequest.stream){delete newRequest.stream_options}return newRequest}};init_esbuild_shims();init_esbuild_shims();function ensureReasoningContentOnAssistantMessage(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content==="string"){return message}return{...assistant,reasoning_content:""}}__name(ensureReasoningContentOnAssistantMessage,"ensureReasoningContentOnAssistantMessage");function stripReasoningContent(message){if(!("reasoning_content"in message)){return message}const next={...message};delete next["reasoning_content"];return next}__name(stripReasoningContent,"stripReasoningContent");function isDeepSeekHostname(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="api.deepseek.com"||hostname.endsWith(".api.deepseek.com")}catch{return false}}__name(isDeepSeekHostname,"isDeepSeekHostname");function isDeepSeekProvider(contentGeneratorConfig){if(isDeepSeekHostname(contentGeneratorConfig))return true;const model=contentGeneratorConfig.model??"";return model.toLowerCase().includes("deepseek")}__name(isDeepSeekProvider,"isDeepSeekProvider");var DeepSeekOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"DeepSeekOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDeepSeekProvider=isDeepSeekProvider;static isDeepSeekHostname=isDeepSeekHostname;supportedReasoningEffortsFor(model){return!this.getReasoningCapabilities(model)?.profile&&isDeepSeekHostname(this.contentGeneratorConfig)?REASONING_EFFORT_TIERS:super.supportedReasoningEffortsFor(model)}buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);const profile=this.getReasoningCapabilities(baseRequest.model)?.profile;const reshaped=(!profile||profile==="deepseek-openai")&&isDeepSeekHostname(this.contentGeneratorConfig)?applyDeepSeekReasoningEffort(baseRequest,this.contentGeneratorConfig.baseUrl):baseRequest;if(!reshaped.messages?.length){return reshaped}const messages=reshaped.messages.map(message=>{const content=this.contentGeneratorConfig.modalities?.image?message:flattenContentParts(message);return isDeepSeekHostname(this.contentGeneratorConfig)||!profile||profile==="deepseek-openai"?ensureReasoningContentOnAssistantMessage(content):content});return{...reshaped,messages}}getDefaultGenerationConfig(){return{}}};function flattenContentParts(message){if(!("content"in message)){return message}const{content}=message;if(typeof content==="string"||content===null||content===void 0){return message}if(!Array.isArray(content)){return message}const text=content.map(part=>{if(typeof part==="string"){return part}if(part.type==="text"){return part.text??""}return`[Unsupported content type: ${part.type}]`}).join("\n\n");return{...message,content:text}}__name(flattenContentParts,"flattenContentParts");init_esbuild_shims();var debugLogger=createDebugLogger("ZAI");function isZaiHostname(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl;if(!baseUrl){return false}try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="z.ai"||hostname.endsWith(".z.ai")||hostname==="bigmodel.cn"||hostname.endsWith(".bigmodel.cn")}catch{return false}}__name(isZaiHostname,"isZaiHostname");function isZaiProvider(contentGeneratorConfig){if(isZaiHostname(contentGeneratorConfig)){return true}const model=contentGeneratorConfig.model??"";return model.toLowerCase().startsWith("glm-")}__name(isZaiProvider,"isZaiProvider");function isGlmTieredEffortModel(model){if(!model){return false}const parsed=/^glm-(\d+)(?:\.(\d+))?/.exec(model.toLowerCase());if(!parsed){return false}const major=Number(parsed[1]);const minor=Number(parsed[2]??0);return major>5||major===5&&minor>=2}__name(isGlmTieredEffortModel,"isGlmTieredEffortModel");var ZaiOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"ZaiOpenAICompatibleProvider")}static isZaiProvider=isZaiProvider;static isZaiHostname=isZaiHostname;nonZaiHostnameFlattenWarned=false;supportedReasoningEffortsFor(model){return isZaiHostname(this.contentGeneratorConfig)&&isGlmTieredEffortModel(model??this.contentGeneratorConfig.model)?REASONING_EFFORT_TIERS:super.supportedReasoningEffortsFor(model)}buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);if(isZaiHostname(this.contentGeneratorConfig)){return flattenReasoningEffort(baseRequest)}const reasoning=baseRequest["reasoning"];if(reasoning?.effort&&!baseRequest["reasoning_effort"]&&!this.nonZaiHostnameFlattenWarned){debugLogger.warn(`GLM model '${this.contentGeneratorConfig.model??"unknown"}' on a non-Z.ai hostname; leaving nested reasoning.effort='${String(reasoning.effort)}' unflattened (reasoning_effort reshape is hostname-gated).`);this.nonZaiHostnameFlattenWarned=true}return baseRequest}};function flattenReasoningEffort(request){const r=request;const nested=r["reasoning"];const effort=nested?.effort;if(typeof effort!=="string"||!effort){return request}const next={...r};if(typeof next["reasoning_effort"]!=="string"||!next["reasoning_effort"]){next["reasoning_effort"]=effort}if(nested&&Object.keys(nested).length===1){delete next["reasoning"]}else if(nested){const{effort:_drop,...rest}=nested;next["reasoning"]=rest}return next}__name(flattenReasoningEffort,"flattenReasoningEffort");init_esbuild_shims();var MINIMAX_KNOWN_HOSTS=["api.minimaxi.com","api.minimax.io"];var MINIMAX_HOST_SUFFIXES=[".minimaxi.com",".minimax.io"];var MiniMaxOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"MiniMaxOpenAICompatibleProvider")}static isMiniMaxProvider(config){if(!config.baseUrl)return false;try{const hostname=new URL(config.baseUrl).hostname.toLowerCase();if(MINIMAX_KNOWN_HOSTS.includes(hostname)){return true}return MINIMAX_HOST_SUFFIXES.some(suffix=>hostname.endsWith(suffix))}catch{return false}}buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);baseRequest.tools=baseRequest.tools?.map(tool=>tool.function.parameters===void 0?{...tool,function:{...tool.function,parameters:{type:"object",properties:{}}}}:tool);return baseRequest}getResponseParsingOptions(){return{taggedThinkingTags:true}}};init_esbuild_shims();var MISTRAL_API_HOST="api.mistral.ai";var MISTRAL_MODEL_MARKERS=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function isMistralHostname(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname===MISTRAL_API_HOST||hostname.endsWith(`.${MISTRAL_API_HOST}`)}catch{return false}}__name(isMistralHostname,"isMistralHostname");function isMistralProvider(config){if(isMistralHostname(config))return true;const model=config.model?.toLowerCase()??"";return MISTRAL_MODEL_MARKERS.some(marker=>model.includes(marker))}__name(isMistralProvider,"isMistralProvider");var MistralOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"MistralOpenAICompatibleProvider")}static isMistralProvider=isMistralProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);if(!isMistralHostname(this.contentGeneratorConfig)&&this.getReasoningCapabilities(request.model)?.profile==="deepseek-openai")return baseRequest;return{...baseRequest,messages:baseRequest.messages.map(stripReasoningContent)}}};init_esbuild_shims();var CEREBRAS_API_HOST="api.cerebras.ai";function isCerebrasProvider(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname===CEREBRAS_API_HOST||hostname.endsWith(`.${CEREBRAS_API_HOST}`)}catch{return false}}__name(isCerebrasProvider,"isCerebrasProvider");var CerebrasOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"CerebrasOpenAICompatibleProvider")}static isCerebrasProvider=isCerebrasProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);return{...baseRequest,messages:baseRequest.messages.map(stripReasoningContent)}}};init_esbuild_shims();var FIREWORKS_API_HOST="api.fireworks.ai";function isFireworksProvider(config){const baseUrl=config.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname===FIREWORKS_API_HOST||hostname.endsWith(`.${FIREWORKS_API_HOST}`)}catch{return false}}__name(isFireworksProvider,"isFireworksProvider");var FireworksOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"FireworksOpenAICompatibleProvider")}static isFireworksProvider=isFireworksProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);return{...baseRequest,messages:baseRequest.messages.map(unmirrorReasoningField)}}};function unmirrorReasoningField(message){if(message.role!=="assistant"){return message}const assistant=message;if(assistant.reasoning!==assistant.reasoning_content){return message}if(typeof assistant.reasoning!=="string"){return message}const{reasoning:_drop,...rest}=assistant;return rest}__name(unmirrorReasoningField,"unmirrorReasoningField");init_esbuild_shims();function isMiMoProvider(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl??"";if(baseUrl){try{const hostname=new URL(baseUrl).hostname.toLowerCase();if(hostname==="xiaomimimo.com"||hostname.endsWith(".xiaomimimo.com")){return true}}catch{}}const model=contentGeneratorConfig.model??"";return model.toLowerCase().startsWith("mimo-")}__name(isMiMoProvider,"isMiMoProvider");var MiMoOpenAICompatibleProvider=class extends DefaultOpenAICompatibleProvider{static{__name(this,"MiMoOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isMiMoProvider=isMiMoProvider;buildRequest(request,userPromptId){const baseRequest=super.buildRequest(request,userPromptId);if(this.getReasoningCapabilities(request.model)?.profile&&!isMiMoProvider({...this.contentGeneratorConfig,model:""})||!baseRequest.messages?.length){return baseRequest}return{...baseRequest,messages:baseRequest.messages.map(ensureReasoningContentOnAssistantMessage)}}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??true}}};init_esbuild_shims();init_esbuild_shims();var debugLogger2=createDebugLogger("STREAMING_TOOL_CALL_PARSER");var StreamingToolCallParser=class{static{__name(this,"StreamingToolCallParser")}buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;namelessToolCallIndices=new Set;idToIndexMap=new Map;pendingIndexRemaps=new Map;nextAvailableIndex=0;conflictingToolCallIdentity=false;invalidToolCallIndex=false;addChunk(index,chunk,id,name){const validName=name?.trim()||void 0;if(!Number.isSafeInteger(index)||index<0){this.conflictingToolCallIdentity=true;this.invalidToolCallIndex=true;return{complete:false,error:new Error(`Invalid tool call index: ${index}`)}}if(!id&&!validName&&!chunk.trim()){const depth2=this.depths.get(index)??0;const inString2=this.inStrings.get(index)??false;if(!this.buffers.has(index)||depth2===0&&!inString2){return{complete:false}}}let actualIndex=index;const isKnownId=Boolean(id&&this.idToIndexMap.has(id));const existingName=this.toolCallMeta.get(index)?.name;const isNameOnlyDelta=Boolean(validName&&chunk.length===0&&(!existingName||existingName===validName));if(id){if(this.idToIndexMap.has(id)){actualIndex=this.idToIndexMap.get(id)}else if(this.pendingIndexRemaps.has(index)&&!this.toolCallMeta.get(this.pendingIndexRemaps.get(index))?.id){actualIndex=this.pendingIndexRemaps.get(index);this.idToIndexMap.set(id,actualIndex)}else{if(this.buffers.has(index)){const existingBuffer=this.buffers.get(index);const existingDepth=this.depths.get(index);const existingMeta=this.toolCallMeta.get(index);if(existingMeta?.id&&existingMeta.id!==id){let existingComplete=existingDepth===0;if(existingComplete&&existingBuffer.trim()){try{JSON.parse(existingBuffer)}catch{existingComplete=false}}if(existingComplete){actualIndex=0;while(this.buffers.has(actualIndex))actualIndex+=1;if(!existingMeta.name){this.conflictingToolCallIdentity=true}}else{this.conflictingToolCallIdentity=true}}}this.idToIndexMap.set(id,actualIndex)}}else if(!isNameOnlyDelta){if(this.pendingIndexRemaps.has(index)){actualIndex=this.pendingIndexRemaps.get(index);const existingBuffer=this.buffers.get(actualIndex);const existingDepth=this.depths.get(actualIndex);if(existingDepth===0&&existingBuffer.trim()){try{JSON.parse(existingBuffer);actualIndex=this.findMostRecentIncompleteIndex()}catch{}}}else if(this.buffers.has(index)){const existingBuffer=this.buffers.get(index);const existingDepth=this.depths.get(index);if(existingDepth>0||!existingBuffer.trim()){actualIndex=index}else{try{JSON.parse(existingBuffer);actualIndex=this.findMostRecentIncompleteIndex()}catch{actualIndex=index}}}}if(!this.buffers.has(actualIndex)){this.buffers.set(actualIndex,"");this.depths.set(actualIndex,0);this.inStrings.set(actualIndex,false);this.escapes.set(actualIndex,false);this.toolCallMeta.set(actualIndex,{})}const currentBuffer=this.buffers.get(actualIndex);const currentDepth=this.depths.get(actualIndex);const meta=this.toolCallMeta.get(actualIndex);if(chunk.length===0&&(id||validName)){if(id)meta.id=id;if(validName&&!meta.name)meta.name=validName;if(!meta.name&&meta.id){this.namelessToolCallIndices.add(actualIndex)}else{this.namelessToolCallIndices.delete(actualIndex)}if(actualIndex!==index){this.pendingIndexRemaps.set(index,actualIndex)}return{actualIndex,complete:false}}if(isKnownId&&currentDepth===0){if(currentBuffer.trim()){try{JSON.parse(currentBuffer);debugLogger2.debug(`Ignoring replay chunk for completed toolCall id=${id}`);return{actualIndex,complete:false}}catch{}}}const identityChanged=Boolean(id&&meta.id&&meta.id!==id);if(id)meta.id=id;if(validName){if(!identityChanged&&meta.name&&meta.name!==validName){this.conflictingToolCallIdentity=true}else{meta.name=validName}}if(actualIndex!==index){this.pendingIndexRemaps.set(index,actualIndex)}const currentInString=this.inStrings.get(actualIndex);const currentEscape=this.escapes.get(actualIndex);const newBuffer=currentBuffer+chunk;this.buffers.set(actualIndex,newBuffer);if(!meta.name&&(meta.id||/\S/.test(newBuffer))){this.namelessToolCallIndices.add(actualIndex)}else{this.namelessToolCallIndices.delete(actualIndex)}let depth=currentDepth;let inString=currentInString;let escape=currentEscape;for(const char of chunk){if(!inString){if(char==="{"||char==="[")depth++;else if(char==="}"||char==="]")depth--}if(char==='"'&&!escape){inString=!inString}escape=char==="\\"&&!escape}this.depths.set(actualIndex,depth);this.inStrings.set(actualIndex,inString);this.escapes.set(actualIndex,escape);if(depth===0&&newBuffer.trim().length>0){try{const parsed=JSON.parse(newBuffer);return{actualIndex,complete:true,value:parsed}}catch(e){if(inString){try{const repaired=JSON.parse(newBuffer+'"');return{actualIndex,complete:true,value:repaired,repaired:true}}catch{}}return{actualIndex,complete:false,error:e instanceof Error?e:new Error(String(e))}}}return{actualIndex,complete:false}}getToolCallMeta(index){return this.toolCallMeta.get(index)||{}}hasNamelessToolCall(){return this.namelessToolCallIndices.size>0}hasConflictingToolCallIdentity(){return this.conflictingToolCallIdentity}hasInvalidToolCallIndex(){return this.invalidToolCallIndex}hasInvalidToolCallArguments(){for(const[index,buffer]of this.buffers.entries()){if(!this.toolCallMeta.get(index)?.name||buffer.length===0)continue;if(!parseToolCallArguments(buffer).ok)return true}return false}getCompletedToolCalls(){const completed=[];const emittedIds=new Set;for(const[index,buffer]of this.buffers.entries()){const meta=this.toolCallMeta.get(index);if(meta?.name){if(meta.id){if(emittedIds.has(meta.id)){continue}emittedIds.add(meta.id)}let args={};if(buffer.trim()){try{args=JSON.parse(buffer)}catch{const inString=this.inStrings.get(index);if(inString){try{args=JSON.parse(buffer+'"')}catch{args=safeJsonParse(buffer,{})}}else{args=safeJsonParse(buffer,{})}}if(typeof args!=="object"||args===null||Array.isArray(args)){debugLogger2.debug(`Collapsing non-object arguments for tool call ${meta.name} (id=${meta.id}) at index ${index}; buffer likely polluted by a misrouted fragment`);args={}}}else{debugLogger2.debug(`Emitting no-argument tool call ${meta.name} (id=${meta.id}) at index ${index} with empty buffer`)}completed.push({id:meta.id,name:meta.name,args,index})}}return completed}findNextAvailableIndex(){while(this.buffers.has(this.nextAvailableIndex)){const buffer=this.buffers.get(this.nextAvailableIndex);const depth=this.depths.get(this.nextAvailableIndex);const meta=this.toolCallMeta.get(this.nextAvailableIndex);if(!meta?.name||depth>0||!meta?.id){return this.nextAvailableIndex}if(buffer.trim()){try{JSON.parse(buffer)}catch{return this.nextAvailableIndex}}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let maxIndex=-1;for(const[index,buffer]of this.buffers.entries()){const depth=this.depths.get(index);const meta=this.toolCallMeta.get(index);if(meta?.id&&(depth>0||!buffer.trim()&&!meta?.name)){maxIndex=Math.max(maxIndex,index)}else if(buffer.trim()){try{JSON.parse(buffer)}catch{maxIndex=Math.max(maxIndex,index)}}}return maxIndex>=0?maxIndex:this.findNextAvailableIndex()}resetIndex(index){this.buffers.set(index,"");this.depths.set(index,0);this.inStrings.set(index,false);this.escapes.set(index,false);this.toolCallMeta.set(index,{});this.namelessToolCallIndices.delete(index);for(const[providerIndex,actualIndex]of this.pendingIndexRemaps){if(providerIndex===index||actualIndex===index){this.pendingIndexRemaps.delete(providerIndex)}}}reset(){this.buffers.clear();this.depths.clear();this.inStrings.clear();this.escapes.clear();this.toolCallMeta.clear();this.namelessToolCallIndices.clear();this.idToIndexMap.clear();this.pendingIndexRemaps.clear();this.nextAvailableIndex=0;this.conflictingToolCallIdentity=false;this.invalidToolCallIndex=false}getBuffer(index){return this.buffers.get(index)||""}getState(index){return{depth:this.depths.get(index)||0,inString:this.inStrings.get(index)||false,escape:this.escapes.get(index)||false}}hasIncompleteToolCalls(){for(const[index]of this.buffers.entries()){const meta=this.toolCallMeta.get(index);if(!meta?.name)continue;const depth=this.depths.get(index)||0;const inString=this.inStrings.get(index)||false;if(depth>0||inString){return true}}return false}};var debugLogger3=createDebugLogger("OPENAI_PIPELINE");var OPENAI_STRICT_SCHEMA_KEYS=new Set(["type","properties","required","additionalProperties","items","description","enum"]);var OPENAI_STRICT_UNSUPPORTED_SCHEMA_KEYS=new Set(["minLength","maxLength","minItems","maxItems","uniqueItems"]);function asObject(value){if(!value||typeof value!=="object"||Array.isArray(value)){return void 0}return value}__name(asObject,"asObject");function profileReasoning(profile,reasoning,disableField){if(reasoning===void 0)return{};const enabled=reasoning!==false;const effort=reasoning&&reasoning.effort;switch(profile){case"openai-reasoning":return{reasoning:enabled?reasoning:{enabled:false}};case"openai-effort":case"dashscope-effort":return effort||!enabled?{reasoning_effort:enabled?effort:"none"}:{};case"deepseek-openai":return{...disableField==="enable_thinking"?{enable_thinking:enabled}:{thinking:{type:enabled?"enabled":"disabled"}},...effort?{reasoning_effort:effort}:{}};case"dashscope-thinking":return{enable_thinking:enabled};case"qwen-chat-template":return{chat_template_kwargs:{enable_thinking:enabled}};default:return{}}}__name(profileReasoning,"profileReasoning");function applyConfiguredReasoningEffort(request,capabilities){if(capabilities?.profile){const loose2=request;const{reasoning:reasoning2,...rest2}=loose2;const{effort:_effort,...siblings}=asObject(reasoning2)??{};return{...Object.keys(siblings).length?{reasoning:siblings}:{},...profileReasoning(capabilities.profile,reasoning2,capabilities.disableField),...rest2}}if(!capabilities||capabilities.toggleOnly||!Array.isArray(capabilities.efforts)){return request}const loose=request;const reasoning=asObject(loose["reasoning"]);if(!reasoning||!("effort"in reasoning))return request;const effort=capabilities.efforts.find(candidate=>candidate===reasoning["effort"]);if(effort&&getGptReasoningCapabilities(loose["model"]))return request;const{effort:_drop,...rest}=reasoning;const next={...loose};if(Object.keys(rest).length>0)next["reasoning"]=rest;else delete next["reasoning"];if(effort&&next["reasoning_effort"]===void 0){next["reasoning_effort"]=effort}return next}__name(applyConfiguredReasoningEffort,"applyConfiguredReasoningEffort");function normalizeSchemaType(value){if(typeof value!=="string")return void 0;const normalized=value.toLowerCase();return["object","array","string","number","integer","boolean","null"].includes(normalized)?normalized:void 0}__name(normalizeSchemaType,"normalizeSchemaType");function normalizeOpenAIStrictSchema(schema){const source=asObject(schema);if(!source)return void 0;const type=normalizeSchemaType(source["type"]);if(!type)return void 0;const normalized={type};for(const[key,value]of Object.entries(source)){if(key==="type"||OPENAI_STRICT_UNSUPPORTED_SCHEMA_KEYS.has(key)||!OPENAI_STRICT_SCHEMA_KEYS.has(key)){continue}normalized[key]=value}if(type==="object"){const properties=asObject(source["properties"]);if(!properties)return void 0;const normalizedProperties={};for(const[key,value]of Object.entries(properties)){const property=normalizeOpenAIStrictSchema(value);if(!property)return void 0;normalizedProperties[key]=property}const propertyKeys=Object.keys(normalizedProperties);const required=source["required"];if(!Array.isArray(required)||!propertyKeys.every(key=>required.includes(key))||required.length!==propertyKeys.length){return void 0}normalized["properties"]=normalizedProperties;normalized["required"]=required;normalized["additionalProperties"]=false}if(type==="array"){const items=normalizeOpenAIStrictSchema(source["items"]);if(!items)return void 0;normalized["items"]=items}return normalized}__name(normalizeOpenAIStrictSchema,"normalizeOpenAIStrictSchema");function isRequiredThinkingError(error){if(getErrorStatus(error)!==400)return false;const providerMessage=getRateLimitErrorDetails(error).providerMessage;const message=`${getErrorMessage(error)} ${providerMessage??""}`;return message.includes("enable_thinking")&&/(?:restricted to|must be) true\b/i.test(message)}__name(isRequiredThinkingError,"isRequiredThinkingError");function wireRequestHasMediaContent(wireRequest){const messages=wireRequest?.["messages"];if(!Array.isArray(messages))return false;return messages.some(message=>{const content=message.content;return Array.isArray(content)&&content.some(part=>{const type=part.type;return type==="image_url"||type==="input_audio"||type==="video_url"||type==="file"})})}__name(wireRequestHasMediaContent,"wireRequestHasMediaContent");var StreamContentError=class extends Error{static{__name(this,"StreamContentError")}constructor(message){super(message);this.name="StreamContentError"}};var NON_SSE_BODY_PREFIX_LIMIT=512;function isSSECompatibleContentType(contentType){if(!contentType)return true;const mediaType=(contentType.split(";")[0]??"").trim().toLowerCase();return mediaType==="text/event-stream"||mediaType==="application/x-ndjson"||mediaType==="application/stream+json"}__name(isSSECompatibleContentType,"isSSECompatibleContentType");function hasNonThoughtCandidateParts(response){return Boolean(response.candidates?.some(candidate=>candidate.content?.parts?.some(part=>!part.thought)))}__name(hasNonThoughtCandidateParts,"hasNonThoughtCandidateParts");function flushTrailingThinkingTag(abortSignal,context,finishSeen,completed){if(abortSignal?.aborted===true||context.hasThinkingTagInReasoning||finishSeen||context.pendingUntrustedResponseParts!==void 0||context.taggedThinkingParser!==void 0){return{}}const filter=context.trailingThinkingTagFilter;const trailingText=filter?.parse("",true,completed);const sanitizedTagName=filter?.sanitizedTagName;if(filter){filter.sanitizedTagName=void 0}if(!trailingText)return{sanitizedTagName};const response=new GenerateContentResponse;response.candidates=[{content:{parts:[{text:trailingText}],role:"model"},index:0}];return{response,sanitizedTagName}}__name(flushTrailingThinkingTag,"flushTrailingThinkingTag");var NonSSEResponseError=class extends Error{constructor(contentType,httpStatus,bodyPrefix,requestId){const preview=bodyPrefix.length>0?` Body prefix: ${bodyPrefix}`:"";super(`Streaming request received a non-SSE response (HTTP ${httpStatus}, Content-Type: ${contentType||"unknown"}).${preview}`);this.contentType=contentType;this.httpStatus=httpStatus;this.bodyPrefix=bodyPrefix;this.requestId=requestId;this.name="NonSSEResponseError";this.status=httpStatus;this.request_id=requestId}static{__name(this,"NonSSEResponseError")}status;request_id};var PROVIDER_OUTPUT_BUDGET_KEYS=["max_completion_tokens","max_new_tokens"];function hasProviderOutputBudgetKey(samplingParams){return PROVIDER_OUTPUT_BUDGET_KEYS.some(key=>samplingParams[key]!==void 0)}__name(hasProviderOutputBudgetKey,"hasProviderOutputBudgetKey");function getWireOutputBudget(request){if(typeof request.max_tokens==="number"&&request.max_tokens>0){return request.max_tokens}const wire=request;for(const key of PROVIDER_OUTPUT_BUDGET_KEYS){const value=wire[key];if(typeof value==="number"&&value>0){return value}}return void 0}__name(getWireOutputBudget,"getWireOutputBudget");function clampProviderOutputBudgetKeys(samplingParams,requestMaxTokens){if(typeof requestMaxTokens!=="number")return samplingParams;for(const key of PROVIDER_OUTPUT_BUDGET_KEYS){const value=samplingParams[key];if(typeof value==="number"&&value>requestMaxTokens){samplingParams[key]=requestMaxTokens}}return samplingParams}__name(clampProviderOutputBudgetKeys,"clampProviderOutputBudgetKeys");var ContentGenerationPipeline=class{constructor(config){this.config=config;this.contentGeneratorConfig=config.contentGeneratorConfig;this.client=this.config.provider.buildClient();this.streamIdleTimeoutMs=resolveStreamIdleTimeoutMs(this.contentGeneratorConfig);this.streamMaxLifetimeMs=resolveStreamMaxLifetimeMs(this.contentGeneratorConfig)}static{__name(this,"ContentGenerationPipeline")}client;contentGeneratorConfig;requiredThinkingModels=new Set;streamIdleTimeoutMs;streamMaxLifetimeMs;async execute(request,userPromptId){return this.executeWithErrorHandling(request,userPromptId,false,async(openaiRequest,context,telemetryAttempt)=>{const parentSignal=request.config?.abortSignal;const perRequestAc=parentSignal?createChildAbortController(parentSignal):void 0;try{const openaiResponse=await this.client.chat.completions.create(openaiRequest,{signal:perRequestAc?.signal});reportOpenAiResponse(telemetryAttempt,openaiResponse);const llmResponse=OpenAIContentConverter.convertOpenAIResponseToLlm(openaiResponse,context);return llmResponse}finally{perRequestAc?.abort()}})}async executeStream(request,userPromptId){return this.executeWithErrorHandling(request,userPromptId,true,async(openaiRequest,context,telemetryAttempt)=>{const parentSignal=request.config?.abortSignal;const perRequestAc=createChildAbortController(parentSignal);let stream;try{const createPromise=this.client.chat.completions.create(openaiRequest,{signal:perRequestAc.signal});if(typeof createPromise.withResponse==="function"){const{data,response:httpResponse,request_id}=await createPromise.withResponse();stream=data;const contentType=httpResponse.headers.get("content-type")??null;if(!isSSECompatibleContentType(contentType)){let bodyPrefix="";try{if(httpResponse.body){const reader=httpResponse.body.getReader();const{value}=await reader.read();reader.releaseLock();if(value){bodyPrefix=new TextDecoder().decode(value).slice(0,NON_SSE_BODY_PREFIX_LIMIT)}}}catch{}throw new NonSSEResponseError(contentType,httpResponse.status,bodyPrefix,request_id)}}else{stream=await createPromise}}catch(e){perRequestAc.abort();throw e}const idleMs=this.streamIdleTimeoutMs;const maxLifetimeMs=this.streamMaxLifetimeMs;const guarded=idleMs>0||maxLifetimeMs>0?withStreamGuards(stream,idleMs,maxLifetimeMs,()=>perRequestAc.abort(),parentSignal):stream;const innerStream=this.processStreamWithLogging(guarded,context,request,openaiRequest,userPromptId,telemetryAttempt);async function*drainThenCleanup(){try{yield*innerStream}finally{perRequestAc.abort()}}__name(drainThenCleanup,"drainThenCleanup");return drainThenCleanup()})}async*processStreamWithLogging(stream,context,request,openaiRequest,userPromptId,telemetryAttempt){let pendingFinishResponse=null;let finishYielded=false;let finishSeen=false;let contentYielded=request.continuationInFlight===true;let pendingFinishProtocolTagSanitized;const logPendingProtocolTagSanitized=__name((response,sanitization)=>{if(!sanitization)return;const event=new ProtocolTagSanitizedEvent({model:context.model,promptId:userPromptId,responseId:response?.responseId,tagName:sanitization.tagName,toolCallCount:sanitization.toolCallCount});debugLogger3.warn("Sanitized a model protocol tag",{model:event.model,promptId:event.prompt_id,responseId:event.response_id,tagName:event.tag_name,toolCallCount:event.tool_call_count});logProtocolTagSanitized(this.config.cliConfig,event)},"logPendingProtocolTagSanitized");const logFlushedTrailingTag=__name(flushed=>{if(flushed.sanitizedTagName){logPendingProtocolTagSanitized(flushed.response,{tagName:flushed.sanitizedTagName,toolCallCount:0})}return flushed.response},"logFlushedTrailingTag");try{for await(const chunk of stream){reportOpenAiChunk(telemetryAttempt,chunk);if(chunk.choices?.[0]?.finish_reason==="error_finish"){const errorContent=chunk.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new StreamContentError(errorContent)}const response=OpenAIContentConverter.convertOpenAIChunkToLlm(chunk,context);const sanitization=context.protocolTagSanitized;if(sanitization){context.protocolTagSanitized=void 0}if((response.candidates?.[0]?.content?.parts?.length??0)===0&&!response.candidates?.[0]?.finishReason&&!response.usageMetadata&&getToolCallPreparations(response).length===0){continue}if(response.candidates?.[0]?.finishReason){finishSeen=true}if(pendingFinishProtocolTagSanitized&&pendingFinishResponse&&!response.candidates?.[0]?.finishReason&&response.candidates?.some(candidate=>(candidate.content?.parts?.length??0)>0)){throw new InvalidStreamError("Model response continued after a finish reason.","PROTOCOL_TAG_LEAK")}if(finishYielded){if(response.usageMetadata){const pending=pendingFinishResponse;if(pending){pending.usageMetadata=response.usageMetadata}}continue}if(!pendingFinishResponse&&response.candidates?.[0]?.finishReason&&sanitization){pendingFinishProtocolTagSanitized=sanitization}const shouldYield=this.handleChunkMerging(response,pendingFinishResponse,mergedResponse=>{pendingFinishResponse=mergedResponse});if(shouldYield){if(pendingFinishResponse){logPendingProtocolTagSanitized(pendingFinishResponse,pendingFinishProtocolTagSanitized);this.settleParkedTruncationOverride(pendingFinishResponse,context);finishYielded=true;yield pendingFinishResponse}else{contentYielded||=hasNonThoughtCandidateParts(response);logPendingProtocolTagSanitized(response,sanitization);yield response}}}if(context.pendingThinkingTagCandidate&&!context.pendingThinkingTagCandidate.closingTagName&&!/\S/.test(context.pendingThinkingTagCandidate.text)){const pendingParts=context.pendingUntrustedResponseParts;context.pendingThinkingTagCandidate=void 0;context.pendingUntrustedResponseParts=void 0;if(pendingParts?.length){const response=new GenerateContentResponse;response.candidates=[{content:{parts:pendingParts,role:"model"},index:0}];contentYielded||=hasNonThoughtCandidateParts(response);yield response}}else if(context.pendingThinkingTagCandidate||context.responseParsingOptions?.taggedThinkingTagsAfterReasoning&&context.taggedThinkingParser?.hasUnclosedThought()){throw new InvalidStreamError("Model response leaked thinking tags.","PROTOCOL_TAG_LEAK")}const flushedTail=logFlushedTrailingTag(flushTrailingThinkingTag(request.config?.abortSignal,context,finishSeen,true));if(flushedTail){contentYielded||=hasNonThoughtCandidateParts(flushedTail);yield flushedTail}if(pendingFinishResponse&&!finishYielded){logPendingProtocolTagSanitized(pendingFinishResponse,pendingFinishProtocolTagSanitized);this.settleParkedTruncationOverride(pendingFinishResponse,context);finishYielded=true;yield pendingFinishResponse}}catch(error){await this.invalidateOmniOssCacheOnError(openaiRequest,error);if(error instanceof InvalidStreamError){throw error}const flushedTail=logFlushedTrailingTag(flushTrailingThinkingTag(request.config?.abortSignal,context,finishSeen,false));if(flushedTail){contentYielded||=hasNonThoughtCandidateParts(flushedTail);yield flushedTail}const parked=pendingFinishResponse;const parkedHasToolCall=parked?.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall));if(pendingFinishResponse&&!finishYielded&&request.config?.abortSignal?.aborted!==true&&(!parkedHasToolCall||contentYielded)){logPendingProtocolTagSanitized(pendingFinishResponse,pendingFinishProtocolTagSanitized);if(parkedHasToolCall){markFlushedToolCallPark(pendingFinishResponse)}this.settleParkedTruncationOverride(pendingFinishResponse,context);yield pendingFinishResponse;finishYielded=true}if(error instanceof StreamContentError){throw redactProxyError(error)}if(error instanceof StreamInactivityTimeoutError||error instanceof StreamLifetimeExceededError){const isLifetime=error instanceof StreamLifetimeExceededError;debugLogger3.warn(isLifetime?"OpenAI stream lifetime cap exceeded":"OpenAI stream inactivity timeout",{chunksReceived:error.chunksReceived,wallClockMs:error.streamLifetimeMs,...isLifetime?{maxLifetimeMs:error.maxLifetimeMs}:{idleMs:error.idleMs}});throw redactProxyError(error)}if(context.pendingThinkingTagCandidate?.closingTagName&&request.config?.abortSignal?.aborted!==true){context.pendingThinkingTagCandidate=void 0;context.pendingUntrustedResponseParts=void 0;throw new InvalidStreamError("Model response leaked thinking tags.","PROTOCOL_TAG_LEAK")}await this.handleError(error,context,request)}}handleChunkMerging(response,pendingFinishResponse,setPendingFinish){const isFinishChunk=response.candidates?.[0]?.finishReason;if(isFinishChunk){if(pendingFinishResponse){if(response.usageMetadata){pendingFinishResponse.usageMetadata=response.usageMetadata}if(response.modelVersion){pendingFinishResponse.modelVersion=response.modelVersion}setPendingFinish(pendingFinishResponse)}else{setPendingFinish(response)}return false}else if(pendingFinishResponse){const mergedResponse=new GenerateContentResponse;mergedResponse.candidates=pendingFinishResponse.candidates;if(response.usageMetadata){mergedResponse.usageMetadata=response.usageMetadata}else{mergedResponse.usageMetadata=pendingFinishResponse.usageMetadata}mergedResponse.responseId=response.responseId||pendingFinishResponse.responseId;mergedResponse.createTime=response.createTime||pendingFinishResponse.createTime;mergedResponse.modelVersion=response.modelVersion||pendingFinishResponse.modelVersion;mergedResponse.promptFeedback=response.promptFeedback||pendingFinishResponse.promptFeedback;setPendingFinish(mergedResponse);return true}return true}settleParkedTruncationOverride(response,context){const parked=context.pendingTruncationOverride;if(!parked){return}context.pendingTruncationOverride=void 0;const candidate=response.candidates?.[0];if(!candidate||candidate.finishReason!==FinishReason.MAX_TOKENS){return}const verdict=corroborateTruncationFromCompletionTokens(response.usageMetadata?.candidatesTokenCount,context.maxOutputTokens);if(verdict==="disproved"){candidate.finishReason=parked.finishReason;markToolCallArgumentsIncomplete(candidate.content?.parts)}debugLogger3.debug("Settled a parked truncation override",{candidatesTokenCount:response.usageMetadata?.candidatesTokenCount??null,maxOutputTokens:context.maxOutputTokens??null,verdict,downgraded:verdict==="disproved",from:FinishReason.MAX_TOKENS,to:candidate.finishReason})}async buildRequest(request,userPromptId,context,isStreaming){const reasoningCapabilities=resolveReasoningForModel(this.config.cliConfig,this.contentGeneratorConfig,context.model);const convertedMessages=OpenAIContentConverter.convertLlmRequestToOpenAI(request,context);const messages=reasoningCapabilities?.profile==="deepseek-openai"?convertedMessages.map(ensureReasoningContentOnAssistantMessage):convertedMessages;let baseRequest={messages,...this.buildGenerateContentConfig({...request,model:context.model}),...this.buildResponseFormat(request),model:context.model};if(isStreaming){baseRequest.stream=true;baseRequest.stream_options={include_usage:true}}else{baseRequest.stream=false}const effectiveReasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model:context.model},reasoningCapabilities);if(reasoningCapabilities&&!("reasoning"in baseRequest)&&effectiveReasoning&&request.config?.thinkingConfig?.includeThoughts!==false){baseRequest={...baseRequest,reasoning:effectiveReasoning}}if(this.contentGeneratorConfig.samplingParams?.["reasoning"]===void 0&&(!reasoningCapabilities?.profile&&!getBuiltinDeepSeekReasoning({...this.contentGeneratorConfig,model:context.model})||this.contentGeneratorConfig.extra_body?.["reasoning"]===void 0)&&(reasoningCapabilities?.profile||!isOpenRouterHostname(this.contentGeneratorConfig))){baseRequest=applyConfiguredReasoningEffort(baseRequest,reasoningCapabilities)}if(request.config?.tools&&request.config.tools.length>0){baseRequest.tools=await OpenAIContentConverter.convertLlmToolsToOpenAI(request.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto");const fcMode=request.config?.toolConfig?.functionCallingConfig?.mode;if(fcMode==="ANY"){baseRequest["tool_choice"]="required"}else if(fcMode==="NONE"){baseRequest["tool_choice"]="none"}}let providerRequest=this.config.provider.buildRequest(baseRequest,userPromptId,trailingReattachPartCount(request.contents));if(this.contentGeneratorConfig.enableCacheControl!==false&&isOfficialOpenAIEndpoint(this.contentGeneratorConfig)){providerRequest=applyOfficialOpenAIPromptCaching(providerRequest,this.config.cliConfig.getSessionId?.(),request.promptCacheSharing===true,isInForkExecution()?void 0:getCurrentAgentId()??void 0)}const model=(context.model??"").toLowerCase();const isDashScope=DashScopeOpenAICompatibleProvider.isDashScopeProvider(this.contentGeneratorConfig);const explicitThinkingMandatory=reasoningCapabilities?.canDisable===false||this.requiresThinking(model);const profile=reasoningCapabilities?.profile;const thinkingMandatory=explicitThinkingMandatory||!profile&&getGptReasoningCapabilities(model)?.thinkingMandatory===true;const reasoningDisabled=request.config?.thinkingConfig?.includeThoughts===false||this.contentGeneratorConfig.reasoning===false;if((profile==="openai-effort"||profile==="dashscope-effort")&&isReasoningEffortPlaceholder(providerRequest.reasoning_effort)&&effectiveReasoning&&this.contentGeneratorConfig.samplingParams?.["reasoning"]===void 0&&this.contentGeneratorConfig.extra_body?.["reasoning"]===void 0)providerRequest.reasoning_effort=effectiveReasoning.effort;if(reasoningDisabled&&profile){const typed2=providerRequest;if(!thinkingMandatory||request.config?.thinkingConfig?.includeThoughts===false){delete typed2["reasoning"];delete typed2["reasoning_effort"]}if(!thinkingMandatory){if(isDashScope&&profile==="dashscope-effort"){delete typed2["thinking_budget"];delete typed2["enable_thinking"]}const template=asObject(typed2["chat_template_kwargs"]);Object.assign(typed2,profileReasoning(profile,false,reasoningCapabilities?.disableField));if(profile==="qwen-chat-template"){delete typed2["enable_thinking"];typed2["chat_template_kwargs"]={...template,enable_thinking:false}}else if(reasoningCapabilities?.disableField==="enable_thinking"){delete typed2["reasoning_effort"];typed2["enable_thinking"]=false}}}else if(reasoningDisabled){const typed2=providerRequest;if(!thinkingMandatory&&isQwenFamilyWireModel(model)){if(isDashScope){if(isTieredEffortWireModel(model)){delete typed2["enable_thinking"];delete typed2["thinking_budget"];typed2["reasoning_effort"]="none"}else{typed2["enable_thinking"]=false}}else{delete typed2["enable_thinking"];const existing=typed2["chat_template_kwargs"]??{};typed2["chat_template_kwargs"]={...existing,enable_thinking:false}}}if(!thinkingMandatory){if(reasoningCapabilities?.disableField==="reasoning_effort"){delete typed2["enable_thinking"];delete typed2["thinking_budget"];typed2["reasoning_effort"]="none"}else if(reasoningCapabilities?.disableField==="enable_thinking"){typed2["enable_thinking"]=false}}if("reasoning"in typed2){delete typed2["reasoning"]}if("reasoning_effort"in typed2&&typed2["reasoning_effort"]!=="none"){delete typed2["reasoning_effort"]}const gptReasoning=getGptReasoningCapabilities(model);if(gptReasoning&&!reasoningCapabilities&&!gptReasoning.thinkingMandatory&&!thinkingMandatory&&!isOpenRouterHostname(this.contentGeneratorConfig)){typed2["reasoning_effort"]="none"}if(isDeepSeekHostname(this.contentGeneratorConfig)||reasoningCapabilities?.disableField==="thinking"){typed2["thinking"]={type:"disabled"}}if(!thinkingMandatory&&isOpenRouterHostname(this.contentGeneratorConfig)){typed2["reasoning"]={enabled:false}}}if(thinkingMandatory){const typed2=providerRequest;if(typed2["enable_thinking"]===false){delete typed2["enable_thinking"]}if(typed2["reasoning_effort"]==="none"){delete typed2["reasoning_effort"]}const thinking=asObject(typed2["thinking"]);if(thinking?.["type"]==="disabled"){const remaining={...thinking};delete remaining["type"];if(Object.keys(remaining).length>0)typed2["thinking"]=remaining;else delete typed2["thinking"]}const chatTemplateKwargs=typed2["chat_template_kwargs"];if(chatTemplateKwargs?.["enable_thinking"]===false){const remaining={...chatTemplateKwargs};delete remaining["enable_thinking"];if(Object.keys(remaining).length>0){typed2["chat_template_kwargs"]=remaining}else{delete typed2["chat_template_kwargs"]}}}const typed=providerRequest;const reasoningEffort=typed["reasoning_effort"];const thinkingBudget=typed["thinking_budget"];if(isDashScope&&typed["tool_choice"]==="required"&&(explicitThinkingMandatory||isQwenFamilyWireModel(model)&&(typed["enable_thinking"]===true||thinkingBudget!=null&&typed["enable_thinking"]!==false||typeof reasoningEffort==="string"&&reasoningEffort!=="none"))){debugLogger3.debug("DashScope: dropping tool_choice=required while thinking is enabled",{model,reasoningEffort,thinkingBudget,explicitThinkingMandatory});delete typed["tool_choice"]}return providerRequest}buildResponseFormat(request){if(!isOfficialOpenAIEndpoint(this.contentGeneratorConfig))return{};if(request.config?.responseMimeType!=="application/json")return{};const schema=request.config.responseJsonSchema??request.config.responseSchema;if(!schema)return{response_format:{type:"json_object"}};const strictSchema=normalizeOpenAIStrictSchema(schema);if(!strictSchema)return{response_format:{type:"json_object"}};return{response_format:{type:"json_schema",json_schema:{name:"response",schema:strictSchema,strict:true}}}}requiresThinking(model){const normalizedModel=model.toLowerCase();return this.requiredThinkingModels.has(normalizedModel)||this.contentGeneratorConfig.thinkingMandatory===true&&normalizedModel===(this.contentGeneratorConfig.model??"").toLowerCase()}buildGenerateContentConfig(request){const defaultSamplingParams=this.config.provider.getDefaultGenerationConfig();const configSamplingParams=this.contentGeneratorConfig.samplingParams;const getParameterValue=__name((configKey,requestKey)=>{const configValue=configSamplingParams?.[configKey];const requestValue=requestKey?request.config?.[requestKey]:void 0;const defaultValue=requestKey?defaultSamplingParams[requestKey]:void 0;if(configValue!==void 0)return configValue;if(requestValue!==void 0)return requestValue;return defaultValue},"getParameterValue");const addParameterIfDefined=__name((key,configKey,requestKey)=>{const value=getParameterValue(configKey,requestKey);return value!==void 0?{[key]:value}:{}},"addParameterIfDefined");if(configSamplingParams!==void 0){const rawEffort={...configSamplingParams,...this.contentGeneratorConfig.extra_body}["reasoning_effort"];const samplingParams=getGptReasoningCapabilities(request.model||this.contentGeneratorConfig.model)&&configSamplingParams["reasoning"]===void 0&&(isReasoningEffortPlaceholder(configSamplingParams["reasoning_effort"])||isReasoningEffortPlaceholder(rawEffort))?{...this.buildReasoningConfig(request),...configSamplingParams}:configSamplingParams;const requestMaxTokens=request.config?.maxOutputTokens;const maxTokens=reconcileMaxTokens(configSamplingParams.max_tokens,requestMaxTokens)??configSamplingParams.max_tokens??(hasProviderOutputBudgetKey(configSamplingParams)?void 0:requestMaxTokens);return clampProviderOutputBudgetKeys(maxTokens!==void 0?{...samplingParams,max_tokens:maxTokens}:{...samplingParams},requestMaxTokens)}const params={...addParameterIfDefined("temperature","temperature","temperature"),...addParameterIfDefined("top_p","top_p","topP"),...addParameterIfDefined("max_tokens","max_tokens","maxOutputTokens"),...addParameterIfDefined("top_k","top_k","topK"),...addParameterIfDefined("repetition_penalty","repetition_penalty"),...addParameterIfDefined("presence_penalty","presence_penalty","presencePenalty"),...addParameterIfDefined("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(request)};return params}buildReasoningConfig(request){if(request.config?.thinkingConfig?.includeThoughts===false){return{}}const reasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model:request.model||this.contentGeneratorConfig.model},resolveReasoningForModel(this.config.cliConfig,this.contentGeneratorConfig,request.model));if(reasoning===false||reasoning===void 0){return{}}return{reasoning}}async executeWithErrorHandling(request,userPromptId,isStreaming,executor){const context=this.createRequestContext(request,isStreaming);let openaiRequest;const executeAttempt=__name(async(attemptContext=context)=>{openaiRequest=await this.buildRequest(request,userPromptId,attemptContext,isStreaming);attemptContext.maxOutputTokens=getWireOutputBudget(openaiRequest);openaiRequestCaptureContext.getStore()?.(openaiRequest);runtimeDiagnostics.recordOpenAIWireRequest(openaiRequest);const telemetryAttempt=reportOpenAiRequest(openaiRequest);return executor(openaiRequest,attemptContext,telemetryAttempt)},"executeAttempt");try{return await executeAttempt()}catch(error){await this.invalidateOmniOssCacheOnError(openaiRequest,error);const model=context.model.toLowerCase();const wireRequest=openaiRequest;const chatTemplateKwargs=wireRequest?.["chat_template_kwargs"];if((wireRequest?.["enable_thinking"]===false||chatTemplateKwargs?.["enable_thinking"]===false||wireRequest?.["reasoning_effort"]==="none")&&request.config?.abortSignal?.aborted!==true&&isRequiredThinkingError(error)){this.requiredThinkingModels.add(model);debugLogger3.warn("Retrying with required thinking enabled",{model,originalError:getErrorMessage(error)});try{return await executeAttempt()}catch(retryError){return await this.handleError(retryError,context,request)}}if(request.config?.abortSignal?.aborted!==true&&getErrorStatus(error)===400&&wireRequestHasMediaContent(wireRequest)){debugLogger3.warn("Media-bearing request rejected with 400; retrying once with media degraded to placeholders",{model,originalError:getErrorMessage(error)});try{return await executeAttempt({...context,modalities:{}})}catch(retryError){return await this.handleError(retryError,context,request)}}return await this.handleError(error,context,request)}}async invalidateOmniOssCacheOnError(openaiRequest,error){try{if(!this.config.cliConfig.isOmniEnabled?.())return;if(getErrorStatus(error)===429)return;const message=getErrorMessage(error);if(!/oss:\/\//i.test(message)&&!(/download/i.test(message)&&/resource|media/i.test(message))){return}const urls=new Set;for(const m of openaiRequest?.messages??[]){const content=m.content;if(!Array.isArray(content))continue;for(const part of content){const p=part;for(const u of[p.image_url?.url,p.video_url?.url,p.input_audio?.data]){if(typeof u==="string"&&u.startsWith("oss://"))urls.add(u)}}}if(urls.size===0)return;const{OmniUploadCache}=await import("./upload-cache-2R5KHOGA.js");const{OmniObjectStore}=await import("./storage-JMQT2RMJ.js");const store=new OmniObjectStore(this.config.cliConfig.storage.getQwenDir());const cache=new OmniUploadCache(store.getOmniRootDir());for(const u of urls)await cache.invalidateByUrl(u)}catch{}}async handleError(error,context,request){this.config.errorHandler.handle(redactProxyError(error),context,request)}createRequestContext(request,isStreaming){const effectiveModel=getRequestModel(this.contentGeneratorConfig,request.model||this.contentGeneratorConfig.model);const providerOverrides=this.config.provider.getRequestContextOverrides?.()??{};const toolCallParser=isStreaming?new StreamingToolCallParser:void 0;const responseParsingOptions=this.config.provider.getResponseParsingOptions?.(effectiveModel);const taggedThinkingParser=isStreaming&&responseParsingOptions?.taggedThinkingTags?new TaggedThinkingParser:void 0;return{model:effectiveModel,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:providerOverrides.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??true,toolResultContentFormat:providerOverrides.toolResultContentFormat??this.contentGeneratorConfig.toolResultContentFormat??"parts",...toolCallParser?{toolCallParser}:{},...responseParsingOptions?{responseParsingOptions}:{},...taggedThinkingParser?{taggedThinkingParser}:{}}}};init_esbuild_shims();var debugLogger4=createDebugLogger("OPENAI_ERROR");var EnhancedErrorHandler=class{constructor(shouldSuppressLogging=()=>false){this.shouldSuppressLogging=shouldSuppressLogging}static{__name(this,"EnhancedErrorHandler")}handle(error,context,request){const redactedError=redactProxyError(error);const isTimeoutError=this.isTimeoutError(redactedError);const errorMessage=this.buildErrorMessage(redactedError,context,isTimeoutError);if(!this.shouldSuppressErrorLogging(redactedError,request)){debugLogger4.error("OpenAI API Error:",errorMessage,this.buildDiagnostics(redactedError,context))}if(isTimeoutError){const timeoutError=new Error(`${errorMessage}
4
4
 
5
5
  ${this.getTimeoutTroubleshootingTips()}`,{cause:redactedError});const status=getErrorStatus(redactedError);const transportCode=getTransportCode(redactedError);throw Object.assign(timeoutError,{...status!==void 0?{status}:{},...status===void 0&&transportCode===void 0?{code:"ETIMEDOUT"}:{}})}throw redactedError}shouldSuppressErrorLogging(error,request){return this.shouldSuppressLogging(error,request)}isTimeoutError(error){if(!error)return false;const errorMessage=error instanceof Error?error.message.toLowerCase():String(error).toLowerCase();const errorCode=error?.code;const errorType=error?.type;return errorMessage.includes("timeout")||errorMessage.includes("timed out")||errorMessage.includes("connection timeout")||errorMessage.includes("request timeout")||errorMessage.includes("read timeout")||errorMessage.includes("etimedout")||errorMessage.includes("esockettimedout")||errorCode==="ETIMEDOUT"||errorCode==="ESOCKETTIMEDOUT"||errorType==="timeout"||errorMessage.includes("request timed out")||errorMessage.includes("deadline exceeded")}buildErrorMessage(error,context,isTimeoutError){const durationSeconds=Math.round((Date.now()-context.startTime)/1e3);if(isTimeoutError){return`Request timeout after ${durationSeconds}s. Try reducing input length or increasing timeout in config.`}return error instanceof Error?getErrorMessage(error):String(error)}buildDiagnostics(error,context){const details=getRateLimitErrorDetails(error);const requestId=this.getRequestId(error)??details.requestId;const statusCode=getErrorStatus(error);return{model:context.model,durationMs:Date.now()-context.startTime,errorType:getErrorType(error),...statusCode!==void 0?{statusCode}:{},...details.providerCode!==void 0?{providerCode:details.providerCode}:{},...details.providerMessage!==void 0?{providerMessage:details.providerMessage}:{},...requestId!==void 0?{requestId}:{},...details.transport!=="unknown"?{transport:details.transport}:{}}}getRequestId(error){if(!error||typeof error!=="object")return void 0;const source=error;for(const value of[source.requestID,source.request_id,source.response_id]){if(typeof value==="string"&&value){return value}}return void 0}getTimeoutTroubleshootingTips(){const tips=["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"];return`Troubleshooting tips:
6
6
  ${tips.join("\n")}`}};var debugLogger5=createDebugLogger("OPENAI");var OpenAIContentGenerator=class{static{__name(this,"OpenAIContentGenerator")}pipeline;constructor(contentGeneratorConfig,cliConfig,provider){const pipelineConfig={cliConfig,provider,contentGeneratorConfig,errorHandler:new EnhancedErrorHandler((error,request)=>this.shouldSuppressErrorLogging(error,request))};this.pipeline=new ContentGenerationPipeline(pipelineConfig)}shouldSuppressErrorLogging(error,request){if(isAbortError(error)&&request.config?.abortSignal?.aborted){return true}return false}async generateContent(request,userPromptId){return this.pipeline.execute(request,userPromptId)}async generateContentStream(request,userPromptId){return this.pipeline.executeStream(request,userPromptId)}async embedContent(request){const text=extractTextFromContents(request.contents);try{const embedding=await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:text});return{embeddings:[{values:embedding.data[0].embedding}]}}catch(error){const redactedError=redactProxyError(error);debugLogger5.error("OpenAI API Embedding Error:",redactedError);throw new Error(`OpenAI API error: ${redactedError instanceof Error?redactedError.message:String(redactedError)}`)}}};function createOpenAIContentGenerator(contentGeneratorConfig,cliConfig){const provider=determineProvider(contentGeneratorConfig,cliConfig);return new OpenAIContentGenerator(contentGeneratorConfig,cliConfig,provider)}__name(createOpenAIContentGenerator,"createOpenAIContentGenerator");function determineProvider(contentGeneratorConfig,cliConfig){const config=contentGeneratorConfig||cliConfig.getContentGeneratorConfig();if(DashScopeOpenAICompatibleProvider.isDashScopeProvider(config)){return new DashScopeOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(DeepSeekOpenAICompatibleProvider.isDeepSeekProvider(config)){return new DeepSeekOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(ZaiOpenAICompatibleProvider.isZaiProvider(config)){return new ZaiOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(MiMoOpenAICompatibleProvider.isMiMoProvider(config)){return new MiMoOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(ModelScopeOpenAICompatibleProvider.isModelScopeProvider(config)){return new ModelScopeOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(MiniMaxOpenAICompatibleProvider.isMiniMaxProvider(config)){return new MiniMaxOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(MistralOpenAICompatibleProvider.isMistralProvider(config)){return new MistralOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(CerebrasOpenAICompatibleProvider.isCerebrasProvider(config)){return new CerebrasOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}if(FireworksOpenAICompatibleProvider.isFireworksProvider(config)){return new FireworksOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}return new DefaultOpenAICompatibleProvider(contentGeneratorConfig,cliConfig)}__name(determineProvider,"determineProvider");export{DeepSeekOpenAICompatibleProvider,MiniMaxOpenAICompatibleProvider,MistralOpenAICompatibleProvider,CerebrasOpenAICompatibleProvider,FireworksOpenAICompatibleProvider,MiMoOpenAICompatibleProvider,ContentGenerationPipeline,EnhancedErrorHandler,OpenAIContentGenerator,createOpenAIContentGenerator,determineProvider};