@qwen-code/qwen-code 0.26.2-preview.0 → 0.26.2-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 (300) hide show
  1. package/chunks/{MaxSizedBox-K6YUM3DX.js → MaxSizedBox-EGHZ2BPF.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-75IC33SN.js → StandaloneSessionPicker-UVCW6YW3.js} +1 -1
  3. package/chunks/{acp-subagent-executor-3NHBJRPL.js → acp-subagent-executor-AQ7AWSD4.js} +1 -1
  4. package/chunks/{acpAgent-JT6KQPTH.js → acpAgent-IV7JAGD7.js} +3 -3
  5. package/chunks/{advisor-TI2UVEZK.js → advisor-UZ4TF65D.js} +1 -1
  6. package/chunks/{agent-SWIZZZMY.js → agent-CNLVAWDD.js} +1 -1
  7. package/chunks/{agent-headless-USWEJ4GW.js → agent-headless-ZJUJLUJS.js} +1 -1
  8. package/chunks/{agent-host-client-ZFIMQX33.js → agent-host-client-SN5V2KBH.js} +1 -1
  9. package/chunks/{agent-host-connections-LOFD7O7Q.js → agent-host-connections-VKMAJIIU.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-HMLEI4FI.js → anthropicContentGenerator-QTJVPAMI.js} +1 -1
  11. package/chunks/{autofix-pr-NKR2VSLB.js → autofix-pr-U7GNSH27.js} +1 -1
  12. package/chunks/{batch-JQZ3TOHA.js → batch-MBEWETXN.js} +1 -1
  13. package/chunks/{bridge-EIWWT4P6.js → bridge-TEJLNYV3.js} +1 -1
  14. package/chunks/{channel-settings-store-FLRLUA67.js → channel-settings-store-QNCKWWBL.js} +1 -1
  15. package/chunks/{chunk-244YTFYD.js → chunk-23KDY7UW.js} +1 -1
  16. package/chunks/{chunk-7TDMQJTD.js → chunk-2DWWSMTV.js} +1 -1
  17. package/chunks/{chunk-UU2LTNSF.js → chunk-3IZMVLVZ.js} +1 -1
  18. package/chunks/{chunk-B6T4ESBM.js → chunk-3JI7IKJL.js} +1 -1
  19. package/chunks/{chunk-Y5TT2G3N.js → chunk-427MARCP.js} +1 -1
  20. package/chunks/{chunk-KX7JS2P7.js → chunk-4NNNGSQY.js} +3 -3
  21. package/chunks/{chunk-6TQS2WQO.js → chunk-4RM7KY3Z.js} +2 -2
  22. package/chunks/{chunk-YL3N2UGG.js → chunk-5X7S4AE6.js} +5 -5
  23. package/chunks/{chunk-K2HAY5PY.js → chunk-5XAECBED.js} +1 -1
  24. package/chunks/{chunk-VCHFBETO.js → chunk-66KKSLUO.js} +1 -1
  25. package/chunks/{chunk-BSJR2KEF.js → chunk-6CIIDUZW.js} +1 -1
  26. package/chunks/{chunk-22CLK7PK.js → chunk-7EBRMQYW.js} +1 -1
  27. package/chunks/{chunk-J4TFGZ4A.js → chunk-7FSC2NKA.js} +1 -1
  28. package/chunks/{chunk-6JFC5M6B.js → chunk-A5TAAMML.js} +1 -1
  29. package/chunks/{chunk-DHHACQVN.js → chunk-AOYSX44A.js} +1 -1
  30. package/chunks/{chunk-VFVZ2DY7.js → chunk-AZCMQ3DD.js} +2 -2
  31. package/chunks/{chunk-BQJXWIMR.js → chunk-B6F7CVBP.js} +1 -1
  32. package/chunks/{chunk-OVPEAKOQ.js → chunk-BDQOLT37.js} +1 -1
  33. package/chunks/{chunk-5SYUBQNO.js → chunk-BIWEUAKG.js} +1 -1
  34. package/chunks/{chunk-BZM66PQO.js → chunk-BJ5R7LOM.js} +1 -1
  35. package/chunks/{chunk-4R2OHBH3.js → chunk-BKUFRNME.js} +1 -1
  36. package/chunks/{chunk-NIYWNFVF.js → chunk-BNZSPX2I.js} +1 -1
  37. package/chunks/{chunk-FJV2ECNY.js → chunk-D2URRVOK.js} +1 -1
  38. package/chunks/{chunk-GT6CHVAI.js → chunk-DANP7CMW.js} +1 -1
  39. package/chunks/{chunk-FHFLD4DR.js → chunk-DBHLRZGI.js} +1 -1
  40. package/chunks/{chunk-Y2UXZJLM.js → chunk-DL7TKH2E.js} +2 -2
  41. package/chunks/{chunk-MCQE2U7N.js → chunk-DOWKH5OZ.js} +6 -6
  42. package/chunks/{chunk-UHRLBY3C.js → chunk-DPHQJPCU.js} +1 -1
  43. package/chunks/{chunk-PV2VT25U.js → chunk-DPNGBOI7.js} +1 -1
  44. package/chunks/{chunk-NCDNF7UJ.js → chunk-DXRXF4QD.js} +1 -1
  45. package/chunks/{chunk-OCVRMNEQ.js → chunk-DZ3GV34J.js} +1 -1
  46. package/chunks/{chunk-3QIAXWWW.js → chunk-EU2MKUK4.js} +1 -1
  47. package/chunks/{chunk-KMAVI6FB.js → chunk-EVBUXPGM.js} +1 -1
  48. package/chunks/{chunk-BVSTV4JM.js → chunk-F3ZRU2SA.js} +1 -1
  49. package/chunks/{chunk-TBZY477Y.js → chunk-FCZYH27X.js} +1 -1
  50. package/chunks/{chunk-JCOK67LT.js → chunk-FNDMWG43.js} +1 -1
  51. package/chunks/{chunk-5SF32OGU.js → chunk-GDXLJJSW.js} +1 -1
  52. package/chunks/{chunk-SO6FCPRI.js → chunk-GZYIXB7Y.js} +1 -1
  53. package/chunks/{chunk-WZPTWC7X.js → chunk-HHNAH4IH.js} +1 -1
  54. package/chunks/{chunk-7KCAOXNL.js → chunk-HOKROBQZ.js} +1 -1
  55. package/chunks/{chunk-34ZBUQJV.js → chunk-IGPAATQW.js} +1 -1
  56. package/chunks/{chunk-2ZTRKK2O.js → chunk-INFBJDWM.js} +1 -1
  57. package/chunks/{chunk-IEJ2CGRN.js → chunk-J3R7ZNSA.js} +1 -1
  58. package/chunks/{chunk-KT5MPRYB.js → chunk-JCRS367I.js} +1 -1
  59. package/chunks/{chunk-7JWJTRP6.js → chunk-JFVXZFMV.js} +1 -1
  60. package/chunks/{chunk-47LP4MBD.js → chunk-JKMGS2VD.js} +1 -1
  61. package/chunks/{chunk-WRJ3PMDZ.js → chunk-JUQ7T2MV.js} +1 -1
  62. package/chunks/{chunk-NZX3UWNF.js → chunk-KQ4TDFNE.js} +1 -1
  63. package/chunks/{chunk-X7D4VKMX.js → chunk-L6BKKN42.js} +1 -1
  64. package/chunks/{chunk-YG5HVFMY.js → chunk-L7Y6MOHS.js} +1 -1
  65. package/chunks/{chunk-UFTIUKD4.js → chunk-LGYXZJI3.js} +1 -1
  66. package/chunks/{chunk-JQGGILML.js → chunk-LPOEVTKD.js} +1 -1
  67. package/chunks/{chunk-5KI55A6S.js → chunk-LRXS7ZI2.js} +1 -1
  68. package/chunks/{chunk-CKVHEYXW.js → chunk-LYYVSCNL.js} +1 -1
  69. package/chunks/{chunk-LIIMQ4DI.js → chunk-LZNBHBAJ.js} +6 -6
  70. package/chunks/{chunk-H4GDEXMF.js → chunk-M3C6RDGC.js} +1 -1
  71. package/chunks/{chunk-KKKUB3RQ.js → chunk-MNVMHVQJ.js} +1 -1
  72. package/chunks/{chunk-2B3W7IQY.js → chunk-MVGQFFIK.js} +1 -1
  73. package/chunks/{chunk-Q35A2RGO.js → chunk-NC7BCZPQ.js} +1 -1
  74. package/chunks/{chunk-2ZOTG3NW.js → chunk-NE627MUW.js} +1 -1
  75. package/chunks/{chunk-W4P2EN3V.js → chunk-NZNRCPGE.js} +1 -1
  76. package/chunks/{chunk-YPDQJQ3S.js → chunk-P3M4WWRA.js} +1 -1
  77. package/chunks/{chunk-DVB36ASH.js → chunk-P534ONQN.js} +1 -1
  78. package/chunks/{chunk-EL5J4ESB.js → chunk-QF44NNSC.js} +1 -1
  79. package/chunks/{chunk-IQPJOBPI.js → chunk-QHGCDHNW.js} +1 -1
  80. package/chunks/{chunk-EVZC4KEQ.js → chunk-QWJX7NIP.js} +1 -1
  81. package/chunks/{chunk-J2TJL2F4.js → chunk-S53G54DW.js} +2 -2
  82. package/chunks/{chunk-3A6LFJJV.js → chunk-SMNFL3AD.js} +1 -1
  83. package/chunks/{chunk-WDO3K3P2.js → chunk-TOBNWST4.js} +1 -1
  84. package/chunks/{chunk-AVGJ4HE3.js → chunk-TQSBUHAM.js} +1 -1
  85. package/chunks/{chunk-ABUS7DNN.js → chunk-TW5QEP2J.js} +1 -1
  86. package/chunks/{chunk-WYM4Z4D5.js → chunk-UEB2F43V.js} +1 -1
  87. package/chunks/{chunk-FUUPMVD2.js → chunk-UPPE4I6H.js} +1 -1
  88. package/chunks/{chunk-UHBJVFZA.js → chunk-US42COBM.js} +1 -1
  89. package/chunks/{chunk-RMQNBSMK.js → chunk-UUY6XSQI.js} +1 -1
  90. package/chunks/{chunk-UVQUQNCA.js → chunk-UZI3IA27.js} +1 -1
  91. package/chunks/{chunk-SXJ2E33J.js → chunk-V6VMUJ47.js} +1 -1
  92. package/chunks/{chunk-5UFCNJGN.js → chunk-VG2ZINTO.js} +1 -1
  93. package/chunks/{chunk-JPPPJ2GN.js → chunk-VJI6MHWX.js} +1 -1
  94. package/chunks/{chunk-AUI7WVSU.js → chunk-VOBNHBCJ.js} +1 -1
  95. package/chunks/{chunk-3BNJDZHU.js → chunk-VUEZWMI4.js} +1 -1
  96. package/chunks/{chunk-LMNKCL55.js → chunk-W7ZX6WB3.js} +2 -2
  97. package/chunks/{chunk-HVS6V2UZ.js → chunk-WA2LKUVP.js} +1 -1
  98. package/chunks/{chunk-7APLU2XE.js → chunk-WFFCJ5PF.js} +1 -1
  99. package/chunks/{chunk-3TD4WAG5.js → chunk-WQY5GE65.js} +1 -1
  100. package/chunks/{chunk-3YWRMF6C.js → chunk-WSESLSKK.js} +1 -1
  101. package/chunks/{chunk-NILCQMZ7.js → chunk-XFJV5NYT.js} +1 -1
  102. package/chunks/{chunk-LGBGUITT.js → chunk-XIYLRIW4.js} +1 -1
  103. package/chunks/{chunk-KS74L67R.js → chunk-XQ2NYKJH.js} +1 -1
  104. package/chunks/{chunk-JB2NOB6W.js → chunk-Y3VRWG52.js} +1 -1
  105. package/chunks/{chunk-GVZ6D2NL.js → chunk-YBISME5B.js} +1 -1
  106. package/chunks/{chunk-2C2253QI.js → chunk-YJNWPSB3.js} +1 -1
  107. package/chunks/{chunk-O2T3GQ6F.js → chunk-YWVV5STA.js} +1 -1
  108. package/chunks/{chunk-MAQZSOHI.js → chunk-ZH4J3FL6.js} +1 -1
  109. package/chunks/{chunk-THNEKTPK.js → chunk-ZSKCF6DI.js} +1 -1
  110. package/chunks/{chunk-Z7BAHKO5.js → chunk-ZW6456SD.js} +1 -1
  111. package/chunks/{chunk-DMSZ2TB3.js → chunk-ZWM3LLT7.js} +1 -1
  112. package/chunks/{codex-subagent-executor-DQ5LQQWO.js → codex-subagent-executor-DWWT7246.js} +1 -1
  113. package/chunks/{config-utils-CY6HLKZ5.js → config-utils-NGZB522W.js} +1 -1
  114. package/chunks/{contextCommand-SGBWI7O6.js → contextCommand-7QCW2YNX.js} +1 -1
  115. package/chunks/{core-runtime-4DP27LCC.js → core-runtime-PSVNDJPD.js} +1 -1
  116. package/chunks/{create-sub-session-ECPDZMBX.js → create-sub-session-JTSEMEJE.js} +1 -1
  117. package/chunks/{cron-create-OO4OG3EI.js → cron-create-VGIDTUMX.js} +1 -1
  118. package/chunks/{daemon-git-worktree-guard-OYDNHT7P.js → daemon-git-worktree-guard-IQRGS7IH.js} +1 -1
  119. package/chunks/{daemon-status-provider-JGDLXPC6.js → daemon-status-provider-R4MYCYPG.js} +1 -1
  120. package/chunks/{daemon-trust-policy-5HRARS54.js → daemon-trust-policy-VAUKFZ2N.js} +1 -1
  121. package/chunks/{daemon-trust-policy-monitor-RM7FVIIC.js → daemon-trust-policy-monitor-E5HIO6RP.js} +1 -1
  122. package/chunks/{deferred-core-runtime-3CXBZIOG.js → deferred-core-runtime-FLOFQJPU.js} +1 -1
  123. package/chunks/{edit-DJPESAAY.js → edit-OOVQUGKV.js} +1 -1
  124. package/chunks/{enterPlanMode-IHBLRIF3.js → enterPlanMode-AUWVTQLT.js} +1 -1
  125. package/chunks/{environment-JN5SD347.js → environment-RM5OXYP4.js} +1 -1
  126. package/chunks/{errors-NUJCME3Y.js → errors-CLDJGHVD.js} +1 -1
  127. package/chunks/{execution-tool-I3SWG6I3.js → execution-tool-JFBVOKPW.js} +1 -1
  128. package/chunks/{execution-worker-62UZMAMJ.js → execution-worker-MNJZD72W.js} +1 -1
  129. package/chunks/{exitPlanMode-JIC4V3FE.js → exitPlanMode-PC6XG4TW.js} +1 -1
  130. package/chunks/{fast-path-NIOIL5YI.js → fast-path-V4DN3CRZ.js} +1 -1
  131. package/chunks/{glob-EQ4QNAHF.js → glob-DTZROBDS.js} +1 -1
  132. package/chunks/{goal-tools-DYTTSBQG.js → goal-tools-FUVGTY33.js} +1 -1
  133. package/chunks/{handleAutoUpdate-44BTG5L5.js → handleAutoUpdate-U4LVTHGU.js} +1 -1
  134. package/chunks/{i18n-FTHZAHCT.js → i18n-XOKNDFYP.js} +1 -1
  135. package/chunks/{initializer-MSGKXC75.js → initializer-XBR5J4CY.js} +1 -1
  136. package/chunks/{installationInfo-4XJMJJYU.js → installationInfo-4AOEOUI6.js} +1 -1
  137. package/chunks/{interactive-mod-session-DFLRYO2Q.js → interactive-mod-session-YGZK2JK2.js} +1 -1
  138. package/chunks/{list-ODZ7Z6VI.js → list-TCGKVPH4.js} +1 -1
  139. package/chunks/{llm-O64DHKP7.js → llm-SKFTN5UN.js} +4 -4
  140. package/chunks/{llm-content-generator-SK24I6QS.js → llm-content-generator-GWHXT3WS.js} +1 -1
  141. package/chunks/{loadedSettingsAdapter-6PEBUZT5.js → loadedSettingsAdapter-ZALZGZE7.js} +1 -1
  142. package/chunks/{local-ED3UEKWP.js → local-RWTWYS5Z.js} +1 -1
  143. package/chunks/{local-execution-environment-PUKES5LO.js → local-execution-environment-R6JWLD65.js} +1 -1
  144. package/chunks/{loggingContentGenerator-UHOJVSRR.js → loggingContentGenerator-UJV6QFOY.js} +1 -1
  145. package/chunks/{loop-wakeup-NSJQETPZ.js → loop-wakeup-BU2RRYHA.js} +1 -1
  146. package/chunks/{manage-memory-5RRB6FLH.js → manage-memory-XI57JN4T.js} +1 -1
  147. package/chunks/{managed-execution-engine-MZAP7SK6.js → managed-execution-engine-BA5PABMP.js} +1 -1
  148. package/chunks/{managed-local-serve-XMES3HXL.js → managed-local-serve-MFKN22K6.js} +1 -1
  149. package/chunks/{managed-npm-update-R5KGY7G2.js → managed-npm-update-ZGN43NUA.js} +1 -1
  150. package/chunks/{managed-runtime-attestation-worker-O2KNHHV6.js → managed-runtime-attestation-worker-YN2VBGYN.js} +1 -1
  151. package/chunks/{managed-runtime-bootstrap-HOTLM6DE.js → managed-runtime-bootstrap-SGQVMUJE.js} +1 -1
  152. package/chunks/{managed-runtime-session-worker-QZX44ZTD.js → managed-runtime-session-worker-4UMF3VBY.js} +1 -1
  153. package/chunks/{managed-runtime-ssh-worker-U425WQ65.js → managed-runtime-ssh-worker-7XA6KRBN.js} +1 -1
  154. package/chunks/{managed-session-authority-THHDHCBP.js → managed-session-authority-IJGYAOEL.js} +1 -1
  155. package/chunks/{mcp-AR7EK4WY.js → mcp-V3L7B5YK.js} +1 -1
  156. package/chunks/{memory-C2TSF6BK.js → memory-3T6FPNAK.js} +1 -1
  157. package/chunks/{model-call-collection-25WR55OH.js → model-call-collection-WTTITWWM.js} +1 -1
  158. package/chunks/{model-configuration-KC7DQGKV.js → model-configuration-T6SSGI4J.js} +1 -1
  159. package/chunks/{modelConfigUtils-QEHMVLSQ.js → modelConfigUtils-TQA25QJC.js} +1 -1
  160. package/chunks/{monitor-PDQUZD23.js → monitor-5ZAOJSEE.js} +1 -1
  161. package/chunks/{nonInteractiveCli-WY2YFONU.js → nonInteractiveCli-YFINLVA7.js} +1 -1
  162. package/chunks/{nonInteractiveToolExecutor-7RJZYPHJ.js → nonInteractiveToolExecutor-DE3WACL5.js} +1 -1
  163. package/chunks/{notebook-edit-P4ITXF5H.js → notebook-edit-UK6HBRO3.js} +1 -1
  164. package/chunks/{omni-AYUPB2QM.js → omni-65LF5QK4.js} +1 -1
  165. package/chunks/{openaiContentGenerator-V5IK4ITO.js → openaiContentGenerator-HX7NCSV5.js} +1 -1
  166. package/chunks/{openaiResponsesContentGenerator-DYDH6KWT.js → openaiResponsesContentGenerator-CFA6U6Y5.js} +1 -1
  167. package/chunks/{pidfile-INPBL2DK.js → pidfile-ZVKJUNTZ.js} +1 -1
  168. package/chunks/{processUtils-J4UDEDS4.js → processUtils-VS6CJT7E.js} +1 -1
  169. package/chunks/{prompt-terminal-ledger-QLOQWHYE.js → prompt-terminal-ledger-UF5RDB57.js} +1 -1
  170. package/chunks/{qwenContentGenerator-RU43XKKB.js → qwenContentGenerator-GM3ZSI7E.js} +1 -1
  171. package/chunks/{reactive-degrade-2Q3Z3KAR.js → reactive-degrade-TSAQWZ5F.js} +1 -1
  172. package/chunks/{read-file-472BQ25I.js → read-file-J267NT45.js} +1 -1
  173. package/chunks/{resumeHistoryUtils-7SUFKZDC.js → resumeHistoryUtils-IM46VFDV.js} +1 -1
  174. package/chunks/{review-WX52IWJR.js → review-4B64XTCL.js} +1 -1
  175. package/chunks/{ripGrep-4GPGLKAM.js → ripGrep-YLOSXO7P.js} +1 -1
  176. package/chunks/{run-qwen-serve-MXK4RBKL.js → run-qwen-serve-SAHEC44O.js} +1 -1
  177. package/chunks/{runtime-WHU3AGFT.js → runtime-SJDZHV6J.js} +1 -1
  178. package/chunks/{sandboxConfig-7DBXEQJH.js → sandboxConfig-47EXXMUA.js} +1 -1
  179. package/chunks/{scheduled-tasks-O5RV6G6U.js → scheduled-tasks-E6RCTUUS.js} +1 -1
  180. package/chunks/{scheduler-HLMS5LR5.js → scheduler-SE3IWIWA.js} +1 -1
  181. package/chunks/{search-memory-PYND7ZX3.js → search-memory-2W7VJC4Q.js} +1 -1
  182. package/chunks/{send-message-TMLYTQOI.js → send-message-63YGQP6G.js} +1 -1
  183. package/chunks/{serve-EBNBRAME.js → serve-F4ML2WNL.js} +1 -1
  184. package/chunks/{server-63BRDBL5.js → server-S56IB4TT.js} +3 -3
  185. package/chunks/{session-XB6J4CZD.js → session-2CUVLZ4H.js} +1 -1
  186. package/chunks/{session-attachments-root-PFK475N2.js → session-attachments-root-FINBX7K5.js} +1 -1
  187. package/chunks/{session-execution-engine-selector-P6TJTCKR.js → session-execution-engine-selector-UGC7DGUN.js} +1 -1
  188. package/chunks/{session-pr-refresh-PM7VAQTV.js → session-pr-refresh-KQLQ4MZY.js} +1 -1
  189. package/chunks/{sessionService-PO3LLZIZ.js → sessionService-Q6N7LF7Z.js} +1 -1
  190. package/chunks/{settings-JDQSRXP3.js → settings-23I6H76E.js} +1 -1
  191. package/chunks/{shell-JCEX3HKM.js → shell-IUECEVVY.js} +1 -1
  192. package/chunks/{skill-JSZBONIZ.js → skill-YKUETMPC.js} +1 -1
  193. package/chunks/{skill-settings-YGFG6GPN.js → skill-settings-ODYXOPCA.js} +1 -1
  194. package/chunks/{spawnChannel-VIIWSWTL.js → spawnChannel-7XU2SRWZ.js} +1 -1
  195. package/chunks/{standalone-update-2UU6FQZL.js → standalone-update-SWI2RL3L.js} +1 -1
  196. package/chunks/{start-opentui-ui-OSZZNSLY.js → start-opentui-ui-T53QJGCH.js} +1 -1
  197. package/chunks/{startInteractiveUI-FFH66MYH.js → startInteractiveUI-USTZGQOE.js} +1 -1
  198. package/chunks/{team-create-TKGDJ3NU.js → team-create-4A2XUE3D.js} +1 -1
  199. package/chunks/{team-plan-approval-3VJF4G6Z.js → team-plan-approval-4TS5CYN6.js} +1 -1
  200. package/chunks/{terminal-image-renderer-T3VJRZGP.js → terminal-image-renderer-C7553YV6.js} +1 -1
  201. package/chunks/{theme-manager-ZGUFLFUI.js → theme-manager-GTW75GOO.js} +1 -1
  202. package/chunks/{tool-call-3EQS5KSE.js → tool-call-YTUMWL3A.js} +1 -1
  203. package/chunks/{tool-result-media-7LFNVQ6E.js → tool-result-media-JYOYBX4J.js} +1 -1
  204. package/chunks/{tool-search-UDZ4S7T5.js → tool-search-Y4XTT2WF.js} +1 -1
  205. package/chunks/{total-session-admission-U4MII4RA.js → total-session-admission-EMJ5NRGL.js} +1 -1
  206. package/chunks/{trustedFolders-2NQJCIN3.js → trustedFolders-YG6WAVRE.js} +1 -1
  207. package/chunks/{update-relaunch-YKLWSCLC.js → update-relaunch-4QYQRCP4.js} +1 -1
  208. package/chunks/{updateCheck-YDLTQQRU.js → updateCheck-VRFPSX4G.js} +1 -1
  209. package/chunks/{upload-config-5QQKWF4O.js → upload-config-UCKGUYYQ.js} +1 -1
  210. package/chunks/{useAutoAcceptIndicator-AJS4WTU2.js → useAutoAcceptIndicator-2VGLKD7B.js} +1 -1
  211. package/chunks/{validateNonInterActiveAuth-AETOT7ZW.js → validateNonInterActiveAuth-GGMQXKKU.js} +1 -1
  212. package/chunks/{version-IB6DLRAG.js → version-Y46PG7II.js} +1 -1
  213. package/chunks/{web-fetch-LS3QARNR.js → web-fetch-7MPU555L.js} +1 -1
  214. package/chunks/{web-search-FGHRIVEB.js → web-search-HU2CL2X2.js} +1 -1
  215. package/chunks/{workflow-FX6XNETQ.js → workflow-U3D34QQX.js} +1 -1
  216. package/chunks/{workflow-ancestor-trust-5XXBGN6F.js → workflow-ancestor-trust-OWC4YTMR.js} +1 -1
  217. package/chunks/{workspace-agents-UJKLYPUK.js → workspace-agents-KHLAWSAR.js} +1 -1
  218. package/chunks/{workspace-providers-status-4JOHMTAW.js → workspace-providers-status-T57SE3YX.js} +1 -1
  219. package/chunks/{workspace-recovery-worker-XFEYQ4TP.js → workspace-recovery-worker-VYQ723ZE.js} +1 -1
  220. package/chunks/{workspace-registration-store-LWAPVNYC.js → workspace-registration-store-I7PR3A2Y.js} +1 -1
  221. package/chunks/{workspace-registry-M7OC376O.js → workspace-registry-YYUBXCLH.js} +1 -1
  222. package/chunks/{workspace-runtime-coordinator-CYHIL47L.js → workspace-runtime-coordinator-5ICAQO7W.js} +1 -1
  223. package/chunks/{workspace-service-43VZZ56B.js → workspace-service-YROWXOLQ.js} +1 -1
  224. package/chunks/{workspace-skills-status-V2TT6UJQ.js → workspace-skills-status-DKKQDTZJ.js} +1 -1
  225. package/chunks/{workspace-trust-reconciler-YZ4AG5ZW.js → workspace-trust-reconciler-3FPMUZDO.js} +1 -1
  226. package/chunks/{write-file-TGEH5MEZ.js → write-file-7QQVYFDT.js} +1 -1
  227. package/chunks/{zoom-image-TT6R7H2H.js → zoom-image-WL5EB6Q7.js} +1 -1
  228. package/cli.js +2 -2
  229. package/execution-worker.js +1 -1
  230. package/export-transcript-document.js +1 -1
  231. package/package.json +3 -3
  232. package/web-shell/assets/{PierreFilePreview-OsApm5-S.js → PierreFilePreview-BZ17f56_.js} +1 -1
  233. package/web-shell/assets/{SpreadsheetPreview-I1v1EzV7.js → SpreadsheetPreview-Bvkvr_5u.js} +1 -1
  234. package/web-shell/assets/{WorkspaceFileBrowser-BO6aug7i.js → WorkspaceFileBrowser-BJ_I4Uoz.js} +1 -1
  235. package/web-shell/assets/{abnfDiagram-VCTEODGH-DxuLMyN0.js → abnfDiagram-VCTEODGH-iuaBM15V.js} +1 -1
  236. package/web-shell/assets/{agents-route-CSJf6QPO.js → agents-route-CycwfNSC.js} +1 -1
  237. package/web-shell/assets/{arc-3--LekYQ.js → arc-C0lt8n55.js} +1 -1
  238. package/web-shell/assets/{architectureDiagram-5GKGNRK7-Dihq4uto.js → architectureDiagram-5GKGNRK7-Bw326d-A.js} +1 -1
  239. package/web-shell/assets/{blockDiagram-NRAW4CY4-BnaRPM2o.js → blockDiagram-NRAW4CY4-CHtFgBjV.js} +1 -1
  240. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BtC94eMa.js → c4Diagram-UCG6FXSJ-Bx66oJT9.js} +1 -1
  241. package/web-shell/assets/channel-CRJuO00u.js +1 -0
  242. package/web-shell/assets/{chunk-2Q5K7J3B-2ZTXWP6M.js → chunk-2Q5K7J3B-BIshvfa_.js} +1 -1
  243. package/web-shell/assets/{chunk-5VM5RSS4-DBh7DP1F.js → chunk-5VM5RSS4-BZeRS6uD.js} +1 -1
  244. package/web-shell/assets/{chunk-F27PBJKO-xzqbWXBw.js → chunk-F27PBJKO-El-CGY2R.js} +1 -1
  245. package/web-shell/assets/{chunk-G27WJ6UU-DxnCrpxK.js → chunk-G27WJ6UU-DO8ZfQL_.js} +1 -1
  246. package/web-shell/assets/{chunk-JWPE2WC7-BPjRsozm.js → chunk-JWPE2WC7-yYFrrKAj.js} +1 -1
  247. package/web-shell/assets/{chunk-LCL6LL3I-Q2HgB3lf.js → chunk-LCL6LL3I-BFGuOKN0.js} +1 -1
  248. package/web-shell/assets/{chunk-POPQ4Y6H-9tlPaKu-.js → chunk-POPQ4Y6H-GRHK6sdV.js} +1 -1
  249. package/web-shell/assets/{chunk-SVP7TREG-DkNdOHCU.js → chunk-SVP7TREG-DwDu6GqZ.js} +1 -1
  250. package/web-shell/assets/{chunk-XXDRQBXY-D0G-Dhfi.js → chunk-XXDRQBXY-RoNDjkIy.js} +1 -1
  251. package/web-shell/assets/classDiagram-DTDB5LWJ-pPPByLA7.js +1 -0
  252. package/web-shell/assets/classDiagram-v2-JRS7N3AN-pPPByLA7.js +1 -0
  253. package/web-shell/assets/{cose-bilkent-JH36ORCC-Ck0tHxul.js → cose-bilkent-JH36ORCC-CYNiiONE.js} +1 -1
  254. package/web-shell/assets/{cynefin-OW5HDTMX-a4-NTMHi.js → cynefin-OW5HDTMX-DC1_lDIG.js} +1 -1
  255. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Pg41Zbf2.js → cynefinDiagram-5FMLGOSQ-D2VxKm2n.js} +1 -1
  256. package/web-shell/assets/{dagre-3AP2YEHR-DT_ZmqkF.js → dagre-3AP2YEHR-C4_BHzpM.js} +1 -1
  257. package/web-shell/assets/{diagram-S7CK7UJ4-hapdMOl1.js → diagram-S7CK7UJ4-BpAO4-Gv.js} +1 -1
  258. package/web-shell/assets/{diagram-UQ7AKVKN-YZ0nbk56.js → diagram-UQ7AKVKN-DqUsFdsX.js} +1 -1
  259. package/web-shell/assets/{diagram-VSXAHHWV-DA_yNbWy.js → diagram-VSXAHHWV-DcMXIYMy.js} +1 -1
  260. package/web-shell/assets/{diagram-VX7I27RA-DoULuCLT.js → diagram-VX7I27RA-I3nr09ex.js} +1 -1
  261. package/web-shell/assets/{diagram-Z3DM3KII-B5c9o9zL.js → diagram-Z3DM3KII-CN-gvsTo.js} +1 -1
  262. package/web-shell/assets/{docx-preview-BulxdBjs.js → docx-preview-31J6RsS0.js} +1 -1
  263. package/web-shell/assets/{ebnfDiagram-PWID7BFC-B5hgIg3m.js → ebnfDiagram-PWID7BFC-DOQvLWlM.js} +1 -1
  264. package/web-shell/assets/{erDiagram-SSCWMZ5O-BEfEPozi.js → erDiagram-SSCWMZ5O-Cb5ijFZh.js} +1 -1
  265. package/web-shell/assets/{flowDiagram-A5DVABFB-CQHNk92v.js → flowDiagram-A5DVABFB-BecqqjnZ.js} +1 -1
  266. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-BabdVgIM.js → ganttDiagram-EL5Y4UJY-DWY5vzQl.js} +1 -1
  267. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-ujRZBFUo.js → gitGraphDiagram-WWUBYQGX-DqBnsZmZ.js} +1 -1
  268. package/web-shell/assets/{index-B9uXebIR.js → index-DDmiUW3b.js} +6 -6
  269. package/web-shell/assets/{index-DSZXdZnu.js → index-DabH7kHA.js} +1 -1
  270. package/web-shell/assets/{infoDiagram-RXCK75RN-CUHj9jJC.js → infoDiagram-RXCK75RN-MlotyOdT.js} +1 -1
  271. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-CulW_q81.js → ishikawaDiagram-5VMMS53U-Daq_85C7.js} +1 -1
  272. package/web-shell/assets/{journeyDiagram-EYS64GPL-BR46CvRQ.js → journeyDiagram-EYS64GPL-OipivCxL.js} +1 -1
  273. package/web-shell/assets/{kanban-definition-3QL26DDD-HAoUqzFy.js → kanban-definition-3QL26DDD-zqaz7dLu.js} +1 -1
  274. package/web-shell/assets/{layout-DYLl7fyA.js → layout-Bi3msQMQ.js} +1 -1
  275. package/web-shell/assets/{linear-DPXABjDZ.js → linear-D4gPORvD.js} +1 -1
  276. package/web-shell/assets/{mermaid.core-Bi30Gi0n.js → mermaid.core-BUnytF7a.js} +6 -6
  277. package/web-shell/assets/{mindmap-definition-FBJOCRG2-B1_lUq4o.js → mindmap-definition-FBJOCRG2-B_X4iChu.js} +1 -1
  278. package/web-shell/assets/{pegDiagram-XKGWAZYB-Cy8tjJJC.js → pegDiagram-XKGWAZYB-z4wYBoBW.js} +1 -1
  279. package/web-shell/assets/{pieDiagram-E7YTZNPT-D6waLVVi.js → pieDiagram-E7YTZNPT-Dvyg6FYo.js} +1 -1
  280. package/web-shell/assets/{quadrantDiagram-AXDQQJYC--6ehi_FI.js → quadrantDiagram-AXDQQJYC-CJBWU2Dk.js} +1 -1
  281. package/web-shell/assets/{railroadDiagram-O6MQD6OU-BhLy40X4.js → railroadDiagram-O6MQD6OU-Dl_An1O0.js} +1 -1
  282. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BVNXTgNP.js → requirementDiagram-EFPCY7ZU-Tw8FwaYU.js} +1 -1
  283. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BHgTytxV.js → sankeyDiagram-P5KCCOFB-BCPCkbR0.js} +1 -1
  284. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-CgOsTvhu.js → sequenceDiagram-WJ2MYXX4-DDj7uFTG.js} +1 -1
  285. package/web-shell/assets/{sizeCapture-X5ZJPWSS-vCQBQ5FI.js → sizeCapture-X5ZJPWSS-B9eVSpKb.js} +1 -1
  286. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DytMYRWJ.js → stateDiagram-HBIQ2CUA-Bf4BZP_V.js} +1 -1
  287. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BPJi6Gre.js +1 -0
  288. package/web-shell/assets/{swimlanes-XN3QIQJK-CTGnifOP.js → swimlanes-XN3QIQJK-dyTWsZFj.js} +1 -1
  289. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bw4NRtJQ.js +8 -0
  290. package/web-shell/assets/{timeline-definition-24CTP7MA-DEJ1cbn2.js → timeline-definition-24CTP7MA-DVl1A4uL.js} +1 -1
  291. package/web-shell/assets/{vennDiagram-4TSXK5OY-K1e4SjS0.js → vennDiagram-4TSXK5OY-Boosxy9D.js} +1 -1
  292. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DEX-GkRp.js → wardleyDiagram-VM6X3IG4-C6wlY8jy.js} +1 -1
  293. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-B6wYXreH.js → xychartDiagram-S5SC5T6Z-CkzZe3ro.js} +1 -1
  294. package/web-shell/index.html +1 -1
  295. package/web-shell/sw.js +1 -1
  296. package/web-shell/assets/channel-CLVrtVFX.js +0 -1
  297. package/web-shell/assets/classDiagram-DTDB5LWJ-Df2T70oB.js +0 -1
  298. package/web-shell/assets/classDiagram-v2-JRS7N3AN-Df2T70oB.js +0 -1
  299. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CcjUJGng.js +0 -1
  300. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dt8NvQfX.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{getUserSettingsPath,v1ToV2Migration}from"./chunk-2B3W7IQY.js";import{LoadedTrustedFolders,TrustLevel,getExplicitTrustLevel,getTrustedFoldersPath,isWorkflowAncestorDirectorySafe,parseJsoncObject}from"./chunk-LGBGUITT.js";import{arePathsEquivalent}from"./chunk-IDXJIDME.js";import{require_strip_json_comments}from"./chunk-DOLUT3XC.js";import{getSystemDefaultsPath,getSystemSettingsPath}from"./chunk-PTHIQ7ZN.js";import{ideContextStore}from"./chunk-LIIMQ4DI.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs/promises";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var MAX_TRUSTED_FOLDERS_BYTES=1024*1024;var MAX_SETTINGS_BYTES=4*1024*1024;function evaluateDaemonWorkflowAncestorTrust(snapshot,query){const denied=__name(()=>query.ancestorDirs.map(()=>false),"denied");if(snapshot.settingsError)return denied();if(!snapshot.folderTrustEnabled){return query.ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(snapshot.trustedFoldersError||snapshot.ideTrust===false&&(arePathsEquivalent(query.workspaceCwd,query.ideScopeCwd)||arePathsEquivalent(query.canonicalTargetDir,query.ideScopeCwd))){return denied()}const folders=new LoadedTrustedFolders({path:getTrustedFoldersPath(),config:{...snapshot.trustedFolders}},[]);if(folders.isPathTrusted(query.canonicalTargetDir)!==true){return denied()}return query.ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}__name(evaluateDaemonWorkflowAncestorTrust,"evaluateDaemonWorkflowAncestorTrust");function policyError(code,filePath,error){return{code,path:filePath,message:error instanceof Error?error.message:String(error)}}__name(policyError,"policyError");async function readJsonObject(filePath,maxBytes,requireRegularFile,retryMissing=false,allowTrailingComma=false){const delays=[0,50,200];let result={};for(const delay of delays){if(delay>0){await new Promise(resolve=>setTimeout(resolve,delay))}result=await readJsonObjectOnce(filePath,maxBytes,requireRegularFile,allowTrailingComma);if(!result.error&&(!result.missing||!retryMissing))return result}return result}__name(readJsonObject,"readJsonObject");async function readJsonObjectOnce(filePath,maxBytes,requireRegularFile,allowTrailingComma){let stat2;try{stat2=await fs.lstat(filePath)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return{value:{},missing:true}}return{error:policyError("trust_policy_unreadable",filePath,error)}}if(!requireRegularFile&&stat2.isSymbolicLink()){try{stat2=await fs.stat(filePath)}catch(error){return{error:policyError("trust_policy_unreadable",filePath,error)}}}if(requireRegularFile&&stat2.isSymbolicLink()||!stat2.isFile()){return{error:policyError("trust_policy_invalid",filePath,new Error("Trust policy input must be a regular file."))}}if(stat2.size>maxBytes){return{error:policyError("trust_policy_invalid",filePath,new Error(`Trust policy input exceeds ${maxBytes} bytes.`))}}try{const raw=await fs.readFile(filePath,"utf8");const parsed=allowTrailingComma?parseJsoncObject(raw):JSON.parse((0,import_strip_json_comments.default)(raw));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){throw new Error("Trust policy input must contain a JSON object.")}return{value:parsed}}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return{value:{},missing:true}}return{error:policyError("trust_policy_invalid",filePath,error)}}}__name(readJsonObjectOnce,"readJsonObjectOnce");function migrateFolderTrustSettings(value,scope){if(!value||!v1ToV2Migration.shouldMigrate(value))return value;return v1ToV2Migration.migrate(value,scope).settings}__name(migrateFolderTrustSettings,"migrateFolderTrustSettings");function folderTrustSetting(value,filePath){if(!value||!("security"in value))return{};const security=value?.["security"];if(typeof security!=="object"||security===null||Array.isArray(security)){return{error:policyError("trust_policy_invalid",filePath,new Error("`security` must be an object."))}}if(!("folderTrust"in security))return{};const folderTrust=security["folderTrust"];if(typeof folderTrust!=="object"||folderTrust===null||Array.isArray(folderTrust)){return{error:policyError("trust_policy_invalid",filePath,new Error("`security.folderTrust` must be an object."))}}if(!("enabled"in folderTrust))return{};const enabled=folderTrust["enabled"];if(typeof enabled==="boolean")return{value:enabled};return{error:policyError("trust_policy_invalid",filePath,new Error("`security.folderTrust.enabled` must be a boolean."))}}__name(folderTrustSetting,"folderTrustSetting");function parseTrustedFolders(value,filePath){const config={};for(const[rulePath,rawLevel]of Object.entries(value??{})){if(!Object.values(TrustLevel).includes(rawLevel)){return{config:{},error:policyError("trust_policy_invalid",filePath,new Error(`Invalid trust level for ${JSON.stringify(rulePath)}.`))}}config[rulePath]=rawLevel}return{config}}__name(parseTrustedFolders,"parseTrustedFolders");function semanticRevision(input){const sortedRules=Object.entries(input.trustedFolders).sort(([a],[b])=>a.localeCompare(b));return createHash("sha256").update(JSON.stringify({folderTrustEnabled:input.folderTrustEnabled,ideTrust:input.ideTrust??null,trustedFolders:sortedRules,settingsError:input.settingsError?.code??null,trustedFoldersError:input.trustedFoldersError?.code??null})).digest("hex")}__name(semanticRevision,"semanticRevision");async function readDaemonTrustPolicySnapshot(){const[user,system,systemDefaults]=await Promise.all([readJsonObject(getUserSettingsPath(),MAX_SETTINGS_BYTES,false),readJsonObject(getSystemSettingsPath(),MAX_SETTINGS_BYTES,false),readJsonObject(getSystemDefaultsPath(),MAX_SETTINGS_BYTES,false)]);const systemFolderTrust=folderTrustSetting(migrateFolderTrustSettings(system.value,"System"),getSystemSettingsPath());const userFolderTrust=folderTrustSetting(migrateFolderTrustSettings(user.value,"User"),getUserSettingsPath());const defaultsFolderTrust=folderTrustSetting(migrateFolderTrustSettings(systemDefaults.value,"SystemDefaults"),getSystemDefaultsPath());const settingsError=system.error??systemFolderTrust.error??user.error??userFolderTrust.error??systemDefaults.error??defaultsFolderTrust.error;const folderTrustEnabled=systemFolderTrust.value??userFolderTrust.value??defaultsFolderTrust.value??false;const trustedFoldersFile=await readJsonObject(getTrustedFoldersPath(),MAX_TRUSTED_FOLDERS_BYTES,true,folderTrustEnabled,true);const parsedTrustedFolders=parseTrustedFolders(trustedFoldersFile.value,getTrustedFoldersPath());const trustedFoldersError=trustedFoldersFile.error??parsedTrustedFolders.error;const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;const revision=semanticRevision({folderTrustEnabled,ideTrust,trustedFolders:parsedTrustedFolders.config,...settingsError?{settingsError}:{},...trustedFoldersError?{trustedFoldersError}:{}});return{revision,folderTrustEnabled,ideTrust,trustedFolders:Object.freeze({...parsedTrustedFolders.config}),...settingsError?{settingsError}:{},...trustedFoldersError?{trustedFoldersError}:{}}}__name(readDaemonTrustPolicySnapshot,"readDaemonTrustPolicySnapshot");function explicitTrustLevel(snapshot,workspaceCwd){return getExplicitTrustLevel(snapshot.trustedFolders,workspaceCwd)}__name(explicitTrustLevel,"explicitTrustLevel");function evaluateDaemonWorkspaceTrust(snapshot,workspaceCwd,processCwd=process.cwd()){if(snapshot.settingsError){return{state:"error",targetTrusted:false,source:"none",explicitTrustLevel:null,error:snapshot.settingsError}}if(!snapshot.folderTrustEnabled){return{state:"trusted",targetTrusted:true,source:"disabled",explicitTrustLevel:null}}if(snapshot.ideTrust!==void 0&&arePathsEquivalent(workspaceCwd,processCwd)){return{state:snapshot.ideTrust?"trusted":"untrusted",targetTrusted:snapshot.ideTrust,source:"ide",explicitTrustLevel:null}}if(snapshot.trustedFoldersError){return{state:"error",targetTrusted:false,source:"none",explicitTrustLevel:null,error:snapshot.trustedFoldersError}}const folders=new LoadedTrustedFolders({path:getTrustedFoldersPath(),config:{...snapshot.trustedFolders}},[]);const trusted=folders.isPathTrusted(workspaceCwd);return{state:trusted===true?"trusted":trusted===false?"untrusted":"unknown",targetTrusted:trusted===true,source:trusted===void 0?"none":"file",explicitTrustLevel:explicitTrustLevel(snapshot,workspaceCwd)}}__name(evaluateDaemonWorkspaceTrust,"evaluateDaemonWorkspaceTrust");export{evaluateDaemonWorkflowAncestorTrust,readDaemonTrustPolicySnapshot,evaluateDaemonWorkspaceTrust};
