@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.
- package/chunks/{MaxSizedBox-K6YUM3DX.js → MaxSizedBox-EGHZ2BPF.js} +1 -1
- package/chunks/{StandaloneSessionPicker-75IC33SN.js → StandaloneSessionPicker-UVCW6YW3.js} +1 -1
- package/chunks/{acp-subagent-executor-3NHBJRPL.js → acp-subagent-executor-AQ7AWSD4.js} +1 -1
- package/chunks/{acpAgent-JT6KQPTH.js → acpAgent-IV7JAGD7.js} +3 -3
- package/chunks/{advisor-TI2UVEZK.js → advisor-UZ4TF65D.js} +1 -1
- package/chunks/{agent-SWIZZZMY.js → agent-CNLVAWDD.js} +1 -1
- package/chunks/{agent-headless-USWEJ4GW.js → agent-headless-ZJUJLUJS.js} +1 -1
- package/chunks/{agent-host-client-ZFIMQX33.js → agent-host-client-SN5V2KBH.js} +1 -1
- package/chunks/{agent-host-connections-LOFD7O7Q.js → agent-host-connections-VKMAJIIU.js} +1 -1
- package/chunks/{anthropicContentGenerator-HMLEI4FI.js → anthropicContentGenerator-QTJVPAMI.js} +1 -1
- package/chunks/{autofix-pr-NKR2VSLB.js → autofix-pr-U7GNSH27.js} +1 -1
- package/chunks/{batch-JQZ3TOHA.js → batch-MBEWETXN.js} +1 -1
- package/chunks/{bridge-EIWWT4P6.js → bridge-TEJLNYV3.js} +1 -1
- package/chunks/{channel-settings-store-FLRLUA67.js → channel-settings-store-QNCKWWBL.js} +1 -1
- package/chunks/{chunk-244YTFYD.js → chunk-23KDY7UW.js} +1 -1
- package/chunks/{chunk-7TDMQJTD.js → chunk-2DWWSMTV.js} +1 -1
- package/chunks/{chunk-UU2LTNSF.js → chunk-3IZMVLVZ.js} +1 -1
- package/chunks/{chunk-B6T4ESBM.js → chunk-3JI7IKJL.js} +1 -1
- package/chunks/{chunk-Y5TT2G3N.js → chunk-427MARCP.js} +1 -1
- package/chunks/{chunk-KX7JS2P7.js → chunk-4NNNGSQY.js} +3 -3
- package/chunks/{chunk-6TQS2WQO.js → chunk-4RM7KY3Z.js} +2 -2
- package/chunks/{chunk-YL3N2UGG.js → chunk-5X7S4AE6.js} +5 -5
- package/chunks/{chunk-K2HAY5PY.js → chunk-5XAECBED.js} +1 -1
- package/chunks/{chunk-VCHFBETO.js → chunk-66KKSLUO.js} +1 -1
- package/chunks/{chunk-BSJR2KEF.js → chunk-6CIIDUZW.js} +1 -1
- package/chunks/{chunk-22CLK7PK.js → chunk-7EBRMQYW.js} +1 -1
- package/chunks/{chunk-J4TFGZ4A.js → chunk-7FSC2NKA.js} +1 -1
- package/chunks/{chunk-6JFC5M6B.js → chunk-A5TAAMML.js} +1 -1
- package/chunks/{chunk-DHHACQVN.js → chunk-AOYSX44A.js} +1 -1
- package/chunks/{chunk-VFVZ2DY7.js → chunk-AZCMQ3DD.js} +2 -2
- package/chunks/{chunk-BQJXWIMR.js → chunk-B6F7CVBP.js} +1 -1
- package/chunks/{chunk-OVPEAKOQ.js → chunk-BDQOLT37.js} +1 -1
- package/chunks/{chunk-5SYUBQNO.js → chunk-BIWEUAKG.js} +1 -1
- package/chunks/{chunk-BZM66PQO.js → chunk-BJ5R7LOM.js} +1 -1
- package/chunks/{chunk-4R2OHBH3.js → chunk-BKUFRNME.js} +1 -1
- package/chunks/{chunk-NIYWNFVF.js → chunk-BNZSPX2I.js} +1 -1
- package/chunks/{chunk-FJV2ECNY.js → chunk-D2URRVOK.js} +1 -1
- package/chunks/{chunk-GT6CHVAI.js → chunk-DANP7CMW.js} +1 -1
- package/chunks/{chunk-FHFLD4DR.js → chunk-DBHLRZGI.js} +1 -1
- package/chunks/{chunk-Y2UXZJLM.js → chunk-DL7TKH2E.js} +2 -2
- package/chunks/{chunk-MCQE2U7N.js → chunk-DOWKH5OZ.js} +6 -6
- package/chunks/{chunk-UHRLBY3C.js → chunk-DPHQJPCU.js} +1 -1
- package/chunks/{chunk-PV2VT25U.js → chunk-DPNGBOI7.js} +1 -1
- package/chunks/{chunk-NCDNF7UJ.js → chunk-DXRXF4QD.js} +1 -1
- package/chunks/{chunk-OCVRMNEQ.js → chunk-DZ3GV34J.js} +1 -1
- package/chunks/{chunk-3QIAXWWW.js → chunk-EU2MKUK4.js} +1 -1
- package/chunks/{chunk-KMAVI6FB.js → chunk-EVBUXPGM.js} +1 -1
- package/chunks/{chunk-BVSTV4JM.js → chunk-F3ZRU2SA.js} +1 -1
- package/chunks/{chunk-TBZY477Y.js → chunk-FCZYH27X.js} +1 -1
- package/chunks/{chunk-JCOK67LT.js → chunk-FNDMWG43.js} +1 -1
- package/chunks/{chunk-5SF32OGU.js → chunk-GDXLJJSW.js} +1 -1
- package/chunks/{chunk-SO6FCPRI.js → chunk-GZYIXB7Y.js} +1 -1
- package/chunks/{chunk-WZPTWC7X.js → chunk-HHNAH4IH.js} +1 -1
- package/chunks/{chunk-7KCAOXNL.js → chunk-HOKROBQZ.js} +1 -1
- package/chunks/{chunk-34ZBUQJV.js → chunk-IGPAATQW.js} +1 -1
- package/chunks/{chunk-2ZTRKK2O.js → chunk-INFBJDWM.js} +1 -1
- package/chunks/{chunk-IEJ2CGRN.js → chunk-J3R7ZNSA.js} +1 -1
- package/chunks/{chunk-KT5MPRYB.js → chunk-JCRS367I.js} +1 -1
- package/chunks/{chunk-7JWJTRP6.js → chunk-JFVXZFMV.js} +1 -1
- package/chunks/{chunk-47LP4MBD.js → chunk-JKMGS2VD.js} +1 -1
- package/chunks/{chunk-WRJ3PMDZ.js → chunk-JUQ7T2MV.js} +1 -1
- package/chunks/{chunk-NZX3UWNF.js → chunk-KQ4TDFNE.js} +1 -1
- package/chunks/{chunk-X7D4VKMX.js → chunk-L6BKKN42.js} +1 -1
- package/chunks/{chunk-YG5HVFMY.js → chunk-L7Y6MOHS.js} +1 -1
- package/chunks/{chunk-UFTIUKD4.js → chunk-LGYXZJI3.js} +1 -1
- package/chunks/{chunk-JQGGILML.js → chunk-LPOEVTKD.js} +1 -1
- package/chunks/{chunk-5KI55A6S.js → chunk-LRXS7ZI2.js} +1 -1
- package/chunks/{chunk-CKVHEYXW.js → chunk-LYYVSCNL.js} +1 -1
- package/chunks/{chunk-LIIMQ4DI.js → chunk-LZNBHBAJ.js} +6 -6
- package/chunks/{chunk-H4GDEXMF.js → chunk-M3C6RDGC.js} +1 -1
- package/chunks/{chunk-KKKUB3RQ.js → chunk-MNVMHVQJ.js} +1 -1
- package/chunks/{chunk-2B3W7IQY.js → chunk-MVGQFFIK.js} +1 -1
- package/chunks/{chunk-Q35A2RGO.js → chunk-NC7BCZPQ.js} +1 -1
- package/chunks/{chunk-2ZOTG3NW.js → chunk-NE627MUW.js} +1 -1
- package/chunks/{chunk-W4P2EN3V.js → chunk-NZNRCPGE.js} +1 -1
- package/chunks/{chunk-YPDQJQ3S.js → chunk-P3M4WWRA.js} +1 -1
- package/chunks/{chunk-DVB36ASH.js → chunk-P534ONQN.js} +1 -1
- package/chunks/{chunk-EL5J4ESB.js → chunk-QF44NNSC.js} +1 -1
- package/chunks/{chunk-IQPJOBPI.js → chunk-QHGCDHNW.js} +1 -1
- package/chunks/{chunk-EVZC4KEQ.js → chunk-QWJX7NIP.js} +1 -1
- package/chunks/{chunk-J2TJL2F4.js → chunk-S53G54DW.js} +2 -2
- package/chunks/{chunk-3A6LFJJV.js → chunk-SMNFL3AD.js} +1 -1
- package/chunks/{chunk-WDO3K3P2.js → chunk-TOBNWST4.js} +1 -1
- package/chunks/{chunk-AVGJ4HE3.js → chunk-TQSBUHAM.js} +1 -1
- package/chunks/{chunk-ABUS7DNN.js → chunk-TW5QEP2J.js} +1 -1
- package/chunks/{chunk-WYM4Z4D5.js → chunk-UEB2F43V.js} +1 -1
- package/chunks/{chunk-FUUPMVD2.js → chunk-UPPE4I6H.js} +1 -1
- package/chunks/{chunk-UHBJVFZA.js → chunk-US42COBM.js} +1 -1
- package/chunks/{chunk-RMQNBSMK.js → chunk-UUY6XSQI.js} +1 -1
- package/chunks/{chunk-UVQUQNCA.js → chunk-UZI3IA27.js} +1 -1
- package/chunks/{chunk-SXJ2E33J.js → chunk-V6VMUJ47.js} +1 -1
- package/chunks/{chunk-5UFCNJGN.js → chunk-VG2ZINTO.js} +1 -1
- package/chunks/{chunk-JPPPJ2GN.js → chunk-VJI6MHWX.js} +1 -1
- package/chunks/{chunk-AUI7WVSU.js → chunk-VOBNHBCJ.js} +1 -1
- package/chunks/{chunk-3BNJDZHU.js → chunk-VUEZWMI4.js} +1 -1
- package/chunks/{chunk-LMNKCL55.js → chunk-W7ZX6WB3.js} +2 -2
- package/chunks/{chunk-HVS6V2UZ.js → chunk-WA2LKUVP.js} +1 -1
- package/chunks/{chunk-7APLU2XE.js → chunk-WFFCJ5PF.js} +1 -1
- package/chunks/{chunk-3TD4WAG5.js → chunk-WQY5GE65.js} +1 -1
- package/chunks/{chunk-3YWRMF6C.js → chunk-WSESLSKK.js} +1 -1
- package/chunks/{chunk-NILCQMZ7.js → chunk-XFJV5NYT.js} +1 -1
- package/chunks/{chunk-LGBGUITT.js → chunk-XIYLRIW4.js} +1 -1
- package/chunks/{chunk-KS74L67R.js → chunk-XQ2NYKJH.js} +1 -1
- package/chunks/{chunk-JB2NOB6W.js → chunk-Y3VRWG52.js} +1 -1
- package/chunks/{chunk-GVZ6D2NL.js → chunk-YBISME5B.js} +1 -1
- package/chunks/{chunk-2C2253QI.js → chunk-YJNWPSB3.js} +1 -1
- package/chunks/{chunk-O2T3GQ6F.js → chunk-YWVV5STA.js} +1 -1
- package/chunks/{chunk-MAQZSOHI.js → chunk-ZH4J3FL6.js} +1 -1
- package/chunks/{chunk-THNEKTPK.js → chunk-ZSKCF6DI.js} +1 -1
- package/chunks/{chunk-Z7BAHKO5.js → chunk-ZW6456SD.js} +1 -1
- package/chunks/{chunk-DMSZ2TB3.js → chunk-ZWM3LLT7.js} +1 -1
- package/chunks/{codex-subagent-executor-DQ5LQQWO.js → codex-subagent-executor-DWWT7246.js} +1 -1
- package/chunks/{config-utils-CY6HLKZ5.js → config-utils-NGZB522W.js} +1 -1
- package/chunks/{contextCommand-SGBWI7O6.js → contextCommand-7QCW2YNX.js} +1 -1
- package/chunks/{core-runtime-4DP27LCC.js → core-runtime-PSVNDJPD.js} +1 -1
- package/chunks/{create-sub-session-ECPDZMBX.js → create-sub-session-JTSEMEJE.js} +1 -1
- package/chunks/{cron-create-OO4OG3EI.js → cron-create-VGIDTUMX.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-OYDNHT7P.js → daemon-git-worktree-guard-IQRGS7IH.js} +1 -1
- package/chunks/{daemon-status-provider-JGDLXPC6.js → daemon-status-provider-R4MYCYPG.js} +1 -1
- package/chunks/{daemon-trust-policy-5HRARS54.js → daemon-trust-policy-VAUKFZ2N.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-RM7FVIIC.js → daemon-trust-policy-monitor-E5HIO6RP.js} +1 -1
- package/chunks/{deferred-core-runtime-3CXBZIOG.js → deferred-core-runtime-FLOFQJPU.js} +1 -1
- package/chunks/{edit-DJPESAAY.js → edit-OOVQUGKV.js} +1 -1
- package/chunks/{enterPlanMode-IHBLRIF3.js → enterPlanMode-AUWVTQLT.js} +1 -1
- package/chunks/{environment-JN5SD347.js → environment-RM5OXYP4.js} +1 -1
- package/chunks/{errors-NUJCME3Y.js → errors-CLDJGHVD.js} +1 -1
- package/chunks/{execution-tool-I3SWG6I3.js → execution-tool-JFBVOKPW.js} +1 -1
- package/chunks/{execution-worker-62UZMAMJ.js → execution-worker-MNJZD72W.js} +1 -1
- package/chunks/{exitPlanMode-JIC4V3FE.js → exitPlanMode-PC6XG4TW.js} +1 -1
- package/chunks/{fast-path-NIOIL5YI.js → fast-path-V4DN3CRZ.js} +1 -1
- package/chunks/{glob-EQ4QNAHF.js → glob-DTZROBDS.js} +1 -1
- package/chunks/{goal-tools-DYTTSBQG.js → goal-tools-FUVGTY33.js} +1 -1
- package/chunks/{handleAutoUpdate-44BTG5L5.js → handleAutoUpdate-U4LVTHGU.js} +1 -1
- package/chunks/{i18n-FTHZAHCT.js → i18n-XOKNDFYP.js} +1 -1
- package/chunks/{initializer-MSGKXC75.js → initializer-XBR5J4CY.js} +1 -1
- package/chunks/{installationInfo-4XJMJJYU.js → installationInfo-4AOEOUI6.js} +1 -1
- package/chunks/{interactive-mod-session-DFLRYO2Q.js → interactive-mod-session-YGZK2JK2.js} +1 -1
- package/chunks/{list-ODZ7Z6VI.js → list-TCGKVPH4.js} +1 -1
- package/chunks/{llm-O64DHKP7.js → llm-SKFTN5UN.js} +4 -4
- package/chunks/{llm-content-generator-SK24I6QS.js → llm-content-generator-GWHXT3WS.js} +1 -1
- package/chunks/{loadedSettingsAdapter-6PEBUZT5.js → loadedSettingsAdapter-ZALZGZE7.js} +1 -1
- package/chunks/{local-ED3UEKWP.js → local-RWTWYS5Z.js} +1 -1
- package/chunks/{local-execution-environment-PUKES5LO.js → local-execution-environment-R6JWLD65.js} +1 -1
- package/chunks/{loggingContentGenerator-UHOJVSRR.js → loggingContentGenerator-UJV6QFOY.js} +1 -1
- package/chunks/{loop-wakeup-NSJQETPZ.js → loop-wakeup-BU2RRYHA.js} +1 -1
- package/chunks/{manage-memory-5RRB6FLH.js → manage-memory-XI57JN4T.js} +1 -1
- package/chunks/{managed-execution-engine-MZAP7SK6.js → managed-execution-engine-BA5PABMP.js} +1 -1
- package/chunks/{managed-local-serve-XMES3HXL.js → managed-local-serve-MFKN22K6.js} +1 -1
- package/chunks/{managed-npm-update-R5KGY7G2.js → managed-npm-update-ZGN43NUA.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-O2KNHHV6.js → managed-runtime-attestation-worker-YN2VBGYN.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-HOTLM6DE.js → managed-runtime-bootstrap-SGQVMUJE.js} +1 -1
- package/chunks/{managed-runtime-session-worker-QZX44ZTD.js → managed-runtime-session-worker-4UMF3VBY.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-U425WQ65.js → managed-runtime-ssh-worker-7XA6KRBN.js} +1 -1
- package/chunks/{managed-session-authority-THHDHCBP.js → managed-session-authority-IJGYAOEL.js} +1 -1
- package/chunks/{mcp-AR7EK4WY.js → mcp-V3L7B5YK.js} +1 -1
- package/chunks/{memory-C2TSF6BK.js → memory-3T6FPNAK.js} +1 -1
- package/chunks/{model-call-collection-25WR55OH.js → model-call-collection-WTTITWWM.js} +1 -1
- package/chunks/{model-configuration-KC7DQGKV.js → model-configuration-T6SSGI4J.js} +1 -1
- package/chunks/{modelConfigUtils-QEHMVLSQ.js → modelConfigUtils-TQA25QJC.js} +1 -1
- package/chunks/{monitor-PDQUZD23.js → monitor-5ZAOJSEE.js} +1 -1
- package/chunks/{nonInteractiveCli-WY2YFONU.js → nonInteractiveCli-YFINLVA7.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-7RJZYPHJ.js → nonInteractiveToolExecutor-DE3WACL5.js} +1 -1
- package/chunks/{notebook-edit-P4ITXF5H.js → notebook-edit-UK6HBRO3.js} +1 -1
- package/chunks/{omni-AYUPB2QM.js → omni-65LF5QK4.js} +1 -1
- package/chunks/{openaiContentGenerator-V5IK4ITO.js → openaiContentGenerator-HX7NCSV5.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-DYDH6KWT.js → openaiResponsesContentGenerator-CFA6U6Y5.js} +1 -1
- package/chunks/{pidfile-INPBL2DK.js → pidfile-ZVKJUNTZ.js} +1 -1
- package/chunks/{processUtils-J4UDEDS4.js → processUtils-VS6CJT7E.js} +1 -1
- package/chunks/{prompt-terminal-ledger-QLOQWHYE.js → prompt-terminal-ledger-UF5RDB57.js} +1 -1
- package/chunks/{qwenContentGenerator-RU43XKKB.js → qwenContentGenerator-GM3ZSI7E.js} +1 -1
- package/chunks/{reactive-degrade-2Q3Z3KAR.js → reactive-degrade-TSAQWZ5F.js} +1 -1
- package/chunks/{read-file-472BQ25I.js → read-file-J267NT45.js} +1 -1
- package/chunks/{resumeHistoryUtils-7SUFKZDC.js → resumeHistoryUtils-IM46VFDV.js} +1 -1
- package/chunks/{review-WX52IWJR.js → review-4B64XTCL.js} +1 -1
- package/chunks/{ripGrep-4GPGLKAM.js → ripGrep-YLOSXO7P.js} +1 -1
- package/chunks/{run-qwen-serve-MXK4RBKL.js → run-qwen-serve-SAHEC44O.js} +1 -1
- package/chunks/{runtime-WHU3AGFT.js → runtime-SJDZHV6J.js} +1 -1
- package/chunks/{sandboxConfig-7DBXEQJH.js → sandboxConfig-47EXXMUA.js} +1 -1
- package/chunks/{scheduled-tasks-O5RV6G6U.js → scheduled-tasks-E6RCTUUS.js} +1 -1
- package/chunks/{scheduler-HLMS5LR5.js → scheduler-SE3IWIWA.js} +1 -1
- package/chunks/{search-memory-PYND7ZX3.js → search-memory-2W7VJC4Q.js} +1 -1
- package/chunks/{send-message-TMLYTQOI.js → send-message-63YGQP6G.js} +1 -1
- package/chunks/{serve-EBNBRAME.js → serve-F4ML2WNL.js} +1 -1
- package/chunks/{server-63BRDBL5.js → server-S56IB4TT.js} +3 -3
- package/chunks/{session-XB6J4CZD.js → session-2CUVLZ4H.js} +1 -1
- package/chunks/{session-attachments-root-PFK475N2.js → session-attachments-root-FINBX7K5.js} +1 -1
- package/chunks/{session-execution-engine-selector-P6TJTCKR.js → session-execution-engine-selector-UGC7DGUN.js} +1 -1
- package/chunks/{session-pr-refresh-PM7VAQTV.js → session-pr-refresh-KQLQ4MZY.js} +1 -1
- package/chunks/{sessionService-PO3LLZIZ.js → sessionService-Q6N7LF7Z.js} +1 -1
- package/chunks/{settings-JDQSRXP3.js → settings-23I6H76E.js} +1 -1
- package/chunks/{shell-JCEX3HKM.js → shell-IUECEVVY.js} +1 -1
- package/chunks/{skill-JSZBONIZ.js → skill-YKUETMPC.js} +1 -1
- package/chunks/{skill-settings-YGFG6GPN.js → skill-settings-ODYXOPCA.js} +1 -1
- package/chunks/{spawnChannel-VIIWSWTL.js → spawnChannel-7XU2SRWZ.js} +1 -1
- package/chunks/{standalone-update-2UU6FQZL.js → standalone-update-SWI2RL3L.js} +1 -1
- package/chunks/{start-opentui-ui-OSZZNSLY.js → start-opentui-ui-T53QJGCH.js} +1 -1
- package/chunks/{startInteractiveUI-FFH66MYH.js → startInteractiveUI-USTZGQOE.js} +1 -1
- package/chunks/{team-create-TKGDJ3NU.js → team-create-4A2XUE3D.js} +1 -1
- package/chunks/{team-plan-approval-3VJF4G6Z.js → team-plan-approval-4TS5CYN6.js} +1 -1
- package/chunks/{terminal-image-renderer-T3VJRZGP.js → terminal-image-renderer-C7553YV6.js} +1 -1
- package/chunks/{theme-manager-ZGUFLFUI.js → theme-manager-GTW75GOO.js} +1 -1
- package/chunks/{tool-call-3EQS5KSE.js → tool-call-YTUMWL3A.js} +1 -1
- package/chunks/{tool-result-media-7LFNVQ6E.js → tool-result-media-JYOYBX4J.js} +1 -1
- package/chunks/{tool-search-UDZ4S7T5.js → tool-search-Y4XTT2WF.js} +1 -1
- package/chunks/{total-session-admission-U4MII4RA.js → total-session-admission-EMJ5NRGL.js} +1 -1
- package/chunks/{trustedFolders-2NQJCIN3.js → trustedFolders-YG6WAVRE.js} +1 -1
- package/chunks/{update-relaunch-YKLWSCLC.js → update-relaunch-4QYQRCP4.js} +1 -1
- package/chunks/{updateCheck-YDLTQQRU.js → updateCheck-VRFPSX4G.js} +1 -1
- package/chunks/{upload-config-5QQKWF4O.js → upload-config-UCKGUYYQ.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-AJS4WTU2.js → useAutoAcceptIndicator-2VGLKD7B.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AETOT7ZW.js → validateNonInterActiveAuth-GGMQXKKU.js} +1 -1
- package/chunks/{version-IB6DLRAG.js → version-Y46PG7II.js} +1 -1
- package/chunks/{web-fetch-LS3QARNR.js → web-fetch-7MPU555L.js} +1 -1
- package/chunks/{web-search-FGHRIVEB.js → web-search-HU2CL2X2.js} +1 -1
- package/chunks/{workflow-FX6XNETQ.js → workflow-U3D34QQX.js} +1 -1
- package/chunks/{workflow-ancestor-trust-5XXBGN6F.js → workflow-ancestor-trust-OWC4YTMR.js} +1 -1
- package/chunks/{workspace-agents-UJKLYPUK.js → workspace-agents-KHLAWSAR.js} +1 -1
- package/chunks/{workspace-providers-status-4JOHMTAW.js → workspace-providers-status-T57SE3YX.js} +1 -1
- package/chunks/{workspace-recovery-worker-XFEYQ4TP.js → workspace-recovery-worker-VYQ723ZE.js} +1 -1
- package/chunks/{workspace-registration-store-LWAPVNYC.js → workspace-registration-store-I7PR3A2Y.js} +1 -1
- package/chunks/{workspace-registry-M7OC376O.js → workspace-registry-YYUBXCLH.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-CYHIL47L.js → workspace-runtime-coordinator-5ICAQO7W.js} +1 -1
- package/chunks/{workspace-service-43VZZ56B.js → workspace-service-YROWXOLQ.js} +1 -1
- package/chunks/{workspace-skills-status-V2TT6UJQ.js → workspace-skills-status-DKKQDTZJ.js} +1 -1
- package/chunks/{workspace-trust-reconciler-YZ4AG5ZW.js → workspace-trust-reconciler-3FPMUZDO.js} +1 -1
- package/chunks/{write-file-TGEH5MEZ.js → write-file-7QQVYFDT.js} +1 -1
- package/chunks/{zoom-image-TT6R7H2H.js → zoom-image-WL5EB6Q7.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +3 -3
- package/web-shell/assets/{PierreFilePreview-OsApm5-S.js → PierreFilePreview-BZ17f56_.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-I1v1EzV7.js → SpreadsheetPreview-Bvkvr_5u.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-BO6aug7i.js → WorkspaceFileBrowser-BJ_I4Uoz.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-DxuLMyN0.js → abnfDiagram-VCTEODGH-iuaBM15V.js} +1 -1
- package/web-shell/assets/{agents-route-CSJf6QPO.js → agents-route-CycwfNSC.js} +1 -1
- package/web-shell/assets/{arc-3--LekYQ.js → arc-C0lt8n55.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-Dihq4uto.js → architectureDiagram-5GKGNRK7-Bw326d-A.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-BnaRPM2o.js → blockDiagram-NRAW4CY4-CHtFgBjV.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-BtC94eMa.js → c4Diagram-UCG6FXSJ-Bx66oJT9.js} +1 -1
- package/web-shell/assets/channel-CRJuO00u.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-2ZTXWP6M.js → chunk-2Q5K7J3B-BIshvfa_.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-DBh7DP1F.js → chunk-5VM5RSS4-BZeRS6uD.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-xzqbWXBw.js → chunk-F27PBJKO-El-CGY2R.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-DxnCrpxK.js → chunk-G27WJ6UU-DO8ZfQL_.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-BPjRsozm.js → chunk-JWPE2WC7-yYFrrKAj.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-Q2HgB3lf.js → chunk-LCL6LL3I-BFGuOKN0.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-9tlPaKu-.js → chunk-POPQ4Y6H-GRHK6sdV.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-DkNdOHCU.js → chunk-SVP7TREG-DwDu6GqZ.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-D0G-Dhfi.js → chunk-XXDRQBXY-RoNDjkIy.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-pPPByLA7.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-pPPByLA7.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-Ck0tHxul.js → cose-bilkent-JH36ORCC-CYNiiONE.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-a4-NTMHi.js → cynefin-OW5HDTMX-DC1_lDIG.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Pg41Zbf2.js → cynefinDiagram-5FMLGOSQ-D2VxKm2n.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-DT_ZmqkF.js → dagre-3AP2YEHR-C4_BHzpM.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-hapdMOl1.js → diagram-S7CK7UJ4-BpAO4-Gv.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-YZ0nbk56.js → diagram-UQ7AKVKN-DqUsFdsX.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-DA_yNbWy.js → diagram-VSXAHHWV-DcMXIYMy.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-DoULuCLT.js → diagram-VX7I27RA-I3nr09ex.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-B5c9o9zL.js → diagram-Z3DM3KII-CN-gvsTo.js} +1 -1
- package/web-shell/assets/{docx-preview-BulxdBjs.js → docx-preview-31J6RsS0.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-B5hgIg3m.js → ebnfDiagram-PWID7BFC-DOQvLWlM.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-BEfEPozi.js → erDiagram-SSCWMZ5O-Cb5ijFZh.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-CQHNk92v.js → flowDiagram-A5DVABFB-BecqqjnZ.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-BabdVgIM.js → ganttDiagram-EL5Y4UJY-DWY5vzQl.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-ujRZBFUo.js → gitGraphDiagram-WWUBYQGX-DqBnsZmZ.js} +1 -1
- package/web-shell/assets/{index-B9uXebIR.js → index-DDmiUW3b.js} +6 -6
- package/web-shell/assets/{index-DSZXdZnu.js → index-DabH7kHA.js} +1 -1
- package/web-shell/assets/{infoDiagram-RXCK75RN-CUHj9jJC.js → infoDiagram-RXCK75RN-MlotyOdT.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-CulW_q81.js → ishikawaDiagram-5VMMS53U-Daq_85C7.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-BR46CvRQ.js → journeyDiagram-EYS64GPL-OipivCxL.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-HAoUqzFy.js → kanban-definition-3QL26DDD-zqaz7dLu.js} +1 -1
- package/web-shell/assets/{layout-DYLl7fyA.js → layout-Bi3msQMQ.js} +1 -1
- package/web-shell/assets/{linear-DPXABjDZ.js → linear-D4gPORvD.js} +1 -1
- package/web-shell/assets/{mermaid.core-Bi30Gi0n.js → mermaid.core-BUnytF7a.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-B1_lUq4o.js → mindmap-definition-FBJOCRG2-B_X4iChu.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-Cy8tjJJC.js → pegDiagram-XKGWAZYB-z4wYBoBW.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-D6waLVVi.js → pieDiagram-E7YTZNPT-Dvyg6FYo.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC--6ehi_FI.js → quadrantDiagram-AXDQQJYC-CJBWU2Dk.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-BhLy40X4.js → railroadDiagram-O6MQD6OU-Dl_An1O0.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BVNXTgNP.js → requirementDiagram-EFPCY7ZU-Tw8FwaYU.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BHgTytxV.js → sankeyDiagram-P5KCCOFB-BCPCkbR0.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-CgOsTvhu.js → sequenceDiagram-WJ2MYXX4-DDj7uFTG.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-vCQBQ5FI.js → sizeCapture-X5ZJPWSS-B9eVSpKb.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-DytMYRWJ.js → stateDiagram-HBIQ2CUA-Bf4BZP_V.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BPJi6Gre.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-CTGnifOP.js → swimlanes-XN3QIQJK-dyTWsZFj.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bw4NRtJQ.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-DEJ1cbn2.js → timeline-definition-24CTP7MA-DVl1A4uL.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-K1e4SjS0.js → vennDiagram-4TSXK5OY-Boosxy9D.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DEX-GkRp.js → wardleyDiagram-VM6X3IG4-C6wlY8jy.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-B6wYXreH.js → xychartDiagram-S5SC5T6Z-CkzZe3ro.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-CLVrtVFX.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-Df2T70oB.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-Df2T70oB.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CcjUJGng.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dt8NvQfX.js +0 -8
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{parseChannelConfig}from"./chunk-FJUXMWZW.js";import{getPlugin,registerPlugin}from"./chunk-MHZY2JYX.js";import{getExtensionManager}from"./chunk-
|
|
3
|
+
import{parseChannelConfig}from"./chunk-FJUXMWZW.js";import{getPlugin,registerPlugin}from"./chunk-MHZY2JYX.js";import{getExtensionManager}from"./chunk-NZNRCPGE.js";import{sanitizeLogText}from"./chunk-44WSAMWG.js";import{loadSettings}from"./chunk-MVGQFFIK.js";import{hashDaemonWorkspace}from"./chunk-VTDSLBET.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as path from"node:path";import{pathToFileURL}from"node:url";function resolveChannelLocale(value){if(typeof value!=="string")return"en";const language=value.trim().replaceAll("_","-").toLowerCase();return language==="zh"||language.startsWith("zh-")||language==="chinese"||language==="\u4E2D\u6587"?"zh":"en"}__name(resolveChannelLocale,"resolveChannelLocale");function sessionsPath(){return path.join(Storage.getGlobalQwenDir(),"channels","sessions.json")}__name(sessionsPath,"sessionsPath");function daemonChannelStatePath(workspaceCwd,fileName){return path.join(Storage.getGlobalQwenDir(),"channels","daemon",hashDaemonWorkspace(workspaceCwd),fileName)}__name(daemonChannelStatePath,"daemonChannelStatePath");function daemonSessionRoutesPath(workspaceCwd){return daemonChannelStatePath(workspaceCwd,"routes.json")}__name(daemonSessionRoutesPath,"daemonSessionRoutesPath");function daemonObservedContactsPath(workspaceCwd){return daemonChannelStatePath(workspaceCwd,"observed-contacts.json")}__name(daemonObservedContactsPath,"daemonObservedContactsPath");function daemonChannelLoopPath(workspaceCwd){return daemonChannelStatePath(workspaceCwd,"cron.json")}__name(daemonChannelLoopPath,"daemonChannelLoopPath");function daemonChannelStateDir(workspaceCwd,channelName){const label=channelName.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,32)||"channel";const hash=createHash("sha256").update(channelName).digest("hex").slice(0,16);return daemonChannelStatePath(workspaceCwd,path.join("instances",`${label}-${hash}`))}__name(daemonChannelStateDir,"daemonChannelStateDir");function channelLoopPath(){return path.join(Storage.getGlobalQwenDir(),"channels","cron.json")}__name(channelLoopPath,"channelLoopPath");function loadChannelsConfig(cwd=process.cwd(),settings=loadSettings(cwd)){const channels=settings.merged.channels;return channels||{}}__name(loadChannelsConfig,"loadChannelsConfig");function resolveExtensionChannelEntrySpecifier(extensionPath,entry){return pathToFileURL(path.join(extensionPath,entry)).href}__name(resolveExtensionChannelEntrySpecifier,"resolveExtensionChannelEntrySpecifier");async function loadChannelsFromExtensions(){let loaded=0;try{const extensionManager=await getExtensionManager();const extensions=extensionManager.getLoadedExtensions().filter(e=>e.isActive&&e.channels);for(const ext of extensions){for(const[channelType,channelDef]of Object.entries(ext.channels)){if(await getPlugin(channelType)){writeStderrLine(`[Extensions] Skipping channel "${channelType}" from "${ext.name}": type already registered`);continue}const entrySpecifier=resolveExtensionChannelEntrySpecifier(ext.path,channelDef.entry);try{const module=await import(entrySpecifier);const plugin=module.plugin;if(!plugin||typeof plugin.createChannel!=="function"){writeStderrLine(`[Extensions] "${ext.name}": channel entry point does not export a valid plugin object`);continue}if(plugin.channelType!==channelType){writeStderrLine(`[Extensions] "${ext.name}": channelType mismatch \u2014 manifest says "${channelType}", plugin says "${plugin.channelType}"`);continue}registerPlugin(plugin);loaded++;writeStdoutLine(`[Extensions] Loaded channel "${channelType}" from "${ext.name}"`)}catch(err){writeStderrLine(`[Extensions] Failed to load channel "${channelType}" from "${ext.name}": ${err instanceof Error?err.message:String(err)}`)}}}}catch(err){writeStderrLine(`[Extensions] Failed to load extensions: ${err instanceof Error?err.message:String(err)}`)}return loaded}__name(loadChannelsFromExtensions,"loadChannelsFromExtensions");async function createChannel(name,config,bridge,options){const channelPlugin=await getPlugin(config.type);if(!channelPlugin){throw new Error(`Unknown channel type: "${config.type}".`)}return channelPlugin.createChannel(name,config,bridge,options)}__name(createChannel,"createChannel");function selectFirstModel(parsed,bridgeLabel){const models=[...new Set(parsed.map(channel=>channel.config.model).filter(model=>Boolean(model)))];if(models.length>1){writeStderrLine(`[Channel] Warning: Multiple models configured (${models.join(", ")}). ${bridgeLabel} will use "${models[0]}".`)}return models[0]}__name(selectFirstModel,"selectFirstModel");function registerToolCallDispatch(bridge,router,channels){bridge.on("toolCall",event=>{const target=router.getTarget(event.sessionId);if(target){const channel=channels.get(target.channelName);if(channel){channel.dispatchToolCall(event)}}})}__name(registerToolCallDispatch,"registerToolCallDispatch");function registerBackgroundResponseRelay(bridge,router,channels){bridge.on("backgroundResponse",(sessionId,text,context)=>{const target=router.getTarget(sessionId);if(!target){writeStderrLine(`[Channel] No route for background response from session ${sanitizeLogText(sessionId,128)}`);return}const channel=channels.get(target.channelName);if(!channel){writeStderrLine(`[Channel] No channel "${sanitizeLogText(target.channelName,64)}" for background response from session ${sanitizeLogText(sessionId,128)}`);return}void channel.dispatchBackgroundResponse(sessionId,text,context).catch(err=>{writeStderrLine(`[Channel] Background response relay failed for session ${sanitizeLogText(sessionId,128)}: ${err instanceof Error?sanitizeLogText(err.message,512):sanitizeLogText(String(err),512)}`)})})}__name(registerBackgroundResponseRelay,"registerBackgroundResponseRelay");function cancelPermissionRequest(bridge,requestId){if(!bridge.respondToPermission){return}void bridge.respondToPermission(requestId,{outcome:{outcome:"cancelled"}}).catch(err=>{writeStderrLine(`[Channel] Permission cancellation failed for ${sanitizeLogText(requestId,128)}: ${err instanceof Error?sanitizeLogText(err.message,512):sanitizeLogText(String(err),512)}`)})}__name(cancelPermissionRequest,"cancelPermissionRequest");function registerPermissionRelay(bridge,router,channels){bridge.on("permissionRequest",event=>{const target=router.getTarget(event.sessionId);if(!target){writeStderrLine(`[Channel] No route for session ${sanitizeLogText(event.sessionId,128)}; cancelling permission ${sanitizeLogText(event.requestId,128)}`);cancelPermissionRequest(bridge,event.requestId);return}const channel=channels.get(target.channelName);if(!channel){writeStderrLine(`[Channel] No channel "${sanitizeLogText(target.channelName,64)}" for session ${sanitizeLogText(event.sessionId,128)}; cancelling permission ${sanitizeLogText(event.requestId,128)}`);cancelPermissionRequest(bridge,event.requestId);return}channel.dispatchPermissionRequest(event).catch(err=>{writeStderrLine(`[Channel] Permission relay failed for ${sanitizeLogText(event.requestId,128)}: ${err instanceof Error?sanitizeLogText(err.message,512):sanitizeLogText(String(err),512)}`);cancelPermissionRequest(bridge,event.requestId)})});bridge.on("permissionResolved",event=>{for(const channel of channels.values()){channel.dispatchPermissionResolved(event)}})}__name(registerPermissionRelay,"registerPermissionRelay");function registerSessionCleanup(bridge,router,channels){bridge.on("sessionDied",event=>{const safeId=sanitizeLogText(event.sessionId,128);const safeReason=event.reason?sanitizeLogText(event.reason,512):"";writeStderrLine(`[Channel] Session ${safeId} died${safeReason?` (${safeReason})`:""}, updating routing state`);const target=router.getTarget(event.sessionId);const channel=target?channels.get(target.channelName):void 0;if(channel){channel.onSessionDied(event.sessionId)}else{router.handleSessionDied(event.sessionId)}})}__name(registerSessionCleanup,"registerSessionCleanup");async function parseConfiguredChannels(channelsConfig,selectedNames,opts={}){const parsed=[];for(const name of selectedNames){const rawConfig=channelsConfig[name];if(!rawConfig||typeof rawConfig!=="object"){throw new Error(`Error in channel "${name}": channel is not configured. Add a "${name}" entry under "channels" in settings.json.`)}try{parsed.push({name,config:await parseChannelConfig(name,rawConfig,opts.defaultCwd,{resolveEnvVars:"available"})})}catch(err){throw new Error(`Error in channel "${name}": ${err instanceof Error?err.message:String(err)}`)}}return parsed}__name(parseConfiguredChannels,"parseConfiguredChannels");export{resolveChannelLocale,sessionsPath,daemonSessionRoutesPath,daemonObservedContactsPath,daemonChannelLoopPath,daemonChannelStateDir,channelLoopPath,loadChannelsConfig,resolveExtensionChannelEntrySpecifier,loadChannelsFromExtensions,createChannel,selectFirstModel,registerToolCallDispatch,registerBackgroundResponseRelay,registerPermissionRelay,registerSessionCleanup,parseConfiguredChannels};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DEFAULT_RING_SIZE,EVENT_SCHEMA_VERSION,EventBus,isSummaryReplayEvent,logEventSizingFailed,mcpAppTextFallback,serializedBridgeEventByteLength,summarizeReplay,summarizeReplayEvent}from"./chunk-BWQ5AIEA.js";import{JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeJournalGrowthPoolBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{MCP_RESTART_SERVER_DEADLINE_MS}from"./chunk-IFPLGH5C.js";import{channelFactoryForwardsChildEnv,defaultSpawnChannelFactory}from"./chunk-OBGX5CDE.js";import{BridgeChannelClosedError,BridgeTimeoutError,SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS,STATUS_SCHEMA_VERSION,SessionRestoreTimeoutError,createIdleWorkspaceExtensionsStatus,createIdleWorkspaceHooksStatus}from"./chunk-LUDNUVSA.js";import{ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM,ACTIVE_WORK_CLOSE_TIMEOUT_MS,ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,ACTIVE_WORK_HEARTBEAT_META_KEY,ACTIVE_WORK_HEARTBEAT_VERSION,ACTIVE_WORK_HOLD_CATEGORIES,ACTIVE_WORK_MAX_SESSION_HOLDS,ACTIVE_WORK_MAX_SNAPSHOT_SESSIONS,ACTIVE_WORK_NOTIFICATION_METHOD,ACTIVE_WORK_STALE_INTERVALS,CHANNEL_LIVENESS_META_KEY,CHANNEL_LIVENESS_VERSION,CHANNEL_OUTPUT_MODE_META_KEY,CHANNEL_PROMPT_META_KEY,CHANNEL_STARTUP_PROFILE_META_KEY,CHANNEL_STARTUP_PROFILE_VERSION,DAEMON_ATTACHMENT_CONTEXT_META_KEY,DAEMON_ATTACHMENT_REFERENCES_META_KEY,DAEMON_CHANNEL_DELIVERY_META_KEY,DAEMON_INPUT_ANNOTATIONS_META_KEY,DAEMON_MODEL_PROMPT_META_KEY,DAEMON_PERMISSION_CANCEL_REASON_META_KEY,DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUBMITTED_PROMPT_META_KEY,DAEMON_SUPPRESS_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUPPRESS_WORKTREE_CONTEXT_RESTORE_META_KEY,IMAGE_ONLY_PROMPT_TEXT,LOAD_REPLAY_BULK_MODE,LOAD_REPLAY_HIDE_INHERITED_META_KEY,LOAD_REPLAY_MAX_UPDATES,LOAD_REPLAY_META_KEY,LOAD_REPLAY_MODE_META_KEY,LOAD_REPLAY_PAGE_SIZE_META_KEY,LOAD_REPLAY_VERSION,MID_TURN_QUEUE_DRAIN_METHOD,MID_TURN_RECONCILIATION_RING_SIZE,MID_TURN_SEND_NOW_METHOD,PROMPT_CANCEL_METHOD,PROMPT_CANCEL_REASON_META_KEY,REQUESTED_SESSION_ID_META_KEY,SESSION_INITIALIZATION_DEADLINE_META_KEY,SESSION_INITIALIZATION_TIMEOUT_ERROR_KIND,SESSION_MODEL_PERSIST_DEFAULT_META_KEY,SUBMITTED_PROMPT_META_KEY,TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,USER_CANCEL_ABORT_REASON,WORKTREE_MCP_DEFER_META_KEY,activeWorkCloseRetryDelayMs,clampActiveWorkIntervalMs,getPromptCancelAbortReason,isValidTrustedModelPrompt,parseBackgroundNotificationTurn,sessionCloseDrainBudgetMs}from"./chunk-WBDNGVHU.js";import{BranchWhilePromptActiveError,BridgeChannelQuarantinedError,CancelSentinelCollisionError,CdWhilePromptActiveError,InvalidClientIdError,InvalidPermissionOptionError,InvalidRewindTargetError,InvalidSessionMetadataError,InvalidSessionScopeError,ManagedSessionBranchUnsupportedError,McpAuthenticationInProgressError,PermissionForbiddenError,PromptDeadlineExceededError,PromptQueueFullError,RequestedSessionIdRejectedError,RestoreInProgressError,SessionBusyError,SessionLimitExceededError,SessionNotFoundError,SessionResetPendingError,SessionShellClientRequiredError,SessionShellDisabledError,StandaloneSessionSpawnError,WorkspaceChangePartiallyAppliedError,WorkspaceDrainingError,WorkspaceMismatchError,WorkspaceRuntimeStopError,isNotCurrentlyGeneratingCancelError}from"./chunk-VTZZXEWA.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{CHANNEL_DELIVERY_ERROR_CODES,LIVE_TASK_TOOL_NAMES,MAX_LIVE_SCREEN_CONTEXT_TEXT_CHARS,MAX_LIVE_SPEAK_TO_USER_MESSAGE_CHARS,MAX_SUB_SESSION_NAME_CHARS}from"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_READY_META_KEY,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,isValidExternalToolGuardDenialReason}from"./chunk-NIEO2TBE.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError}from"./chunk-WSOEJTOC.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import{MAX_SUB_SESSION_PROMPT_CHARS}from"./chunk-MD3ZEOBX.js";import{MAX_DIRECTORY_ARTIFACT_DEPTH,MAX_DIRECTORY_ARTIFACT_FILES,collectRecordableWorkspaceFiles,isOfficeDocumentExtension,isRecordableDerivedChild,pathHasSkippedDirectoryComponent}from"./chunk-MZUOREFD.js";import{MAX_CRON_GATE_CHARS,SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SESSION_TRANSCRIPT_MAX_LIMIT,TURN_RESULT_CODE_TEXT_TRUNCATED,TURN_RESULT_TEXT_MAX_CHARS,TrustGateError,canonicalSessionPrUrl,normalizeTurnResultError,toSessionPrInfo}from"./chunk-LIIMQ4DI.js";import{SESSION_EXECUTION_ENGINE_META_KEY}from"./chunk-7DCW657A.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{PUBLISHED_CONTENT_SHA256_METADATA_KEY,SESSION_ARTIFACT_PERSISTENCE_VERSION,WORKSPACE_CONTENT_MTIME_MS_METADATA_KEY,WORKSPACE_CONTENT_SHA256_METADATA_KEY,WORKSPACE_CONTENT_SIZE_BYTES_METADATA_KEY,deleteArtifactSnapshot,getWebPreviewSnapshotId,isAdoptableContentFingerprintKey,isPrototypeMetadataKey,isReservedWorkspaceMetadataKey,metadataBudgetBytes,normalizeSnapshotPayload,retainArtifactSnapshot,sessionArtifactIdentityKey,stableSessionArtifactId}from"./chunk-TRA6EVDT.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,isValidCronTaskRoutingId}from"./chunk-T6W33SET.js";import{SessionSourceError,validateSessionSourceInput}from"./chunk-G5PYYZMM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ShellExecutionService}from"./chunk-CQCSNHPU.js";import{DAEMON_TRACEPARENT_META_KEY,DAEMON_TRACESTATE_META_KEY}from"./chunk-VTDSLBET.js";import{getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{INVOCATION_CONTEXT_META_KEY,PRIVATE_ACP_CAPABILITY_ENV,PRIVATE_PARENT_CAPABILITY_META_KEY}from"./chunk-SLD7H2FA.js";import{REASONING_EFFORT_TIERS}from"./chunk-HEDN54OB.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{inspect}from"node:util";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var LogSafeAcpRequestError=class extends RequestError{constructor(code,message,data,reservePreparedResponse){super(code,message,data);this.reservePreparedResponse=reservePreparedResponse}static{__name(this,"LogSafeAcpRequestError")}toResult(){const result=super.toResult();if("error"in result){Object.defineProperty(result.error,inspect.custom,{configurable:true,value:__name(()=>({code:result.error.code,payloadOmitted:true}),"value")});try{this.reservePreparedResponse?.(result.error)}catch{}}return result}};var MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS=1024;var MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS=128;var MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS=512;function logSafeAcpErrorDetails(error){const details=error instanceof Error?error.message:isRecord(error)&&typeof error["message"]==="string"?error["message"]:void 0;if(!details)return void 0;return{details:details.length<=MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS?details:`${details.slice(0,MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS)}\u2026`}}__name(logSafeAcpErrorDetails,"logSafeAcpErrorDetails");function boundedAcpErrorString(value,maxChars){return value.length<=maxChars?value:`${value.slice(0,maxChars)}\u2026`}__name(boundedAcpErrorString,"boundedAcpErrorString");function logSafeRequestErrorMessage(code){switch(code){case-32700:return"Parse error";case-32600:return"Invalid request";case-32601:return"Method not found";case-32602:return"Invalid params";case-32603:return"Internal error";case-32e3:return"Authentication required";case-32002:return"Resource not found";default:return"ACP client request failed"}}__name(logSafeRequestErrorMessage,"logSafeRequestErrorMessage");function logSafeRequestErrorData(data){if(!isRecord(data)||typeof data["errorKind"]!=="string"){return void 0}const status=data["status"];const hint=data["hint"];return{errorKind:boundedAcpErrorString(data["errorKind"],MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS),...typeof status==="number"&&Number.isFinite(status)?{status}:{},...typeof hint==="string"?{hint:boundedAcpErrorString(hint,MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS)}:{}}}__name(logSafeRequestErrorData,"logSafeRequestErrorData");var AcpInboundHandlerLimitError=class extends Error{constructor(maxActiveHandlers,maxActiveHandlerBytes,requiredBytes,availableBytes){super("ACP inbound handler capacity exceeded");this.maxActiveHandlers=maxActiveHandlers;this.maxActiveHandlerBytes=maxActiveHandlerBytes;this.requiredBytes=requiredBytes;this.availableBytes=availableBytes;this.name="AcpInboundHandlerLimitError"}static{__name(this,"AcpInboundHandlerLimitError")}code="acp_handler_limit_exceeded"};function estimateAcpHandlerBytes(value,limitBytes){let bytes=0;const stack=[value];const seen=new WeakSet;while(stack.length>0){const current=stack.pop();if(current===null){bytes+=4}else if(typeof current==="string"){bytes+=Buffer.byteLength(current)+2}else if(typeof current==="number"){bytes+=24}else if(typeof current==="boolean"){bytes+=5}else if(Array.isArray(current)){if(seen.has(current))return limitBytes+1;seen.add(current);bytes+=2+Math.max(0,current.length-1);if(bytes+current.length>limitBytes)return limitBytes+1;for(let index=current.length-1;index>=0;index--){stack.push(current[index])}}else if(isRecord(current)){if(seen.has(current))return limitBytes+1;seen.add(current);const entries=Object.entries(current);bytes+=2+Math.max(0,entries.length-1);for(const[key,entryValue]of entries){bytes+=Buffer.byteLength(key)+3;stack.push(entryValue)}}else{bytes+=4}if(bytes>limitBytes)return limitBytes+1}return Math.max(1,bytes)}__name(estimateAcpHandlerBytes,"estimateAcpHandlerBytes");var AcpInboundHandlerAdmission=class{constructor(guard){this.guard=guard}static{__name(this,"AcpInboundHandlerAdmission")}activeHandlers=0;activeBytes=0;async run(params,operation){const envelopeBytes=Math.min(2048,this.guard.maxActiveHandlerBytes);const requiredBytes=envelopeBytes+estimateAcpHandlerBytes(params,Math.max(0,this.guard.maxActiveHandlerBytes-envelopeBytes));const availableBytes=Math.max(0,this.guard.maxActiveHandlerBytes-this.activeBytes);if(this.activeHandlers>=this.guard.maxActiveHandlers||requiredBytes>availableBytes){const error=new AcpInboundHandlerLimitError(this.guard.maxActiveHandlers,this.guard.maxActiveHandlerBytes,requiredBytes,availableBytes);this.guard.fail(error);throw error}this.activeHandlers++;this.activeBytes+=requiredBytes;try{return await operation()}finally{this.activeHandlers--;this.activeBytes-=requiredBytes}}};async function withLogSafeAcpError(operation,reservePreparedResponse){try{return await operation()}catch(error){if(error instanceof RequestError){const code=Number.isFinite(error.code)?error.code:-32603;throw new LogSafeAcpRequestError(code,logSafeRequestErrorMessage(code),logSafeRequestErrorData(error.data),reservePreparedResponse)}throw new LogSafeAcpRequestError(-32603,"Internal error",logSafeAcpErrorDetails(error),reservePreparedResponse)}}__name(withLogSafeAcpError,"withLogSafeAcpError");function createLogSafeAcpClient(client,transportGuard){const admission=new AcpInboundHandlerAdmission(transportGuard);const runNotification=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,operation)),"runNotification");const runRequest=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,async()=>{const result=await operation();transportGuard.reservePreparedResponse(result??null);return result}),transportGuard.reservePreparedResponse),"runRequest");return{requestPermission:__name(params=>runRequest(params,()=>client.requestPermission(params)),"requestPermission"),sessionUpdate:__name(params=>runNotification(params,()=>client.sessionUpdate(params)),"sessionUpdate"),writeTextFile:client.writeTextFile?params=>runRequest(params,()=>client.writeTextFile(params)):void 0,readTextFile:client.readTextFile?params=>runRequest(params,()=>client.readTextFile(params)):void 0,createTerminal:client.createTerminal?params=>runRequest(params,()=>client.createTerminal(params)):void 0,terminalOutput:client.terminalOutput?params=>runRequest(params,()=>client.terminalOutput(params)):void 0,releaseTerminal:client.releaseTerminal?params=>runRequest(params,async()=>await client.releaseTerminal(params)??{}):void 0,waitForTerminalExit:client.waitForTerminalExit?params=>runRequest(params,()=>client.waitForTerminalExit(params)):void 0,killTerminal:client.killTerminal?params=>runRequest(params,async()=>await client.killTerminal(params)??{}):void 0,extMethod:client.extMethod?(method,params)=>runRequest(params,()=>client.extMethod(method,params)):void 0,extNotification:client.extNotification?(method,params)=>runNotification(params,()=>client.extNotification(method,params)):void 0}}__name(createLogSafeAcpClient,"createLogSafeAcpClient");var OUTBOUND_GUARDED_CONNECTION_METHODS=new Set(["initialize","newSession","loadSession","unstable_forkSession","unstable_listSessions","unstable_resumeSession","setSessionMode","unstable_setSessionModel","setSessionConfigOption","authenticate","prompt","cancel","extMethod","extNotification"]);function createOutboundGuardedConnection(connection,transportGuard){const wrappers=new Map;return new Proxy(connection,{get(target,property){const value=Reflect.get(target,property,target);if(typeof value!=="function"||!OUTBOUND_GUARDED_CONNECTION_METHODS.has(property)){return value}let wrapper=wrappers.get(property);if(!wrapper){wrapper=__name(async(...args)=>{const release=transportGuard.reserveOutboundOperation(args);try{return await Reflect.apply(value,target,args)}finally{release()}},"wrapper");wrappers.set(property,wrapper)}return wrapper}})}__name(createOutboundGuardedConnection,"createOutboundGuardedConnection");function createHarnessConnection(client,channel){const rawConnection=new ClientSideConnection(()=>channel.transportGuard?createLogSafeAcpClient(client,channel.transportGuard):client,channel.stream);return channel.transportGuard?createOutboundGuardedConnection(rawConnection,channel.transportGuard):rawConnection}__name(createHarnessConnection,"createHarnessConnection");init_esbuild_shims();function createChannelLifecycle(defaultEngine){const channels=new Map;const aliveChannels=new Set;const starting=new Map;return{get current(){return channels.get(defaultEngine)},get starting(){return starting.get(defaultEngine)},currentFor:__name((engine=defaultEngine)=>channels.get(engine),"currentFor"),startingFor:__name((engine=defaultEngine)=>starting.get(engine),"startingFor"),startups:__name(()=>starting.values(),"startups"),get size(){return aliveChannels.size},has(info){return aliveChannels.has(info)},values(){return aliveChannels.values()},track(info){aliveChannels.add(info)},publish(info){channels.set(info.executionEngine,info)},remove(info){aliveChannels.delete(info);if(channels.get(info.executionEngine)===info)channels.delete(info.executionEngine)},startSpawn(spawn,engine=defaultEngine){let promise=starting.get(engine);if(!promise){promise=spawn();starting.set(engine,promise)}return promise},finishSpawn(engine=defaultEngine){starting.delete(engine)}}}__name(createChannelLifecycle,"createChannelLifecycle");init_esbuild_shims();import{randomBytes,randomUUID}from"node:crypto";init_esbuild_shims();function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient){return{protocolVersion:PROTOCOL_VERSION,_meta:{[ACTIVE_WORK_HEARTBEAT_META_KEY]:{v:ACTIVE_WORK_HEARTBEAT_VERSION,intervalMs:ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,categories:[...ACTIVE_WORK_HOLD_CATEGORIES]},[CHANNEL_STARTUP_PROFILE_META_KEY]:{v:CHANNEL_STARTUP_PROFILE_VERSION},[CHANNEL_LIVENESS_META_KEY]:{v:CHANNEL_LIVENESS_VERSION},[PRIVATE_PARENT_CAPABILITY_META_KEY]:privateParentCapability},clientCapabilities:{_meta:{"qwen.goalProposals":true},fs:{readTextFile:delegateReadTextFileToClient,writeTextFile:true}},clientInfo:{name:"qwen-serve-bridge",version:"0"}}}__name(createChannelInitializeRequest,"createChannelInitializeRequest");function negotiateChannelCapabilities(response,requireExternalToolGuard){if(requireExternalToolGuard){const guardAck=response._meta?.[EXTERNAL_TOOL_GUARD_READY_META_KEY];if(guardAck!==EXTERNAL_TOOL_GUARD_REQUIRED_VALUE){throw new Error(`ACP child did not acknowledge the required external tool guard (received: ${JSON.stringify(guardAck)}).`)}}let activeWork;const activeWorkCapability=isRecord2(response._meta)?response._meta[ACTIVE_WORK_HEARTBEAT_META_KEY]:void 0;if(isRecord2(activeWorkCapability)&&activeWorkCapability["v"]===ACTIVE_WORK_HEARTBEAT_VERSION){const advertised=activeWorkCapability["categories"];activeWork={intervalMs:clampActiveWorkIntervalMs(activeWorkCapability["intervalMs"]),categories:Array.isArray(advertised)?ACTIVE_WORK_HOLD_CATEGORIES.filter(category=>advertised.includes(category)):[]}}const channelLivenessCapability=isRecord2(response._meta)?response._meta[CHANNEL_LIVENESS_META_KEY]:void 0;return{activeWork,channelLiveness:isRecord2(channelLivenessCapability)&&channelLivenessCapability["v"]===CHANNEL_LIVENESS_VERSION}}__name(negotiateChannelCapabilities,"negotiateChannelCapabilities");init_esbuild_shims();init_esbuild_shims();async function withTimeout(p,ms,label){let timer;const timeoutP=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BridgeTimeoutError(label,ms)),ms)});try{return await Promise.race([p,timeoutP])}finally{if(timer)clearTimeout(timer)}}__name(withTimeout,"withTimeout");async function terminateChannel(channel,timeoutMs,context){try{await withTimeout(channel.kill(),timeoutMs,`${context} teardown`)}catch(error){try{channel.killSync()}catch(forceError){throw new AggregateError([error,forceError],`ACP channel teardown failed (${context})`)}throw error}}__name(terminateChannel,"terminateChannel");function channelUnavailableReject(channel,context){const unavailable=channel.transportFailed?Promise.race([channel.exited,channel.transportFailed]):channel.exited;const reject=__name(()=>{throw new BridgeChannelClosedError(context)},"reject");return unavailable.then(reject,reject)}__name(channelUnavailableReject,"channelUnavailableReject");init_esbuild_shims();import{performance as performance2}from"node:perf_hooks";var CHANNEL_LIVENESS_INTERVAL_MS=15e3;var CHANNEL_LIVENESS_PROBE_TIMEOUT_MS=1e4;var CHANNEL_LIVENESS_FAILURE_THRESHOLD=2;var CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS=1e3;var CHANNEL_LIVENESS_TIMEOUT_CODE="acp_channel_liveness_timeout";var CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE="acp_channel_liveness_protocol_error";var ChannelLivenessFailure=class extends Error{constructor(code){super(code===CHANNEL_LIVENESS_TIMEOUT_CODE?"ACP channel failed consecutive liveness probes":"ACP channel returned an invalid liveness response");this.code=code;this.name="ChannelLivenessFailure"}static{__name(this,"ChannelLivenessFailure")}};function isValidResponse(response,nonce){return typeof response==="object"&&response!==null&&!Array.isArray(response)&&response["v"]===CHANNEL_LIVENESS_VERSION&&response["nonce"]===nonce}__name(isValidResponse,"isValidResponse");function startChannelLivenessMonitor(options){const now=options.now??(()=>performance2.now());let stopped=false;let timer;let consecutiveTimeouts=0;let nextNonce=0;let resolveStopped;const stoppedOutcome=new Promise(resolve3=>{resolveStopped=resolve3});const isActive=__name(()=>!stopped&&options.isActive(),"isActive");const stop=__name(()=>{stopped=true;if(timer!==void 0){clearTimeout(timer);timer=void 0}resolveStopped({kind:"stopped"})},"stop");const fail=__name(error=>{if(!isActive())return;stop();options.onFailure(error)},"fail");const timerWasLate=__name(expectedAt=>now()>expectedAt+CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS,"timerWasLate");const runProbe=__name(async()=>{if(!isActive())return;const nonce=nextNonce;nextNonce=nonce===Number.MAX_SAFE_INTEGER?0:Math.max(0,nonce+1);const response=Promise.resolve().then(()=>options.probe(nonce)).then(value=>({kind:"response",response:value}),()=>({kind:"rejected"}));let outcome;while(true){const expectedAt=now()+CHANNEL_LIVENESS_PROBE_TIMEOUT_MS;const timeout=new Promise(resolve3=>{timer=setTimeout(()=>{timer=void 0;resolve3(timerWasLate(expectedAt)?{kind:"local_delay"}:{kind:"timeout"})},CHANNEL_LIVENESS_PROBE_TIMEOUT_MS);timer.unref()});outcome=await Promise.race([response,timeout,stoppedOutcome]);if(timer!==void 0){clearTimeout(timer);timer=void 0}if(outcome.kind==="stopped"||!isActive())return;if(outcome.kind!=="local_delay")break;consecutiveTimeouts=0}if(outcome.kind==="response"){if(!isValidResponse(outcome.response,nonce)){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}if(outcome.kind==="rejected"){await Promise.resolve();fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts++;if(consecutiveTimeouts>=CHANNEL_LIVENESS_FAILURE_THRESHOLD){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_TIMEOUT_CODE));return}void runProbe()},"runProbe");function schedule(delayMs){if(!isActive())return;const expectedAt=now()+delayMs;timer=setTimeout(()=>{timer=void 0;if(!isActive())return;if(timerWasLate(expectedAt)){consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}void runProbe()},delayMs);timer.unref()}__name(schedule,"schedule");schedule(CHANNEL_LIVENESS_INTERVAL_MS);return{stop}}__name(startChannelLivenessMonitor,"startChannelLivenessMonitor");init_esbuild_shims();var MAX_PROFILE_DURATION_MS=6e5;var ATTRIBUTE_PREFIX="qwen-code.daemon.acp_startup";function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord3,"isRecord");function readDuration(source,key){const value=source[key];return typeof value==="number"&&Number.isFinite(value)&&value>=0&&value<=MAX_PROFILE_DURATION_MS?value:void 0}__name(readDuration,"readDuration");function readDurations(source,keys){if(!isRecord3(source)){return{values:{},complete:false}}const values={};let complete=true;for(const key of keys){const value=readDuration(source,key);if(value===void 0){complete=false}else{values[key]=value}}return{values,complete}}__name(readDurations,"readDurations");function addDurationAttributes(attributes,group,values){for(const[key,value]of Object.entries(values)){if(group==="phase"&&key==="unattributedMs")continue;const attributeKey=key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`);attributes[`${ATTRIBUTE_PREFIX}.${group}.${attributeKey}`]=value}}__name(addDurationAttributes,"addDurationAttributes");var PHASE_KEYS=["processToProfilerReadyMs","geminiImportMs","argsParseMs","settingsLoadMs","configConstructionMs","appInitializationMs","acpImportMs","bootstrapConfigInitializationMs","transportSetupMs","initializeHandlerMs","unattributedMs"];var CONFIG_KEYS=["extensionsInitialMs","hooksMs","skillsMs","extensionsFinalMs","hierarchicalMemoryMs","toolRegistryMs","ripgrepProbeMs","toolWarmupMs","otherMs"];function getChannelStartupProfileAttributes(response,receivedAtEpochMs,initializeTimeoutMs){if(!isRecord3(response)||!isRecord3(response["_meta"])){return void 0}const profile=response["_meta"][CHANNEL_STARTUP_PROFILE_META_KEY];if(!isRecord3(profile)||profile["v"]!==CHANNEL_STARTUP_PROFILE_VERSION){return void 0}const phases=readDurations(profile["phases"],PHASE_KEYS);const config=readDurations(profile["config"],CONFIG_KEYS);const processToResponseMs=readDuration(profile,"processToResponseMs");const responseBuiltAtEpochMs=profile["responseBuiltAtEpochMs"];const childComplete=profile["complete"]===true;const validResponseEpoch=typeof responseBuiltAtEpochMs==="number"&&Number.isFinite(responseBuiltAtEpochMs)&&responseBuiltAtEpochMs>=0;const effectiveComplete=childComplete&&phases.complete&&config.complete&&processToResponseMs!==void 0&&validResponseEpoch;const attributes={[`${ATTRIBUTE_PREFIX}.profile.version`]:CHANNEL_STARTUP_PROFILE_VERSION,[`${ATTRIBUTE_PREFIX}.profile.complete`]:effectiveComplete};if(processToResponseMs!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.process_to_response_ms`]=processToResponseMs}if(phases.values["unattributedMs"]!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.unattributed_ms`]=phases.values["unattributedMs"]}addDurationAttributes(attributes,"phase",phases.values);addDurationAttributes(attributes,"config",config.values);if(validResponseEpoch){const transportMs=receivedAtEpochMs-responseBuiltAtEpochMs;if(Number.isFinite(transportMs)&&transportMs>=0&&transportMs<=initializeTimeoutMs){attributes[`${ATTRIBUTE_PREFIX}.response_transport_ms`]=transportMs}}return attributes}__name(getChannelStartupProfileAttributes,"getChannelStartupProfileAttributes");init_esbuild_shims();function writeStderrLine(message){process.stderr.write(message.endsWith("\n")?message:`${message}
|
|
3
|
+
import{DEFAULT_RING_SIZE,EVENT_SCHEMA_VERSION,EventBus,isSummaryReplayEvent,logEventSizingFailed,mcpAppTextFallback,serializedBridgeEventByteLength,summarizeReplay,summarizeReplayEvent}from"./chunk-BWQ5AIEA.js";import{JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeJournalGrowthPoolBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{MCP_RESTART_SERVER_DEADLINE_MS}from"./chunk-IFPLGH5C.js";import{channelFactoryForwardsChildEnv,defaultSpawnChannelFactory}from"./chunk-OBGX5CDE.js";import{BridgeChannelClosedError,BridgeTimeoutError,SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS,STATUS_SCHEMA_VERSION,SessionRestoreTimeoutError,createIdleWorkspaceExtensionsStatus,createIdleWorkspaceHooksStatus}from"./chunk-LUDNUVSA.js";import{ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM,ACTIVE_WORK_CLOSE_TIMEOUT_MS,ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,ACTIVE_WORK_HEARTBEAT_META_KEY,ACTIVE_WORK_HEARTBEAT_VERSION,ACTIVE_WORK_HOLD_CATEGORIES,ACTIVE_WORK_MAX_SESSION_HOLDS,ACTIVE_WORK_MAX_SNAPSHOT_SESSIONS,ACTIVE_WORK_NOTIFICATION_METHOD,ACTIVE_WORK_STALE_INTERVALS,CHANNEL_LIVENESS_META_KEY,CHANNEL_LIVENESS_VERSION,CHANNEL_OUTPUT_MODE_META_KEY,CHANNEL_PROMPT_META_KEY,CHANNEL_STARTUP_PROFILE_META_KEY,CHANNEL_STARTUP_PROFILE_VERSION,DAEMON_ATTACHMENT_CONTEXT_META_KEY,DAEMON_ATTACHMENT_REFERENCES_META_KEY,DAEMON_CHANNEL_DELIVERY_META_KEY,DAEMON_INPUT_ANNOTATIONS_META_KEY,DAEMON_MODEL_PROMPT_META_KEY,DAEMON_PERMISSION_CANCEL_REASON_META_KEY,DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUBMITTED_PROMPT_META_KEY,DAEMON_SUPPRESS_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUPPRESS_WORKTREE_CONTEXT_RESTORE_META_KEY,IMAGE_ONLY_PROMPT_TEXT,LOAD_REPLAY_BULK_MODE,LOAD_REPLAY_HIDE_INHERITED_META_KEY,LOAD_REPLAY_MAX_UPDATES,LOAD_REPLAY_META_KEY,LOAD_REPLAY_MODE_META_KEY,LOAD_REPLAY_PAGE_SIZE_META_KEY,LOAD_REPLAY_VERSION,MID_TURN_QUEUE_DRAIN_METHOD,MID_TURN_RECONCILIATION_RING_SIZE,MID_TURN_SEND_NOW_METHOD,PROMPT_CANCEL_METHOD,PROMPT_CANCEL_REASON_META_KEY,REQUESTED_SESSION_ID_META_KEY,SESSION_INITIALIZATION_DEADLINE_META_KEY,SESSION_INITIALIZATION_TIMEOUT_ERROR_KIND,SESSION_MODEL_PERSIST_DEFAULT_META_KEY,SUBMITTED_PROMPT_META_KEY,TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,USER_CANCEL_ABORT_REASON,WORKTREE_MCP_DEFER_META_KEY,activeWorkCloseRetryDelayMs,clampActiveWorkIntervalMs,getPromptCancelAbortReason,isValidTrustedModelPrompt,parseBackgroundNotificationTurn,sessionCloseDrainBudgetMs}from"./chunk-WBDNGVHU.js";import{BranchWhilePromptActiveError,BridgeChannelQuarantinedError,CancelSentinelCollisionError,CdWhilePromptActiveError,InvalidClientIdError,InvalidPermissionOptionError,InvalidRewindTargetError,InvalidSessionMetadataError,InvalidSessionScopeError,ManagedSessionBranchUnsupportedError,McpAuthenticationInProgressError,PermissionForbiddenError,PromptDeadlineExceededError,PromptQueueFullError,RequestedSessionIdRejectedError,RestoreInProgressError,SessionBusyError,SessionLimitExceededError,SessionNotFoundError,SessionResetPendingError,SessionShellClientRequiredError,SessionShellDisabledError,StandaloneSessionSpawnError,WorkspaceChangePartiallyAppliedError,WorkspaceDrainingError,WorkspaceMismatchError,WorkspaceRuntimeStopError,isNotCurrentlyGeneratingCancelError}from"./chunk-VTZZXEWA.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{CHANNEL_DELIVERY_ERROR_CODES,LIVE_TASK_TOOL_NAMES,MAX_LIVE_SCREEN_CONTEXT_TEXT_CHARS,MAX_LIVE_SPEAK_TO_USER_MESSAGE_CHARS,MAX_SUB_SESSION_NAME_CHARS}from"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_READY_META_KEY,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,isValidExternalToolGuardDenialReason}from"./chunk-NIEO2TBE.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError}from"./chunk-WSOEJTOC.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import{MAX_SUB_SESSION_PROMPT_CHARS}from"./chunk-MD3ZEOBX.js";import{MAX_DIRECTORY_ARTIFACT_DEPTH,MAX_DIRECTORY_ARTIFACT_FILES,collectRecordableWorkspaceFiles,isOfficeDocumentExtension,isRecordableDerivedChild,pathHasSkippedDirectoryComponent}from"./chunk-MZUOREFD.js";import{MAX_CRON_GATE_CHARS,SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SESSION_TRANSCRIPT_MAX_LIMIT,TURN_RESULT_CODE_TEXT_TRUNCATED,TURN_RESULT_TEXT_MAX_CHARS,TrustGateError,canonicalSessionPrUrl,normalizeTurnResultError,toSessionPrInfo}from"./chunk-LZNBHBAJ.js";import{SESSION_EXECUTION_ENGINE_META_KEY}from"./chunk-7DCW657A.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{PUBLISHED_CONTENT_SHA256_METADATA_KEY,SESSION_ARTIFACT_PERSISTENCE_VERSION,WORKSPACE_CONTENT_MTIME_MS_METADATA_KEY,WORKSPACE_CONTENT_SHA256_METADATA_KEY,WORKSPACE_CONTENT_SIZE_BYTES_METADATA_KEY,deleteArtifactSnapshot,getWebPreviewSnapshotId,isAdoptableContentFingerprintKey,isPrototypeMetadataKey,isReservedWorkspaceMetadataKey,metadataBudgetBytes,normalizeSnapshotPayload,retainArtifactSnapshot,sessionArtifactIdentityKey,stableSessionArtifactId}from"./chunk-TRA6EVDT.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,isValidCronTaskRoutingId}from"./chunk-T6W33SET.js";import{SessionSourceError,validateSessionSourceInput}from"./chunk-G5PYYZMM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ShellExecutionService}from"./chunk-CQCSNHPU.js";import{DAEMON_TRACEPARENT_META_KEY,DAEMON_TRACESTATE_META_KEY}from"./chunk-VTDSLBET.js";import{getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{INVOCATION_CONTEXT_META_KEY,PRIVATE_ACP_CAPABILITY_ENV,PRIVATE_PARENT_CAPABILITY_META_KEY}from"./chunk-SLD7H2FA.js";import{REASONING_EFFORT_TIERS}from"./chunk-HEDN54OB.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{inspect}from"node:util";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var LogSafeAcpRequestError=class extends RequestError{constructor(code,message,data,reservePreparedResponse){super(code,message,data);this.reservePreparedResponse=reservePreparedResponse}static{__name(this,"LogSafeAcpRequestError")}toResult(){const result=super.toResult();if("error"in result){Object.defineProperty(result.error,inspect.custom,{configurable:true,value:__name(()=>({code:result.error.code,payloadOmitted:true}),"value")});try{this.reservePreparedResponse?.(result.error)}catch{}}return result}};var MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS=1024;var MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS=128;var MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS=512;function logSafeAcpErrorDetails(error){const details=error instanceof Error?error.message:isRecord(error)&&typeof error["message"]==="string"?error["message"]:void 0;if(!details)return void 0;return{details:details.length<=MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS?details:`${details.slice(0,MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS)}\u2026`}}__name(logSafeAcpErrorDetails,"logSafeAcpErrorDetails");function boundedAcpErrorString(value,maxChars){return value.length<=maxChars?value:`${value.slice(0,maxChars)}\u2026`}__name(boundedAcpErrorString,"boundedAcpErrorString");function logSafeRequestErrorMessage(code){switch(code){case-32700:return"Parse error";case-32600:return"Invalid request";case-32601:return"Method not found";case-32602:return"Invalid params";case-32603:return"Internal error";case-32e3:return"Authentication required";case-32002:return"Resource not found";default:return"ACP client request failed"}}__name(logSafeRequestErrorMessage,"logSafeRequestErrorMessage");function logSafeRequestErrorData(data){if(!isRecord(data)||typeof data["errorKind"]!=="string"){return void 0}const status=data["status"];const hint=data["hint"];return{errorKind:boundedAcpErrorString(data["errorKind"],MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS),...typeof status==="number"&&Number.isFinite(status)?{status}:{},...typeof hint==="string"?{hint:boundedAcpErrorString(hint,MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS)}:{}}}__name(logSafeRequestErrorData,"logSafeRequestErrorData");var AcpInboundHandlerLimitError=class extends Error{constructor(maxActiveHandlers,maxActiveHandlerBytes,requiredBytes,availableBytes){super("ACP inbound handler capacity exceeded");this.maxActiveHandlers=maxActiveHandlers;this.maxActiveHandlerBytes=maxActiveHandlerBytes;this.requiredBytes=requiredBytes;this.availableBytes=availableBytes;this.name="AcpInboundHandlerLimitError"}static{__name(this,"AcpInboundHandlerLimitError")}code="acp_handler_limit_exceeded"};function estimateAcpHandlerBytes(value,limitBytes){let bytes=0;const stack=[value];const seen=new WeakSet;while(stack.length>0){const current=stack.pop();if(current===null){bytes+=4}else if(typeof current==="string"){bytes+=Buffer.byteLength(current)+2}else if(typeof current==="number"){bytes+=24}else if(typeof current==="boolean"){bytes+=5}else if(Array.isArray(current)){if(seen.has(current))return limitBytes+1;seen.add(current);bytes+=2+Math.max(0,current.length-1);if(bytes+current.length>limitBytes)return limitBytes+1;for(let index=current.length-1;index>=0;index--){stack.push(current[index])}}else if(isRecord(current)){if(seen.has(current))return limitBytes+1;seen.add(current);const entries=Object.entries(current);bytes+=2+Math.max(0,entries.length-1);for(const[key,entryValue]of entries){bytes+=Buffer.byteLength(key)+3;stack.push(entryValue)}}else{bytes+=4}if(bytes>limitBytes)return limitBytes+1}return Math.max(1,bytes)}__name(estimateAcpHandlerBytes,"estimateAcpHandlerBytes");var AcpInboundHandlerAdmission=class{constructor(guard){this.guard=guard}static{__name(this,"AcpInboundHandlerAdmission")}activeHandlers=0;activeBytes=0;async run(params,operation){const envelopeBytes=Math.min(2048,this.guard.maxActiveHandlerBytes);const requiredBytes=envelopeBytes+estimateAcpHandlerBytes(params,Math.max(0,this.guard.maxActiveHandlerBytes-envelopeBytes));const availableBytes=Math.max(0,this.guard.maxActiveHandlerBytes-this.activeBytes);if(this.activeHandlers>=this.guard.maxActiveHandlers||requiredBytes>availableBytes){const error=new AcpInboundHandlerLimitError(this.guard.maxActiveHandlers,this.guard.maxActiveHandlerBytes,requiredBytes,availableBytes);this.guard.fail(error);throw error}this.activeHandlers++;this.activeBytes+=requiredBytes;try{return await operation()}finally{this.activeHandlers--;this.activeBytes-=requiredBytes}}};async function withLogSafeAcpError(operation,reservePreparedResponse){try{return await operation()}catch(error){if(error instanceof RequestError){const code=Number.isFinite(error.code)?error.code:-32603;throw new LogSafeAcpRequestError(code,logSafeRequestErrorMessage(code),logSafeRequestErrorData(error.data),reservePreparedResponse)}throw new LogSafeAcpRequestError(-32603,"Internal error",logSafeAcpErrorDetails(error),reservePreparedResponse)}}__name(withLogSafeAcpError,"withLogSafeAcpError");function createLogSafeAcpClient(client,transportGuard){const admission=new AcpInboundHandlerAdmission(transportGuard);const runNotification=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,operation)),"runNotification");const runRequest=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,async()=>{const result=await operation();transportGuard.reservePreparedResponse(result??null);return result}),transportGuard.reservePreparedResponse),"runRequest");return{requestPermission:__name(params=>runRequest(params,()=>client.requestPermission(params)),"requestPermission"),sessionUpdate:__name(params=>runNotification(params,()=>client.sessionUpdate(params)),"sessionUpdate"),writeTextFile:client.writeTextFile?params=>runRequest(params,()=>client.writeTextFile(params)):void 0,readTextFile:client.readTextFile?params=>runRequest(params,()=>client.readTextFile(params)):void 0,createTerminal:client.createTerminal?params=>runRequest(params,()=>client.createTerminal(params)):void 0,terminalOutput:client.terminalOutput?params=>runRequest(params,()=>client.terminalOutput(params)):void 0,releaseTerminal:client.releaseTerminal?params=>runRequest(params,async()=>await client.releaseTerminal(params)??{}):void 0,waitForTerminalExit:client.waitForTerminalExit?params=>runRequest(params,()=>client.waitForTerminalExit(params)):void 0,killTerminal:client.killTerminal?params=>runRequest(params,async()=>await client.killTerminal(params)??{}):void 0,extMethod:client.extMethod?(method,params)=>runRequest(params,()=>client.extMethod(method,params)):void 0,extNotification:client.extNotification?(method,params)=>runNotification(params,()=>client.extNotification(method,params)):void 0}}__name(createLogSafeAcpClient,"createLogSafeAcpClient");var OUTBOUND_GUARDED_CONNECTION_METHODS=new Set(["initialize","newSession","loadSession","unstable_forkSession","unstable_listSessions","unstable_resumeSession","setSessionMode","unstable_setSessionModel","setSessionConfigOption","authenticate","prompt","cancel","extMethod","extNotification"]);function createOutboundGuardedConnection(connection,transportGuard){const wrappers=new Map;return new Proxy(connection,{get(target,property){const value=Reflect.get(target,property,target);if(typeof value!=="function"||!OUTBOUND_GUARDED_CONNECTION_METHODS.has(property)){return value}let wrapper=wrappers.get(property);if(!wrapper){wrapper=__name(async(...args)=>{const release=transportGuard.reserveOutboundOperation(args);try{return await Reflect.apply(value,target,args)}finally{release()}},"wrapper");wrappers.set(property,wrapper)}return wrapper}})}__name(createOutboundGuardedConnection,"createOutboundGuardedConnection");function createHarnessConnection(client,channel){const rawConnection=new ClientSideConnection(()=>channel.transportGuard?createLogSafeAcpClient(client,channel.transportGuard):client,channel.stream);return channel.transportGuard?createOutboundGuardedConnection(rawConnection,channel.transportGuard):rawConnection}__name(createHarnessConnection,"createHarnessConnection");init_esbuild_shims();function createChannelLifecycle(defaultEngine){const channels=new Map;const aliveChannels=new Set;const starting=new Map;return{get current(){return channels.get(defaultEngine)},get starting(){return starting.get(defaultEngine)},currentFor:__name((engine=defaultEngine)=>channels.get(engine),"currentFor"),startingFor:__name((engine=defaultEngine)=>starting.get(engine),"startingFor"),startups:__name(()=>starting.values(),"startups"),get size(){return aliveChannels.size},has(info){return aliveChannels.has(info)},values(){return aliveChannels.values()},track(info){aliveChannels.add(info)},publish(info){channels.set(info.executionEngine,info)},remove(info){aliveChannels.delete(info);if(channels.get(info.executionEngine)===info)channels.delete(info.executionEngine)},startSpawn(spawn,engine=defaultEngine){let promise=starting.get(engine);if(!promise){promise=spawn();starting.set(engine,promise)}return promise},finishSpawn(engine=defaultEngine){starting.delete(engine)}}}__name(createChannelLifecycle,"createChannelLifecycle");init_esbuild_shims();import{randomBytes,randomUUID}from"node:crypto";init_esbuild_shims();function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient){return{protocolVersion:PROTOCOL_VERSION,_meta:{[ACTIVE_WORK_HEARTBEAT_META_KEY]:{v:ACTIVE_WORK_HEARTBEAT_VERSION,intervalMs:ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,categories:[...ACTIVE_WORK_HOLD_CATEGORIES]},[CHANNEL_STARTUP_PROFILE_META_KEY]:{v:CHANNEL_STARTUP_PROFILE_VERSION},[CHANNEL_LIVENESS_META_KEY]:{v:CHANNEL_LIVENESS_VERSION},[PRIVATE_PARENT_CAPABILITY_META_KEY]:privateParentCapability},clientCapabilities:{_meta:{"qwen.goalProposals":true},fs:{readTextFile:delegateReadTextFileToClient,writeTextFile:true}},clientInfo:{name:"qwen-serve-bridge",version:"0"}}}__name(createChannelInitializeRequest,"createChannelInitializeRequest");function negotiateChannelCapabilities(response,requireExternalToolGuard){if(requireExternalToolGuard){const guardAck=response._meta?.[EXTERNAL_TOOL_GUARD_READY_META_KEY];if(guardAck!==EXTERNAL_TOOL_GUARD_REQUIRED_VALUE){throw new Error(`ACP child did not acknowledge the required external tool guard (received: ${JSON.stringify(guardAck)}).`)}}let activeWork;const activeWorkCapability=isRecord2(response._meta)?response._meta[ACTIVE_WORK_HEARTBEAT_META_KEY]:void 0;if(isRecord2(activeWorkCapability)&&activeWorkCapability["v"]===ACTIVE_WORK_HEARTBEAT_VERSION){const advertised=activeWorkCapability["categories"];activeWork={intervalMs:clampActiveWorkIntervalMs(activeWorkCapability["intervalMs"]),categories:Array.isArray(advertised)?ACTIVE_WORK_HOLD_CATEGORIES.filter(category=>advertised.includes(category)):[]}}const channelLivenessCapability=isRecord2(response._meta)?response._meta[CHANNEL_LIVENESS_META_KEY]:void 0;return{activeWork,channelLiveness:isRecord2(channelLivenessCapability)&&channelLivenessCapability["v"]===CHANNEL_LIVENESS_VERSION}}__name(negotiateChannelCapabilities,"negotiateChannelCapabilities");init_esbuild_shims();init_esbuild_shims();async function withTimeout(p,ms,label){let timer;const timeoutP=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BridgeTimeoutError(label,ms)),ms)});try{return await Promise.race([p,timeoutP])}finally{if(timer)clearTimeout(timer)}}__name(withTimeout,"withTimeout");async function terminateChannel(channel,timeoutMs,context){try{await withTimeout(channel.kill(),timeoutMs,`${context} teardown`)}catch(error){try{channel.killSync()}catch(forceError){throw new AggregateError([error,forceError],`ACP channel teardown failed (${context})`)}throw error}}__name(terminateChannel,"terminateChannel");function channelUnavailableReject(channel,context){const unavailable=channel.transportFailed?Promise.race([channel.exited,channel.transportFailed]):channel.exited;const reject=__name(()=>{throw new BridgeChannelClosedError(context)},"reject");return unavailable.then(reject,reject)}__name(channelUnavailableReject,"channelUnavailableReject");init_esbuild_shims();import{performance as performance2}from"node:perf_hooks";var CHANNEL_LIVENESS_INTERVAL_MS=15e3;var CHANNEL_LIVENESS_PROBE_TIMEOUT_MS=1e4;var CHANNEL_LIVENESS_FAILURE_THRESHOLD=2;var CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS=1e3;var CHANNEL_LIVENESS_TIMEOUT_CODE="acp_channel_liveness_timeout";var CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE="acp_channel_liveness_protocol_error";var ChannelLivenessFailure=class extends Error{constructor(code){super(code===CHANNEL_LIVENESS_TIMEOUT_CODE?"ACP channel failed consecutive liveness probes":"ACP channel returned an invalid liveness response");this.code=code;this.name="ChannelLivenessFailure"}static{__name(this,"ChannelLivenessFailure")}};function isValidResponse(response,nonce){return typeof response==="object"&&response!==null&&!Array.isArray(response)&&response["v"]===CHANNEL_LIVENESS_VERSION&&response["nonce"]===nonce}__name(isValidResponse,"isValidResponse");function startChannelLivenessMonitor(options){const now=options.now??(()=>performance2.now());let stopped=false;let timer;let consecutiveTimeouts=0;let nextNonce=0;let resolveStopped;const stoppedOutcome=new Promise(resolve3=>{resolveStopped=resolve3});const isActive=__name(()=>!stopped&&options.isActive(),"isActive");const stop=__name(()=>{stopped=true;if(timer!==void 0){clearTimeout(timer);timer=void 0}resolveStopped({kind:"stopped"})},"stop");const fail=__name(error=>{if(!isActive())return;stop();options.onFailure(error)},"fail");const timerWasLate=__name(expectedAt=>now()>expectedAt+CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS,"timerWasLate");const runProbe=__name(async()=>{if(!isActive())return;const nonce=nextNonce;nextNonce=nonce===Number.MAX_SAFE_INTEGER?0:Math.max(0,nonce+1);const response=Promise.resolve().then(()=>options.probe(nonce)).then(value=>({kind:"response",response:value}),()=>({kind:"rejected"}));let outcome;while(true){const expectedAt=now()+CHANNEL_LIVENESS_PROBE_TIMEOUT_MS;const timeout=new Promise(resolve3=>{timer=setTimeout(()=>{timer=void 0;resolve3(timerWasLate(expectedAt)?{kind:"local_delay"}:{kind:"timeout"})},CHANNEL_LIVENESS_PROBE_TIMEOUT_MS);timer.unref()});outcome=await Promise.race([response,timeout,stoppedOutcome]);if(timer!==void 0){clearTimeout(timer);timer=void 0}if(outcome.kind==="stopped"||!isActive())return;if(outcome.kind!=="local_delay")break;consecutiveTimeouts=0}if(outcome.kind==="response"){if(!isValidResponse(outcome.response,nonce)){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}if(outcome.kind==="rejected"){await Promise.resolve();fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts++;if(consecutiveTimeouts>=CHANNEL_LIVENESS_FAILURE_THRESHOLD){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_TIMEOUT_CODE));return}void runProbe()},"runProbe");function schedule(delayMs){if(!isActive())return;const expectedAt=now()+delayMs;timer=setTimeout(()=>{timer=void 0;if(!isActive())return;if(timerWasLate(expectedAt)){consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}void runProbe()},delayMs);timer.unref()}__name(schedule,"schedule");schedule(CHANNEL_LIVENESS_INTERVAL_MS);return{stop}}__name(startChannelLivenessMonitor,"startChannelLivenessMonitor");init_esbuild_shims();var MAX_PROFILE_DURATION_MS=6e5;var ATTRIBUTE_PREFIX="qwen-code.daemon.acp_startup";function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord3,"isRecord");function readDuration(source,key){const value=source[key];return typeof value==="number"&&Number.isFinite(value)&&value>=0&&value<=MAX_PROFILE_DURATION_MS?value:void 0}__name(readDuration,"readDuration");function readDurations(source,keys){if(!isRecord3(source)){return{values:{},complete:false}}const values={};let complete=true;for(const key of keys){const value=readDuration(source,key);if(value===void 0){complete=false}else{values[key]=value}}return{values,complete}}__name(readDurations,"readDurations");function addDurationAttributes(attributes,group,values){for(const[key,value]of Object.entries(values)){if(group==="phase"&&key==="unattributedMs")continue;const attributeKey=key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`);attributes[`${ATTRIBUTE_PREFIX}.${group}.${attributeKey}`]=value}}__name(addDurationAttributes,"addDurationAttributes");var PHASE_KEYS=["processToProfilerReadyMs","geminiImportMs","argsParseMs","settingsLoadMs","configConstructionMs","appInitializationMs","acpImportMs","bootstrapConfigInitializationMs","transportSetupMs","initializeHandlerMs","unattributedMs"];var CONFIG_KEYS=["extensionsInitialMs","hooksMs","skillsMs","extensionsFinalMs","hierarchicalMemoryMs","toolRegistryMs","ripgrepProbeMs","toolWarmupMs","otherMs"];function getChannelStartupProfileAttributes(response,receivedAtEpochMs,initializeTimeoutMs){if(!isRecord3(response)||!isRecord3(response["_meta"])){return void 0}const profile=response["_meta"][CHANNEL_STARTUP_PROFILE_META_KEY];if(!isRecord3(profile)||profile["v"]!==CHANNEL_STARTUP_PROFILE_VERSION){return void 0}const phases=readDurations(profile["phases"],PHASE_KEYS);const config=readDurations(profile["config"],CONFIG_KEYS);const processToResponseMs=readDuration(profile,"processToResponseMs");const responseBuiltAtEpochMs=profile["responseBuiltAtEpochMs"];const childComplete=profile["complete"]===true;const validResponseEpoch=typeof responseBuiltAtEpochMs==="number"&&Number.isFinite(responseBuiltAtEpochMs)&&responseBuiltAtEpochMs>=0;const effectiveComplete=childComplete&&phases.complete&&config.complete&&processToResponseMs!==void 0&&validResponseEpoch;const attributes={[`${ATTRIBUTE_PREFIX}.profile.version`]:CHANNEL_STARTUP_PROFILE_VERSION,[`${ATTRIBUTE_PREFIX}.profile.complete`]:effectiveComplete};if(processToResponseMs!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.process_to_response_ms`]=processToResponseMs}if(phases.values["unattributedMs"]!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.unattributed_ms`]=phases.values["unattributedMs"]}addDurationAttributes(attributes,"phase",phases.values);addDurationAttributes(attributes,"config",config.values);if(validResponseEpoch){const transportMs=receivedAtEpochMs-responseBuiltAtEpochMs;if(Number.isFinite(transportMs)&&transportMs>=0&&transportMs<=initializeTimeoutMs){attributes[`${ATTRIBUTE_PREFIX}.response_transport_ms`]=transportMs}}return attributes}__name(getChannelStartupProfileAttributes,"getChannelStartupProfileAttributes");init_esbuild_shims();function writeStderrLine(message){process.stderr.write(message.endsWith("\n")?message:`${message}
|
|
4
4
|
`)}__name(writeStderrLine,"writeStderrLine");function isRecord4(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord4,"isRecord");function safeTransportFailureCode(error){if(!isRecord4(error))return void 0;const code=error["code"];return typeof code==="string"&&/^[a-z0-9_.-]{1,64}$/iu.test(code)?code:void 0}__name(safeTransportFailureCode,"safeTransportFailureCode");function safeTransportFailureDetail(error){if(!isRecord4(error)||error["code"]!=="ndjson_queue_limit_exceeded"){return void 0}const queueError=error;const budget=typeof queueError.budget==="string"&&/^[a-z0-9_.-]{1,64}$/iu.test(queueError.budget)?queueError.budget:"unknown";const numbers=[];for(const value of[queueError.requiredBytes,queueError.availableBytes,queueError.maxQueuedBytes]){numbers.push(typeof value==="number"&&Number.isFinite(value)?String(Math.max(0,Math.floor(value))):"?")}return`${budget}:required=${numbers[0]}:available=${numbers[1]}:cap=${numbers[2]}`}__name(safeTransportFailureDetail,"safeTransportFailureDetail");function createChannelStartup({channelFactory,executionEngines,boundWorkspace,childEnvOverrides,initTimeoutMs,telemetry,channelLifecycle,initialRuntimeEpoch,runtimeEpochSource,delegateReadTextFileToClient,isExternalToolGuardRequired,isShuttingDown,constructHarnessChannel,handleChannelTransportUnavailable,handleChannelExit,killChannelWithLog,sessionCount}){let runtimeEpoch=initialRuntimeEpoch;async function start(engine){const factory=engine===void 0?channelFactory:executionEngines[engine];const privateParentCapability=randomBytes(32).toString("base64url");const acpChannelId=randomUUID();const startupStartedAt=Date.now();const startupAbort=new AbortController;const startup={};const factoryPromise=telemetry.withSpan("channel.spawn",{"qwen-code.daemon.bridge.operation":"channel.spawn","qwen-code.daemon.channel.reused":false,"qwen-code.daemon.acp_channel.id":acpChannelId},async()=>await factory(boundWorkspace,{...childEnvOverrides,[PRIVATE_ACP_CAPABILITY_ENV]:privateParentCapability},startupAbort.signal,startup));let channel;try{channel=await withTimeout(factoryPromise,initTimeoutMs,"channel factory")}catch(error){const failure=error instanceof BridgeTimeoutError?startup.getTimeoutError?.()??error:error;startupAbort.abort(failure);void factoryPromise.then(lateChannel=>terminateChannel(lateChannel,initTimeoutMs,"late channel factory result").catch(teardownError=>{writeStderrLine(`qwen serve: late ACP channel teardown failed: ${String(teardownError)}`)}),()=>void 0);throw failure}let info;try{info=constructHarnessChannel(channel,acpChannelId,engine)}catch(error){try{channel.killSync()}catch{}try{await Promise.race([channel.exited.then(()=>void 0),terminateChannel(channel,initTimeoutMs,"channel construction failure")])}catch(teardownError){throw new AggregateError([error,teardownError],"ACP channel construction and teardown failed")}throw error}const{connection}=info;const markTransportFailed=__name(error=>{if(!info.isDying){info.transportFailureInitiatedTeardown=true}info.transportFailed=true;info.transportFailureCode=safeTransportFailureCode(error);info.transportFailureDetail=safeTransportFailureDetail(error);info.isDying=true;info.channelLiveness?.stop();handleChannelTransportUnavailable(info)},"markTransportFailed");void channel.transportFailed?.then(markTransportFailed,markTransportFailed);channelLifecycle.track(info);const engineChannelCount=[...channelLifecycle.values()].filter(candidate=>candidate.executionEngine===engine).length;if(engineChannelCount>2){writeStderrLine(`qwen serve: WARNING engine=${engine??"single"} channelCount=${engineChannelCount} (expected 1, max 2 per engine during killSession-then-spawnOrAttach overlap) \u2014 possible channel leak; check that prior channels' channel.exited fired and the handler ran cleanup.`)}void channel.exited.then(exitInfo=>{handleChannelExit(info,exitInfo)});let channelLivenessNegotiated=false;try{await telemetry.withSpan("channel.initialize",{"qwen-code.daemon.bridge.operation":"channel.initialize","qwen-code.daemon.acp_channel.id":acpChannelId},async()=>{const remainingStartupMs=Math.max(1,initTimeoutMs-(Date.now()-startupStartedAt));const response=await withTimeout(Promise.race([connection.initialize(createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient)),channelUnavailableReject(channel,"during initialize")]),remainingStartupMs,"initialize");const capabilities=negotiateChannelCapabilities(response,isExternalToolGuardRequired());if(capabilities.activeWork){info.activeWork={...capabilities.activeWork,seq:0}}channelLivenessNegotiated=capabilities.channelLiveness;try{const attributes=getChannelStartupProfileAttributes(response,Date.now(),initTimeoutMs);if(attributes&&telemetry.setActiveSpanAttributes){telemetry.setActiveSpanAttributes(attributes)}}catch{}return response})}catch(err){info.isDying=true;startupAbort.abort(err);await terminateChannel(channel,initTimeoutMs,"channel initialization failure").catch(()=>void 0);throw err}if(info.isDying){await channel.kill().catch(()=>{});throw new BridgeChannelClosedError("during initialize")}if(isShuttingDown()){info.isDying=true;startupAbort.abort(new Error("AcpSessionBridge is shutting down"));await terminateChannel(channel,initTimeoutMs,"late shutdown").catch(()=>void 0);throw new Error("AcpSessionBridge is shutting down")}if(!channelLifecycle.has(info)){info.isDying=true;const error=new BridgeChannelClosedError("during channel initialization");startupAbort.abort(error);await terminateChannel(channel,initTimeoutMs,"exited during initialization").catch(()=>void 0);throw error}const previousRuntimeEpoch=runtimeEpochSource.current();const nextRuntimeEpoch=runtimeEpochSource.allocate();if(!Number.isSafeInteger(previousRuntimeEpoch)||previousRuntimeEpoch<runtimeEpoch||!Number.isSafeInteger(nextRuntimeEpoch)||nextRuntimeEpoch<=previousRuntimeEpoch){info.isDying=true;const epochError=new Error(`Runtime epoch source must increase monotonically (local=${runtimeEpoch}, current=${previousRuntimeEpoch}, next=${nextRuntimeEpoch}).`);startupAbort.abort(epochError);await terminateChannel(channel,initTimeoutMs,"invalid runtime epoch").catch(()=>void 0);throw epochError}runtimeEpoch=nextRuntimeEpoch;info.runtimeEpoch=nextRuntimeEpoch;info.lastUsedAt=Date.now();channelLifecycle.publish(info);info.handshakeComplete=true;if(channelLivenessNegotiated){const failChannelLiveness=__name(error=>{if(info.isDying||!channelLifecycle.has(info))return;markTransportFailed(error);telemetry.event("channel.liveness_failed",{"qwen-code.daemon.acp_channel.id":info.id,"qwen-code.daemon.channel.session_count":sessionCount(info),"qwen-code.daemon.channel.transport_error_code":error.code});writeStderrLine(`qwen serve: channel liveness failed (${error.code}); killing channel`);if(info.channel.transportGuard){info.channel.transportGuard.fail(error)}else{void killChannelWithLog(info,"channel liveness failure")}},"failChannelLiveness");info.channelLiveness=startChannelLivenessMonitor({probe:__name(nonce=>info.connection.extMethod(SERVE_STATUS_EXT_METHODS.channelPing,{v:CHANNEL_LIVENESS_VERSION,nonce}),"probe"),onFailure:failChannelLiveness,isActive:__name(()=>channelLifecycle.currentFor(engine)===info&&channelLifecycle.has(info)&&!info.isDying&&!isShuttingDown(),"isActive")})}telemetry.metrics?.channelLifecycle("spawn");return info}__name(start,"start");return{get epoch(){return runtimeEpoch},start}}__name(createChannelStartup,"createChannelStartup");function isRecord5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord5,"isRecord");function createChannelHarness(options){const{initTimeoutMs,telemetry,isShuttingDown,hasNoSessionWork,hasNoWorkspaceWork,channelShouldReapWhenIdle,sessionCount}=options;const defaultEngine=options.executionEngines?"legacy":void 0;const channelLifecycle=createChannelLifecycle(defaultEngine);let keepAliveUntil=0;const runtimeOperationReservations=new Map;const pendingKeepAliveDeadlines=new Map;const idleTimers=new Map;const pendingIdleTimers=new Set;function liveHarnessChannel(engine=defaultEngine){const channel=channelLifecycle.currentFor(engine);return channel&&!channel.isDying?channel:void 0}__name(liveHarnessChannel,"liveHarnessChannel");function hasNoChannelWork(ci,exclusions){if(!hasNoSessionWork(ci,exclusions))return false;if(ci.retireWhenSessionsDrain)return true;return ci.workspaceControlInFlight===0&&hasNoWorkspaceWork(ci)&&(runtimeOperationReservations.get(ci.executionEngine)??0)===0}__name(hasNoChannelWork,"hasNoChannelWork");function cancelIdleTimer(channel){if(channel)pendingIdleTimers.delete(channel);else pendingIdleTimers.clear();for(const[owner,timer]of idleTimers){if(channel!==void 0&&owner!==channel)continue;clearTimeout(timer);idleTimers.delete(owner)}}__name(cancelIdleTimer,"cancelIdleTimer");async function killChannelWithLog(ci,context){ci.isDying=true;options.onChannelTerminationStart?.(ci);cancelIdleTimer(ci);ci.channelLiveness?.stop();await terminateChannel(ci.channel,initTimeoutMs,context??"channel kill").catch(err=>{writeStderrLine(`qwen serve: channel kill failed${context?` (${context})`:""}: ${String(err)}`)})}__name(killChannelWithLog,"killChannelWithLog");async function retireChannelAfterSessionsDrain(ci,context){if(ci.isDying)return;if(hasNoSessionWork(ci)){await killChannelWithLog(ci,context);return}ci.retireWhenSessionsDrain=true;writeStderrLine(`qwen serve: ${context}; deferring channel retirement until ${sessionCount(ci)} active session(s) drain`)}__name(retireChannelAfterSessionsDrain,"retireChannelAfterSessionsDrain");async function retireChannelOnTimeout(ci,error,context){if(error instanceof BridgeTimeoutError&&!ci.isDying){await retireChannelAfterSessionsDrain(ci,context)}}__name(retireChannelOnTimeout,"retireChannelOnTimeout");function configuredChannelIdleTimeoutMs(){const raw=options.getChannelIdleTimeoutMs();return raw!==void 0&&Number.isFinite(raw)&&raw>0?Math.min(raw,2147483647):0}__name(configuredChannelIdleTimeoutMs,"configuredChannelIdleTimeoutMs");function resolvedChannelIdleTimeoutMs(engine=defaultEngine){const configured=configuredChannelIdleTimeoutMs();if(engine!==defaultEngine)return configured;const now=Date.now();let pendingKeepAliveMs=0;for(const deadline of pendingKeepAliveDeadlines.values()){pendingKeepAliveMs=Math.max(pendingKeepAliveMs,deadline-now)}return Math.max(configured,keepAliveUntil-now,pendingKeepAliveMs)}__name(resolvedChannelIdleTimeoutMs,"resolvedChannelIdleTimeoutMs");async function startIdleTimer(ci,context,exclusions){if(options.isRuntimeStopping()||ci.isDying||liveHarnessChannel(ci.executionEngine)!==ci)return;if(!hasNoChannelWork(ci,exclusions)){pendingIdleTimers.add(ci);return}cancelIdleTimer(ci);const timeoutMs=resolvedChannelIdleTimeoutMs(ci.executionEngine);if(timeoutMs<=0){await killChannelWithLog(ci,context);return}const idleTimer=setTimeout(()=>{idleTimers.delete(ci);if(hasNoChannelWork(ci)){writeStderrLine(`qwen serve: idle timeout (${timeoutMs}ms) expired, killing channel`);void killChannelWithLog(ci,"idle timeout")}else{pendingIdleTimers.add(ci)}},timeoutMs);idleTimers.set(ci,idleTimer);idleTimer.unref()}__name(startIdleTimer,"startIdleTimer");function retireChannel(info,context){info.isDying=true;cancelIdleTimer(info);if(info.executionEngine===defaultEngine)keepAliveUntil=0;info.channelLiveness?.stop();return terminateChannel(info.channel,initTimeoutMs,context)}__name(retireChannel,"retireChannel");async function reapPendingEmptyChannel(ci,opts){if(!channelShouldReapWhenIdle(ci)||!hasNoChannelWork(ci,opts))return;ci.emptyReapPending=false;ci.isDying=true;options.onChannelTerminationStart?.(ci);ci.channelLiveness?.stop();await terminateChannel(ci.channel,initTimeoutMs,"pending empty channel").catch(()=>{})}__name(reapPendingEmptyChannel,"reapPendingEmptyChannel");async function withWorkspaceControl(ci,fn,recordUse=true){if(options.isRuntimeStopping())throw new WorkspaceDrainingError(options.boundWorkspace??"");if(liveHarnessChannel(ci.executionEngine)===ci)cancelIdleTimer(ci);if(recordUse)ci.lastUsedAt=Date.now();ci.workspaceControlInFlight++;try{return await fn()}catch(error){await retireChannelOnTimeout(ci,error,"workspace control timeout");throw error}finally{if(recordUse)ci.lastUsedAt=Date.now();ci.workspaceControlInFlight=Math.max(0,ci.workspaceControlInFlight-1);await reapPendingEmptyChannel(ci);if(!ci.isDying&&liveHarnessChannel(ci.executionEngine)===ci){await startIdleTimer(ci,"workspace control")}}}__name(withWorkspaceControl,"withWorkspaceControl");async function settleReleasedRuntimeWork(context){const channels=Array.from(channelLifecycle.values());for(const ci of channels){await reapPendingEmptyChannel(ci)}for(const ci of channels){if(!ci.isDying&&pendingIdleTimers.has(ci)&&!idleTimers.has(ci)&&hasNoChannelWork(ci)){await startIdleTimer(ci,context)}}}__name(settleReleasedRuntimeWork,"settleReleasedRuntimeWork");function reserveRuntimeOperation(engine=defaultEngine){runtimeOperationReservations.set(engine,(runtimeOperationReservations.get(engine)??0)+1)}__name(reserveRuntimeOperation,"reserveRuntimeOperation");function decrementRuntimeOperationReservation(engine=defaultEngine){const remaining=(runtimeOperationReservations.get(engine)??0)-1;if(remaining>0)runtimeOperationReservations.set(engine,remaining);else runtimeOperationReservations.delete(engine)}__name(decrementRuntimeOperationReservation,"decrementRuntimeOperationReservation");async function releaseRuntimeOperationReservation(context,engine=defaultEngine){decrementRuntimeOperationReservation(engine);const channel=liveHarnessChannel(engine);if(channel)pendingIdleTimers.add(channel);await settleReleasedRuntimeWork(context)}__name(releaseRuntimeOperationReservation,"releaseRuntimeOperationReservation");async function ensureChannel(engine=defaultEngine){if(options.isRuntimeStopping())throw new WorkspaceDrainingError(options.boundWorkspace??"");if(isShuttingDown()){throw new Error("AcpSessionBridge is shutting down")}const current=channelLifecycle.currentFor(engine);if(current)cancelIdleTimer(current);if(current&&!current.isDying)return current;const starting=channelLifecycle.startingFor(engine);if(starting)return await starting;const promise=channelLifecycle.startSpawn(()=>channelStartup.start(engine),engine);try{return await promise}finally{channelLifecycle.finishSpawn(engine)}}__name(ensureChannel,"ensureChannel");const preheat=__name(async options2=>{if(isShuttingDown()){throw new Error("AcpSessionBridge is shutting down")}reserveRuntimeOperation();const rawKeepAliveMs=options2?.keepAliveMs;const keepAliveMs=rawKeepAliveMs!==void 0&&Number.isFinite(rawKeepAliveMs)&&rawKeepAliveMs>0?Math.min(rawKeepAliveMs,2147483647):void 0;const pendingKeepAliveToken=keepAliveMs===void 0?void 0:Symbol();if(pendingKeepAliveToken&&keepAliveMs!==void 0){pendingKeepAliveDeadlines.set(pendingKeepAliveToken,Date.now()+keepAliveMs)}let channel;try{await telemetry.withSpan("channel.preheat",{"qwen-code.daemon.bridge.operation":"channel.preheat"},async()=>{const info=await ensureChannel();channel=info;info.lastUsedAt=Date.now();if(keepAliveMs!==void 0){keepAliveUntil=Math.max(keepAliveUntil,Date.now()+keepAliveMs)}})}finally{if(pendingKeepAliveToken){pendingKeepAliveDeadlines.delete(pendingKeepAliveToken)}decrementRuntimeOperationReservation();if(channel&&channelLifecycle.has(channel)&&resolvedChannelIdleTimeoutMs()>0){pendingIdleTimers.add(channel)}await settleReleasedRuntimeWork("channel preheat")}},"preheat");const channelStartup=createChannelStartup({...options,channelLifecycle,killChannelWithLog,handleChannelExit(info,exitInfo){info.channelLiveness?.stop();options.handleChannelTransportUnavailable(info);cancelIdleTimer(info);options.beforeChannelExit(info);channelLifecycle.remove(info);options.handleChannelExit(info,exitInfo)}});return{get current(){return channelLifecycle.current},get starting(){return channelLifecycle.starting},currentFor:channelLifecycle.currentFor,startingFor:channelLifecycle.startingFor,startups:channelLifecycle.startups,get epoch(){return channelStartup.epoch},get runtimeOperationReservations(){return Array.from(runtimeOperationReservations.values()).reduce((total,count)=>total+count,0)},get pendingKeepAliveCount(){return pendingKeepAliveDeadlines.size},createConnection:createHarnessConnection,withWorktreeInitialization(request,worktree){return worktree?{...request,_meta:{...isRecord5(request._meta)?request._meta:{},[WORKTREE_MCP_DEFER_META_KEY]:true}}:request},changeSessionCwd(channel,sessionId,req){return channel.connection.extMethod(SERVE_CONTROL_EXT_METHODS.sessionCd,{sessionId,path:req.path,...req.allowedRoots?{allowedRoots:req.allowedRoots}:{},...req.managedRelocation?{managedRelocation:req.managedRelocation}:{},...req.conversationDirectoryExpectation?{conversationDirectoryExpectation:req.conversationDirectoryExpectation}:{}})},executeShell(command,cwd,onOutput,signal){return ShellExecutionService.execute(command,cwd,onOutput,signal,false,{terminalWidth:120,terminalHeight:40},{streamStdout:true})},values:channelLifecycle.values,has:channelLifecycle.has,ensure:ensureChannel,configuredChannelIdleTimeoutMs,cancelIdleTimer,startIdleTimer,killChannelWithLog,retireChannelAfterSessionsDrain,retireChannelOnTimeout,hasNoChannelWork,reapPendingEmptyChannel,withWorkspaceControl,reserveRuntimeOperation,releaseRuntimeOperationReservation,settleReleasedRuntimeWork,preheat,reclaimIdleChannel(info){writeStderrLine(`qwen serve: reclaiming idle ACP channel ${info.id}`);return retireChannel(info,"capacity reclamation")},stopChannel(info){return retireChannel(info,"user-confirmed workspace stop")},markDying(channels){for(const ci of channels){ci.isDying=true;ci.channelLiveness?.stop()}},killAllSync(channels){for(const info of channels){info.channelLiveness?.stop();try{info.channel.killSync()}catch{}}},terminate(channel){return terminateChannel(channel.channel,initTimeoutMs,"bridge shutdown")}}}__name(createChannelHarness,"createChannelHarness");init_esbuild_shims();init_esbuild_shims();var SessionStartupConfigError=class extends Error{constructor(code,message,sessionId){super(message);this.code=code;this.sessionId=sessionId}static{__name(this,"SessionStartupConfigError")}name="SessionStartupConfigError"};function isReasoningSelection(value){return typeof value==="string"&&(value==="default"||value==="none"||REASONING_EFFORT_TIERS.some(tier=>tier===value))}__name(isReasoningSelection,"isReasoningSelection");function parseSessionStartupConfig(value,request={}){if(value===void 0)return void 0;const config=value;if(!config||typeof config!=="object"||Array.isArray(config)||Object.keys(config).some(key=>key!=="modelServiceId"&&key!=="reasoningEffort")||typeof config.modelServiceId!=="string"||!config.modelServiceId.trim()||config.modelServiceId.length>MAX_CRON_TASK_ROUTING_ID_LENGTH||new RegExp("\\p{Cc}","u").test(config.modelServiceId)||config.reasoningEffort!==void 0&&!isReasoningSelection(config.reasoningEffort)||request.modelServiceId!==void 0||request.sessionScope==="single"){throw new SessionStartupConfigError("invalid_startup_config","startupConfig requires modelServiceId (1-256 characters) and an optional valid reasoningEffort, without unknown fields, a legacy modelServiceId or single session scope.")}return{modelServiceId:config.modelServiceId.trim(),...config.reasoningEffort!==void 0?{reasoningEffort:config.reasoningEffort}:{}}}__name(parseSessionStartupConfig,"parseSessionStartupConfig");function rejectInvalidSelection(error,sessionId){if(error===null||typeof error!=="object"||!("code"in error)||!("message"in error)||typeof error.message!=="string"){throw error}if(error.code===-32602){throw new SessionStartupConfigError("startup_config_rejected",error.message,sessionId)}throw error}__name(rejectInvalidSelection,"rejectInvalidSelection");async function applySessionStartupConfig(bridge,sessionId,config){const model=await bridge.setSessionConfigOption(sessionId,{sessionId,configId:"model",value:config.modelServiceId}).catch(error=>rejectInvalidSelection(error,sessionId));const modelServiceId=model.configOptions?.find(option=>option.id==="model")?.currentValue;if(!modelServiceId){throw new SessionStartupConfigError("startup_config_rejected","The session did not confirm its model selection.",sessionId)}if(config.reasoningEffort===void 0)return{modelServiceId};const result=await bridge.setSessionConfigOption(sessionId,{sessionId,configId:"reasoning_effort",value:config.reasoningEffort}).catch(error=>rejectInvalidSelection(error,sessionId));const reasoning=result.configOptions?.find(option=>option.id==="reasoning_effort");const currentModel=result.configOptions?.find(option=>option.id==="model")?.currentValue;const selection=reasoning?.currentValue;if(currentModel!==modelServiceId||!isReasoningSelection(selection)||config.reasoningEffort!=="default"&&selection!==config.reasoningEffort){throw new SessionStartupConfigError("startup_config_rejected","The session did not confirm its model and reasoning selection.",sessionId)}const meta=reasoning?._meta?.["qwenCode/reasoning"];const toggleOnly=meta!==null&&typeof meta==="object"&&"toggleOnly"in meta&&meta.toggleOnly===true;return{modelServiceId,reasoningEffort:config.reasoningEffort,effectiveReasoning:selection==="none"?{state:"disabled"}:selection==="default"?toggleOnly?{state:"enabled"}:{state:"provider-default"}:{state:"enabled",effort:selection}}}__name(applySessionStartupConfig,"applySessionStartupConfig");import{randomUUID as randomUUID4}from"node:crypto";import*as path5 from"node:path";init_esbuild_shims();var TURN_BOUNDARY_TYPES=new Set(["turn_complete","turn_error"]);var TRANSIENT_TYPES=new Set(["history_truncated","slow_client_warning","client_evicted","replay_complete","stream_error"]);var LATEST_WINS_UPDATES=new Set(["available_commands_update","current_mode_update"]);var REPLAY_SEGMENT_COMPACT_THRESHOLD=64;var LIVE_JOURNAL_TEXT_CHUNKS_PER_EVENT=256;function createLiveJournalState(){return{entries:[],entryBytes:[],entryEvents:[],totalBytes:0,totalEvents:0,truncatedEvents:0}}__name(createLiveJournalState,"createLiveJournalState");function replayRecordId(event){if(event.type!=="session_update")return void 0;const data=event.data;if(!data||typeof data!=="object"||Array.isArray(data))return void 0;const update=data["update"];if(!update||typeof update!=="object"||Array.isArray(update)){return void 0}const meta=update["_meta"];if(!meta||typeof meta!=="object"||Array.isArray(meta)){return void 0}const recordId=meta["qwen.session.recordId"];return typeof recordId==="string"?recordId:void 0}__name(replayRecordId,"replayRecordId");function lastRecordIdIn(events){for(let i=events.length-1;i>=0;i--){const id=replayRecordId(events[i]);if(id!==void 0)return id}return void 0}__name(lastRecordIdIn,"lastRecordIdIn");function lastSummaryRecordIdIn(events){for(let i=events.length-1;i>=0;i--){if(!isSummaryReplayEvent(events[i]))continue;const id=replayRecordId(events[i]);if(id!==void 0)return id}return void 0}__name(lastSummaryRecordIdIn,"lastSummaryRecordIdIn");var JOURNAL_GROWTH_REASK_INTERVAL_MS=1e4;var JOURNAL_GROWTH_MAX_GRANTS_PER_BREACH=64;var TurnBoundaryCompactionEngine=class{static{__name(this,"TurnBoundaryCompactionEngine")}maxReplayBytes;maxJournalEvents;maxJournalBytes;onJournalGrowth;now;journalGrowthDeniedAt;onReplayWindowEviction;replaySegments=[];replaySegmentStart=0;replayBytes=0;fullJournal=createLiveJournalState();summaryJournal=createLiveJournalState();lastEventId=0;closed=false;truncatedEvents=0;truncatedTurns=0;activeRecordId;summaryRecordId;replayAnchorRecordId;slots=[];toolSlotIndex=new Map;textSlotIndex={text:new Map,thought:new Map};constructor(opts={}){this.maxReplayBytes=normalizeCompactedReplayMaxBytes(opts.maxReplayBytes);this.maxJournalEvents=normalizeMaxJournalEvents(opts.maxJournalEvents);this.maxJournalBytes=normalizeMaxJournalBytes(opts.maxJournalBytes);this.onJournalGrowth=opts.onJournalGrowth;this.now=opts.now??(()=>performance.now());this.onReplayWindowEviction=opts.onReplayWindowEviction}journalLimits(){return{maxEvents:this.maxJournalEvents,maxBytes:this.maxJournalBytes}}ingest(event,byteLength){if(this.closed)return;if(event.id!==void 0){this.lastEventId=event.id}if(TRANSIENT_TYPES.has(event.type))return;const summaryEvent=summarizeReplayEvent(event);const seenRecordId=replayRecordId(event);if(seenRecordId!==void 0){this.activeRecordId=seenRecordId;if(summaryEvent)this.summaryRecordId=seenRecordId}this.appendLiveJournal(this.fullJournal,event,byteLength);if(summaryEvent){this.appendLiveJournal(this.summaryJournal,summaryEvent,summaryEvent===event?byteLength:void 0)}if(TURN_BOUNDARY_TYPES.has(event.type)){this.compactCurrentTurn(event);return}if(event.type==="session_update"){this.classifySessionUpdate(event);return}this.slots.push({kind:"misc",event})}snapshot(liveReplayMode="full"){const compactedTurns=this.flattenReplaySegments();if(this.truncatedEvents>0){compactedTurns.unshift(this.makeHistoryTruncatedEvent(compactedTurns.length))}return{compactedTurns,liveJournal:this.liveJournalSnapshot(liveReplayMode),lastEventId:this.lastEventId}}liveJournalSnapshot(liveReplayMode="full"){const journal=liveReplayMode==="summary"?this.summaryJournal:this.fullJournal;const journalRecordId=liveReplayMode==="summary"?this.summaryRecordId:this.activeRecordId;const liveJournal=journal.entries.map(entry=>isLiveJournalTextSegment(entry)?mergeLiveJournalTextEvent(entry.firstEvent,entry.lastEvent,entry.chunks):entry);if(journal.truncatedEvents>0){liveJournal.unshift({v:EVENT_SCHEMA_VERSION,type:"history_truncated",data:{reason:"replay_window_exceeded",scope:"live_journal",truncatedEvents:journal.truncatedEvents,retainedEvents:journal.totalEvents,maxBytes:this.maxJournalBytes,maxEvents:this.maxJournalEvents,...journalRecordId!==void 0?{recordId:journalRecordId}:{},fullTranscriptAvailable:true}})}return liveJournal}seed(snapshot){if(this.closed)return;this.resetReplayWindow();this.lastEventId=snapshot.lastEventId;this.activeRecordId=void 0;this.summaryRecordId=void 0;this.activeRecordId=lastRecordIdIn(snapshot.compactedTurns);this.summaryRecordId=lastSummaryRecordIdIn(snapshot.compactedTurns);for(const event of snapshot.compactedTurns){if(TRANSIENT_TYPES.has(event.type))continue;this.addReplaySegment([event],0)}this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}seedReplayEvents(events){if(this.closed)return;this.resetReplayWindow();this.activeRecordId=void 0;this.summaryRecordId=void 0;this.activeRecordId=lastRecordIdIn(events);this.summaryRecordId=lastSummaryRecordIdIn(events);let recordEvents=[];let recordId;const flushRecord=__name(()=>{this.addReplaySegment(recordEvents,0);recordEvents=[];recordId=void 0},"flushRecord");for(const event of events){this.recordLastEventId(event);if(TRANSIENT_TYPES.has(event.type))continue;const nextRecordId=replayRecordId(event);if(nextRecordId===void 0){flushRecord();this.addReplaySegment([event],0);continue}if(recordId!==void 0&&recordId!==nextRecordId){flushRecord()}recordId=nextRecordId;recordEvents.push(event)}flushRecord();this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}close(){if(this.closed)return;this.closed=true;this.resetReplayWindow();this.resetJournal();this.activeRecordId=void 0;this.summaryRecordId=void 0;this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}appendLiveJournal(journal,event,byteLength){const bytes=byteLength??serializedBridgeEventByteLength(event)??0;const textChunk=liveJournalTextChunk(event);const current=journal.textSegment;const currentIndex=journal.entries.length-1;if(textChunk&¤t&&journal.entries[currentIndex]===current&¤t.chunks.length<LIVE_JOURNAL_TEXT_CHUNKS_PER_EVENT&&journal.entryBytes[currentIndex]+bytes<=this.maxJournalBytes&¤t.sessionUpdate===textChunk.sessionUpdate&¤t.parentToolCallId===textChunk.parentToolCallId&&stringArraysEqual(current.sourceRecordIds,textChunk.sourceRecordIds)&¤t.promptId===event.promptId&¤t.originatorClientId===event.originatorClientId&¤t.sessionId===captureSessionId(event)&&hasOnlyTimestampEnvelopeMeta(current.lastEvent._meta)&&hasOnlyTimestampEnvelopeMeta(event._meta)){current.chunks.push(textChunk.text);current.lastEvent=event;journal.entryBytes[currentIndex]+=bytes;journal.entryEvents[currentIndex]+=1;journal.totalBytes+=bytes;journal.totalEvents+=1}else{let entry=event;if(textChunk){const segment={sessionUpdate:textChunk.sessionUpdate,chunks:[textChunk.text],sourceRecordIds:textChunk.sourceRecordIds,parentToolCallId:textChunk.parentToolCallId,promptId:event.promptId,originatorClientId:event.originatorClientId,sessionId:captureSessionId(event),firstEvent:event,lastEvent:event};entry=segment;journal.textSegment=segment}else{journal.textSegment=void 0}journal.entries.push(entry);journal.entryBytes.push(bytes);journal.entryEvents.push(1);journal.totalBytes+=bytes;journal.totalEvents+=1}if(!TURN_BOUNDARY_TYPES.has(event.type)&&(journal.entries.length>this.maxJournalEvents||journal.totalBytes>this.maxJournalBytes&&journal.entries.length>1)){this.maybeGrowJournalLimits(journal)}while(journal.entries.length>this.maxJournalEvents||journal.totalBytes>this.maxJournalBytes&&journal.entries.length>1){const dropped=journal.entries.shift();journal.totalBytes-=journal.entryBytes.shift()??0;const droppedEvents=journal.entryEvents.shift()??0;journal.totalEvents-=droppedEvents;journal.truncatedEvents+=droppedEvents;if(dropped===journal.textSegment){journal.textSegment=void 0}}}maybeGrowJournalLimits(journal){const advisor=this.onJournalGrowth;if(!advisor||this.closed)return;const now=this.now();if(this.journalGrowthDeniedAt!==void 0){const sinceDenialMs=now-this.journalGrowthDeniedAt;if(sinceDenialMs>=0&&sinceDenialMs<JOURNAL_GROWTH_REASK_INTERVAL_MS){return}}const originalEvents=this.maxJournalEvents;const originalBytes=this.maxJournalBytes;const originalRetained=this.retainedTailCount(journal,originalEvents,originalBytes);for(let step=0;step<JOURNAL_GROWTH_MAX_GRANTS_PER_BREACH;step++){let grant;try{grant=advisor({maxEvents:this.maxJournalEvents,maxBytes:this.maxJournalBytes})}catch{grant=void 0}if(!grant||!Number.isSafeInteger(grant.maxBytes)||!Number.isSafeInteger(grant.maxEvents)||grant.maxBytes<=this.maxJournalBytes||grant.maxEvents<this.maxJournalEvents){break}this.maxJournalBytes=grant.maxBytes;this.maxJournalEvents=grant.maxEvents;if(this.retainedTailCount(journal,grant.maxEvents,grant.maxBytes)>originalRetained){this.journalGrowthDeniedAt=void 0;return}}this.maxJournalEvents=originalEvents;this.maxJournalBytes=originalBytes;this.journalGrowthDeniedAt=now}retainedTailCount(journal,maxEvents,maxBytes){let count=0;let bytes=0;for(let i=journal.entries.length-1;i>=0;i--){const entryBytes=journal.entryBytes[i]??0;if(count+1>maxEvents)break;if(count>=1&&bytes+entryBytes>maxBytes)break;count+=1;bytes+=entryBytes}return count}classifySessionUpdate(event){const data=event.data;const updateType=data?.update?.sessionUpdate;if(!updateType){this.slots.push({kind:"misc",event});return}switch(updateType){case"agent_message_chunk":{const meta=data?.update?._meta;if(hasDiscreteMessageMeta(data?.update?._meta)||meta?.["executionLifecycle"]!==void 0){this.slots.push({kind:"misc",event});break}this.mergeTextSlot("text",event,data);break}case"agent_thought_chunk":{if(hasDiscreteMessageMeta(data?.update?._meta)){this.slots.push({kind:"misc",event});break}this.mergeTextSlot("thought",event,data);break}case"tool_call":case"tool_call_update":{const update=data?.update;const meta=update?.["_meta"];if(meta?.["toolLifecycle"]!==void 0&&update?.["status"]===void 0&&update?.["content"]===void 0){this.slots.push({kind:"misc",event});break}const toolCallId=data?.update?.toolCallId;if(!toolCallId){this.slots.push({kind:"misc",event});break}const existingIdx=this.toolSlotIndex.get(toolCallId);if(existingIdx!==void 0){const slot=this.slots[existingIdx];slot.event=mergeToolCallEvent(slot.event,event)}else{const normalizedEvent=normalizeToolCallType(event);this.toolSlotIndex.set(toolCallId,this.slots.length);this.slots.push({kind:"tool",toolCallId,event:normalizedEvent});const toolParent=extractParentToolCallIdFromMeta(data?.update?._meta);if(toolParent){this.textSlotIndex.text.delete(toolParent);this.textSlotIndex.thought.delete(toolParent)}}break}default:{if(LATEST_WINS_UPDATES.has(updateType)){const existingIdx=this.slots.findIndex(s=>s.kind==="latestWins"&&s.key===updateType);if(existingIdx!==-1){this.slots[existingIdx].event=event}else{this.slots.push({kind:"latestWins",key:updateType,event})}}else{this.slots.push({kind:"misc",event})}break}}}mergeTextSlot(kind,event,data){const text=data?.update?.content?.text??"";const meta=data?.update?._meta;const parentToolCallId=extractParentToolCallIdFromMeta(meta);const sourceRecordIds=extractSourceRecordIdsFromMeta(meta);if(parentToolCallId!=null){const entries=this.textSlotIndex[kind].get(parentToolCallId)??[];const existingIdx=entries.find(entry=>stringArraysEqual(entry.sourceRecordIds,sourceRecordIds))?.index;if(existingIdx!==void 0){const slot=this.slots[existingIdx];slot.chunks.push(text);if(event.id!==void 0)slot.lastEventId=event.id;slot.lastMeta=mergeTranscriptUpdateMeta(slot.lastMeta,meta);slot.lastEnvelopeMeta=event._meta??slot.lastEnvelopeMeta;slot.lastTurn=captureTurnFields(event,slot.lastTurn);slot.lastSessionId=captureSessionId(event)??slot.lastSessionId}else{entries.push({sourceRecordIds,index:this.slots.length});this.textSlotIndex[kind].set(parentToolCallId,entries);this.slots.push({kind,parentToolCallId,chunks:[text],sourceRecordIds,lastEventId:event.id??0,lastMeta:meta,lastEnvelopeMeta:event._meta,lastTurn:captureTurnFields(event),lastSessionId:captureSessionId(event)})}}else{const lastSlot=this.slots[this.slots.length-1];if(lastSlot&&lastSlot.kind===kind&&lastSlot.parentToolCallId==null&&stringArraysEqual(lastSlot.sourceRecordIds,sourceRecordIds)){lastSlot.chunks.push(text);if(event.id!==void 0)lastSlot.lastEventId=event.id;lastSlot.lastMeta=mergeTranscriptUpdateMeta(lastSlot.lastMeta,meta);lastSlot.lastEnvelopeMeta=event._meta??lastSlot.lastEnvelopeMeta;lastSlot.lastTurn=captureTurnFields(event,lastSlot.lastTurn);lastSlot.lastSessionId=captureSessionId(event)??lastSlot.lastSessionId}else{this.slots.push({kind,parentToolCallId:void 0,chunks:[text],sourceRecordIds,lastEventId:event.id??0,lastMeta:meta,lastEnvelopeMeta:event._meta,lastTurn:captureTurnFields(event),lastSessionId:captureSessionId(event)})}}}compactCurrentTurn(boundaryEvent){const compacted=[];for(const slot of this.slots){switch(slot.kind){case"text":case"thought":compacted.push(makeMergedSessionUpdateEvent(slot.kind==="text"?"agent_message_chunk":"agent_thought_chunk",slot.chunks.join(""),slot.lastEventId,slot.lastMeta,slot.lastEnvelopeMeta,slot.lastTurn,slot.lastSessionId));break;case"tool":case"misc":case"latestWins":compacted.push(slot.event);break;default:break}}compacted.push(boundaryEvent);this.addReplaySegment(compacted,1);this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}recordLastEventId(event){if(event.id!==void 0){this.lastEventId=event.id}}resetJournal(){this.fullJournal=createLiveJournalState();this.summaryJournal=createLiveJournalState();this.journalGrowthDeniedAt=void 0}addReplaySegment(events,turnCount){if(events.length===0)return;const bytes=events.reduce((sum,event)=>{const size=serializedBridgeEventByteLength(event);if(size===void 0){logEventSizingFailed(event.type);return sum}return sum+size},0);this.replaySegments.push({events:events.slice(),bytes,turnCount});this.replayBytes+=bytes;this.enforceReplayWindow()}enforceReplayWindow(){this.degradeReplayAppHtml(this.replaySegments.length-1);let droppedSegmentCount=0;let droppedBytes=0;let droppedEvents=0;let droppedTurns=0;let lastDroppedRecordId;while(this.replayBytes>this.maxReplayBytes&&this.activeReplaySegmentCount()>1){const dropped=this.replaySegments[this.replaySegmentStart];this.replaySegmentStart+=1;droppedSegmentCount+=1;droppedBytes+=dropped.bytes;droppedEvents+=dropped.events.length;droppedTurns+=dropped.turnCount;this.replayBytes-=dropped.bytes;this.truncatedEvents+=dropped.events.length;this.truncatedTurns+=dropped.turnCount;const droppedRecordId=lastRecordIdIn(dropped.events);if(droppedRecordId!==void 0){lastDroppedRecordId=droppedRecordId}}this.degradeReplayAppHtml(this.replaySegments.length);if(droppedSegmentCount>0){this.replayAnchorRecordId??=this.firstRetainedReplayRecordId()??lastDroppedRecordId;this.compactReplaySegmentQueueIfNeeded();this.notifyReplayWindowEviction({droppedBytes,droppedEvents,droppedSegments:droppedSegmentCount,droppedTurns,maxBytes:this.maxReplayBytes,retainedBytes:this.replayBytes,retainedEvents:this.flattenReplaySegments().length})}}firstRetainedReplayRecordId(){for(let i=this.replaySegmentStart;i<this.replaySegments.length;i++){const recordId=lastRecordIdIn(this.replaySegments[i].events);if(recordId!==void 0)return recordId}return void 0}flattenReplaySegments(){return this.replaySegments.slice(this.replaySegmentStart).flatMap(segment=>segment.events)}degradeReplayAppHtml(end){for(let i=this.replaySegmentStart;i<end&&this.replayBytes>this.maxReplayBytes;i++){const segment=this.replaySegments[i];for(let j=0;j<segment.events.length&&this.replayBytes>this.maxReplayBytes;j++){const event=segment.events[j];const degraded=mcpAppTextFallback(event);if(degraded===void 0)continue;const originalBytes=serializedBridgeEventByteLength(event);const degradedBytes=serializedBridgeEventByteLength(degraded);if(originalBytes===void 0||degradedBytes===void 0)continue;segment.events[j]=degraded;segment.bytes+=degradedBytes-originalBytes;this.replayBytes+=degradedBytes-originalBytes}}}activeReplaySegmentCount(){return this.replaySegments.length-this.replaySegmentStart}compactReplaySegmentQueueIfNeeded(){if(this.replaySegmentStart<REPLAY_SEGMENT_COMPACT_THRESHOLD)return;this.replaySegments.splice(0,this.replaySegmentStart);this.replaySegmentStart=0}notifyReplayWindowEviction(eviction){try{this.onReplayWindowEviction?.(eviction)}catch{}}makeHistoryTruncatedEvent(retainedEvents){return{v:EVENT_SCHEMA_VERSION,type:"history_truncated",data:{reason:"replay_window_exceeded",truncatedEvents:this.truncatedEvents,retainedEvents,maxBytes:this.maxReplayBytes,...this.truncatedTurns>0?{truncatedTurns:this.truncatedTurns}:{},...this.replayAnchorRecordId!==void 0?{recordId:this.replayAnchorRecordId}:{},fullTranscriptAvailable:true}}}resetReplayWindow(){this.replaySegments=[];this.replaySegmentStart=0;this.replayBytes=0;this.truncatedEvents=0;this.truncatedTurns=0;this.replayAnchorRecordId=void 0}clearTextSlotIndex(){this.textSlotIndex.text.clear();this.textSlotIndex.thought.clear()}};function isLiveJournalTextSegment(entry){return"firstEvent"in entry}__name(isLiveJournalTextSegment,"isLiveJournalTextSegment");function liveJournalTextChunk(event){if(event.type!=="session_update")return void 0;const data=event.data;const sessionUpdate=data?.update?.sessionUpdate;if(sessionUpdate!=="agent_message_chunk"&&sessionUpdate!=="agent_thought_chunk"){return void 0}if(!hasOnlyModeledChunkKeys(data)){return void 0}if(hasDiscreteMessageMeta(data?.update?._meta)||hasUnmodeledTextMeta(data?.update?._meta)){return void 0}const content=data?.update?.content;if(content?.type!=="text"||typeof content.text!=="string"){return void 0}return{sessionUpdate,text:content.text,sourceRecordIds:extractSourceRecordIdsFromMeta(data?.update?._meta),parentToolCallId:extractParentToolCallIdFromMeta(data?.update?._meta)}}__name(liveJournalTextChunk,"liveJournalTextChunk");function hasOnlyModeledChunkKeys(data){if(!data||!data.update)return false;const content=data.update.content;return Object.keys(data).every(key=>key==="sessionId"||key==="update")&&Object.keys(data.update).every(key=>key==="sessionUpdate"||key==="content"||key==="_meta")&&(content===void 0||typeof content==="object"&&content!==null&&Object.keys(content).every(key=>key==="type"||key==="text"))}__name(hasOnlyModeledChunkKeys,"hasOnlyModeledChunkKeys");function mergeLiveJournalTextEvent(existing,incoming,chunks){const existingData=existing.data;const incomingData=incoming.data;return{...existing,...incoming,data:{...existingData,...incomingData,update:{...existingData.update,...incomingData.update,content:{type:"text",text:chunks.join("")}}}}}__name(mergeLiveJournalTextEvent,"mergeLiveJournalTextEvent");function makeMergedSessionUpdateEvent(sessionUpdate,text,eventId,meta,envelopeMeta,turn,sessionId){return{id:eventId||void 0,v:EVENT_SCHEMA_VERSION,type:"session_update",...turn?.promptId!==void 0?{promptId:turn.promptId}:{},...turn?.originatorClientId!==void 0?{originatorClientId:turn.originatorClientId}:{},...envelopeMeta!==void 0?{_meta:envelopeMeta}:{},data:{...sessionId!==void 0?{sessionId}:{},update:{sessionUpdate,content:{type:"text",text},...meta!=null?{_meta:meta}:{}}}}}__name(makeMergedSessionUpdateEvent,"makeMergedSessionUpdateEvent");function captureTurnFields(event,previous){const promptId=event.promptId??previous?.promptId;const originatorClientId=event.originatorClientId??previous?.originatorClientId;if(promptId===void 0&&originatorClientId===void 0){return void 0}return{...promptId!==void 0?{promptId}:{},...originatorClientId!==void 0?{originatorClientId}:{}}}__name(captureTurnFields,"captureTurnFields");function captureSessionId(event){const sessionId=event.data?.sessionId;return typeof sessionId==="string"?sessionId:void 0}__name(captureSessionId,"captureSessionId");function normalizeToolCallType(event){const data=event.data;if(data?.update?.sessionUpdate==="tool_call_update"){return{...event,data:{...data,update:{...data.update,sessionUpdate:"tool_call"}}}}return event}__name(normalizeToolCallType,"normalizeToolCallType");function extractParentToolCallIdFromMeta(meta){if(typeof meta==="object"&&meta!==null){const val=meta["parentToolCallId"];return typeof val==="string"&&val.length>0?val:void 0}return void 0}__name(extractParentToolCallIdFromMeta,"extractParentToolCallIdFromMeta");function extractSourceRecordIdsFromMeta(meta){if(typeof meta!=="object"||meta===null)return void 0;const transcript=meta["qwenTranscript"];if(typeof transcript!=="object"||transcript===null)return void 0;const ids=transcript["sourceRecordIds"];if(!Array.isArray(ids))return void 0;const normalized=[...new Set(ids.filter(id=>typeof id==="string"))];return normalized.length>0?normalized:void 0}__name(extractSourceRecordIdsFromMeta,"extractSourceRecordIdsFromMeta");function stringArraysEqual(left,right){if(left===right)return true;if(!left||!right||left.length!==right.length)return false;return left.every((value,index)=>value===right[index])}__name(stringArraysEqual,"stringArraysEqual");function hasDiscreteMessageMeta(meta){return typeof meta==="object"&&meta!==null&&meta["qwenDiscreteMessage"]===true}__name(hasDiscreteMessageMeta,"hasDiscreteMessageMeta");function hasOnlyTimestampEnvelopeMeta(meta){if(meta===void 0)return true;if(typeof meta!=="object"||meta===null)return false;return Object.keys(meta).every(key=>key==="timestamp"||key==="serverTimestamp")}__name(hasOnlyTimestampEnvelopeMeta,"hasOnlyTimestampEnvelopeMeta");function hasUnmodeledTextMeta(meta){if(meta===void 0)return false;if(typeof meta!=="object"||meta===null)return true;const record=meta;for(const[key,value]of Object.entries(record)){if(key==="timestamp"||key==="serverTimestamp"){continue}if(key==="parentToolCallId"){if(typeof value!=="string")return true;continue}if(key==="subagentType"){if(typeof value!=="string")return true;continue}if(key==="qwenTranscript"){if(typeof value!=="object"||value===null)return true;const transcript=value;for(const[field,fieldValue]of Object.entries(transcript)){if(field==="sourceRecordIds"){if(!Array.isArray(fieldValue)||fieldValue.some(id=>typeof id!=="string")){return true}continue}if(field==="planToolCallId"){if(typeof fieldValue!=="string")return true;continue}return true}continue}return true}return false}__name(hasUnmodeledTextMeta,"hasUnmodeledTextMeta");function mergeToolCallEvent(existing,incoming){const existingData=existing.data;const incomingData=incoming.data;const existingUpdate=existingData?.update??{};const incomingUpdate=incomingData?.update??{};const merged={...existingUpdate};for(const[key,value]of Object.entries(incomingUpdate)){if(value!==void 0&&value!==null){merged[key]=value}}const updateMeta=mergeTranscriptUpdateMeta(existingUpdate["_meta"],incomingUpdate["_meta"]);if(updateMeta!==void 0)merged["_meta"]=updateMeta;merged["sessionUpdate"]="tool_call";const mergedMeta=existing._meta||incoming._meta?{...existing._meta??{},...incoming._meta??{}}:void 0;const promptId=incoming.promptId??existing.promptId;const originatorClientId=incoming.originatorClientId??existing.originatorClientId;return{id:incoming.id??existing.id,v:EVENT_SCHEMA_VERSION,type:"session_update",...promptId!==void 0?{promptId}:{},...originatorClientId!==void 0?{originatorClientId}:{},...mergedMeta?{_meta:mergedMeta}:{},data:{...existingData,...incomingData,update:merged}}}__name(mergeToolCallEvent,"mergeToolCallEvent");function mergeTranscriptUpdateMeta(existing,incoming){const existingRecord=typeof existing==="object"&&existing!==null?existing:void 0;const incomingRecord=typeof incoming==="object"&&incoming!==null?incoming:void 0;if(!existingRecord&&!incomingRecord)return void 0;const sourceRecordIds=[...new Set([...extractSourceRecordIdsFromMeta(existingRecord)??[],...extractSourceRecordIdsFromMeta(incomingRecord)??[]])];const existingTranscript=extractTranscriptMeta(existingRecord);const incomingTranscript=extractTranscriptMeta(incomingRecord);return{...existingRecord??{},...incomingRecord??{},...existingTranscript||incomingTranscript||sourceRecordIds.length>0?{qwenTranscript:{...existingTranscript??{},...incomingTranscript??{},...sourceRecordIds.length>0?{sourceRecordIds}:{}}}:{}}}__name(mergeTranscriptUpdateMeta,"mergeTranscriptUpdateMeta");function extractTranscriptMeta(meta){const transcript=meta?.["qwenTranscript"];return typeof transcript==="object"&&transcript!==null?transcript:void 0}__name(extractTranscriptMeta,"extractTranscriptMeta");init_esbuild_shims();function createJournalGrowthPolicy(opts){const hardCapEvents=Math.min(Number.MAX_SAFE_INTEGER,Math.max(opts.baselineEvents,Math.ceil(opts.hardCapBytes/opts.baselineBytes*opts.baselineEvents)));return{grant(request){if(request.currentMaxBytes>=opts.hardCapBytes)return void 0;const extraGranted=request.allSessionLimits.reduce((sum,session)=>sum+Math.max(0,session.limitBytes-session.baselineBytes),0);const available=opts.poolBytes-extraGranted;if(available<=0)return void 0;const maxBytes=Math.min(request.currentMaxBytes*2,request.currentMaxBytes+available,opts.hardCapBytes);if(maxBytes<=request.currentMaxBytes)return void 0;const maxEvents=Math.min(Math.max(request.currentMaxEvents,Math.ceil(maxBytes/opts.baselineBytes*opts.baselineEvents)),hardCapEvents);return{maxBytes,maxEvents}}}}__name(createJournalGrowthPolicy,"createJournalGrowthPolicy");init_esbuild_shims();var DEFAULT_SESSION_RESTORE_TIMEOUT_MS=6e4;var MAX_SESSION_RESTORE_TIMEOUT_MS=2147483647;var MIN_RESTORE_RETRY_AFTER_SECONDS=5;var MAX_RESTORE_RETRY_AFTER_SECONDS=120;function restoreRetryAfterSeconds(timeoutMs){return Math.min(MAX_RESTORE_RETRY_AFTER_SECONDS,Math.max(MIN_RESTORE_RETRY_AFTER_SECONDS,Math.ceil(timeoutMs/1e3)))}__name(restoreRetryAfterSeconds,"restoreRetryAfterSeconds");function assertValidTimeoutMs(field,timeoutMs){if(!Number.isFinite(timeoutMs)||!Number.isInteger(timeoutMs)||timeoutMs<=0||timeoutMs>MAX_SESSION_RESTORE_TIMEOUT_MS){throw new TypeError(`Invalid ${field}: ${timeoutMs}. Must be a positive integer no greater than ${MAX_SESSION_RESTORE_TIMEOUT_MS}.`)}}__name(assertValidTimeoutMs,"assertValidTimeoutMs");function resolveSessionRestoreTimeoutMs(opts){if(opts.sessionRestoreTimeoutMs!==void 0){assertValidTimeoutMs("sessionRestoreTimeoutMs",opts.sessionRestoreTimeoutMs);return opts.sessionRestoreTimeoutMs}if(opts.initializeTimeoutMs!==void 0){assertValidTimeoutMs("initializeTimeoutMs",opts.initializeTimeoutMs);return Math.max(opts.initializeTimeoutMs,DEFAULT_SESSION_RESTORE_TIMEOUT_MS)}return DEFAULT_SESSION_RESTORE_TIMEOUT_MS}__name(resolveSessionRestoreTimeoutMs,"resolveSessionRestoreTimeoutMs");init_esbuild_shims();var SESSION_SOURCE_META_KEY="qwen.session.source";var SESSION_SOURCE_TYPE_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/;var MAX_SESSION_SOURCE_ID_LENGTH=256;var STANDALONE_SESSION_SOURCE_TYPE="standalone";var DAEMON_OWNED_STANDALONE_CREATION_KEY="daemonOwnedStandaloneCreation";function isReservedStandaloneSessionSourceType(sourceType){return sourceType===STANDALONE_SESSION_SOURCE_TYPE}__name(isReservedStandaloneSessionSourceType,"isReservedStandaloneSessionSourceType");var SCHEDULED_TASK_RUN_SOURCE_TYPE="default";var SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX="scheduled_task_run:";function isScheduledTaskRunSource(source){return source.sourceType===SCHEDULED_TASK_RUN_SOURCE_TYPE&&source.sourceId?.startsWith(SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX)===true}__name(isScheduledTaskRunSource,"isScheduledTaskRunSource");function parseSessionSource(sourceType,sourceId){if(sourceType===void 0&&sourceId===void 0)return{};if(typeof sourceType!=="string"||!SESSION_SOURCE_TYPE_PATTERN.test(sourceType)){return{error:"`sourceType` must match [a-z][a-z0-9_-]{0,63} when provided"}}if(sourceId===void 0)return{sourceType};if(typeof sourceId!=="string"||sourceId.length===0||sourceId.length>MAX_SESSION_SOURCE_ID_LENGTH||[...sourceId].some(character=>{const code=character.charCodeAt(0);return code<=31||code===127})){return{error:`\`sourceId\` must be a non-empty string of at most ${MAX_SESSION_SOURCE_ID_LENGTH} characters without control characters`}}return{sourceType,sourceId}}__name(parseSessionSource,"parseSessionSource");init_esbuild_shims();import{constants as fsConstants,promises as fs,statSync}from"node:fs";import{tmpdir}from"node:os";import*as path from"node:path";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";var SESSION_ATTACHMENT_CHUNK_BYTES=512*1024;var UPLOAD_LIFETIME_MS=5*60*1e3;var MAX_STAGED_BYTES=128*1024*1024;var MAX_ACTIVE_UPLOADS=32;var MAX_SESSION_UPLOADS=8;var MAX_RECEIPTS=1024;var SessionAttachmentUploadError=class extends Error{constructor(status,code,message,cause){super(message,{cause});this.status=status;this.code=code;this.name="SessionAttachmentUploadError"}static{__name(this,"SessionAttachmentUploadError")}};var uploads=new Set;var receipts=new Set;var stagedBytes=0;var activeUploads=0;var sweepTimer;function sweep(){const now=Date.now();for(const upload of uploads){if(upload.state!=="completing"&&upload.expiresAt<=now){upload.owner.discard(upload)}}}__name(sweep,"sweep");function notFound(){return new SessionAttachmentUploadError(404,"attachment_upload_not_found","Attachment upload is unavailable")}__name(notFound,"notFound");var SessionAttachmentUploads=class{static{__name(this,"SessionAttachmentUploads")}records=new Map;active=0;closed=false;create(metadata,clientId){if(this.closed)throw notFound();sweep();if(this.active>=MAX_SESSION_UPLOADS||activeUploads>=MAX_ACTIVE_UPLOADS||stagedBytes+metadata.size>MAX_STAGED_BYTES){throw new SessionAttachmentUploadError(429,"attachment_upload_capacity_exceeded","Attachment upload capacity is exhausted; try again later")}stagedBytes+=metadata.size;activeUploads++;this.active++;let data;try{data=Buffer.alloc(metadata.size)}catch(error){stagedBytes-=metadata.size;activeUploads--;this.active--;throw error}const upload={id:randomUUID2(),owner:this,clientId,metadata:{...metadata},data,offset:0,previousOffset:-1,expiresAt:Date.now()+UPLOAD_LIFETIME_MS,state:"receiving"};this.records.set(upload.id,upload);uploads.add(upload);if(!sweepTimer){sweepTimer=setInterval(sweep,3e4);sweepTimer.unref()}return{uploadId:upload.id}}append(id,offset,data,clientId){const upload=this.get(id,clientId);if(upload.state!=="receiving"||!upload.data){throw new SessionAttachmentUploadError(409,"attachment_upload_finalizing","Attachment upload no longer accepts chunks")}if(!Number.isSafeInteger(offset)||offset<0||data.length===0){throw new SessionAttachmentUploadError(400,"invalid_attachment_upload_chunk","A nonempty chunk and a non-negative integer offset are required")}if(data.length>SESSION_ATTACHMENT_CHUNK_BYTES||offset+data.length>upload.metadata.size){throw new SessionAttachmentUploadError(413,"attachment_upload_too_large","Chunk exceeds the attachment upload size limit")}if(offset===upload.previousOffset&&offset+data.length===upload.offset&&upload.data.subarray(offset,upload.offset).equals(data)){return{offset:upload.offset}}if(offset!==upload.offset||data.length!==Math.min(SESSION_ATTACHMENT_CHUNK_BYTES,upload.metadata.size-offset)){throw new SessionAttachmentUploadError(409,"attachment_upload_offset_conflict","Chunk does not match the expected attachment offset or length")}data.copy(upload.data,offset);upload.previousOffset=offset;upload.offset+=data.length;return{offset:upload.offset}}complete(id,clientId,commit){const upload=this.get(id,clientId);if(upload.completion)return upload.completion;if(upload.offset!==upload.metadata.size){throw new SessionAttachmentUploadError(409,"attachment_upload_incomplete","Attachment upload has not received all bytes")}upload.state="completing";let retryableFailure=false;const assertActive=__name(()=>{if(this.closed||this.records.get(id)!==upload)throw notFound()},"assertActive");upload.completion=Promise.resolve().then(()=>{assertActive();return commit(upload.data,upload.metadata,assertActive)}).then(reference=>{upload.state="completed";return reference},error=>{if(error instanceof SessionAttachmentUploadError&&error.code==="attachment_upload_store_busy"){upload.state="receiving";upload.completion=void 0;retryableFailure=true}else{upload.state="failed"}throw error}).finally(()=>{if(retryableFailure){if(this.closed||this.records.get(id)!==upload){this.discard(upload)}return}this.releaseBuffer(upload);if(this.closed||this.records.get(id)!==upload){this.discard(upload);return}upload.expiresAt=Date.now()+UPLOAD_LIFETIME_MS;receipts.add(upload);while(receipts.size>MAX_RECEIPTS){const oldest2=receipts.values().next().value;oldest2.owner.discard(oldest2)}});return upload.completion}cancel(id,clientId){sweep();const upload=this.records.get(id);if(!upload||upload.clientId!==clientId)return;if(upload.state==="completing"||upload.state==="completed"){throw new SessionAttachmentUploadError(409,upload.state==="completing"?"attachment_upload_finalizing":"attachment_upload_completed","Attachment completion cannot be cancelled")}this.discard(upload)}cancelClient(clientId){for(const upload of this.records.values()){if(upload.clientId===clientId)this.discard(upload)}}close(){this.closed=true;for(const upload of this.records.values())this.discard(upload)}discard(upload){this.records.delete(upload.id);if(upload.state==="completing")return;this.releaseBuffer(upload);uploads.delete(upload);receipts.delete(upload);if(uploads.size===0&&sweepTimer){clearInterval(sweepTimer);sweepTimer=void 0}}get(id,clientId){const upload=this.records.get(id);if(!upload||upload.clientId!==clientId)throw notFound();if(upload.state!=="completing"&&upload.expiresAt<=Date.now()){this.discard(upload);throw notFound()}return upload}releaseBuffer(upload){if(!upload.data)return;upload.data=void 0;stagedBytes-=upload.metadata.size;activeUploads--;this.active--}};var SESSION_ATTACHMENT_MAX_ITEM_BYTES=8*1024*1024;var SESSION_ATTACHMENT_MAX_NAME_BYTES=255;var SUPPORTED_IMAGE_MIME_TYPES=new Set(["image/bmp","image/gif","image/jpeg","image/png","image/webp"]);function hasVerifiableInode(ino){return Number.isSafeInteger(ino)&&ino>0}__name(hasVerifiableInode,"hasVerifiableInode");async function openDurableAttachmentDirectory(directory,openedHandle){const handle=openedHandle??await fs.open(directory,fsConstants.O_RDONLY|(process.platform==="win32"?0:fsConstants.O_NOFOLLOW??0));try{const opened=await handle.stat();const current=await fs.stat(directory);const openedInodeVerifiable=hasVerifiableInode(opened.ino);const currentInodeVerifiable=hasVerifiableInode(current.ino);if(!opened.isDirectory()||!current.isDirectory()||opened.dev!==current.dev||openedInodeVerifiable!==currentInodeVerifiable||openedInodeVerifiable&&opened.ino!==current.ino){throw new Error("Session attachment parent directory changed.")}return{path:directory,handle,dev:opened.dev,ino:opened.ino,inodeVerifiable:openedInodeVerifiable}}catch(error){await handle.close().catch(()=>void 0);throw error}}__name(openDurableAttachmentDirectory,"openDurableAttachmentDirectory");async function openDurableAttachmentDirectoryIfPresent(directory){let handle;try{handle=await fs.open(directory,fsConstants.O_RDONLY|(process.platform==="win32"?0:fsConstants.O_NOFOLLOW??0))}catch(error){if(error.code==="ENOENT")return void 0;throw error}return openDurableAttachmentDirectory(directory,handle)}__name(openDurableAttachmentDirectoryIfPresent,"openDurableAttachmentDirectoryIfPresent");async function syncDurableAttachmentDirectory(expected){const opened=await expected.handle.stat();const openedInodeVerifiable=hasVerifiableInode(opened.ino);const current=await fs.stat(expected.path);const currentInodeVerifiable=hasVerifiableInode(current.ino);if(!opened.isDirectory()||!current.isDirectory()||opened.dev!==expected.dev||openedInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&&opened.ino!==expected.ino||current.dev!==expected.dev||currentInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&¤t.ino!==expected.ino){throw new Error("Session attachment parent directory changed.")}try{await expected.handle.sync()}catch(error){if(process.platform!=="win32"||!["EACCES","EINVAL","EPERM"].includes(error.code??"")){throw error}}const after=await fs.stat(expected.path);const afterInodeVerifiable=hasVerifiableInode(after.ino);if(!after.isDirectory()||after.dev!==expected.dev||afterInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&&after.ino!==expected.ino){throw new Error("Session attachment parent directory changed.")}}__name(syncDurableAttachmentDirectory,"syncDurableAttachmentDirectory");var SESSION_ATTACHMENT_UNAVAILABLE_TEXT="[Attachment is no longer available]";var SessionAttachmentReferenceError=class extends Error{constructor(message,code){super(message);this.code=code;this.name="SessionAttachmentReferenceError"}static{__name(this,"SessionAttachmentReferenceError")}};function isSessionAttachmentReference(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const record=value;return(record["type"]==="image"||record["type"]==="resource")&&typeof record["attachmentId"]==="string"&&record["attachmentId"].length>0&&typeof record["mimeType"]==="string"&&record["mimeType"].length>0&&(record["type"]!=="image"||record["mimeType"].startsWith("image/"))&&typeof record["size"]==="number"&&Number.isSafeInteger(record["size"])&&record["size"]>=0&&(record["type"]!=="image"||record["size"]>0)}__name(isSessionAttachmentReference,"isSessionAttachmentReference");function safeAttachmentName(name){const safeName=path.basename(name.replaceAll("\\","/")).trim();const isWindowsReserved=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(safeName);const hasInvalidCharacter=Array.from(safeName).some(character=>{const codePoint=character.codePointAt(0);return codePoint!==void 0&&(codePoint<=31||codePoint===127||codePoint>=55296&&codePoint<=57343)});return!safeName||safeName==="."||safeName===".."||safeName.endsWith(".")||isWindowsReserved||/[<>:"|?*]/.test(safeName)||hasInvalidCharacter||Buffer.byteLength(safeName)>SESSION_ATTACHMENT_MAX_NAME_BYTES?void 0:safeName}__name(safeAttachmentName,"safeAttachmentName");function truncateUtf8(value,maxBytes){let bytes=0;let result="";for(const character of value){const characterBytes=Buffer.byteLength(character);if(bytes+characterBytes>maxBytes)break;result+=character;bytes+=characterBytes}return result}__name(truncateUtf8,"truncateUtf8");function deduplicatedName(name,suffix){if(suffix===0)return name;const extension=path.extname(name);const suffixText=` (${suffix})`;const stem=name.slice(0,-extension.length||void 0);const extensionBudget=SESSION_ATTACHMENT_MAX_NAME_BYTES-Buffer.byteLength(suffixText)-1;const safeExtension=truncateUtf8(extension,extensionBudget).replace(/[. ]+$/u,"");const stemBudget=SESSION_ATTACHMENT_MAX_NAME_BYTES-Buffer.byteLength(suffixText)-Buffer.byteLength(safeExtension);return`${truncateUtf8(stem,stemBudget)}${suffixText}${safeExtension}`}__name(deduplicatedName,"deduplicatedName");function imageName(mimeType){const extension=mimeType.slice("image/".length).split(/[;+]/,1)[0];return`image.${extension==="jpg"?"jpeg":extension||"img"}`}__name(imageName,"imageName");function mimeTypeForName(name){if([".ts",".mts",".cts",".tsx"].includes(path.extname(name).toLowerCase())){return"text/plain"}return getSpecificMimeType(name)??"application/octet-stream"}__name(mimeTypeForName,"mimeTypeForName");function isSupportedImageMimeType(mimeType){return SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)}__name(isSupportedImageMimeType,"isSupportedImageMimeType");function isTextMimeType(mimeType){return mimeType.startsWith("text/")||mimeType==="application/json"||mimeType.endsWith("+json")||mimeType==="application/xml"||mimeType.endsWith("+xml")||mimeType==="application/javascript"||mimeType==="application/typescript"||mimeType==="application/yaml"||mimeType==="application/x-yaml"||mimeType==="application/toml"}__name(isTextMimeType,"isTextMimeType");function isTextAttachment(data,mimeType){if(isTextMimeType(mimeType))return true;if(mimeType.startsWith("image/")||mimeType.startsWith("audio/")||mimeType.startsWith("video/")||mimeType.startsWith("font/")||mimeType==="application/pdf"||data.includes(0)){return false}return Buffer.from(data.toString("utf8"),"utf8").equals(data)}__name(isTextAttachment,"isTextAttachment");function statSize(filePath){try{return statSync(filePath).size}catch{return void 0}}__name(statSize,"statSize");function statSizeStrict(filePath){try{return statSync(filePath).size}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(statSizeStrict,"statSizeStrict");function withAttachmentDegradationMarker(blocks){for(let i=blocks.length-1;i>=0;i--){const block=blocks[i];if(block.type==="text"){if(block.text.endsWith(SESSION_ATTACHMENT_UNAVAILABLE_TEXT)){return[...blocks]}const next=[...blocks];next[i]={type:"text",text:`${block.text}
|
|
5
5
|
${SESSION_ATTACHMENT_UNAVAILABLE_TEXT}`};return next}}return[...blocks,{type:"text",text:SESSION_ATTACHMENT_UNAVAILABLE_TEXT}]}__name(withAttachmentDegradationMarker,"withAttachmentDegradationMarker");function validateAttachmentName(mimeType,name){const isImage=isSupportedImageMimeType(mimeType);const safeName=safeAttachmentName(name??(isImage?imageName(mimeType):""));if(!safeName){throw new TypeError("Session attachment name is invalid")}const storedMimeType=mimeTypeForName(safeName);if(isImage&&storedMimeType!==mimeType||isSupportedImageMimeType(storedMimeType)&&!isImage){throw new TypeError("Attachment name and Content-Type do not match")}return safeName}__name(validateAttachmentName,"validateAttachmentName");var SessionAttachmentStore=class{constructor(directoryRoot,sessionId,fallbackDirectoryRoot){this.directoryRoot=directoryRoot;if(!directoryRoot||!sessionId)return;this.persistentDirectory=path.join(directoryRoot,`session-${encodeURIComponent(sessionId)}`);if(fallbackDirectoryRoot){this.persistentFallbackDirectory=path.join(fallbackDirectoryRoot,`session-${encodeURIComponent(sessionId)}`)}}static{__name(this,"SessionAttachmentStore")}uploads=new SessionAttachmentUploads;publication=Promise.resolve();readerBatch;directoryPromise;persistentDirectory;persistentFallbackDirectory;activeDirectory;pendingItems=0;pendingNames=new Map;queuedNames=new Map;removingNames=new Set;pendingDrainWaiters=[];copyDrainWaiters=[];copying=false;closing=false;closed=false;createUpload(metadata,clientId){if(this.closed||this.closing)throw new Error("Session attachment store is closed");if(this.copying)throw new Error("Session attachments are being copied");const name=validateAttachmentName(metadata.mimeType,metadata.name);if(!Number.isSafeInteger(metadata.size)||metadata.size<0){throw new TypeError("Attachment size must be a non-negative integer")}if(metadata.size>SESSION_ATTACHMENT_MAX_ITEM_BYTES){throw new RangeError("Session attachment must be at most 8 MiB")}if(metadata.size===0&&isSupportedImageMimeType(metadata.mimeType)){throw new TypeError("Image attachments cannot be empty")}return this.uploads.create({...metadata,name},clientId)}appendUpload(id,offset,data,clientId){return this.uploads.append(id,offset,data,clientId)}completeUpload(id,clientId,assertCanCommit){const assertAvailable=__name(()=>{if(this.closed||this.closing){throw new SessionAttachmentUploadError(404,"attachment_upload_not_found","Attachment upload is unavailable")}if(this.copying){throw new SessionAttachmentUploadError(503,"attachment_upload_store_busy","Session attachments are being copied")}},"assertAvailable");return this.uploads.complete(id,clientId,(data,metadata,assertActive)=>{assertAvailable();return this.putAttachment(data,metadata.mimeType,metadata.name,()=>{assertActive();assertCanCommit()})})}cancelUpload(id,clientId){this.uploads.cancel(id,clientId)}cancelClientUploads(clientId){this.uploads.cancelClient(clientId)}acquirePublication(){this.readerBatch=void 0;const previous=this.publication;let release;this.publication=new Promise(resolve3=>{release=resolve3});return previous.then(()=>release)}acquireReadPublication(){let batch=this.readerBatch;if(!batch){const previous=this.publication;let release;this.publication=new Promise(resolve3=>{release=resolve3});batch={previous,release,count:0};this.readerBatch=batch}batch.count+=1;return batch.previous.then(()=>()=>{if(--batch.count===0){if(this.readerBatch===batch)this.readerBatch=void 0;batch.release()}})}async putAttachment(data,mimeType,name,assertCanCommit){const isImage=isSupportedImageMimeType(mimeType);const safeName=validateAttachmentName(mimeType,name);if(this.closed||this.closing){throw new Error("Session attachment store is closed")}if(this.copying)throw new Error("Session attachments are being copied");if(isImage&&data.byteLength===0||data.byteLength>SESSION_ATTACHMENT_MAX_ITEM_BYTES){throw new RangeError(`Session attachment must be at most ${SESSION_ATTACHMENT_MAX_ITEM_BYTES} bytes and images cannot be empty`)}let filePath;let pendingName;let removeFileOnFailure=false;this.pendingItems+=1;this.queuedNames.set(safeName,(this.queuedNames.get(safeName)??0)+1);const releasePublication=await this.acquirePublication();try{if(this.closed||this.closing)throw new Error("Session attachment store is closed");assertCanCommit?.();const directory=await this.directory();let suffix=0;for(;;){const candidateName=deduplicatedName(safeName,suffix);if(safeAttachmentName(candidateName)!==candidateName){throw new TypeError("Session attachment name is invalid")}if(this.removingNames.has(candidateName)||statSizeStrict(path.join(directory,candidateName))!==void 0){suffix+=1;continue}if(this.persistentFallbackDirectory&&statSizeStrict(path.join(this.persistentFallbackDirectory,candidateName))!==void 0){suffix+=1;continue}if(pendingName!==candidateName){if(pendingName)this.releasePendingName(pendingName);this.reservePendingName(candidateName);pendingName=candidateName}if(this.closed||this.closing)throw new Error("Session attachment store is closed");assertCanCommit?.();filePath=path.join(directory,candidateName);removeFileOnFailure=true;try{await fs.writeFile(filePath,data,{flag:"wx"});break}catch(error){if(error.code!=="EEXIST")throw error;removeFileOnFailure=false;this.releasePendingName(candidateName);pendingName=void 0;filePath=void 0;suffix+=1}}if(this.closed||this.closing){throw new Error("Session attachment store is closed")}assertCanCommit?.();const name2=path.basename(filePath);const storedMimeType=mimeTypeForName(name2);const reference={type:isSupportedImageMimeType(storedMimeType)?"image":"resource",attachmentId:name2,mimeType:storedMimeType,size:data.byteLength};return reference}catch(error){if(removeFileOnFailure&&filePath){await fs.rm(filePath,{force:true}).catch(()=>{pendingName=void 0})}if(assertCanCommit&&error instanceof Error&&"code"in error&&typeof error.code==="string"&&/^E[A-Z]+$/.test(error.code)){throw new SessionAttachmentUploadError(500,"attachment_upload_storage_failed","Could not store attachment",error)}throw error}finally{if(pendingName)this.releasePendingName(pendingName);const queued=this.queuedNames.get(safeName);if(queued===1)this.queuedNames.delete(safeName);else this.queuedNames.set(safeName,queued-1);releasePublication();if(!this.closed){this.pendingItems-=1;if(this.pendingItems===0){this.resolvePendingDrainWaiters()}}}}assertReference(block){if(!block||typeof block!=="object"||Array.isArray(block)||!("attachmentId"in block)){return}if(!isSessionAttachmentReference(block)){throw new SessionAttachmentReferenceError("Invalid session attachment reference","invalid_session_attachment_reference")}this.assertStored(block)}assertReferences(content){const seenIds=new Set;for(const block of content){if(!block||typeof block!=="object"||Array.isArray(block)||!("attachmentId"in block)){continue}if(!isSessionAttachmentReference(block)){throw new SessionAttachmentReferenceError("Invalid session attachment reference","invalid_session_attachment_reference")}const id=block.attachmentId;if(seenIds.has(id)){throw new SessionAttachmentReferenceError(`Session attachment referenced more than once: ${id}`,"invalid_session_attachment_reference")}seenIds.add(id);this.assertStored(block)}}async resolveContent(content,memo){const pendingById=memo??new Map;return await Promise.all(content.map(async block=>{if(!isSessionAttachmentReference(block))return block;const id=block.attachmentId;let pending=pendingById.get(id);if(!pending){const created=this.resolve(block);pendingById.set(id,created);void created.catch(()=>{if(pendingById.get(id)===created){pendingById.delete(id)}});pending=created}return await pending}))}async resolveContentDegrading(content,memo){const retainedBlocks=[];const resolvedBlocks=[];let degraded=0;for(const block of content){if(!isSessionAttachmentReference(block)){retainedBlocks.push(block);resolvedBlocks.push(block);continue}try{const[resolved]=await this.resolveContent([block],memo);if(resolved)resolvedBlocks.push(resolved);retainedBlocks.push(block)}catch(error){if(!(error instanceof SessionAttachmentReferenceError))throw error;degraded+=1}}return{retainedBlocks,resolvedBlocks,degraded}}async read(attachmentId){const attachment=await this.readStored(attachmentId);if(!attachment)return void 0;return{data:attachment.data,mimeType:attachment.mimeType}}async readStored(attachmentId){const releasePublication=await this.acquireReadPublication();try{return await this.readPublished(attachmentId)}finally{releasePublication()}}async readPublished(attachmentId){const name=safeAttachmentName(attachmentId);if(!name||name!==attachmentId||this.pendingNames.has(name))return void 0;let primary;try{primary=await this.tryRead(await this.peekDirectory(),name)}catch(error){if(!this.persistentFallbackDirectory)throw error;primary=void 0}if(primary)return primary;return await this.tryRead(this.persistentFallbackDirectory,name)}async tryRead(directory,name){if(!directory)return void 0;const absolutePath=path.resolve(directory,name);try{return{data:await fs.readFile(absolutePath),mimeType:mimeTypeForName(name),absolutePath}}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async list(){const found=[];const directories=[this.persistentDirectory??this.activeDirectory,this.persistentFallbackDirectory].filter(directory=>Boolean(directory));const foundNames=new Set;let directoryRead=false;let directoryError;for(const directory of directories){let entries;try{entries=await fs.readdir(directory,{withFileTypes:true})}catch(error){if(error.code!=="ENOENT"){directoryError??=error}continue}directoryRead=true;for(const entry of entries){if(!entry.isFile()||this.pendingNames.has(entry.name)||this.removingNames.has(entry.name)||foundNames.has(entry.name)){continue}const name=safeAttachmentName(entry.name);if(!name||name!==entry.name)continue;try{const stat=await fs.stat(path.join(directory,entry.name));const mimeType=mimeTypeForName(entry.name);found.push({reference:{type:isSupportedImageMimeType(mimeType)?"image":"resource",attachmentId:entry.name,mimeType,size:stat.size},mtimeMs:stat.mtimeMs});foundNames.add(entry.name)}catch{}}}if(!directoryRead&&directoryError!==void 0){throw directoryError}found.sort((a,b)=>a.mtimeMs-b.mtimeMs||a.reference.attachmentId.localeCompare(b.reference.attachmentId));return found.map(({reference})=>reference)}async copyFrom(source){if(source===this)return;if(this.closed||this.closing){throw new Error("Session attachment store is closed")}if(this.copying)throw new Error("Session attachments are being copied");if(source.closed||source.closing){throw new Error("Session attachment store is closed")}if(source.copying){throw new Error("Session attachments are being copied")}this.copying=true;source.copying=true;try{if(this.pendingItems>0){await new Promise(resolve3=>this.pendingDrainWaiters.push(resolve3))}if(source.pendingItems>0){await new Promise(resolve3=>source.pendingDrainWaiters.push(resolve3))}if(this.closed)throw new Error("Session attachment store is closed");const sourceDirectories=[source.persistentDirectory??source.activeDirectory,source.persistentFallbackDirectory].filter(directory=>Boolean(directory));if(sourceDirectories.length===0)return;const targetDirectory=await this.directory();const copiedNames=new Set;let sourceDirectoryRead=false;let sourceDirectoryError;for(const sourceDirectory of sourceDirectories){let entries;try{entries=await fs.readdir(sourceDirectory,{withFileTypes:true})}catch(error){if(error.code==="ENOENT")continue;sourceDirectoryError??=error;continue}sourceDirectoryRead=true;await Promise.all(entries.filter(entry=>entry.isFile()&&!source.pendingNames.has(entry.name)&&!source.removingNames.has(entry.name)&&!copiedNames.has(entry.name)).map(async entry=>{const sourcePath=path.join(sourceDirectory,entry.name);try{await fs.copyFile(sourcePath,path.join(targetDirectory,entry.name));copiedNames.add(entry.name)}catch(error){if(error.code==="ENOENT"){try{await fs.stat(sourcePath)}catch(sourceError){if(sourceError.code==="ENOENT"){return}}}throw error}}))}if(!sourceDirectoryRead&&sourceDirectoryError!==void 0){throw sourceDirectoryError}}finally{source.copying=false;this.copying=false;source.resolveCopyDrainWaiters();this.resolveCopyDrainWaiters()}}async remove(attachmentId){const name=safeAttachmentName(attachmentId);if(!name||name!==attachmentId||this.copying||this.pendingNames.has(name)||this.queuedNames.has(name)||this.removingNames.has(name)){return false}this.removingNames.add(name);try{const primaryDirectory=await this.peekDirectory();const[fallbackExists,primaryExists]=await Promise.all([this.hasAttachment(this.persistentFallbackDirectory,name),this.hasAttachment(primaryDirectory,name)]);const fallbackHit=fallbackExists&&await this.tryUnlink(this.persistentFallbackDirectory,name)===true;const primaryHit=primaryExists&&await this.tryUnlink(primaryDirectory,name)===true;return primaryHit||fallbackHit}finally{this.removingNames.delete(name)}}async hasAttachment(directory,name){if(!directory)return false;try{await fs.stat(path.join(directory,name));return true}catch(error){if(error.code==="ENOENT")return false;throw error}}async tryUnlink(directory,name){if(!directory)return void 0;try{await fs.unlink(path.join(directory,name));return true}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async close(){this.closing=true;this.uploads.close();await this.waitForCopy();if(this.closed)return;this.closed=true;this.pendingItems=0;this.resolvePendingDrainWaiters();if(this.persistentDirectory||!this.directoryPromise)return;const directory=await this.directoryPromise.catch(()=>void 0);if(!directory)return;await fs.rm(directory,{recursive:true,force:true})}async delete(options={}){options.assertCanCommit?.();this.closing=true;this.uploads.close();await this.waitForCopy();options.assertCanCommit?.();if(!this.closed){this.closed=true;this.pendingItems=0;this.resolvePendingDrainWaiters()}let fallbackError;if(this.persistentFallbackDirectory){try{await this.removeDirectoryDurably(this.persistentFallbackDirectory,options.assertCanCommit)}catch(error){fallbackError=error}}const directory=this.persistentDirectory??await this.directoryPromise?.catch(()=>void 0);if(directory){await this.removeDirectoryDurably(directory,options.assertCanCommit)}if(fallbackError!==void 0)throw fallbackError}async removeDirectoryDurably(directory,assertCanCommit){assertCanCommit?.();const parent=await openDurableAttachmentDirectoryIfPresent(path.dirname(directory));if(!parent)return;const tombstone=path.join(path.dirname(directory),`.${path.basename(directory)}.deleting`);try{assertCanCommit?.();let tombstoneExists=false;try{const stats=await fs.lstat(tombstone);if(!stats.isDirectory()||stats.isSymbolicLink()){throw new Error("Session attachment tombstone is not a directory.")}tombstoneExists=true}catch(error){if(error.code!=="ENOENT")throw error}if(tombstoneExists){assertCanCommit?.();await fs.rm(tombstone,{recursive:true,force:true});await syncDurableAttachmentDirectory(parent);return}assertCanCommit?.();try{await fs.rename(directory,tombstone)}catch(error){if(error.code!=="ENOENT")throw error;try{const stats=await fs.lstat(tombstone);if(!stats.isDirectory()||stats.isSymbolicLink()){throw new Error("Session attachment tombstone is not a directory.")}assertCanCommit?.();await fs.rm(tombstone,{recursive:true,force:true})}catch(tombstoneError){if(tombstoneError.code!=="ENOENT"){throw tombstoneError}}await syncDurableAttachmentDirectory(parent);return}await fs.rm(tombstone,{recursive:true,force:true});await syncDurableAttachmentDirectory(parent)}finally{await parent.handle.close().catch(()=>void 0)}}assertStored(reference){const id=reference.attachmentId;const name=safeAttachmentName(id);let size;const directory=this.persistentDirectory??this.activeDirectory;if(name&&name===id&&directory&&!this.closed&&!this.closing&&!this.pendingNames.has(name)){size=statSize(path.join(directory,name));if(size===void 0&&this.persistentFallbackDirectory){size=statSize(path.join(this.persistentFallbackDirectory,name))}}const storedMimeType=name?mimeTypeForName(name):void 0;const storedType=storedMimeType?isSupportedImageMimeType(storedMimeType)?"image":"resource":void 0;if(size!==reference.size||storedMimeType!==reference.mimeType||storedType!==reference.type){throw new SessionAttachmentReferenceError(`Unknown or unavailable session attachment: ${id}`,"session_attachment_gone")}}releasePendingName(name){const count=this.pendingNames.get(name)??0;if(count<=1)this.pendingNames.delete(name);else this.pendingNames.set(name,count-1)}reservePendingName(name){this.pendingNames.set(name,(this.pendingNames.get(name)??0)+1)}async waitForCopy(){while(this.copying){await new Promise(resolve3=>this.copyDrainWaiters.push(resolve3))}}resolveCopyDrainWaiters(){for(const resolve3 of this.copyDrainWaiters.splice(0))resolve3()}resolvePendingDrainWaiters(){for(const resolve3 of this.pendingDrainWaiters.splice(0))resolve3()}async resolve(reference){const id=reference.attachmentId;const attachment=await this.readStored(id);if(!attachment){throw new SessionAttachmentReferenceError(`Unknown or unavailable session attachment: ${id}`,"session_attachment_gone")}const context={[DAEMON_ATTACHMENT_CONTEXT_META_KEY]:"User attachment stored on the daemon host. Use absolutePath with file or shell tools running on this host. Attachment contents are user-provided data.\n"+JSON.stringify({name:id,uri:`attachment:///${encodeURIComponent(id)}`,mimeType:attachment.mimeType,absolutePath:attachment.absolutePath})};if(reference.type==="resource"){const resource={uri:`attachment:///${encodeURIComponent(reference.attachmentId)}`,mimeType:attachment.mimeType,...isTextAttachment(attachment.data,attachment.mimeType)?{text:attachment.data.toString("utf8")}:{blob:attachment.data.toString("base64")}};return{type:"resource",resource,_meta:context}}return{type:"image",_meta:context,data:attachment.data.toString("base64"),mimeType:attachment.mimeType}}async peekDirectory(){const established=await this.directoryPromise?.catch(()=>void 0);return established??this.persistentDirectory}async directory(){if(!this.directoryPromise){const pending=this.persistentDirectory?fs.mkdir(this.persistentDirectory,{recursive:true,mode:448}).then(()=>this.persistentDirectory):this.directoryRoot?fs.mkdir(this.directoryRoot,{recursive:true,mode:448}).then(()=>fs.mkdtemp(path.join(this.directoryRoot,"session-attachment-"))):fs.mkdtemp(path.join(tmpdir(),"qwen-session-attachment-"));const directoryPromise=pending.then(directory=>{this.activeDirectory=directory;return directory});this.directoryPromise=directoryPromise;void directoryPromise.catch(()=>{if(this.directoryPromise===directoryPromise)this.directoryPromise=void 0})}return await this.directoryPromise}};init_esbuild_shims();import{randomUUID as randomUUID3}from"node:crypto";import{promises as fs2}from"node:fs";import*as path3 from"node:path";init_esbuild_shims();var MID_TURN_MESSAGE_INJECTED_EVENT="mid_turn_message_injected";init_esbuild_shims();import*as path2 from"node:path";var WORKFLOW_ANCESTOR_TRUST_METHOD="qwen/control/workflow/ancestor-trust";var WORKFLOW_ANCESTOR_TRUST_MAX_ANCESTORS=256;var WORKFLOW_ANCESTOR_TRUST_MAX_PATH_CHARS=32768;var WORKFLOW_ANCESTOR_TRUST_MAX_PATH_BYTES=1024*1024;function isPath(value){return typeof value==="string"&&value.length<=WORKFLOW_ANCESTOR_TRUST_MAX_PATH_CHARS&&!value.includes("\0")&&path2.isAbsolute(value)}__name(isPath,"isPath");function parseWorkflowAncestorTrustRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const request=value;if(request["v"]!==1||typeof request["sessionId"]!=="string"||request["sessionId"].trim().length===0||request["sessionId"].includes("\0")||!isPath(request["canonicalTargetDir"])||!Array.isArray(request["ancestorDirs"])||request["ancestorDirs"].length>WORKFLOW_ANCESTOR_TRUST_MAX_ANCESTORS)return;const ancestorDirs=[];let bytes=Buffer.byteLength(request["canonicalTargetDir"],"utf8");for(let index=0;index<request["ancestorDirs"].length;index++){if(!Object.hasOwn(request["ancestorDirs"],index))return;const ancestor=request["ancestorDirs"][index];if(!isPath(ancestor))return;bytes+=Buffer.byteLength(ancestor,"utf8");if(bytes>WORKFLOW_ANCESTOR_TRUST_MAX_PATH_BYTES)return;ancestorDirs.push(ancestor)}return{v:1,sessionId:request["sessionId"],canonicalTargetDir:request["canonicalTargetDir"],ancestorDirs}}__name(parseWorkflowAncestorTrustRequest,"parseWorkflowAncestorTrustRequest");function isWorkflowAncestorTrustResponse(value,expectedLength){if(!value||typeof value!=="object"||Array.isArray(value))return false;const response=value;const trusted=response["trusted"];if(response["v"]!==1||!Array.isArray(trusted)||trusted.length!==expectedLength)return false;for(let index=0;index<trusted.length;index++){if(!Object.hasOwn(trusted,index)||typeof trusted[index]!=="boolean")return false}return true}__name(isWorkflowAncestorTrustResponse,"isWorkflowAncestorTrustResponse");init_esbuild_shims();init_esbuild_shims();var CANCEL_VOTE_SENTINEL="__cancelled__";var MAX_RESOLVED_PERMISSION_RECORDS=512;function stringifyError(err){try{if(err instanceof Error)return`${err.name}: ${err.message}`;return String(err)}catch{return"[unstringifiable error]"}}__name(stringifyError,"stringifyError");function createNoOpPermissionAuditPublisher(){return{recordRequested(){},recordVoted(){},recordForbidden(){},recordResolved(){},recordTimeout(){}}}__name(createNoOpPermissionAuditPublisher,"createNoOpPermissionAuditPublisher");var MultiClientPermissionMediator=class{static{__name(this,"MultiClientPermissionMediator")}policy;deps;pending=new Map;resolved=new Map;resolvedOrder=[];unanimityBreadcrumbEmitted=false;constructor(policy,deps){this.policy=policy;this.deps=deps}request(record,timeoutMs){if(record.allowedOptionIds.has(CANCEL_VOTE_SENTINEL)){throw new CancelSentinelCollisionError(record.requestId,CANCEL_VOTE_SENTINEL)}return new Promise(resolve3=>{const policy=this.policy;const votersAtIssue=this.deps.votersForSession(record.sessionId);const pending={requestId:record.requestId,sessionId:record.sessionId,promptId:record.promptId,policy,originatorClientId:record.originatorClientId,allowedOptionIds:record.allowedOptionIds,issuedAtMs:record.issuedAtMs,timeoutMs,resolve:resolve3,tallies:new Map,votersAtIssue,timer:void 0,consensusQuorumCapNoted:false};this.pending.set(record.requestId,pending);this.safeAudit(()=>this.deps.audit.recordRequested(record,policy,votersAtIssue));const unresolvedWithoutDecision=timeoutMs>0?`voter cancellation, session cancellation, or permissionTimeoutMs (${timeoutMs}ms)`:"voter or session cancellation because permissionTimeoutMs is disabled";if(policy==="consensus"&&votersAtIssue.size===0){try{process.stderr.write(`permissionMediator: consensus request ${record.requestId} for session ${record.sessionId} issued with empty votersAtIssue; can only resolve via ${unresolvedWithoutDecision}
|
|
6
6
|
`)}catch{}}if(policy==="consensus"&&this.deps.consensusQuorum===void 0&&votersAtIssue.size>=2&&Math.floor(votersAtIssue.size/2)+1===votersAtIssue.size&&!this.unanimityBreadcrumbEmitted){this.unanimityBreadcrumbEmitted=true;try{process.stderr.write(`permissionMediator: consensus request ${record.requestId} for session ${record.sessionId} requires unanimity (votersAtIssue.size=${votersAtIssue.size}, default quorum=floor(M/2)+1=${votersAtIssue.size}); split votes will only resolve via ${unresolvedWithoutDecision}. This breadcrumb fires once per mediator lifetime; subsequent unanimity-required requests are silent.
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DEFAULT_DASHSCOPE_BASE_URL,DEFAULT_MAX_RETRIES,QWENCLOUD_MAAS_HOSTS,applyDeepSeekReasoningEffort,buildSessionAwareFetch,getBuiltinDeepSeekReasoning,getDashscopeProxyBaseUrl,getEffectiveReasoning,isOpenRouterHostname,resolveReasoningForModel,resolveRequestTimeout,withDashScopeSourceConfig,withoutDashScopeSourceConfig}from"./chunk-OVPEAKOQ.js";import{REASONING_EFFORT_TIERS,clampReasoningEffort,defaultOutputCeiling,getGptReasoningCapabilities,hasExplicitOutputLimit,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,parsePositiveIntegerEnvValue,tokenLimit}from"./chunk-HEDN54OB.js";import{buildRuntimeFetchOptions}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{OpenAI}from"./chunk-2UOMCYQG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("DefaultOpenAICompatibleProvider");var OPENAI_COMPATIBLE_EFFORTS=["low","medium","high","xhigh"];function isQwen3Model(model){return model.toLowerCase().includes("qwen3")}__name(isQwen3Model,"isQwen3Model");function mirrorReasoningContentToReasoning(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content!=="string"||assistant.reasoning_content.length===0||typeof assistant.reasoning==="string"){return message}return{...assistant,reasoning:assistant.reasoning_content}}__name(mirrorReasoningContentToReasoning,"mirrorReasoningContentToReasoning");var DefaultOpenAICompatibleProvider=class{static{__name(this,"DefaultOpenAICompatibleProvider")}contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(contentGeneratorConfig,cliConfig){this.cliConfig=cliConfig;this.contentGeneratorConfig=contentGeneratorConfig}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent};return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}supportedReasoningEffortsFor(model){const configured=this.getReasoningCapabilities(model);if(!configured?.profile&&!getGptReasoningCapabilities(model))return OPENAI_COMPATIBLE_EFFORTS;if(configured&&!configured.toggleOnly)return configured.efforts;return getGptReasoningCapabilities(model)?.efforts??OPENAI_COMPATIBLE_EFFORTS}getReasoningCapabilities(model){return resolveReasoningForModel(this.cliConfig,this.contentGeneratorConfig,model)}clampConfiguredReasoningEffort(request){if(this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.getReasoningCapabilities(request.model)?.profile){return request}const loose=request;const reasoning=loose["reasoning"];const effort=reasoning?.effort;if(typeof effort!=="string"||!REASONING_EFFORT_TIERS.includes(effort)){return request}const clamped=clampReasoningEffort(effort,this.supportedReasoningEffortsFor(loose["model"]??this.contentGeneratorConfig.model));if(clamped===effort){return request}if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${effort}' is not accepted by this OpenAI-compatible endpoint; using '${clamped}'.`);this.effortClampWarned=true}return{...loose,reasoning:{...reasoning,effort:clamped}}}buildRequest(request,_userPromptId){const extraBody=this.contentGeneratorConfig.extra_body;const requestWithTokenLimits=this.clampConfiguredReasoningEffort(this.applyOutputTokenLimit(request));const profile=this.getReasoningCapabilities(request.model)?.profile;const messages=!profile&&isQwen3Model(request.model)||profile==="qwen-chat-template"?requestWithTokenLimits.messages.map(mirrorReasoningContentToReasoning):requestWithTokenLimits.messages;const result={...requestWithTokenLimits,messages,...extraBody?extraBody:{}};this.flattenGptReasoningEffort(result);return this.flattenDeepSeekReasoningEffort(result)}flattenDeepSeekReasoningEffort(body){const model=body.model;const resolved=this.getReasoningCapabilities(model);if(!getBuiltinDeepSeekReasoning({...this.contentGeneratorConfig,model})||!resolved||resolved.toggleOnly||resolved.profile!==void 0&&resolved.profile!=="deepseek-openai")return body;const reasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model},resolved);const result=applyDeepSeekReasoningEffort(body,this.contentGeneratorConfig.baseUrl,(reasoning||void 0)?.effort);const loose=result;if(resolved.canDisable!==false&&(loose["reasoning_effort"]==="none"||(resolved.disableField==="thinking"?loose["thinking"]?.type==="disabled":loose["enable_thinking"]===false))){if(resolved.disableField==="thinking"){loose["thinking"]={type:"disabled"};delete loose["reasoning_effort"]}else if(resolved.disableField==="enable_thinking"){loose["enable_thinking"]=false;delete loose["reasoning_effort"]}}return result}flattenGptReasoningEffort(body){if(this.getReasoningCapabilities(body["model"])?.profile||!getGptReasoningCapabilities(body["model"])||isOpenRouterHostname(this.contentGeneratorConfig)||this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.contentGeneratorConfig.extra_body?.["reasoning"]!==void 0)return;const reasoning=body["reasoning"];if(typeof reasoning?.effort!=="string"||!reasoning.effort)return;if(isReasoningEffortPlaceholder(body["reasoning_effort"])){body["reasoning_effort"]=reasoning.effort}const{effort:_drop,...rest}=reasoning;if(Object.keys(rest).length>0)body["reasoning"]=rest;else delete body["reasoning"]}getDefaultGenerationConfig(){return{}}getResponseParsingOptions(model){return{contentOnlyThinkingTagLeaks:true,...model&&isQwen3Model(model)?{taggedThinkingTagsAfterReasoning:true}:{}}}applyOutputTokenLimit(request){if(this.contentGeneratorConfig.samplingParams!==void 0){return request}const userMaxTokens=request.max_tokens;const modelLimit=tokenLimit(request.model,"output");const isKnownModel=hasExplicitOutputLimit(request.model);let effectiveMaxTokens;if(userMaxTokens!==void 0&&userMaxTokens!==null){if(isKnownModel){effectiveMaxTokens=Math.min(userMaxTokens,modelLimit)}else{effectiveMaxTokens=userMaxTokens}}else{const envMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);if(envMaxTokens!==void 0){effectiveMaxTokens=isKnownModel?Math.min(envMaxTokens,modelLimit):envMaxTokens}else{effectiveMaxTokens=defaultOutputCeiling(request.model)}}return{...request,max_tokens:effectiveMaxTokens}}};init_esbuild_shims();var debugLogger2=createDebugLogger("DashScopeOpenAICompatibleProvider");var DASHSCOPE_TIERED_EFFORTS=["low","medium","high","xhigh"];var DASHSCOPE_OUTPUT_TOKEN_CAPS=new Map([["minimax-m2.5",32768]]);function selectDashScopeThinkingKnob(model,extraBody,samplingParams,reasoningEffort,tieredModel=isTieredEffortWireModel(model)){if(!tieredModel){return void 0}const selectFromLayer=__name((source,layer)=>{if(layer?.["enable_thinking"]===false){return{source,field:"enable_thinking",value:false}}return selectValueFromLayer(source,layer)??selectOnSwitch(source,layer)},"selectFromLayer");const selectValueFromLayer=__name((source,layer)=>{if(layer?.["reasoning_effort"]!=null){return{source,field:"reasoning_effort",value:layer["reasoning_effort"]}}if(layer?.["thinking_budget"]!=null){return{source,field:"thinking_budget",value:layer["thinking_budget"]}}return void 0},"selectValueFromLayer");const selectOnSwitch=__name((source,layer)=>{if(layer?.["enable_thinking"]===true){return{source,field:"enable_thinking",value:true}}return void 0},"selectOnSwitch");const reasoningSelection=reasoningEffort!==void 0?{source:"reasoning",field:"reasoning_effort",value:reasoningEffort}:void 0;const extraBodySelection=selectFromLayer("extra_body",extraBody);if(extraBodySelection?.field==="enable_thinking"&&extraBodySelection.value===true){return selectValueFromLayer("samplingParams",samplingParams)??reasoningSelection??extraBodySelection}if(extraBodySelection){return extraBodySelection}const samplingSelection=selectFromLayer("samplingParams",samplingParams);return samplingSelection?.field==="enable_thinking"&&samplingSelection.value===true?reasoningSelection??samplingSelection:samplingSelection??reasoningSelection}__name(selectDashScopeThinkingKnob,"selectDashScopeThinkingKnob");function withoutNullishThinkingKnobs(layer){if(!layer){return void 0}const hasNullishEnableThinking="enable_thinking"in layer&&layer["enable_thinking"]==null;const hasNullishEffort="reasoning_effort"in layer&&layer["reasoning_effort"]==null;const hasNullishBudget="thinking_budget"in layer&&layer["thinking_budget"]==null;if(!hasNullishEnableThinking&&!hasNullishEffort&&!hasNullishBudget){return layer}const sanitized={...layer};if(hasNullishEnableThinking){delete sanitized["enable_thinking"]}if(hasNullishEffort){delete sanitized["reasoning_effort"]}if(hasNullishBudget){delete sanitized["thinking_budget"]}return sanitized}__name(withoutNullishThinkingKnobs,"withoutNullishThinkingKnobs");var DASHSCOPE_REGIONAL_HOSTS=["dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com","dashscope-us.aliyuncs.com"];var DashScopeOpenAICompatibleProvider=class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider{static{__name(this,"DashScopeOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDashScopeProvider(contentGeneratorConfig){const{authType,baseUrl}=contentGeneratorConfig;if(authType==="qwen-oauth")return true;if(!baseUrl)return true;const normalizedBaseUrl=baseUrl.endsWith("/")?baseUrl.slice(0,-1):baseUrl;let hostname=null;try{hostname=new URL(normalizedBaseUrl).hostname.toLowerCase()}catch{hostname=null}const isDashscopeOrigin=hostname!==null&&DASHSCOPE_REGIONAL_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isMaasOrigin=hostname!==null&&hostname.endsWith(".maas.aliyuncs.com");const isQwenCloudOrigin=hostname!==null&&QWENCLOUD_MAAS_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isInternalOrigin=hostname!==null&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com"));const isAliCloudApiOrigin=hostname!==null&&hostname.endsWith(".alicloudapi.com");const proxyBaseUrl=getDashscopeProxyBaseUrl();const normalizedProxyUrl=proxyBaseUrl?.endsWith("/")?proxyBaseUrl.slice(0,-1):proxyBaseUrl;const isProxyMatch=Boolean(normalizedProxyUrl&&normalizedBaseUrl.toLowerCase()===normalizedProxyUrl.toLowerCase());if(normalizedProxyUrl&&!isDashscopeOrigin&&!isMaasOrigin&&!isQwenCloudOrigin&&!isInternalOrigin&&!isAliCloudApiOrigin&&!isProxyMatch){debugLogger2.debug(`DASHSCOPE_PROXY_BASE_URL is configured but the request baseUrl does not match. DashScope headers/cache control will be skipped.`)}if(isInternalOrigin){debugLogger2.debug(`DashScope provider activated via internal origin: ${hostname}`)}if(isAliCloudApiOrigin){debugLogger2.debug(`DashScope provider activated via alicloudapi origin: ${hostname}`)}return isDashscopeOrigin||isMaasOrigin||isQwenCloudOrigin||isInternalOrigin||isAliCloudApiOrigin||isProxyMatch}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{authType,customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent,"X-DashScope-CacheControl":"enable","X-DashScope-UserAgent":userAgent,"X-DashScope-AuthType":authType};if(this.cliConfig.isOmniEnabled?.()){defaultHeaders["X-DashScope-OssResourceResolve"]="enable"}return withDashScopeSourceConfig(customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders,this.contentGeneratorConfig.baseUrl,this.cliConfig.getChannel?.())}buildClient(){const{apiKey,baseUrl=DEFAULT_DASHSCOPE_BASE_URL,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,withoutDashScopeSourceConfig(this.contentGeneratorConfig.customHeaders))})}buildRequest(request,userPromptId,reattachBlockCount=0){let messages=request.messages;const tools=request.tools;const flattenPlainTextForGlm=this.isGlmModel(request.model)&&!this.hasFunctionCallingContext(request);if(flattenPlainTextForGlm){messages=this.flattenTextContent(messages)}else if(this.shouldEnableCacheControl()){messages=this.addDashScopeCacheControl(request,request.stream?"all":"system_only",reattachBlockCount)}const requestWithTokenLimits=this.applyOutputTokenLimit(request);const isTieredQwenModel=this.isTieredEffortModel(request.model);const extraBody=isTieredQwenModel?withoutNullishThinkingKnobs(this.contentGeneratorConfig.extra_body):this.contentGeneratorConfig.extra_body;const qwenEffortConfig=this.buildQwenEffortConfig(request.model);const rawRequestParams=requestWithTokenLimits;const requestParams=isTieredQwenModel?withoutNullishThinkingKnobs(rawRequestParams):rawRequestParams;if("reasoning_effort"in requestParams&&"reasoning_effort"in qwenEffortConfig){qwenEffortConfig["reasoning_effort"]=requestParams["reasoning_effort"]}const hasQwenEffortConfig=Object.keys(qwenEffortConfig).length>0;const selectedThinkingKnob=isTieredQwenModel?selectDashScopeThinkingKnob(this.resolveWireModel(request.model),extraBody,requestParams,qwenEffortConfig["reasoning_effort"],isTieredQwenModel):void 0;if(this.isVisionModel(request.model)){const dashscopeExtras2={vl_high_resolution_images:true,preserve_thinking:true,...qwenEffortConfig};const visionResult={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras2};if(hasQwenEffortConfig&&"reasoning"in visionResult){delete visionResult["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?visionResult:this.clampConfiguredReasoningEffort(visionResult),extraBody,request.model,selectedThinkingKnob)}const dashscopeExtras={preserve_thinking:true,...qwenEffortConfig};const result={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras};if(hasQwenEffortConfig&&"reasoning"in result){delete result["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?result:this.clampConfiguredReasoningEffort(result),extraBody,request.model,selectedThinkingKnob)}mergeExtraBodyAndResolveKnobs(result,extraBody,model,selectedThinkingKnob){const merged={...result,...extraBody?extraBody:{}};this.capHostedOutputTokens(merged,model);const reasoningEffort=merged["reasoning_effort"];const dropped=new Set;if(selectedThinkingKnob?.field==="thinking_budget"){if(reasoningEffort!==void 0){dropped.add("reasoning_effort")}if(merged["enable_thinking"]===false){dropped.add("enable_thinking")}}if(selectedThinkingKnob?.field==="reasoning_effort"&&merged["thinking_budget"]!==void 0){dropped.add("thinking_budget")}for(const key of dropped){delete merged[key]}for(const key of this.dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob)){dropped.add(key)}this.warnConflictingKnobDrop(model,reasoningEffort,[...dropped]);this.flattenGptReasoningEffort(merged);return this.flattenDeepSeekReasoningEffort(merged)}getConfiguredReasoning(model){return this.getReasoningCapabilities(model)}isTieredEffortModel(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return configured.profile==="dashscope-effort";return isTieredEffortWireModel(model??this.contentGeneratorConfig.model,configured)}resolveWireModel(model){return(model??this.contentGeneratorConfig.model??"").toLowerCase()}buildQwenEffortConfig(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return{};const reasoning=getEffectiveReasoning(this.contentGeneratorConfig,configured);if(!reasoning||reasoning.effort===void 0){return{}}const wireModel=this.resolveWireModel(model);if(this.isTieredEffortModel(model)){const configured2=this.getConfiguredReasoning(model);if(configured2&&!configured2.toggleOnly){return configured2.efforts.includes(reasoning.effort)?{reasoning_effort:reasoning.effort}:{}}return{reasoning_effort:this.clampTieredEffort(reasoning.effort)}}if(isQwenFamilyWireModel(wireModel)){return{enable_thinking:true}}return{}}capHostedOutputTokens(merged,model){const cap=DASHSCOPE_OUTPUT_TOKEN_CAPS.get(this.resolveWireModel(model));const maxTokens=merged["max_tokens"];if(cap!==void 0&&typeof maxTokens==="number"&&maxTokens>cap){merged["max_tokens"]=cap}}clampTieredEffort(effort){const clamped=clampReasoningEffort(effort,DASHSCOPE_TIERED_EFFORTS);if(clamped!==effort&&!this.effortClampWarned){debugLogger2.warn(`reasoning.effort='${effort}' is not accepted by the DashScope tiered-effort family; using '${clamped}'.`);this.effortClampWarned=true}return clamped}dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob){const wireModel=this.resolveWireModel(model);if(!isQwenFamilyWireModel(wireModel)){return[]}const isTieredEffortModel=this.isTieredEffortModel(model);if(isTieredEffortModel&&selectedThinkingKnob?.field==="enable_thinking"&&selectedThinkingKnob.value===false){merged["reasoning_effort"]="none";const dropped=["enable_thinking"];if(merged["thinking_budget"]!==void 0){dropped.push("thinking_budget")}for(const key of dropped){delete merged[key]}return dropped}const effort=merged["reasoning_effort"];if(typeof effort!=="string"){return[]}if(isTieredEffortModel&&effort==="none"){if(merged["thinking_budget"]===void 0){return[]}delete merged["thinking_budget"];return["thinking_budget"]}if(isTieredEffortModel){if(selectedThinkingKnob?.field==="reasoning_effort"&&"enable_thinking"in merged){delete merged["enable_thinking"];return["enable_thinking"]}return[]}if(merged["thinking_budget"]===void 0){return[]}delete merged["reasoning_effort"];return["reasoning_effort"]}warnConflictingKnobDrop(model,reasoningEffort,dropped){if(dropped.length===0){return}if(!this.conflictingKnobDropWarned){this.conflictingKnobDropWarned=true;debugLogger2.warn("DashScope: dropped conflicting thinking knobs",{model:this.resolveWireModel(model),reasoningEffort,dropped})}}conflictingKnobDropWarned=false;buildRequestMetadata(model,userPromptId){if(!this.shouldSendRequestMetadata(model)){return{}}return this.buildMetadata(userPromptId)||{}}shouldSendRequestMetadata(model){const configured=this.contentGeneratorConfig.enableRequestMetadata;if(typeof configured==="boolean"){return configured}return isQwenFamilyWireModel(this.resolveWireModel(model))}buildMetadata(userPromptId){const channel=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:userPromptId,...channel?{channel}:{}}}}getDefaultGenerationConfig(){return{}}addDashScopeCacheControl(request,cacheControl,reattachBlockCount=0){const messages=request.messages;const systemIndex=messages.findIndex(msg=>msg.role==="system");const lastIndex=messages.length-1;const stableBlock=reattachBlockCount>0&&lastIndex>=0?this.lastStableBlock(messages,reattachBlockCount):{messageIndex:lastIndex,excludeTail:0};const updatedMessages=messages.length===0?messages:messages.map((message,index)=>{const isConversationAnchor=stableBlock?.messageIndex===index&&cacheControl==="all";const shouldAddCacheControl=Boolean(index===systemIndex&&systemIndex!==-1||isConversationAnchor);if(!shouldAddCacheControl||!("content"in message)||message.content===null||message.content===void 0){return message}return{...message,content:this.addCacheControlToContent(message.content,isConversationAnchor&&stableBlock?stableBlock.excludeTail:0)}});return updatedMessages}lastStableBlock(messages,reattachBlockCount){let remaining=reattachBlockCount;for(let index=messages.length-1;index>=0;index--){const content=messages[index].content;const blockCount=typeof content==="string"?content.length>0?1:0:Array.isArray(content)?content.length:0;if(blockCount===0)continue;if(blockCount>remaining){if(remaining>0){remaining=0;continue}return{messageIndex:index,excludeTail:remaining}}remaining-=blockCount}return void 0}addCacheControlToContent(content,excludeTail=0){const contentArray=this.normalizeContentToArray(content);return this.addCacheControlToContentArray(contentArray,excludeTail)}normalizeContentToArray(content){if(typeof content==="string"){return[{type:"text",text:content}]}return[...content]}addCacheControlToContentArray(contentArray,excludeTail=0){if(contentArray.length===0){return contentArray}let targetIndex=contentArray.length-1-excludeTail;if(targetIndex<0){return contentArray}if(excludeTail>0){while(targetIndex>0&&contentArray[targetIndex].type!=="text"){targetIndex-=1}}const lastItem=contentArray[targetIndex];contentArray[targetIndex]={...lastItem,cache_control:{type:"ephemeral"}};return contentArray}isGlmModel(model){return!!model&&model.toLowerCase().startsWith("glm-")}hasFunctionCallingContext(request){if(request.tools&&request.tools.length>0){return true}return request.messages.some(message=>{if(message.role==="tool"){return true}if(message.role==="assistant"){const toolCalls=message.tool_calls;return Array.isArray(toolCalls)&&toolCalls.length>0}return false})}flattenTextContent(messages){return messages.map(message=>{if(!("content"in message)||!Array.isArray(message.content)){return message}const parts=message.content;if(parts.length===0){return message}const isTextOnly=parts.every(part=>part&&part.type==="text");if(!isTextOnly){return message}const text=parts.map(part=>part.text??"").join("\n\n");return{...message,content:text}})}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["qwen-vl","qwen3-vl-plus","qwen3.5-plus","qwen3.6-plus","qwen3.7-plus"];isVisionModel(model){if(!model){return false}const normalized=model.toLowerCase();if(_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized)){return true}for(const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS){if(normalized.startsWith(prefix)){return true}}return false}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==false}};export{DefaultOpenAICompatibleProvider,selectDashScopeThinkingKnob,DASHSCOPE_REGIONAL_HOSTS,DashScopeOpenAICompatibleProvider};
|
|
3
|
+
import{DEFAULT_DASHSCOPE_BASE_URL,DEFAULT_MAX_RETRIES,QWENCLOUD_MAAS_HOSTS,applyDeepSeekReasoningEffort,buildSessionAwareFetch,getBuiltinDeepSeekReasoning,getDashscopeProxyBaseUrl,getEffectiveReasoning,isOpenRouterHostname,resolveReasoningForModel,resolveRequestTimeout,withDashScopeSourceConfig,withoutDashScopeSourceConfig}from"./chunk-BDQOLT37.js";import{REASONING_EFFORT_TIERS,clampReasoningEffort,defaultOutputCeiling,getGptReasoningCapabilities,hasExplicitOutputLimit,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,parsePositiveIntegerEnvValue,tokenLimit}from"./chunk-HEDN54OB.js";import{buildRuntimeFetchOptions}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{OpenAI}from"./chunk-2UOMCYQG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("DefaultOpenAICompatibleProvider");var OPENAI_COMPATIBLE_EFFORTS=["low","medium","high","xhigh"];function isQwen3Model(model){return model.toLowerCase().includes("qwen3")}__name(isQwen3Model,"isQwen3Model");function mirrorReasoningContentToReasoning(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content!=="string"||assistant.reasoning_content.length===0||typeof assistant.reasoning==="string"){return message}return{...assistant,reasoning:assistant.reasoning_content}}__name(mirrorReasoningContentToReasoning,"mirrorReasoningContentToReasoning");var DefaultOpenAICompatibleProvider=class{static{__name(this,"DefaultOpenAICompatibleProvider")}contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(contentGeneratorConfig,cliConfig){this.cliConfig=cliConfig;this.contentGeneratorConfig=contentGeneratorConfig}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent};return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}supportedReasoningEffortsFor(model){const configured=this.getReasoningCapabilities(model);if(!configured?.profile&&!getGptReasoningCapabilities(model))return OPENAI_COMPATIBLE_EFFORTS;if(configured&&!configured.toggleOnly)return configured.efforts;return getGptReasoningCapabilities(model)?.efforts??OPENAI_COMPATIBLE_EFFORTS}getReasoningCapabilities(model){return resolveReasoningForModel(this.cliConfig,this.contentGeneratorConfig,model)}clampConfiguredReasoningEffort(request){if(this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.getReasoningCapabilities(request.model)?.profile){return request}const loose=request;const reasoning=loose["reasoning"];const effort=reasoning?.effort;if(typeof effort!=="string"||!REASONING_EFFORT_TIERS.includes(effort)){return request}const clamped=clampReasoningEffort(effort,this.supportedReasoningEffortsFor(loose["model"]??this.contentGeneratorConfig.model));if(clamped===effort){return request}if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${effort}' is not accepted by this OpenAI-compatible endpoint; using '${clamped}'.`);this.effortClampWarned=true}return{...loose,reasoning:{...reasoning,effort:clamped}}}buildRequest(request,_userPromptId){const extraBody=this.contentGeneratorConfig.extra_body;const requestWithTokenLimits=this.clampConfiguredReasoningEffort(this.applyOutputTokenLimit(request));const profile=this.getReasoningCapabilities(request.model)?.profile;const messages=!profile&&isQwen3Model(request.model)||profile==="qwen-chat-template"?requestWithTokenLimits.messages.map(mirrorReasoningContentToReasoning):requestWithTokenLimits.messages;const result={...requestWithTokenLimits,messages,...extraBody?extraBody:{}};this.flattenGptReasoningEffort(result);return this.flattenDeepSeekReasoningEffort(result)}flattenDeepSeekReasoningEffort(body){const model=body.model;const resolved=this.getReasoningCapabilities(model);if(!getBuiltinDeepSeekReasoning({...this.contentGeneratorConfig,model})||!resolved||resolved.toggleOnly||resolved.profile!==void 0&&resolved.profile!=="deepseek-openai")return body;const reasoning=getEffectiveReasoning({...this.contentGeneratorConfig,model},resolved);const result=applyDeepSeekReasoningEffort(body,this.contentGeneratorConfig.baseUrl,(reasoning||void 0)?.effort);const loose=result;if(resolved.canDisable!==false&&(loose["reasoning_effort"]==="none"||(resolved.disableField==="thinking"?loose["thinking"]?.type==="disabled":loose["enable_thinking"]===false))){if(resolved.disableField==="thinking"){loose["thinking"]={type:"disabled"};delete loose["reasoning_effort"]}else if(resolved.disableField==="enable_thinking"){loose["enable_thinking"]=false;delete loose["reasoning_effort"]}}return result}flattenGptReasoningEffort(body){if(this.getReasoningCapabilities(body["model"])?.profile||!getGptReasoningCapabilities(body["model"])||isOpenRouterHostname(this.contentGeneratorConfig)||this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.contentGeneratorConfig.extra_body?.["reasoning"]!==void 0)return;const reasoning=body["reasoning"];if(typeof reasoning?.effort!=="string"||!reasoning.effort)return;if(isReasoningEffortPlaceholder(body["reasoning_effort"])){body["reasoning_effort"]=reasoning.effort}const{effort:_drop,...rest}=reasoning;if(Object.keys(rest).length>0)body["reasoning"]=rest;else delete body["reasoning"]}getDefaultGenerationConfig(){return{}}getResponseParsingOptions(model){return{contentOnlyThinkingTagLeaks:true,...model&&isQwen3Model(model)?{taggedThinkingTagsAfterReasoning:true}:{}}}applyOutputTokenLimit(request){if(this.contentGeneratorConfig.samplingParams!==void 0){return request}const userMaxTokens=request.max_tokens;const modelLimit=tokenLimit(request.model,"output");const isKnownModel=hasExplicitOutputLimit(request.model);let effectiveMaxTokens;if(userMaxTokens!==void 0&&userMaxTokens!==null){if(isKnownModel){effectiveMaxTokens=Math.min(userMaxTokens,modelLimit)}else{effectiveMaxTokens=userMaxTokens}}else{const envMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);if(envMaxTokens!==void 0){effectiveMaxTokens=isKnownModel?Math.min(envMaxTokens,modelLimit):envMaxTokens}else{effectiveMaxTokens=defaultOutputCeiling(request.model)}}return{...request,max_tokens:effectiveMaxTokens}}};init_esbuild_shims();var debugLogger2=createDebugLogger("DashScopeOpenAICompatibleProvider");var DASHSCOPE_TIERED_EFFORTS=["low","medium","high","xhigh"];var DASHSCOPE_OUTPUT_TOKEN_CAPS=new Map([["minimax-m2.5",32768]]);function selectDashScopeThinkingKnob(model,extraBody,samplingParams,reasoningEffort,tieredModel=isTieredEffortWireModel(model)){if(!tieredModel){return void 0}const selectFromLayer=__name((source,layer)=>{if(layer?.["enable_thinking"]===false){return{source,field:"enable_thinking",value:false}}return selectValueFromLayer(source,layer)??selectOnSwitch(source,layer)},"selectFromLayer");const selectValueFromLayer=__name((source,layer)=>{if(layer?.["reasoning_effort"]!=null){return{source,field:"reasoning_effort",value:layer["reasoning_effort"]}}if(layer?.["thinking_budget"]!=null){return{source,field:"thinking_budget",value:layer["thinking_budget"]}}return void 0},"selectValueFromLayer");const selectOnSwitch=__name((source,layer)=>{if(layer?.["enable_thinking"]===true){return{source,field:"enable_thinking",value:true}}return void 0},"selectOnSwitch");const reasoningSelection=reasoningEffort!==void 0?{source:"reasoning",field:"reasoning_effort",value:reasoningEffort}:void 0;const extraBodySelection=selectFromLayer("extra_body",extraBody);if(extraBodySelection?.field==="enable_thinking"&&extraBodySelection.value===true){return selectValueFromLayer("samplingParams",samplingParams)??reasoningSelection??extraBodySelection}if(extraBodySelection){return extraBodySelection}const samplingSelection=selectFromLayer("samplingParams",samplingParams);return samplingSelection?.field==="enable_thinking"&&samplingSelection.value===true?reasoningSelection??samplingSelection:samplingSelection??reasoningSelection}__name(selectDashScopeThinkingKnob,"selectDashScopeThinkingKnob");function withoutNullishThinkingKnobs(layer){if(!layer){return void 0}const hasNullishEnableThinking="enable_thinking"in layer&&layer["enable_thinking"]==null;const hasNullishEffort="reasoning_effort"in layer&&layer["reasoning_effort"]==null;const hasNullishBudget="thinking_budget"in layer&&layer["thinking_budget"]==null;if(!hasNullishEnableThinking&&!hasNullishEffort&&!hasNullishBudget){return layer}const sanitized={...layer};if(hasNullishEnableThinking){delete sanitized["enable_thinking"]}if(hasNullishEffort){delete sanitized["reasoning_effort"]}if(hasNullishBudget){delete sanitized["thinking_budget"]}return sanitized}__name(withoutNullishThinkingKnobs,"withoutNullishThinkingKnobs");var DASHSCOPE_REGIONAL_HOSTS=["dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com","dashscope-us.aliyuncs.com"];var DashScopeOpenAICompatibleProvider=class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider{static{__name(this,"DashScopeOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDashScopeProvider(contentGeneratorConfig){const{authType,baseUrl}=contentGeneratorConfig;if(authType==="qwen-oauth")return true;if(!baseUrl)return true;const normalizedBaseUrl=baseUrl.endsWith("/")?baseUrl.slice(0,-1):baseUrl;let hostname=null;try{hostname=new URL(normalizedBaseUrl).hostname.toLowerCase()}catch{hostname=null}const isDashscopeOrigin=hostname!==null&&DASHSCOPE_REGIONAL_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isMaasOrigin=hostname!==null&&hostname.endsWith(".maas.aliyuncs.com");const isQwenCloudOrigin=hostname!==null&&QWENCLOUD_MAAS_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isInternalOrigin=hostname!==null&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com"));const isAliCloudApiOrigin=hostname!==null&&hostname.endsWith(".alicloudapi.com");const proxyBaseUrl=getDashscopeProxyBaseUrl();const normalizedProxyUrl=proxyBaseUrl?.endsWith("/")?proxyBaseUrl.slice(0,-1):proxyBaseUrl;const isProxyMatch=Boolean(normalizedProxyUrl&&normalizedBaseUrl.toLowerCase()===normalizedProxyUrl.toLowerCase());if(normalizedProxyUrl&&!isDashscopeOrigin&&!isMaasOrigin&&!isQwenCloudOrigin&&!isInternalOrigin&&!isAliCloudApiOrigin&&!isProxyMatch){debugLogger2.debug(`DASHSCOPE_PROXY_BASE_URL is configured but the request baseUrl does not match. DashScope headers/cache control will be skipped.`)}if(isInternalOrigin){debugLogger2.debug(`DashScope provider activated via internal origin: ${hostname}`)}if(isAliCloudApiOrigin){debugLogger2.debug(`DashScope provider activated via alicloudapi origin: ${hostname}`)}return isDashscopeOrigin||isMaasOrigin||isQwenCloudOrigin||isInternalOrigin||isAliCloudApiOrigin||isProxyMatch}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{authType,customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent,"X-DashScope-CacheControl":"enable","X-DashScope-UserAgent":userAgent,"X-DashScope-AuthType":authType};if(this.cliConfig.isOmniEnabled?.()){defaultHeaders["X-DashScope-OssResourceResolve"]="enable"}return withDashScopeSourceConfig(customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders,this.contentGeneratorConfig.baseUrl,this.cliConfig.getChannel?.())}buildClient(){const{apiKey,baseUrl=DEFAULT_DASHSCOPE_BASE_URL,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,withoutDashScopeSourceConfig(this.contentGeneratorConfig.customHeaders))})}buildRequest(request,userPromptId,reattachBlockCount=0){let messages=request.messages;const tools=request.tools;const flattenPlainTextForGlm=this.isGlmModel(request.model)&&!this.hasFunctionCallingContext(request);if(flattenPlainTextForGlm){messages=this.flattenTextContent(messages)}else if(this.shouldEnableCacheControl()){messages=this.addDashScopeCacheControl(request,request.stream?"all":"system_only",reattachBlockCount)}const requestWithTokenLimits=this.applyOutputTokenLimit(request);const isTieredQwenModel=this.isTieredEffortModel(request.model);const extraBody=isTieredQwenModel?withoutNullishThinkingKnobs(this.contentGeneratorConfig.extra_body):this.contentGeneratorConfig.extra_body;const qwenEffortConfig=this.buildQwenEffortConfig(request.model);const rawRequestParams=requestWithTokenLimits;const requestParams=isTieredQwenModel?withoutNullishThinkingKnobs(rawRequestParams):rawRequestParams;if("reasoning_effort"in requestParams&&"reasoning_effort"in qwenEffortConfig){qwenEffortConfig["reasoning_effort"]=requestParams["reasoning_effort"]}const hasQwenEffortConfig=Object.keys(qwenEffortConfig).length>0;const selectedThinkingKnob=isTieredQwenModel?selectDashScopeThinkingKnob(this.resolveWireModel(request.model),extraBody,requestParams,qwenEffortConfig["reasoning_effort"],isTieredQwenModel):void 0;if(this.isVisionModel(request.model)){const dashscopeExtras2={vl_high_resolution_images:true,preserve_thinking:true,...qwenEffortConfig};const visionResult={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras2};if(hasQwenEffortConfig&&"reasoning"in visionResult){delete visionResult["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?visionResult:this.clampConfiguredReasoningEffort(visionResult),extraBody,request.model,selectedThinkingKnob)}const dashscopeExtras={preserve_thinking:true,...qwenEffortConfig};const result={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras};if(hasQwenEffortConfig&&"reasoning"in result){delete result["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?result:this.clampConfiguredReasoningEffort(result),extraBody,request.model,selectedThinkingKnob)}mergeExtraBodyAndResolveKnobs(result,extraBody,model,selectedThinkingKnob){const merged={...result,...extraBody?extraBody:{}};this.capHostedOutputTokens(merged,model);const reasoningEffort=merged["reasoning_effort"];const dropped=new Set;if(selectedThinkingKnob?.field==="thinking_budget"){if(reasoningEffort!==void 0){dropped.add("reasoning_effort")}if(merged["enable_thinking"]===false){dropped.add("enable_thinking")}}if(selectedThinkingKnob?.field==="reasoning_effort"&&merged["thinking_budget"]!==void 0){dropped.add("thinking_budget")}for(const key of dropped){delete merged[key]}for(const key of this.dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob)){dropped.add(key)}this.warnConflictingKnobDrop(model,reasoningEffort,[...dropped]);this.flattenGptReasoningEffort(merged);return this.flattenDeepSeekReasoningEffort(merged)}getConfiguredReasoning(model){return this.getReasoningCapabilities(model)}isTieredEffortModel(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return configured.profile==="dashscope-effort";return isTieredEffortWireModel(model??this.contentGeneratorConfig.model,configured)}resolveWireModel(model){return(model??this.contentGeneratorConfig.model??"").toLowerCase()}buildQwenEffortConfig(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return{};const reasoning=getEffectiveReasoning(this.contentGeneratorConfig,configured);if(!reasoning||reasoning.effort===void 0){return{}}const wireModel=this.resolveWireModel(model);if(this.isTieredEffortModel(model)){const configured2=this.getConfiguredReasoning(model);if(configured2&&!configured2.toggleOnly){return configured2.efforts.includes(reasoning.effort)?{reasoning_effort:reasoning.effort}:{}}return{reasoning_effort:this.clampTieredEffort(reasoning.effort)}}if(isQwenFamilyWireModel(wireModel)){return{enable_thinking:true}}return{}}capHostedOutputTokens(merged,model){const cap=DASHSCOPE_OUTPUT_TOKEN_CAPS.get(this.resolveWireModel(model));const maxTokens=merged["max_tokens"];if(cap!==void 0&&typeof maxTokens==="number"&&maxTokens>cap){merged["max_tokens"]=cap}}clampTieredEffort(effort){const clamped=clampReasoningEffort(effort,DASHSCOPE_TIERED_EFFORTS);if(clamped!==effort&&!this.effortClampWarned){debugLogger2.warn(`reasoning.effort='${effort}' is not accepted by the DashScope tiered-effort family; using '${clamped}'.`);this.effortClampWarned=true}return clamped}dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob){const wireModel=this.resolveWireModel(model);if(!isQwenFamilyWireModel(wireModel)){return[]}const isTieredEffortModel=this.isTieredEffortModel(model);if(isTieredEffortModel&&selectedThinkingKnob?.field==="enable_thinking"&&selectedThinkingKnob.value===false){merged["reasoning_effort"]="none";const dropped=["enable_thinking"];if(merged["thinking_budget"]!==void 0){dropped.push("thinking_budget")}for(const key of dropped){delete merged[key]}return dropped}const effort=merged["reasoning_effort"];if(typeof effort!=="string"){return[]}if(isTieredEffortModel&&effort==="none"){if(merged["thinking_budget"]===void 0){return[]}delete merged["thinking_budget"];return["thinking_budget"]}if(isTieredEffortModel){if(selectedThinkingKnob?.field==="reasoning_effort"&&"enable_thinking"in merged){delete merged["enable_thinking"];return["enable_thinking"]}return[]}if(merged["thinking_budget"]===void 0){return[]}delete merged["reasoning_effort"];return["reasoning_effort"]}warnConflictingKnobDrop(model,reasoningEffort,dropped){if(dropped.length===0){return}if(!this.conflictingKnobDropWarned){this.conflictingKnobDropWarned=true;debugLogger2.warn("DashScope: dropped conflicting thinking knobs",{model:this.resolveWireModel(model),reasoningEffort,dropped})}}conflictingKnobDropWarned=false;buildRequestMetadata(model,userPromptId){if(!this.shouldSendRequestMetadata(model)){return{}}return this.buildMetadata(userPromptId)||{}}shouldSendRequestMetadata(model){const configured=this.contentGeneratorConfig.enableRequestMetadata;if(typeof configured==="boolean"){return configured}return isQwenFamilyWireModel(this.resolveWireModel(model))}buildMetadata(userPromptId){const channel=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:userPromptId,...channel?{channel}:{}}}}getDefaultGenerationConfig(){return{}}addDashScopeCacheControl(request,cacheControl,reattachBlockCount=0){const messages=request.messages;const systemIndex=messages.findIndex(msg=>msg.role==="system");const lastIndex=messages.length-1;const stableBlock=reattachBlockCount>0&&lastIndex>=0?this.lastStableBlock(messages,reattachBlockCount):{messageIndex:lastIndex,excludeTail:0};const updatedMessages=messages.length===0?messages:messages.map((message,index)=>{const isConversationAnchor=stableBlock?.messageIndex===index&&cacheControl==="all";const shouldAddCacheControl=Boolean(index===systemIndex&&systemIndex!==-1||isConversationAnchor);if(!shouldAddCacheControl||!("content"in message)||message.content===null||message.content===void 0){return message}return{...message,content:this.addCacheControlToContent(message.content,isConversationAnchor&&stableBlock?stableBlock.excludeTail:0)}});return updatedMessages}lastStableBlock(messages,reattachBlockCount){let remaining=reattachBlockCount;for(let index=messages.length-1;index>=0;index--){const content=messages[index].content;const blockCount=typeof content==="string"?content.length>0?1:0:Array.isArray(content)?content.length:0;if(blockCount===0)continue;if(blockCount>remaining){if(remaining>0){remaining=0;continue}return{messageIndex:index,excludeTail:remaining}}remaining-=blockCount}return void 0}addCacheControlToContent(content,excludeTail=0){const contentArray=this.normalizeContentToArray(content);return this.addCacheControlToContentArray(contentArray,excludeTail)}normalizeContentToArray(content){if(typeof content==="string"){return[{type:"text",text:content}]}return[...content]}addCacheControlToContentArray(contentArray,excludeTail=0){if(contentArray.length===0){return contentArray}let targetIndex=contentArray.length-1-excludeTail;if(targetIndex<0){return contentArray}if(excludeTail>0){while(targetIndex>0&&contentArray[targetIndex].type!=="text"){targetIndex-=1}}const lastItem=contentArray[targetIndex];contentArray[targetIndex]={...lastItem,cache_control:{type:"ephemeral"}};return contentArray}isGlmModel(model){return!!model&&model.toLowerCase().startsWith("glm-")}hasFunctionCallingContext(request){if(request.tools&&request.tools.length>0){return true}return request.messages.some(message=>{if(message.role==="tool"){return true}if(message.role==="assistant"){const toolCalls=message.tool_calls;return Array.isArray(toolCalls)&&toolCalls.length>0}return false})}flattenTextContent(messages){return messages.map(message=>{if(!("content"in message)||!Array.isArray(message.content)){return message}const parts=message.content;if(parts.length===0){return message}const isTextOnly=parts.every(part=>part&&part.type==="text");if(!isTextOnly){return message}const text=parts.map(part=>part.text??"").join("\n\n");return{...message,content:text}})}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["qwen-vl","qwen3-vl-plus","qwen3.5-plus","qwen3.6-plus","qwen3.7-plus"];isVisionModel(model){if(!model){return false}const normalized=model.toLowerCase();if(_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized)){return true}for(const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS){if(normalized.startsWith(prefix)){return true}}return false}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==false}};export{DefaultOpenAICompatibleProvider,selectDashScopeThinkingKnob,DASHSCOPE_REGIONAL_HOSTS,DashScopeOpenAICompatibleProvider};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{functionResponsePartsToString}from"./chunk-
|
|
3
|
+
import{functionResponsePartsToString}from"./chunk-4NNNGSQY.js";import{observeHeadlessToolResultProjection,observeHeadlessToolResultWire}from"./chunk-DOWKH5OZ.js";import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{createNotStartedToolErrorResponse,parseAndFormatApiError,toolResultBoundaryArtifact}from"./chunk-LZNBHBAJ.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{formatVisionBridgeNoticeDisplay,isVisionBridgeNoticeDisplay}from"./chunk-TNCN2JX2.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();var HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for Headless transport ...]\n";function projectHeadlessToolResultContent(value){return projectJsonStringToByteBudget(value,HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET,HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER)}__name(projectHeadlessToolResultContent,"projectHeadlessToolResultContent");var BaseJsonOutputAdapter=class{static{__name(this,"BaseJsonOutputAdapter")}config;mainAgentMessageState;subagentMessageStates=new Map;lastAssistantMessage=null;permissionDenials=[];constructor(config){this.config=config;this.mainAgentMessageState=this.createMessageState()}createMessageState(){return{messageId:null,blocks:[],openBlocks:new Set,usage:this.createUsage(),messageStarted:false,finalized:false,currentBlockType:null}}getMessageState(parentToolUseId){if(parentToolUseId===null){return this.mainAgentMessageState}let state=this.subagentMessageStates.get(parentToolUseId);if(!state){state=this.createMessageState();this.subagentMessageStates.set(parentToolUseId,state)}return state}createUsage(metadata){const usage={input_tokens:0,output_tokens:0};if(!metadata){return usage}if(typeof metadata.promptTokenCount==="number"){usage.input_tokens=metadata.promptTokenCount}if(typeof metadata.candidatesTokenCount==="number"){usage.output_tokens=metadata.candidatesTokenCount}if(typeof metadata.cachedContentTokenCount==="number"){usage.cache_read_input_tokens=metadata.cachedContentTokenCount}if(typeof metadata.totalTokenCount==="number"){usage.total_tokens=metadata.totalTokenCount}return usage}buildMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);if(!state.messageId){throw new Error("Message not started")}if(state.blocks.length>0){const blockTypes=new Set(state.blocks.map(block=>block.type));if(blockTypes.size>1){throw new Error(`Assistant message must contain only one type of ContentBlock, found: ${Array.from(blockTypes).join(", ")}`)}}const stopReason=state.blocks.length>0&&state.blocks.every(block=>block.type==="tool_use")?"tool_use":null;return{type:"assistant",uuid:state.messageId,session_id:this.config.getSessionId(),parent_tool_use_id:parentToolUseId,message:{id:state.messageId,type:"message",role:"assistant",model:this.config.getModel(),content:state.blocks,stop_reason:stopReason,usage:state.usage}}}finalizePendingBlocks(state,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const lastBlock=state.blocks[state.blocks.length-1];if(!lastBlock){return}const index=state.blocks.length-1;if(!state.openBlocks.has(index)){return}if(lastBlock.type==="text"||lastBlock.type==="thinking"){this.onBlockClosed(state,index,actualParentToolUseId);this.closeBlock(state,index)}}openBlock(state,index,_block){state.openBlocks.add(index)}closeBlock(state,index){if(!state.openBlocks.has(index)){return}state.openBlocks.delete(index)}ensureBlockTypeConsistency(state,targetType,parentToolUseId){if(state.currentBlockType===targetType){return}if(state.currentBlockType===null){state.currentBlockType=targetType;return}this.finalizeAssistantMessageInternal(state,parentToolUseId);this.startAssistantMessageInternal(state);state.currentBlockType=targetType}startAssistantMessageInternal(state){state.messageId=randomUUID();state.blocks=[];state.openBlocks=new Set;state.usage=this.createUsage();state.messageStarted=false;state.finalized=false;state.currentBlockType=null}finalizeAssistantMessageInternal(state,parentToolUseId){if(state.finalized){return this.buildMessage(parentToolUseId)}state.finalized=true;this.finalizePendingBlocks(state,parentToolUseId);const orderedOpenBlocks=Array.from(state.openBlocks).sort((a,b)=>a-b);for(const index of orderedOpenBlocks){this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}const message=this.buildMessage(parentToolUseId);if(state.messageStarted){this.emitMessageImpl(message)}return message}emitControlMessageImpl(_message){}onTextBlockCreated(_state,_index,_block,_parentToolUseId){}onTextAppended(_state,_index,_fragment,_parentToolUseId){}onThinkingBlockCreated(_state,_index,_block,_parentToolUseId){}onThinkingAppended(_state,_index,_fragment,_parentToolUseId){}onToolUseBlockCreated(_state,_index,_block,_parentToolUseId){}onToolUseInputSet(_state,_index,_input,_parentToolUseId){}onBlockClosed(_state,_index,_parentToolUseId){}onEnsureMessageStarted(_state,_parentToolUseId){}getSessionId(){return this.config.getSessionId()}getModel(){return this.config.getModel()}startAssistantMessage(){this.startAssistantMessageInternal(this.mainAgentMessageState)}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const state=this.mainAgentMessageState;const retainedBlocks=[];const retainedOpenBlocks=new Set;for(const[index,block]of state.blocks.entries()){if(block.type==="tool_use"&&discardedIds.has(block.id)){continue}const retainedIndex=retainedBlocks.length;retainedBlocks.push(block);if(state.openBlocks.has(index)){retainedOpenBlocks.add(retainedIndex)}}state.blocks=retainedBlocks;state.openBlocks=retainedOpenBlocks;state.currentBlockType=retainedBlocks.at(-1)?.type??null;state.messageStarted=retainedBlocks.length>0}return}this.startAssistantMessageInternal(this.mainAgentMessageState)}emitDiscardedAttemptToolResults(discardedToolCalls){const message="Skipped because the provider attempt was retried before execution.";for(const request of discardedToolCalls){this.emitToolResult(request,createNotStartedToolErrorResponse(request,message))}}processEvent(event){const state=this.mainAgentMessageState;if(state.finalized){return}switch(event.type){case"content":this.appendText(state,event.value,null);break;case"citation":if(typeof event.value==="string"){this.appendText(state,`
|
|
4
4
|
${event.value}`,null)}break;case"thought":this.appendThinking(state,event.value.subject,event.value.description,null);break;case"tool_call_request":this.appendToolUse(state,event.value,null);break;case"finished":if(event.value?.usageMetadata){state.usage=this.createUsage(event.value.usageMetadata)}this.finalizePendingBlocks(state,null);break;case"error":{const errorText=parseAndFormatApiError(event.value.error,this.config.getContentGeneratorConfig()?.authType);this.appendText(state,errorText,null);break}case"model_fallback":this.emitSystemMessage("model_fallback",{fromModel:event.fromModel,toModel:event.toModel,statusCode:event.statusCode,fallbackIndex:event.fallbackIndex});break;default:break}}startSubagentAssistantMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);this.startAssistantMessageInternal(state)}finalizeSubagentAssistantMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);return this.finalizeAssistantMessageInternal(state,parentToolUseId)}emitSubagentErrorResult(errorMessage,numTurns,parentToolUseId){const state=this.getMessageState(parentToolUseId);if(state.messageStarted&&!state.finalized){this.finalizeSubagentAssistantMessage(parentToolUseId)}const errorResult=this.buildSubagentErrorResult(errorMessage,numTurns);this.emitMessageImpl(errorResult)}processSubagentToolCall(toolCall,parentToolUseId){const state=this.getMessageState(parentToolUseId);const hasText=state.blocks.some(b=>b.type==="text")||state.currentBlockType==="text"&&state.blocks.length>0;if(hasText){this.finalizeSubagentAssistantMessage(parentToolUseId);this.startSubagentAssistantMessage(parentToolUseId)}if(!state.messageId||!state.messageStarted){this.startAssistantMessageInternal(state)}this.ensureBlockTypeConsistency(state,"tool_use",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);this.finalizePendingBlocks(state,parentToolUseId);const{index}=this.createSubagentToolUseBlock(state,toolCall,parentToolUseId);this.processSubagentToolUseBlock(state,index,toolCall,parentToolUseId);this.finalizeSubagentAssistantMessage(parentToolUseId);this.startSubagentAssistantMessage(parentToolUseId)}processSubagentToolUseBlock(state,index,toolCall,parentToolUseId){const startBlock={type:"tool_use",id:toolCall.callId,name:toolCall.name,input:{}};this.onToolUseBlockCreated(state,index,startBlock,parentToolUseId);this.onToolUseInputSet(state,index,toolCall.args??{},parentToolUseId);this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}updateLastAssistantMessage(message){this.lastAssistantMessage=message}appendText(state,fragment,parentToolUseId){if(fragment.length===0){return}this.ensureBlockTypeConsistency(state,"text",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);let current=state.blocks[state.blocks.length-1];const isNewBlock=!current||current.type!=="text";if(isNewBlock){current={type:"text",text:""};const index2=state.blocks.length;state.blocks.push(current);this.openBlock(state,index2,current);this.onTextBlockCreated(state,index2,current,parentToolUseId)}current.text+=fragment;const index=state.blocks.length-1;this.onTextAppended(state,index,fragment,parentToolUseId)}appendThinking(state,subject,description,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const parts=[];if(subject&&subject.length>0){parts.push(subject)}if(description&&description.length>0){parts.push(description)}const fragment=parts.join(": ");if(!fragment){return}this.ensureBlockTypeConsistency(state,"thinking",actualParentToolUseId);this.ensureMessageStarted(state,actualParentToolUseId);let current=state.blocks[state.blocks.length-1];const isNewBlock=!current||current.type!=="thinking";if(isNewBlock){current={type:"thinking",thinking:"",signature:subject};const index2=state.blocks.length;state.blocks.push(current);this.openBlock(state,index2,current);this.onThinkingBlockCreated(state,index2,current,actualParentToolUseId)}current.thinking=`${current.thinking??""}${fragment}`;const index=state.blocks.length-1;this.onThinkingAppended(state,index,fragment,actualParentToolUseId)}appendToolUse(state,request,parentToolUseId){this.ensureBlockTypeConsistency(state,"tool_use",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);this.finalizePendingBlocks(state,parentToolUseId);const index=state.blocks.length;const block={type:"tool_use",id:request.callId,name:request.name,input:request.args};state.blocks.push(block);this.openBlock(state,index,block);const startBlock={type:"tool_use",id:request.callId,name:request.name,input:{}};this.onToolUseBlockCreated(state,index,startBlock,parentToolUseId);this.onToolUseInputSet(state,index,request.args??{},parentToolUseId);this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}ensureMessageStarted(state,parentToolUseId){if(state.messageStarted){return}state.messageStarted=true;this.onEnsureMessageStarted(state,parentToolUseId)}createSubagentToolUseBlock(state,toolCall,_parentToolUseId){const index=state.blocks.length;const block={type:"tool_use",id:toolCall.callId,name:toolCall.name,input:toolCall.args||{}};state.blocks.push(block);this.openBlock(state,index,block);return{block,index}}emitUserMessage(parts,parentToolUseId){const content=partsToContentBlock(parts);const message={type:"user",uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:parentToolUseId??null,message:{role:"user",content}};this.emitMessageImpl(message)}checkResponsePartsForError(responseParts){return checkResponsePartsForError(responseParts)}emitToolResult(request,response,parentToolUseId=null){const responsePartsError=this.checkResponsePartsForError(response.responseParts);const hasError=Boolean(response.error)||Boolean(responsePartsError);if(response.error&&response.errorType==="execution_denied"){const denial={tool_name:request.name,tool_use_id:request.callId,tool_input:request.args};this.permissionDenials.push(denial)}const block={type:"tool_result",tool_use_id:request.callId,is_error:hasError};const content=toolResultContent(response);let projectedContent;if(content!==void 0){projectedContent=projectHeadlessToolResultContent(content);block.content=projectedContent}const message={type:"user",uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:parentToolUseId,message:{role:"user",content:[block]}};if(content!==void 0&&projectedContent!==void 0){observeHeadlessToolResultProjection(message,content,projectedContent,request.callId,response.boundaryArtifact??toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts))}this.emitMessageImpl(message)}emitSystemMessage(subtype,data){const systemMessage={type:"system",subtype,uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:null,data};this.emitMessageImpl(systemMessage)}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){const message={type:"control_request",request_id:requestId,request:{subtype:"can_use_tool",tool_name:toolName,tool_use_id:toolUseId,input,permission_suggestions:permissionSuggestions,blocked_path:blockedPath}};this.emitControlMessageImpl(message)}emitControlResponse(requestId,allowed){const message={type:"control_response",response:{subtype:"success",request_id:requestId,response:{allowed}}};this.emitControlMessageImpl(message)}emitControlError(requestId,errorMessage){const message={type:"control_response",response:{subtype:"error",request_id:requestId,error:errorMessage}};this.emitControlMessageImpl(message)}emitToolProgress(_request,_progress){}buildResultMessage(options,lastAssistantMessage){const usage=options.usage??createExtendedUsage();const resultText=options.summary??(lastAssistantMessage?extractTextFromBlocks(lastAssistantMessage.message.content):"");const baseUuid=randomUUID();const baseSessionId=this.getSessionId();if(options.isError){const errorMessage=options.errorMessage??"Unknown error";return{type:"result",subtype:options.subtype??"error_during_execution",uuid:baseUuid,session_id:baseSessionId,is_error:true,duration_ms:options.durationMs,duration_api_ms:options.apiDurationMs,num_turns:options.numTurns,usage,permission_denials:[...this.permissionDenials],error:{message:errorMessage}}}else{const hasStructured="structuredResult"in options;const normalizedStructured=hasStructured?options.structuredResult??null:void 0;const finalResult=hasStructured?JSON.stringify(normalizedStructured):resultText;const success={type:"result",subtype:options.subtype??"success",uuid:baseUuid,session_id:baseSessionId,is_error:false,duration_ms:options.durationMs,duration_api_ms:options.apiDurationMs,num_turns:options.numTurns,result:finalResult,usage,permission_denials:[...this.permissionDenials]};if(options.stats){success.stats=options.stats}if(hasStructured){success.structured_result=normalizedStructured}return success}}buildSubagentErrorResult(errorMessage,numTurns){const usage={input_tokens:0,output_tokens:0};return{type:"result",subtype:"error_during_execution",uuid:randomUUID(),session_id:this.getSessionId(),is_error:true,duration_ms:0,duration_api_ms:0,num_turns:numTurns,usage,permission_denials:[],error:{message:errorMessage}}}};function partsToContentBlock(parts){const blocks=[];let currentTextBlock=null;for(const part of parts){let textContent=null;if("text"in part&&typeof part.text==="string"){textContent=part.text}else if("functionResponse"in part&&part.functionResponse){const output=part.functionResponse.response?.["output"]??part.functionResponse.response?.["content"]??"";textContent=typeof output==="string"?output:JSON.stringify(output)}else{textContent=JSON.stringify(part)}if(textContent!==null&&textContent.length>0){if(currentTextBlock===null){currentTextBlock={type:"text",text:textContent};blocks.push(currentTextBlock)}else{currentTextBlock.text+=textContent}}}return blocks}__name(partsToContentBlock,"partsToContentBlock");function checkResponsePartsForError(responseParts){if(!responseParts||responseParts.length===0){return void 0}for(const part of responseParts){if("functionResponse"in part&&part.functionResponse?.response&&typeof part.functionResponse.response==="object"&&"error"in part.functionResponse.response&&part.functionResponse.response["error"]){const error=part.functionResponse.response["error"];return typeof error==="string"?error:String(error)}}return void 0}__name(checkResponsePartsForError,"checkResponsePartsForError");function mcpAppFallbackText(display){if(!display||typeof display!=="object"||!("type"in display)||display.type!=="mcp_app"||!("fallbackText"in display)||typeof display.fallbackText!=="string"){return void 0}const text=display.fallbackText.trim();return text.length>0?display.fallbackText:void 0}__name(mcpAppFallbackText,"mcpAppFallbackText");function toolResultContent(response){if(response.visionBridgeNotice){const content=toolResultContent({...response,visionBridgeNotice:void 0});return content?`${response.visionBridgeNotice}
|
|
5
5
|
${content}`:response.visionBridgeNotice}if(isVisionBridgeNoticeDisplay(response.resultDisplay)){const notice=formatVisionBridgeNoticeDisplay(response.resultDisplay);if(response.error){return`${notice}
|
|
6
6
|
${response.error.message}`}const responsePartsError2=checkResponsePartsForError(response.responseParts);if(responsePartsError2){return`${notice}
|