3
+ import{getUserSettingsPath,v1ToV2Migration}from"./chunk-MVGQFFIK.js";import{LoadedTrustedFolders,TrustLevel,getExplicitTrustLevel,getTrustedFoldersPath,isWorkflowAncestorDirectorySafe,parseJsoncObject}from"./chunk-XIYLRIW4.js";import{arePathsEquivalent}from"./chunk-IDXJIDME.js";import{require_strip_json_comments}from"./chunk-DOLUT3XC.js";import{getSystemDefaultsPath,getSystemSettingsPath}from"./chunk-PTHIQ7ZN.js";import{ideContextStore}from"./chunk-LZNBHBAJ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs/promises";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var MAX_TRUSTED_FOLDERS_BYTES=1024*1024;var MAX_SETTINGS_BYTES=4*1024*1024;function evaluateDaemonWorkflowAncestorTrust(snapshot,query){const denied=__name(()=>query.ancestorDirs.map(()=>false),"denied");if(snapshot.settingsError)return denied();if(!snapshot.folderTrustEnabled){return query.ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(snapshot.trustedFoldersError||snapshot.ideTrust===false&&(arePathsEquivalent(query.workspaceCwd,query.ideScopeCwd)||arePathsEquivalent(query.canonicalTargetDir,query.ideScopeCwd))){return denied()}const folders=new LoadedTrustedFolders({path:getTrustedFoldersPath(),config:{...snapshot.trustedFolders}},[]);if(folders.isPathTrusted(query.canonicalTargetDir)!==true){return denied()}return query.ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}__name(evaluateDaemonWorkflowAncestorTrust,"evaluateDaemonWorkflowAncestorTrust");function policyError(code,filePath,error){return{code,path:filePath,message:error instanceof Error?error.message:String(error)}}__name(policyError,"policyError");async function readJsonObject(filePath,maxBytes,requireRegularFile,retryMissing=false,allowTrailingComma=false){const delays=[0,50,200];let result={};for(const delay of delays){if(delay>0){await new Promise(resolve=>setTimeout(resolve,delay))}result=await readJsonObjectOnce(filePath,maxBytes,requireRegularFile,allowTrailingComma);if(!result.error&&(!result.missing||!retryMissing))return result}return result}__name(readJsonObject,"readJsonObject");async function readJsonObjectOnce(filePath,maxBytes,requireRegularFile,allowTrailingComma){let stat2;try{stat2=await fs.lstat(filePath)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return{value:{},missing:true}}return{error:policyError("trust_policy_unreadable",filePath,error)}}if(!requireRegularFile&&stat2.isSymbolicLink()){try{stat2=await fs.stat(filePath)}catch(error){return{error:policyError("trust_policy_unreadable",filePath,error)}}}if(requireRegularFile&&stat2.isSymbolicLink()||!stat2.isFile()){return{error:policyError("trust_policy_invalid",filePath,new Error("Trust policy input must be a regular file."))}}if(stat2.size>maxBytes){return{error:policyError("trust_policy_invalid",filePath,new Error(`Trust policy input exceeds ${maxBytes} bytes.`))}}try{const raw=await fs.readFile(filePath,"utf8");const parsed=allowTrailingComma?parseJsoncObject(raw):JSON.parse((0,import_strip_json_comments.default)(raw));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){throw new Error("Trust policy input must contain a JSON object.")}return{value:parsed}}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return{value:{},missing:true}}return{error:policyError("trust_policy_invalid",filePath,error)}}}__name(readJsonObjectOnce,"readJsonObjectOnce");function migrateFolderTrustSettings(value,scope){if(!value||!v1ToV2Migration.shouldMigrate(value))return value;return v1ToV2Migration.migrate(value,scope).settings}__name(migrateFolderTrustSettings,"migrateFolderTrustSettings");function folderTrustSetting(value,filePath){if(!value||!("security"in value))return{};const security=value?.["security"];if(typeof security!=="object"||security===null||Array.isArray(security)){return{error:policyError("trust_policy_invalid",filePath,new Error("`security` must be an object."))}}if(!("folderTrust"in security))return{};const folderTrust=security["folderTrust"];if(typeof folderTrust!=="object"||folderTrust===null||Array.isArray(folderTrust)){return{error:policyError("trust_policy_invalid",filePath,new Error("`security.folderTrust` must be an object."))}}if(!("enabled"in folderTrust))return{};const enabled=folderTrust["enabled"];if(typeof enabled==="boolean")return{value:enabled};return{error:policyError("trust_policy_invalid",filePath,new Error("`security.folderTrust.enabled` must be a boolean."))}}__name(folderTrustSetting,"folderTrustSetting");function parseTrustedFolders(value,filePath){const config={};for(const[rulePath,rawLevel]of Object.entries(value??{})){if(!Object.values(TrustLevel).includes(rawLevel)){return{config:{},error:policyError("trust_policy_invalid",filePath,new Error(`Invalid trust level for ${JSON.stringify(rulePath)}.`))}}config[rulePath]=rawLevel}return{config}}__name(parseTrustedFolders,"parseTrustedFolders");function semanticRevision(input){const sortedRules=Object.entries(input.trustedFolders).sort(([a],[b])=>a.localeCompare(b));return createHash("sha256").update(JSON.stringify({folderTrustEnabled:input.folderTrustEnabled,ideTrust:input.ideTrust??null,trustedFolders:sortedRules,settingsError:input.settingsError?.code??null,trustedFoldersError:input.trustedFoldersError?.code??null})).digest("hex")}__name(semanticRevision,"semanticRevision");async function readDaemonTrustPolicySnapshot(){const[user,system,systemDefaults]=await Promise.all([readJsonObject(getUserSettingsPath(),MAX_SETTINGS_BYTES,false),readJsonObject(getSystemSettingsPath(),MAX_SETTINGS_BYTES,false),readJsonObject(getSystemDefaultsPath(),MAX_SETTINGS_BYTES,false)]);const systemFolderTrust=folderTrustSetting(migrateFolderTrustSettings(system.value,"System"),getSystemSettingsPath());const userFolderTrust=folderTrustSetting(migrateFolderTrustSettings(user.value,"User"),getUserSettingsPath());const defaultsFolderTrust=folderTrustSetting(migrateFolderTrustSettings(systemDefaults.value,"SystemDefaults"),getSystemDefaultsPath());const settingsError=system.error??systemFolderTrust.error??user.error??userFolderTrust.error??systemDefaults.error??defaultsFolderTrust.error;const folderTrustEnabled=systemFolderTrust.value??userFolderTrust.value??defaultsFolderTrust.value??false;const trustedFoldersFile=await readJsonObject(getTrustedFoldersPath(),MAX_TRUSTED_FOLDERS_BYTES,true,folderTrustEnabled,true);const parsedTrustedFolders=parseTrustedFolders(trustedFoldersFile.value,getTrustedFoldersPath());const trustedFoldersError=trustedFoldersFile.error??parsedTrustedFolders.error;const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;const revision=semanticRevision({folderTrustEnabled,ideTrust,trustedFolders:parsedTrustedFolders.config,...settingsError?{settingsError}:{},...trustedFoldersError?{trustedFoldersError}:{}});return{revision,folderTrustEnabled,ideTrust,trustedFolders:Object.freeze({...parsedTrustedFolders.config}),...settingsError?{settingsError}:{},...trustedFoldersError?{trustedFoldersError}:{}}}__name(readDaemonTrustPolicySnapshot,"readDaemonTrustPolicySnapshot");function explicitTrustLevel(snapshot,workspaceCwd){return getExplicitTrustLevel(snapshot.trustedFolders,workspaceCwd)}__name(explicitTrustLevel,"explicitTrustLevel");function evaluateDaemonWorkspaceTrust(snapshot,workspaceCwd,processCwd=process.cwd()){if(snapshot.settingsError){return{state:"error",targetTrusted:false,source:"none",explicitTrustLevel:null,error:snapshot.settingsError}}if(!snapshot.folderTrustEnabled){return{state:"trusted",targetTrusted:true,source:"disabled",explicitTrustLevel:null}}if(snapshot.ideTrust!==void 0&&arePathsEquivalent(workspaceCwd,processCwd)){return{state:snapshot.ideTrust?"trusted":"untrusted",targetTrusted:snapshot.ideTrust,source:"ide",explicitTrustLevel:null}}if(snapshot.trustedFoldersError){return{state:"error",targetTrusted:false,source:"none",explicitTrustLevel:null,error:snapshot.trustedFoldersError}}const folders=new LoadedTrustedFolders({path:getTrustedFoldersPath(),config:{...snapshot.trustedFolders}},[]);const trusted=folders.isPathTrusted(workspaceCwd);return{state:trusted===true?"trusted":trusted===false?"untrusted":"unknown",targetTrusted:trusted===true,source:trusted===void 0?"none":"file",explicitTrustLevel:explicitTrustLevel(snapshot,workspaceCwd)}}__name(evaluateDaemonWorkspaceTrust,"evaluateDaemonWorkspaceTrust");export{evaluateDaemonWorkflowAncestorTrust,readDaemonTrustPolicySnapshot,evaluateDaemonWorkspaceTrust};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{encodeTextFileContentAsync}from"./chunk-LIIMQ4DI.js";import{executeSandbox}from"./chunk-HMIP4IK2.js";import{assertShellSandboxCwd}from"./chunk-SG3M7EYB.js";import{sandboxAsset}from"./chunk-K7TPIVP4.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
3
+ import{encodeTextFileContentAsync}from"./chunk-LZNBHBAJ.js";import{executeSandbox}from"./chunk-HMIP4IK2.js";import{assertShellSandboxCwd}from"./chunk-SG3M7EYB.js";import{sandboxAsset}from"./chunk-K7TPIVP4.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{OpenAIContentConverter,TaggedThinkingParser,corroborateTruncationFromCompletionTokens,openaiRequestCaptureContext}from"./chunk-NKLUALH6.js";import{markToolCallArgumentsIncomplete}from"./chunk-4JNHUZ7M.js";import{DashScopeOpenAICompatibleProvider,DefaultOpenAICompatibleProvider}from"./chunk-JCOK67LT.js";import{getCurrentAgentId}from"./chunk-AGQBNWGY.js";import{extractTextFromContents}from"./chunk-SLYWXBG7.js";import{applyOfficialOpenAIPromptCaching,isOfficialOpenAIEndpoint}from"./chunk-BN4FIQ77.js";import{StreamInactivityTimeoutError,StreamLifetimeExceededError,parseToolCallArguments,resolveStreamIdleTimeoutMs,resolveStreamMaxLifetimeMs,withStreamGuards}from"./chunk-WZPTWC7X.js";import{runtimeDiagnostics}from"./chunk-VFB6Q74I.js";import{reportOpenAiChunk,reportOpenAiRequest,reportOpenAiResponse}from"./chunk-YTKRKP2I.js";import{InvalidStreamError,getToolCallPreparations,markFlushedToolCallPark}from"./chunk-A6LT3FIJ.js";import{safeJsonParse}from"./chunk-5YQRQ63A.js";import{trailingReattachPartCount}from"./chunk-X64RXJQQ.js";import{applyDeepSeekReasoningEffort,getBuiltinDeepSeekReasoning,getEffectiveReasoning,getRequestModel,isOpenRouterHostname,resolveReasoningForModel}from"./chunk-OVPEAKOQ.js";import{getRateLimitErrorDetails,getTransportCode}from"./chunk-NCVLAQE5.js";import{createChildAbortController}from"./chunk-476F6QIM.js";import{ProtocolTagSanitizedEvent,logProtocolTagSanitized}from"./chunk-TNCN2JX2.js";import{REASONING_EFFORT_TIERS,getGptReasoningCapabilities,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,reconcileMaxTokens}from"./chunk-HEDN54OB.js";import{redactProxyError}from"./chunk-ZZZAYAJW.js";import{FinishReason,GenerateContentResponse}from"./chunk-QKX6AI4W.js";import{isInForkExecution}from"./chunk-B3ZFUGTC.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};const reasoningContent=next["reasoning_content"];delete next["reasoning_content"];if(message.role==="assistant"&&typeof reasoningContent==="string"&&reasoningContent.length>0&&Object.entries(next).every(([key,value])=>key==="role"||key==="name"||value===void 0||value===null||value===""||Array.isArray(value)&&value.length===0)){return[]}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.flatMap(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.flatMap(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-NKLUALH6.js";import{markToolCallArgumentsIncomplete}from"./chunk-4JNHUZ7M.js";import{DashScopeOpenAICompatibleProvider,DefaultOpenAICompatibleProvider}from"./chunk-FNDMWG43.js";import{getCurrentAgentId}from"./chunk-AGQBNWGY.js";import{extractTextFromContents}from"./chunk-SLYWXBG7.js";import{applyOfficialOpenAIPromptCaching,isOfficialOpenAIEndpoint}from"./chunk-BN4FIQ77.js";import{StreamInactivityTimeoutError,StreamLifetimeExceededError,parseToolCallArguments,resolveStreamIdleTimeoutMs,resolveStreamMaxLifetimeMs,withStreamGuards}from"./chunk-HHNAH4IH.js";import{runtimeDiagnostics}from"./chunk-VFB6Q74I.js";import{reportOpenAiChunk,reportOpenAiRequest,reportOpenAiResponse}from"./chunk-YTKRKP2I.js";import{InvalidStreamError,getToolCallPreparations,markFlushedToolCallPark}from"./chunk-A6LT3FIJ.js";import{safeJsonParse}from"./chunk-5YQRQ63A.js";import{trailingReattachPartCount}from"./chunk-X64RXJQQ.js";import{applyDeepSeekReasoningEffort,getBuiltinDeepSeekReasoning,getEffectiveReasoning,getRequestModel,isOpenRouterHostname,resolveReasoningForModel}from"./chunk-BDQOLT37.js";import{getRateLimitErrorDetails,getTransportCode}from"./chunk-NCVLAQE5.js";import{createChildAbortController}from"./chunk-476F6QIM.js";import{ProtocolTagSanitizedEvent,logProtocolTagSanitized}from"./chunk-TNCN2JX2.js";import{REASONING_EFFORT_TIERS,getGptReasoningCapabilities,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,reconcileMaxTokens}from"./chunk-HEDN54OB.js";import{redactProxyError}from"./chunk-ZZZAYAJW.js";import{FinishReason,GenerateContentResponse}from"./chunk-QKX6AI4W.js";import{isInForkExecution}from"./chunk-B3ZFUGTC.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};const reasoningContent=next["reasoning_content"];delete next["reasoning_content"];if(message.role==="assistant"&&typeof reasoningContent==="string"&&reasoningContent.length>0&&Object.entries(next).every(([key,value])=>key==="role"||key==="name"||value===void 0||value===null||value===""||Array.isArray(value)&&value.length===0)){return[]}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.flatMap(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.flatMap(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};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-ZZJXFLVM.js";import{CoreToolScheduler}from"./chunk-LIIMQ4DI.js";import{ToolNames,canonicalToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{isDeepStrictEqual}from"node:util";async function modToolRequest(config,request){const name=canonicalToolName(request.name);if(request.goalContext||name===ToolNames.STRUCTURED_OUTPUT||name===ToolNames.TOOL_SEARCH||name===ToolNames.SEARCH_MEMORY||request.executionOrigin?.kind==="fixed_policy")return void 0;if(name!==ToolNames.TOOL_CALL)return config.getToolRegistry().getTool(name)||config.getToolRegistry().getAllToolNames().includes(name)?{...request,name}:void 0;const targetName=request.args["name"];let args=request.args["arguments"];if(typeof args==="string"){try{args=JSON.parse(args)}catch{return void 0}}if(typeof targetName!=="string"||!record(args))return void 0;const registry=config.getToolRegistry();const resolved=resolveRegisteredToolName(canonicalToolName(targetName),registry.getAllToolNames());if(typeof resolved!=="string"||resolved===ToolNames.TOOL_CALL||resolved===ToolNames.TOOL_SEARCH||resolved===ToolNames.SEARCH_MEMORY)return void 0;let target;try{target=await registry.ensureTool(resolved)}catch{return void 0}if(!target||!registry.isDeferredAndHidden(target.name)||target.name===ToolNames.STRUCTURED_OUTPUT)return void 0;return{...request,name:target.name,args}}__name(modToolRequest,"modToolRequest");async function executeModTool(request,execution,middleware,execute,signal){const shadowed=Object.fromEntries(MOD_TOOL_RESERVED.filter(key=>Object.hasOwn(execution.args,key)).map(key=>[key,execution.args[key]]));const input={...execution.args,tool:execution.name,tool_use_id:request.callId};for(const key of MOD_TOOL_RESERVED)delete input[key];input.tool=execution.name;input.tool_use_id=request.callId;if(Object.keys(shadowed).length)input["$shadowed"]=shadowed;const refs=new Map;let latest;let executed;let attempts=0;let answer;try{answer=await middleware(input,async(changed,active,check)=>{active.throwIfAborted();validateInput("tool.call",changed,input);if(++attempts>64)throw new Error("Mod tool execution limit exceeded.");const args={...changed};for(const key of MOD_TOOL_RESERVED)delete args[key];Object.assign(args,shadowed);const nativeRequest=canonicalToolName(request.name)===ToolNames.TOOL_CALL?{...request,args:{...request.args,arguments:structuredClone(args)}}:{...request,args:structuredClone(args)};const completed=await execute(nativeRequest,active,check);latest=completed;if(completed.response.executionStatus==="success"||completed.response.executionStatus==="error"&&executed?.response.executionStatus!=="success")executed=completed;const response2=completed.response;let result2=response2.responseParts.find(part=>part.functionResponse)?.functionResponse?.response??{};let json=JSON.stringify(result2);if(Buffer.byteLength(json)>MOD_MAX_BYTES/2||jsonDepth(json)>MOD_MAX_DEPTH/2){result2={output:"[Native tool result exceeds the Mod payload limit; return this reference unchanged to retain it.]"};json=JSON.stringify(result2)}const value={ref:attempts,result:JSON.parse(json),text:(record(result2)&&typeof result2["output"]==="string"?result2["output"]:json).slice(0,16e3),...response2.error?{isError:true}:{}};refs.set(attempts,{completed,value});return value},signal)}catch(error2){answer={deny:`Mod tool dispatch failed: ${String(error2)}`}}const referenced=!("deny"in answer)&&answer.ref!==void 0?refs.get(answer.ref):void 0;const selected=referenced?.completed??latest;const native=selected?.response;if(latest?.response.error&&(latest.response.executionStatus==="not_started"||latest.response.executionStatus==="cancelled")){if(!executed)return{response:latest.response,completed:latest};const message2=`An earlier Mod tool attempt ran. A later attempt failed: ${latest.response.error.message}`;return{completed:executed,response:{...latest.response,executionStatus:executed.response.executionStatus,error:new Error(message2),resultDisplay:message2,contentLength:message2.length,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{error:message2}}}]}}}if(referenced&&!("deny"in answer)&&isDeepStrictEqual(answer.result,referenced.value.result)){return{response:{...referenced.completed.response,executionStatus:executed?.response.executionStatus??referenced.completed.response.executionStatus},completed:executed??referenced.completed}}const message="deny"in answer?`${executed?"The tool ran; a Mod withheld its result. ":"Tool denied by Mod. "}${answer.deny}`:void 0;const result="deny"in answer?{error:message}:record(answer.result)&&Object.entries(answer.result).every(([key,value])=>(key==="output"||key==="error")&&typeof value==="string")?answer.result:{output:typeof answer.result==="string"?answer.result:JSON.stringify(answer.result)};const text=JSON.stringify(result);const error=message?new Error(message):native?.error??(!("deny"in answer)&&answer.isError?new Error("Mod returned an error result."):void 0);const response={...native,callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:result}}],resultDisplay:text,contentLength:text.length,executionStatus:executed?.response.executionStatus??native?.executionStatus??"not_started",error,errorType:native?.errorType??(error?"execution_denied":void 0)};return{response,completed:executed??selected}}__name(executeModTool,"executeModTool");async function executeToolCall(config,toolCallRequest,abortSignal,options={}){const execution=options.modToolCall&&await modToolRequest(config,toolCallRequest);if(execution&&options.modToolCall){const{response,completed}=await executeModTool(toolCallRequest,execution,options.modToolCall,async(request,signal,check)=>{let completed2;await executeToolCall(config,request,signal,{...options,modToolCall:void 0,modToolCheck:check,recordToolResult:false,onAllToolCallsComplete:__name(async calls=>{completed2=calls[0]},"onAllToolCallsComplete")});if(!completed2)throw new Error("Mod native tool did not complete.");return completed2},abortSignal);if(completed)await options.onAllToolCallsComplete?.([{...completed,response}]);if(options.recordToolResult!==false)config.getChatRecordingService()?.recordToolResult(response.responseParts,{...response,status:completed?.status??(response.error?"error":"success")});return response}return new Promise((resolve,reject)=>{new CoreToolScheduler({config,modToolCheck:options.modToolCheck,chatRecordingService:options.recordToolResult===false?void 0:config.getChatRecordingService(),outputUpdateHandler:options.outputUpdateHandler,onAllToolCallsComplete:__name(async completedToolCalls=>{if(options.onAllToolCallsComplete){await options.onAllToolCallsComplete(completedToolCalls)}resolve(completedToolCalls[0].response)},"onAllToolCallsComplete"),onToolCallsUpdate:options.onToolCallsUpdate,onToolResultFullTurnModel:options.onToolResultFullTurnModel,getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose")}).schedule(toolCallRequest,abortSignal,options.runtimeView).catch(reject)})}__name(executeToolCall,"executeToolCall");export{modToolRequest,executeModTool,executeToolCall};
3
+ import{MOD_MAX_BYTES,MOD_MAX_DEPTH,MOD_TOOL_RESERVED,jsonDepth,record,validateInput}from"./chunk-ZZJXFLVM.js";import{CoreToolScheduler}from"./chunk-LZNBHBAJ.js";import{ToolNames,canonicalToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{isDeepStrictEqual}from"node:util";async function modToolRequest(config,request){const name=canonicalToolName(request.name);if(request.goalContext||name===ToolNames.STRUCTURED_OUTPUT||name===ToolNames.TOOL_SEARCH||name===ToolNames.SEARCH_MEMORY||request.executionOrigin?.kind==="fixed_policy")return void 0;if(name!==ToolNames.TOOL_CALL)return config.getToolRegistry().getTool(name)||config.getToolRegistry().getAllToolNames().includes(name)?{...request,name}:void 0;const targetName=request.args["name"];let args=request.args["arguments"];if(typeof args==="string"){try{args=JSON.parse(args)}catch{return void 0}}if(typeof targetName!=="string"||!record(args))return void 0;const registry=config.getToolRegistry();const resolved=resolveRegisteredToolName(canonicalToolName(targetName),registry.getAllToolNames());if(typeof resolved!=="string"||resolved===ToolNames.TOOL_CALL||resolved===ToolNames.TOOL_SEARCH||resolved===ToolNames.SEARCH_MEMORY)return void 0;let target;try{target=await registry.ensureTool(resolved)}catch{return void 0}if(!target||!registry.isDeferredAndHidden(target.name)||target.name===ToolNames.STRUCTURED_OUTPUT)return void 0;return{...request,name:target.name,args}}__name(modToolRequest,"modToolRequest");async function executeModTool(request,execution,middleware,execute,signal){const shadowed=Object.fromEntries(MOD_TOOL_RESERVED.filter(key=>Object.hasOwn(execution.args,key)).map(key=>[key,execution.args[key]]));const input={...execution.args,tool:execution.name,tool_use_id:request.callId};for(const key of MOD_TOOL_RESERVED)delete input[key];input.tool=execution.name;input.tool_use_id=request.callId;if(Object.keys(shadowed).length)input["$shadowed"]=shadowed;const refs=new Map;let latest;let executed;let attempts=0;let answer;try{answer=await middleware(input,async(changed,active,check)=>{active.throwIfAborted();validateInput("tool.call",changed,input);if(++attempts>64)throw new Error("Mod tool execution limit exceeded.");const args={...changed};for(const key of MOD_TOOL_RESERVED)delete args[key];Object.assign(args,shadowed);const nativeRequest=canonicalToolName(request.name)===ToolNames.TOOL_CALL?{...request,args:{...request.args,arguments:structuredClone(args)}}:{...request,args:structuredClone(args)};const completed=await execute(nativeRequest,active,check);latest=completed;if(completed.response.executionStatus==="success"||completed.response.executionStatus==="error"&&executed?.response.executionStatus!=="success")executed=completed;const response2=completed.response;let result2=response2.responseParts.find(part=>part.functionResponse)?.functionResponse?.response??{};let json=JSON.stringify(result2);if(Buffer.byteLength(json)>MOD_MAX_BYTES/2||jsonDepth(json)>MOD_MAX_DEPTH/2){result2={output:"[Native tool result exceeds the Mod payload limit; return this reference unchanged to retain it.]"};json=JSON.stringify(result2)}const value={ref:attempts,result:JSON.parse(json),text:(record(result2)&&typeof result2["output"]==="string"?result2["output"]:json).slice(0,16e3),...response2.error?{isError:true}:{}};refs.set(attempts,{completed,value});return value},signal)}catch(error2){answer={deny:`Mod tool dispatch failed: ${String(error2)}`}}const referenced=!("deny"in answer)&&answer.ref!==void 0?refs.get(answer.ref):void 0;const selected=referenced?.completed??latest;const native=selected?.response;if(latest?.response.error&&(latest.response.executionStatus==="not_started"||latest.response.executionStatus==="cancelled")){if(!executed)return{response:latest.response,completed:latest};const message2=`An earlier Mod tool attempt ran. A later attempt failed: ${latest.response.error.message}`;return{completed:executed,response:{...latest.response,executionStatus:executed.response.executionStatus,error:new Error(message2),resultDisplay:message2,contentLength:message2.length,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:{error:message2}}}]}}}if(referenced&&!("deny"in answer)&&isDeepStrictEqual(answer.result,referenced.value.result)){return{response:{...referenced.completed.response,executionStatus:executed?.response.executionStatus??referenced.completed.response.executionStatus},completed:executed??referenced.completed}}const message="deny"in answer?`${executed?"The tool ran; a Mod withheld its result. ":"Tool denied by Mod. "}${answer.deny}`:void 0;const result="deny"in answer?{error:message}:record(answer.result)&&Object.entries(answer.result).every(([key,value])=>(key==="output"||key==="error")&&typeof value==="string")?answer.result:{output:typeof answer.result==="string"?answer.result:JSON.stringify(answer.result)};const text=JSON.stringify(result);const error=message?new Error(message):native?.error??(!("deny"in answer)&&answer.isError?new Error("Mod returned an error result."):void 0);const response={...native,callId:request.callId,responseParts:[{functionResponse:{id:request.callId,name:request.name,response:result}}],resultDisplay:text,contentLength:text.length,executionStatus:executed?.response.executionStatus??native?.executionStatus??"not_started",error,errorType:native?.errorType??(error?"execution_denied":void 0)};return{response,completed:executed??selected}}__name(executeModTool,"executeModTool");async function executeToolCall(config,toolCallRequest,abortSignal,options={}){const execution=options.modToolCall&&await modToolRequest(config,toolCallRequest);if(execution&&options.modToolCall){const{response,completed}=await executeModTool(toolCallRequest,execution,options.modToolCall,async(request,signal,check)=>{let completed2;await executeToolCall(config,request,signal,{...options,modToolCall:void 0,modToolCheck:check,recordToolResult:false,onAllToolCallsComplete:__name(async calls=>{completed2=calls[0]},"onAllToolCallsComplete")});if(!completed2)throw new Error("Mod native tool did not complete.");return completed2},abortSignal);if(completed)await options.onAllToolCallsComplete?.([{...completed,response}]);if(options.recordToolResult!==false)config.getChatRecordingService()?.recordToolResult(response.responseParts,{...response,status:completed?.status??(response.error?"error":"success")});return response}return new Promise((resolve,reject)=>{new CoreToolScheduler({config,modToolCheck:options.modToolCheck,chatRecordingService:options.recordToolResult===false?void 0:config.getChatRecordingService(),outputUpdateHandler:options.outputUpdateHandler,onAllToolCallsComplete:__name(async completedToolCalls=>{if(options.onAllToolCallsComplete){await options.onAllToolCallsComplete(completedToolCalls)}resolve(completedToolCalls[0].response)},"onAllToolCallsComplete"),onToolCallsUpdate:options.onToolCallsUpdate,onToolResultFullTurnModel:options.onToolResultFullTurnModel,getPreferredEditor:__name(()=>void 0,"getPreferredEditor"),onEditorClose:__name(()=>{},"onEditorClose")}).schedule(toolCallRequest,abortSignal,options.runtimeView).catch(reject)})}__name(executeToolCall,"executeToolCall");export{modToolRequest,executeModTool,executeToolCall};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{getPackageJson}from"./chunk-O4EDHV64.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function getCliVersion(){const pkgJson=await getPackageJson();return"0.26.2-preview.0"}__name(getCliVersion,"getCliVersion");function formatVersionLabel(version){return/^\d/.test(version)?`v${version}`:version}__name(formatVersionLabel,"formatVersionLabel");export{getCliVersion,formatVersionLabel};
3
+ import{getPackageJson}from"./chunk-O4EDHV64.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function getCliVersion(){const pkgJson=await getPackageJson();return"0.26.2-preview.1"}__name(getCliVersion,"getCliVersion");function formatVersionLabel(version){return/^\d/.test(version)?`v${version}`:version}__name(formatVersionLabel,"formatVersionLabel");export{getCliVersion,formatVersionLabel};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC