@qwen-code/qwen-code 0.25.4-preview.0 → 0.25.4-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled/browser-use/runtime/native-host.js +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/cli.js +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/lib/xdg-open +0 -0
- package/bundled/browser-use/runtime/scripts/native-host-setup.js +0 -0
- package/chunks/{MaxSizedBox-M27H235V.js → MaxSizedBox-E4RKSA7W.js} +1 -1
- package/chunks/{StandaloneSessionPicker-LWWDDYOW.js → StandaloneSessionPicker-2D3UKLVS.js} +1 -1
- package/chunks/{acp-subagent-executor-NUV52JVS.js → acp-subagent-executor-UQYUN6AB.js} +1 -1
- package/chunks/{acpAgent-IUJDXLZM.js → acpAgent-P7WGK2BP.js} +3 -3
- package/chunks/{advisor-MSOUBMJ6.js → advisor-GCH2MBXT.js} +1 -1
- package/chunks/{agent-H7XIWYWQ.js → agent-57T4YAYP.js} +1 -1
- package/chunks/{agent-headless-XDN3D3S3.js → agent-headless-IBON3A7N.js} +1 -1
- package/chunks/{agent-host-client-AZP3PZXS.js → agent-host-client-LE7P72FR.js} +1 -1
- package/chunks/{agent-host-connections-JRVX7I6I.js → agent-host-connections-4DM57L26.js} +1 -1
- package/chunks/{anthropicContentGenerator-N7TV53LD.js → anthropicContentGenerator-C4TPFXUK.js} +1 -1
- package/chunks/{batch-MKSJFJUH.js → batch-YJJGMJWO.js} +1 -1
- package/chunks/{bridge-GNMKKHQ4.js → bridge-FIO2ENBG.js} +1 -1
- package/chunks/{channel-settings-store-Y4YCS7JX.js → channel-settings-store-TEBCLK2B.js} +1 -1
- package/chunks/{chunk-GPOUP5OK.js → chunk-27MTSS3T.js} +1 -1
- package/chunks/{chunk-C4ANA47H.js → chunk-2MGCRPM3.js} +1 -1
- package/chunks/{chunk-6DQNNRRC.js → chunk-2WBKWPSO.js} +1 -1
- package/chunks/{chunk-CATL2PQS.js → chunk-34WLYVDK.js} +5 -5
- package/chunks/{chunk-B7CXPNCV.js → chunk-3J2YNEHG.js} +1 -1
- package/chunks/{chunk-VTNHPXNL.js → chunk-3TBFTELA.js} +1 -1
- package/chunks/{chunk-7JT34VGK.js → chunk-46I6JBVL.js} +1 -1
- package/chunks/{chunk-FEMWELCV.js → chunk-4ZKFLOEH.js} +1 -1
- package/chunks/{chunk-7AYXAVTZ.js → chunk-5DUJIOOX.js} +3 -3
- package/chunks/{chunk-6QLHJSVW.js → chunk-6PWOLWTH.js} +1 -1
- package/chunks/{chunk-OW4QBRSR.js → chunk-6UZ65Z2P.js} +1 -1
- package/chunks/{chunk-V2JZO5MS.js → chunk-7DSJE3CL.js} +1 -1
- package/chunks/{chunk-TJMHIEYI.js → chunk-7LCY7GGX.js} +1 -1
- package/chunks/{chunk-TLJHBK3A.js → chunk-7RNTXEWH.js} +1 -1
- package/chunks/{chunk-YZ7OO4AQ.js → chunk-A3IF6IOB.js} +1 -1
- package/chunks/{chunk-VTF6AVZB.js → chunk-A6OQSOUO.js} +1 -1
- package/chunks/{chunk-Y7YDHCON.js → chunk-AJ6JUUP7.js} +1 -1
- package/chunks/{chunk-QTMHQGWQ.js → chunk-AOMEBVFW.js} +1 -1
- package/chunks/{chunk-KVTG2ZNH.js → chunk-AUNAS7AS.js} +1 -1
- package/chunks/{chunk-BOFD4CN3.js → chunk-AVIDPC5K.js} +1 -1
- package/chunks/{chunk-ETYTRKB2.js → chunk-BOLPBPWC.js} +1 -1
- package/chunks/{chunk-OAPA66DR.js → chunk-BQQBFDBY.js} +1 -1
- package/chunks/{chunk-NOS2CNOI.js → chunk-CN22ATWU.js} +1 -1
- package/chunks/{chunk-XYBEQRSZ.js → chunk-DIHJELGW.js} +1 -1
- package/chunks/{chunk-XCEL3EDX.js → chunk-DJFCI7TU.js} +1 -1
- package/chunks/{chunk-VKEL2XTM.js → chunk-DQPDMFS3.js} +1 -1
- package/chunks/{chunk-DJRFEZBY.js → chunk-DSYKB77N.js} +1 -1
- package/chunks/{chunk-UEW7Q26E.js → chunk-EDNOGHMN.js} +2 -2
- package/chunks/{chunk-RXNGYG64.js → chunk-EE36D2EV.js} +1 -1
- package/chunks/{chunk-NZKX7HYL.js → chunk-EGQDN3FJ.js} +1 -1
- package/chunks/{chunk-DFRSQK5Q.js → chunk-FHFBCG6N.js} +1 -1
- package/chunks/{chunk-PECV2VVZ.js → chunk-GI6T3RBV.js} +1 -1
- package/chunks/{chunk-37BNHIUB.js → chunk-GOLT5JXA.js} +1 -1
- package/chunks/{chunk-KITFF4GL.js → chunk-IDGXHMNL.js} +1 -1
- package/chunks/{chunk-6HIOSLUM.js → chunk-IIZWK7ZP.js} +1 -1
- package/chunks/{chunk-MPGEAX4K.js → chunk-IJC6ZH2S.js} +1 -1
- package/chunks/{chunk-TLYJVB5H.js → chunk-IO6LSEPV.js} +1 -1
- package/chunks/{chunk-QIJKEZZR.js → chunk-IYVNCBMS.js} +1 -1
- package/chunks/{chunk-S4GOHFRN.js → chunk-JHGOWK7M.js} +1 -1
- package/chunks/{chunk-GHRD2MMC.js → chunk-JRJY343T.js} +1 -1
- package/chunks/{chunk-WCYZSCG7.js → chunk-JVUXQU3W.js} +1 -1
- package/chunks/{chunk-DMCTJUIJ.js → chunk-K2K2YYWO.js} +1 -1
- package/chunks/{chunk-37OHWQHB.js → chunk-KF6HU732.js} +2 -2
- package/chunks/{chunk-5LSV73BG.js → chunk-KVWUOBH7.js} +1 -1
- package/chunks/{chunk-7V4BAHFT.js → chunk-LBWBGFHD.js} +1 -1
- package/chunks/{chunk-RKPHDO42.js → chunk-LDXZT3SG.js} +5 -5
- package/chunks/{chunk-BGFA2SAQ.js → chunk-LFOZ6AIH.js} +1 -1
- package/chunks/{chunk-4322TZID.js → chunk-LGQHT42X.js} +2 -2
- package/chunks/{chunk-PDXZ2CUO.js → chunk-M3O2XDHA.js} +1 -1
- package/chunks/{chunk-47K2NMP6.js → chunk-M3UC46LS.js} +1 -1
- package/chunks/{chunk-UFRY7WND.js → chunk-M7JLPTQI.js} +1 -1
- package/chunks/{chunk-SATEKHQP.js → chunk-MBUXP3IS.js} +1 -1
- package/chunks/{chunk-RN6JS263.js → chunk-MEZA3VVH.js} +1 -1
- package/chunks/{chunk-OBFKP7RI.js → chunk-MWN6TR36.js} +1 -1
- package/chunks/{chunk-VHJ43ZYJ.js → chunk-O7XRQWCG.js} +1 -1
- package/chunks/{chunk-H224LNV3.js → chunk-OYFRLT5E.js} +1 -1
- package/chunks/{chunk-3NWFV2YF.js → chunk-PMBGV76N.js} +1 -1
- package/chunks/{chunk-YFAPACDE.js → chunk-PVM4IVFL.js} +6 -6
- package/chunks/{chunk-7WS2EYMQ.js → chunk-PWHD4NK3.js} +1 -1
- package/chunks/{chunk-JZIQSEFO.js → chunk-Q54NROBX.js} +1 -1
- package/chunks/{chunk-FCLAPJ22.js → chunk-QE7R4DPT.js} +1 -1
- package/chunks/{chunk-J6TW7GNF.js → chunk-QIUTQICH.js} +1 -1
- package/chunks/{chunk-TWDCN5H2.js → chunk-QK63EULE.js} +1 -1
- package/chunks/{chunk-HZZT75LI.js → chunk-QTAC4W7J.js} +1 -1
- package/chunks/{chunk-P7DIAJNX.js → chunk-R7HBR4QQ.js} +1 -1
- package/chunks/{chunk-U2FJSKS3.js → chunk-RHEMFKMX.js} +1 -1
- package/chunks/{chunk-TRRY3QMM.js → chunk-RL57IU47.js} +1 -1
- package/chunks/{chunk-SPWDYRDH.js → chunk-S2OOQRLJ.js} +1 -1
- package/chunks/{chunk-QBRADQ7L.js → chunk-SWTMWNTZ.js} +1 -1
- package/chunks/{chunk-AZUDF52L.js → chunk-SXTKQHFZ.js} +1 -1
- package/chunks/{chunk-5RQRSPPD.js → chunk-T5S3MJIK.js} +1 -1
- package/chunks/{chunk-I3ORWQ2U.js → chunk-UDGDEIBB.js} +1 -1
- package/chunks/{chunk-EMDEBV33.js → chunk-UIFBF3E7.js} +1 -1
- package/chunks/{chunk-BGEMWNES.js → chunk-UQDPWI7D.js} +1 -1
- package/chunks/{chunk-I5LKOTZT.js → chunk-VON4MVIM.js} +1 -1
- package/chunks/{chunk-HJPO6MEW.js → chunk-W5D2T2JK.js} +1 -1
- package/chunks/{chunk-F6YYDRMH.js → chunk-WNGYYU67.js} +1 -1
- package/chunks/{chunk-S2GKUZZZ.js → chunk-WO3F62ZD.js} +1 -1
- package/chunks/{chunk-K7KW3ZJQ.js → chunk-WVY5Q6YY.js} +1 -1
- package/chunks/{chunk-GH6DPLWU.js → chunk-Y4Q667BW.js} +1 -1
- package/chunks/{chunk-FH74N7Y7.js → chunk-YJLMFUCS.js} +2 -2
- package/chunks/{chunk-C3Y2S5AM.js → chunk-YKHRCSKP.js} +1 -1
- package/chunks/{chunk-P4UJ7CXJ.js → chunk-YLIS36QA.js} +1 -1
- package/chunks/{chunk-4QIFOIBS.js → chunk-YVZ4XZRB.js} +1 -1
- package/chunks/{chunk-KGRD6G5J.js → chunk-Z27JJPKN.js} +1 -1
- package/chunks/{chunk-KOHHDB2L.js → chunk-ZCIS6MJZ.js} +1 -1
- package/chunks/{chunk-QNNDZYVW.js → chunk-ZHLQ222N.js} +1 -1
- package/chunks/{chunk-KWRZ3WJO.js → chunk-ZP7MTWMR.js} +1 -1
- package/chunks/{codex-subagent-executor-H44VDB5E.js → codex-subagent-executor-6OJVGF2S.js} +1 -1
- package/chunks/{config-utils-4X4SV4RL.js → config-utils-FI3A4QAN.js} +1 -1
- package/chunks/{contextCommand-4KVOHTAJ.js → contextCommand-YEBZQHG4.js} +1 -1
- package/chunks/{core-runtime-4RARI4NX.js → core-runtime-CFMHUAS7.js} +1 -1
- package/chunks/{create-sub-session-CNSRJFYG.js → create-sub-session-G26337FT.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-6XQQPP2H.js → daemon-git-worktree-guard-ITU6NQIV.js} +1 -1
- package/chunks/{daemon-status-provider-PRTEQT5T.js → daemon-status-provider-CSWRGMRX.js} +1 -1
- package/chunks/{daemon-trust-policy-GXKJVZDU.js → daemon-trust-policy-IYD7NOGK.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-L2ORKHMM.js → daemon-trust-policy-monitor-OWUP5SYB.js} +1 -1
- package/chunks/{deferred-core-runtime-RZQFUSPX.js → deferred-core-runtime-CVCQU7O4.js} +1 -1
- package/chunks/{edit-W44XQCIS.js → edit-7YBQLILC.js} +1 -1
- package/chunks/{enterPlanMode-B456A2XO.js → enterPlanMode-L3PVSD2P.js} +1 -1
- package/chunks/{environment-DSGQSQFS.js → environment-BVEOYQHO.js} +1 -1
- package/chunks/{errors-KL725247.js → errors-VQWBGR6D.js} +1 -1
- package/chunks/{execution-tool-KT3EBWHG.js → execution-tool-P7CBXSGZ.js} +1 -1
- package/chunks/{execution-worker-LPQ4HMN4.js → execution-worker-RZXNYK4B.js} +1 -1
- package/chunks/{exitPlanMode-JLKS76IA.js → exitPlanMode-MBUTM3NW.js} +1 -1
- package/chunks/{fast-path-5UD52IHH.js → fast-path-T2FDUSHV.js} +1 -1
- package/chunks/{glob-LYA2H6X3.js → glob-RH7XXSYE.js} +1 -1
- package/chunks/{goal-tools-SHSIDLZX.js → goal-tools-K6XBCE5E.js} +1 -1
- package/chunks/{handleAutoUpdate-T4RE6CZN.js → handleAutoUpdate-PG7R3KPH.js} +1 -1
- package/chunks/{i18n-5DK327WA.js → i18n-EGTBMA3N.js} +1 -1
- package/chunks/{initializer-TJGE4OJA.js → initializer-RIKH4PCP.js} +1 -1
- package/chunks/{installationInfo-MZ62GDIC.js → installationInfo-BBADHZLD.js} +1 -1
- package/chunks/{interactive-mod-session-YCUBQ6RM.js → interactive-mod-session-7RDKAHZ4.js} +1 -1
- package/chunks/{list-4L3LYDQM.js → list-YEGWEHJX.js} +1 -1
- package/chunks/{llm-3JQWBZXV.js → llm-D3LHPY27.js} +4 -4
- package/chunks/{llm-content-generator-6UPJWPOM.js → llm-content-generator-BLTBMV66.js} +1 -1
- package/chunks/{loadedSettingsAdapter-STPKAFJG.js → loadedSettingsAdapter-PLGMKMFO.js} +1 -1
- package/chunks/{local-execution-environment-IE5BOI7Y.js → local-execution-environment-4LDKFNC4.js} +1 -1
- package/chunks/{loggingContentGenerator-4KKWPZJA.js → loggingContentGenerator-376R7DRI.js} +1 -1
- package/chunks/{manage-memory-CRV5SXZZ.js → manage-memory-2ZTIVKNU.js} +1 -1
- package/chunks/{managed-execution-engine-FHLEWVND.js → managed-execution-engine-5LOM3MXG.js} +1 -1
- package/chunks/{managed-npm-update-BRHPOKDU.js → managed-npm-update-2C5JYEXW.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-GIQKZ5BH.js → managed-runtime-attestation-worker-R2FECMZK.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-P72BT46H.js → managed-runtime-bootstrap-KPLGH4UE.js} +1 -1
- package/chunks/{managed-runtime-session-worker-IYCJDB5K.js → managed-runtime-session-worker-EVKNPK3V.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-ONT4V5ZG.js → managed-runtime-ssh-worker-IA4HZ3PD.js} +1 -1
- package/chunks/{mcp-NXCQVE2Y.js → mcp-S67IJLI6.js} +1 -1
- package/chunks/{model-call-collection-3DNL45M5.js → model-call-collection-6OGPDTPG.js} +1 -1
- package/chunks/{model-configuration-6HRNYBWV.js → model-configuration-6RWVBOQS.js} +1 -1
- package/chunks/{modelConfigUtils-SKBN64ZW.js → modelConfigUtils-M3TVVYAO.js} +1 -1
- package/chunks/{monitor-7I7Q73UR.js → monitor-ZHOFTN7N.js} +1 -1
- package/chunks/{nonInteractiveCli-YLYRJUBE.js → nonInteractiveCli-6SUGPTJ4.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-U2ASWT63.js → nonInteractiveToolExecutor-SAHBGO3A.js} +1 -1
- package/chunks/{notebook-edit-WAD7IQCF.js → notebook-edit-ETUOQH6G.js} +1 -1
- package/chunks/{omni-POUUDVU3.js → omni-HV2UBGMZ.js} +1 -1
- package/chunks/{openaiContentGenerator-L7X6IVPL.js → openaiContentGenerator-RZCG7E4M.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-7XCMFI6P.js → openaiResponsesContentGenerator-X23L5JV3.js} +1 -1
- package/chunks/{pidfile-MQQT2ZDA.js → pidfile-26WXQCHG.js} +1 -1
- package/chunks/{processUtils-OZLF72NC.js → processUtils-WXLFGNBT.js} +1 -1
- package/chunks/{prompt-terminal-ledger-IYUF6SUU.js → prompt-terminal-ledger-EIZZHF4A.js} +1 -1
- package/chunks/{qwenContentGenerator-DKH3ILUO.js → qwenContentGenerator-GOY7Y6KH.js} +1 -1
- package/chunks/{reactive-degrade-KSNGHMBN.js → reactive-degrade-MNMTTHO5.js} +1 -1
- package/chunks/{read-file-VEELW4OQ.js → read-file-OJNGPNTQ.js} +1 -1
- package/chunks/{resumeHistoryUtils-4SFDTBXU.js → resumeHistoryUtils-QWOWF4VY.js} +1 -1
- package/chunks/{review-QA6HRLVU.js → review-5S24HP2V.js} +1 -1
- package/chunks/{ripGrep-4J6ASSE3.js → ripGrep-Y4PY2MQF.js} +1 -1
- package/chunks/{run-qwen-serve-EJ67LA5O.js → run-qwen-serve-EOUUDZUK.js} +2 -2
- package/chunks/{runtime-6E2FSB5U.js → runtime-ZBPOQX6E.js} +1 -1
- package/chunks/{sandboxConfig-4VE4LNRI.js → sandboxConfig-R7KDS3P5.js} +1 -1
- package/chunks/{scheduled-tasks-GM5EJMK7.js → scheduled-tasks-Q6V7D6K6.js} +1 -1
- package/chunks/{scheduler-HOSVIIOE.js → scheduler-EBQY6BOK.js} +1 -1
- package/chunks/{search-memory-HEAQCHIK.js → search-memory-HX6E23JC.js} +1 -1
- package/chunks/{send-message-FAQ7XEZ5.js → send-message-OZCCCH2F.js} +1 -1
- package/chunks/{serve-VNKPOWSW.js → serve-CMGCI4BK.js} +1 -1
- package/chunks/{server-U2XBJLOV.js → server-7LOAKPDN.js} +3 -3
- package/chunks/{session-AZGROSFX.js → session-LVQYZSJE.js} +1 -1
- package/chunks/{session-attachments-root-6M2ECUNK.js → session-attachments-root-NWG7JOMN.js} +1 -1
- package/chunks/{session-execution-engine-selector-PYDVOSJF.js → session-execution-engine-selector-PHH47ZMA.js} +1 -1
- package/chunks/{session-pr-refresh-3IS7DLEV.js → session-pr-refresh-5IACZPCY.js} +1 -1
- package/chunks/{sessionService-3FWNA4ZB.js → sessionService-7PFAWLHC.js} +1 -1
- package/chunks/{settings-VHKT7JJC.js → settings-CPZBOHN5.js} +1 -1
- package/chunks/{shell-TYOPVB7H.js → shell-A7NLPS2W.js} +1 -1
- package/chunks/{skill-GJQIE5AX.js → skill-VGANGVOD.js} +1 -1
- package/chunks/{skill-settings-76NI6SF3.js → skill-settings-TSZO3X6N.js} +1 -1
- package/chunks/{spawnChannel-FMSYLDKB.js → spawnChannel-2JQYNQKT.js} +1 -1
- package/chunks/{standalone-update-BPZQDQHD.js → standalone-update-QXC3RM6I.js} +1 -1
- package/chunks/{start-opentui-ui-X7XYV5N3.js → start-opentui-ui-BKJ4JHVK.js} +1 -1
- package/chunks/{startInteractiveUI-UZDF4JUB.js → startInteractiveUI-4QIPR7ZY.js} +1 -1
- package/chunks/{team-create-RFZNEF76.js → team-create-5MU6BGXX.js} +1 -1
- package/chunks/{team-plan-approval-MGW3JGSC.js → team-plan-approval-NZUJ6FSA.js} +1 -1
- package/chunks/{terminal-image-renderer-3UED5GZV.js → terminal-image-renderer-CTMJULJ2.js} +1 -1
- package/chunks/{theme-manager-SF6FSSZW.js → theme-manager-6H7GA6QR.js} +1 -1
- package/chunks/{tool-call-W2CJR74U.js → tool-call-XG4CAD5X.js} +1 -1
- package/chunks/{tool-result-media-XSFON2ZQ.js → tool-result-media-RJ5ONO7R.js} +1 -1
- package/chunks/{tool-search-7GY5YTOU.js → tool-search-KBINGEWV.js} +1 -1
- package/chunks/{total-session-admission-OATGW6M5.js → total-session-admission-XNWYCO7G.js} +1 -1
- package/chunks/{trustedFolders-AM4PSGUB.js → trustedFolders-JT5MOB3A.js} +1 -1
- package/chunks/{update-relaunch-YKY52XUT.js → update-relaunch-HXMQI3HO.js} +1 -1
- package/chunks/{updateCheck-RKQ5CPZM.js → updateCheck-XWE3TWL5.js} +1 -1
- package/chunks/{upload-config-CBT7ARZY.js → upload-config-ET7NRHU7.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-Z3YWPUNO.js → useAutoAcceptIndicator-TPMYKNJX.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-7CQHU2RF.js → validateNonInterActiveAuth-U52KMEDS.js} +1 -1
- package/chunks/{version-N2OB6KWP.js → version-CW4RTJ3H.js} +1 -1
- package/chunks/{web-fetch-L5XCBCBA.js → web-fetch-UPMJ3XIZ.js} +1 -1
- package/chunks/{web-search-4EHUA3LJ.js → web-search-PXABWQVC.js} +1 -1
- package/chunks/{workflow-FGAUAYIP.js → workflow-UQ4V3NBZ.js} +1 -1
- package/chunks/{workflow-ancestor-trust-F7RRN6I3.js → workflow-ancestor-trust-QII5KTUJ.js} +1 -1
- package/chunks/{workspace-agents-QW4TKC52.js → workspace-agents-Q3KKMDX2.js} +1 -1
- package/chunks/{workspace-providers-status-MFSZT3YA.js → workspace-providers-status-3ASB64FB.js} +1 -1
- package/chunks/{workspace-registration-store-WQRDSIEI.js → workspace-registration-store-2NPD6U3B.js} +1 -1
- package/chunks/{workspace-registry-FXZFRSCH.js → workspace-registry-6QJKRCDR.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-LJ5YAT3A.js → workspace-runtime-coordinator-ZXUWDQIB.js} +1 -1
- package/chunks/{workspace-service-U632SUWU.js → workspace-service-YPYTYYUN.js} +1 -1
- package/chunks/{workspace-skills-status-M7YXM3LF.js → workspace-skills-status-VTFHQ6R7.js} +1 -1
- package/chunks/{workspace-trust-reconciler-NLJGGI4K.js → workspace-trust-reconciler-52CZVPKH.js} +1 -1
- package/chunks/{write-file-BJCKSXX7.js → write-file-FDBR76G5.js} +1 -1
- package/chunks/{zoom-image-TLJPD4DB.js → zoom-image-MYKWCCXO.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +4 -4
- package/vendor/landlock-run/arm64-linux/qwen-landlock-run +0 -0
- package/vendor/landlock-run/x64-linux/qwen-landlock-run +0 -0
- package/vendor/ripgrep/arm64-darwin/rg +0 -0
- package/vendor/ripgrep/arm64-linux/rg +0 -0
- package/vendor/ripgrep/x64-darwin/rg +0 -0
- package/vendor/ripgrep/x64-linux/rg +0 -0
- package/vendor/tree-sitter/tree-sitter-bash.wasm +0 -0
- package/vendor/tree-sitter/tree-sitter.wasm +0 -0
- package/web-shell/assets/{PierreFilePreview-D9tbdFw8.js → PierreFilePreview-DGTp45Z4.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-CeFAk2s-.js → SpreadsheetPreview-DVC_YVei.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-iaURw8SR.js → WorkspaceFileBrowser-DaQNpS06.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-Z4CT1NCF.js → abnfDiagram-VCTEODGH-wJbiOoPK.js} +1 -1
- package/web-shell/assets/{agents-route-B7o2Rq-a.js → agents-route-DUhhA1KI.js} +1 -1
- package/web-shell/assets/{arc-DcHBdUJQ.js → arc-CvpNMy1d.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-DRDhEC81.js → architectureDiagram-5GKGNRK7-DIhi3dIz.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-CYRE6WIc.js → blockDiagram-NRAW4CY4-CoeyTlVJ.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-CIM8N_Sj.js → c4Diagram-UCG6FXSJ-BYoK_I9M.js} +1 -1
- package/web-shell/assets/channel-DvtGOCg6.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-Bbfka9Fe.js → chunk-2Q5K7J3B-BeD4GwPg.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-C02zF3RY.js → chunk-5VM5RSS4-BpkJsB_y.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-Dn0wRD2F.js → chunk-F27PBJKO-BROEWQ1J.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-Dwpl3l0W.js → chunk-G27WJ6UU-DA8Wtppt.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-sQbzSoTR.js → chunk-JWPE2WC7-GqB-QFh5.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-DNlNDtfr.js → chunk-LCL6LL3I-DIPUwYsX.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-BOgf1Dl3.js → chunk-POPQ4Y6H-DbnU-jxX.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-DOofWP00.js → chunk-SVP7TREG-DvH7bQ-w.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-Bj9FxhWU.js → chunk-XXDRQBXY-DdVWVo3U.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-9NR5W1rE.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-9NR5W1rE.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-CUlPjyww.js → cose-bilkent-JH36ORCC-JgMKxP9H.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-5noArzI7.js → cynefin-OW5HDTMX-BVUpNgVm.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-DELvTqmf.js → cynefinDiagram-5FMLGOSQ-CxAdk-iS.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-CAL6Z3hL.js → dagre-3AP2YEHR-CvXWkM86.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-DQC2gaIi.js → diagram-S7CK7UJ4-DD_PS4nm.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-CkU6M-3R.js → diagram-UQ7AKVKN-EVZkTODD.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-CvHpHwVx.js → diagram-VSXAHHWV-CGZc1pZU.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-D9l5F9iB.js → diagram-VX7I27RA-DjNql499.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-DW-VFvYx.js → diagram-Z3DM3KII-CCa0WtmR.js} +1 -1
- package/web-shell/assets/{docx-preview-8MQfOGQh.js → docx-preview-DpVElxvj.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-C0Q71wC_.js → ebnfDiagram-PWID7BFC-W2hoOJZF.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-DWDLRh1S.js → erDiagram-SSCWMZ5O-Dz5NxxEb.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-CVzJnl1P.js → flowDiagram-A5DVABFB-BTMAn8b5.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-B320pcgR.js → ganttDiagram-EL5Y4UJY-BaFrd5ZY.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Di4uZh-J.js → gitGraphDiagram-WWUBYQGX-IlmdUqRk.js} +1 -1
- package/web-shell/assets/{index-Csr8Hx_O.js → index-C2ez0ZjE.js} +1 -1
- package/web-shell/assets/{index-C9BecA_H.js → index-Cs-XBNmB.js} +101 -101
- package/web-shell/assets/{infoDiagram-RXCK75RN-CbafhxET.js → infoDiagram-RXCK75RN-BHs9kpar.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-DrQuIDeR.js → ishikawaDiagram-5VMMS53U-DWCEQ85v.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-BschmjBj.js → journeyDiagram-EYS64GPL-RTDAw9yc.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-B7x9BU9N.js → kanban-definition-3QL26DDD-B7Nl9bq6.js} +1 -1
- package/web-shell/assets/{layout-BewPaOyO.js → layout-BabjFEb1.js} +1 -1
- package/web-shell/assets/{linear-CnLILCVp.js → linear-CZuGjuQd.js} +1 -1
- package/web-shell/assets/{mermaid.core-Csj9KPfJ.js → mermaid.core-CK78bIGt.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-CIGTi5gg.js → mindmap-definition-FBJOCRG2-BbcCi_jP.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-CuWBRQzb.js → pegDiagram-XKGWAZYB-DpLQ7u8i.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-Co5ukXCE.js → pieDiagram-E7YTZNPT-BpWFVtM0.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-B0hzjh6o.js → quadrantDiagram-AXDQQJYC-CGzYlaN1.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-nhkJB0xD.js → railroadDiagram-O6MQD6OU-BNQYW-Zi.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-C7NpxjVR.js → requirementDiagram-EFPCY7ZU-C4fCdIDW.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CUWlnhZC.js → sankeyDiagram-P5KCCOFB-BvbbAnMA.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BoykH0_J.js → sequenceDiagram-WJ2MYXX4-DGXNc6E1.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-aF-PkSe5.js → sizeCapture-X5ZJPWSS-C4W45Xf5.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-g5q0b922.js → stateDiagram-HBIQ2CUA-D3q0fen-.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-XKoYIi05.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-BbASszfe.js → swimlanes-XN3QIQJK-D8n-ResR.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-C7qJMSzs.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-AXIV0TJJ.js → timeline-definition-24CTP7MA-Cio4y1mM.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-B-E0rj1h.js → vennDiagram-4TSXK5OY-DVlg0xnc.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DiOOYJ2D.js → wardleyDiagram-VM6X3IG4-CgeIsimQ.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-De_z7HkS.js → xychartDiagram-S5SC5T6Z-UXjyTLnU.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-Bwr9aS_E.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-BmY8Mmyo.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-BmY8Mmyo.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CTOjUMow.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bz6ia3oL.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{isBidiControlChar,stripDisplayControlChars,stripTerminalControlSequences,truncateNotificationLabel}from"./chunk-R2EHHA2C.js";import{SshWorkspaceClient,SshWorkspaceError}from"./chunk-ZLZF2ZDD.js";import{ExecutionCleanupError,MANAGED_RUNTIME_TOOL_NAMES,ManagedRuntimeOutcomeUnknownError}from"./chunk-JUPGJYC2.js";import{AjvJsonSchemaValidator,CallToolResultSchema,CompleteResultSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,CreateTaskResultSchema,ElicitRequestSchema,ElicitResultSchema,EmptyResultSchema,ErrorCode,GetPromptResultSchema,InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION,ListChangedOptionsBaseSchema,ListPromptsResultSchema,ListResourceTemplatesResultSchema,ListResourcesResultSchema,ListToolsResultSchema,McpError,PromptListChangedNotificationSchema,Protocol,ReadBuffer,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SUPPORTED_PROTOCOL_VERSIONS,ToolListChangedNotificationSchema,assertClientRequestTaskCapability,assertToolsCallTaskCapability,getLiteralValue,getObjectShape,isInitializedNotification,isJSONRPCRequest,isJSONRPCResultResponse,mergeCapabilities,safeParse,serializeMessage}from"./chunk-YK7NDQKM.js";import{EMPTY_COMMIT_PREFIX_HASH,HARNESS_DURABLE_WAIT_BOUNDARY,HARNESS_MODEL_START_PHASES,HARNESS_TURN_COMPLETE_BOUNDARY,LITE_READ_BUF_SIZE,LocalJsonlManagedSessionJournalStore,LocalManagedSessionAuthority,LocalManagedSessionResourceStore,MAX_SNAPSHOTS,ManagedSessionCommitRejectedError,ManagedSessionConflictError,ManagedSessionUncommittedTailError,SessionTranscriptChangedError,SessionTranscriptIdentityUnavailableError,SessionWriterError,SessionWriterLease,SessionWriterLostError,SessionWriterUnavailableError,activationAlreadyInstalledError,assertManagedSessionRestoreBundle,createAwaitActionHarnessCheckpoint,createAwaitAgentHarnessCheckpoint,createAwaitCommandHarnessCheckpoint,createAwaitRuntimeHarnessCheckpoint,createConsumedAgentWaitHarnessCheckpoint,createConsumedCommandWaitHarnessCheckpoint,createConsumedRuntimeResultsHarnessCheckpoint,createHookStoppedRuntimeHarnessCheckpoint,createInitialHarnessCheckpoint,createModelOutputCommittedHarnessCheckpoint,createNextTurnReadyHarnessCheckpoint,createResultsReadyHarnessCheckpoint,createTurnSettledHarnessCheckpoint,encodeHarnessCheckpointV1,harnessCommandLockOf,harnessCommandLocked,isManagedExecutionTranscriptSync,isManagedOwnerRecord,isManagedSessionTranscriptSync,localManagedSessionKey,managedSessionResourceRoot,managedToolDigest,managedToolFailureMessage,managedToolResponseParts,parseHarnessCheckpointV1,publishManagedMessageBody,readLastJsonStringFieldSync,readLastMatchingLineFieldSync,readManagedBranchCheckpoint,readManagedExecutionEvidenceSync,readManagedMessageBody,readManagedSessionLog,readManagedSessionSourceSync,readManagedSessionTitleInfoSync,readSessionTitleInfoFromFileSync,tryParseHarnessCheckpointV1}from"./chunk-DD4SV4AJ.js";import{require_main,resolveEnvVarsInObject}from"./chunk-OGI5HG6N.js";import{isShellResultDisplay,mapShellResultText,shellResultText}from"./chunk-T7CHK6C2.js";import{SessionExecutionEngineAccumulator,SessionExecutionEngineError,assertSessionExecutionEngine}from"./chunk-VZDZ34KK.js";import{NEVER,ZodIssueCode,any,array,boolean,coerce_exports,literal,looseObject,number,object,string,url}from"./chunk-PT7NZBDY.js";import{external_exports}from"./chunk-TWP72VRH.js";import{MANAGED_SESSION_FORMAT_VERSION,MANAGED_SESSION_HEADER_SUBTYPE,MANAGED_SESSION_LIMITS,ManagedSessionAppendUnsettledError,ManagedSessionRecordError,assertManagedSessionDurableRef,collectPendingBranchToolCalls,managedSessionReaderFacingBody,parseBranchCheckpointPayload,resolveBranchPoints,resolveCompletedTurnBranchCandidateFromRecords,safeErrorValue,updatePendingBranchToolCalls,validateManagedReaderFacingRecord}from"./chunk-XKVETIZH.js";import{require_content_type}from"./chunk-PHIPLV2I.js";import{consumeUnread,forwardApproval,getInboxPath,readInbox,sendStructuredMessage,wrapConfirmWithBadge,writeMessage}from"./chunk-WK2IBT6D.js";import{claimTask,listTasks,onTasksUpdated,unassignTeammateTasks}from"./chunk-UYEWRLGD.js";import{AGENT_WORKTREE_SLUG_PATTERN,GitWorktreeService,MAX_DIFF_SIZE_BYTES,clearRuntimeStatus,generateAgentWorktreeSlug,gitEnv,gitRemoteEnv,loadSimpleGit,readRuntimeStatus,worktreeBranchForSlug,worktreeHasWork,writeRuntimeStatus,writeWorktreeSessionMarker}from"./chunk-LLX4BCWK.js";import{hasVerifiableInode,openNoFollow,openSyncNoFollow}from"./chunk-QXQGUM3Y.js";import{SessionArtifactSnapshotAccumulator,deleteArtifactSnapshot,getWebPreviewSnapshotId,isSessionArtifactRecord,rebuildSessionArtifactSnapshot,remapSessionArtifactPayloadForFork,retainArtifactSnapshot,selectActiveSideArtifactRecordUuids}from"./chunk-AG3SSCAF.js";import{aggregateTranscriptRecordFragments,isInternalCodeModeToolResult,isTranscriptConversationRecord,isUserPromptSubmitContextPartText,prepareTranscriptRecords,projectUserTranscriptForDisplay,selectTranscriptLeaf,stripGeneratedAttachmentTokens,validateTranscriptRecord,walkTranscriptUuidChain,wrapUserPromptSubmitContext}from"./chunk-BMSATZXW.js";import{CronScheduler,DEFAULT_RECURRING_MAX_AGE_DAYS,closeFileWatcher,normalizeRecurringMaxAge}from"./chunk-57RLZJ6C.js";import{loadSkillsFromDir,parsePriorityField,readBundledReference,resolveBundledReferenceSurface,toolSearchBridgeSentence,validateConfig,validateSymlinkTarget}from"./chunk-GWYQTKSR.js";import{SKILL_FILE_NAME,assertRealProjectSkillPath,getArchivedSkillsRoot,getPendingSkillsRoot,getProjectSkillsRoot,isProjectSkillPath,maybeRunAutoSkillCurator}from"./chunk-XQJOZDV7.js";import{SKILL_NAME_PATTERN,SkillError,SkillErrorCode,authoredSkillName,parseAllowedToolsField,parseModelField,parsePathsField,parseUserInvocableField,qualifySkillName,skillRestrictionNames,validateSkillName}from"./chunk-CV2UAEZA.js";import{AUTO_MEMORY_SCHEMA_VERSION,AUTO_MEMORY_SCOPES,AUTO_MEMORY_TREE_CATEGORIES,AUTO_MEMORY_TYPES,MAX_USAGE_SCENARIO_CHARS,createAutoMemoryTreeSnapshot,listTrustedMemoryMarkdownFiles,normalizeAutoMemoryKeyword,parseAutoMemoryTopicDocument,renderAutoMemoryFocusedSubtree,rereadAutoMemoryDocument,resolveTrustedMemoryFile,resolveTrustedMemoryRoot,sanitizeAutoMemoryPromptField,scanAllAutoMemoryTopicDocuments,scanAllAutoMemoryTopicDocumentsFromRoot,scanAllUserAutoMemoryTopicDocuments,scanAutoMemorySnapshot,scanAutoMemoryTopicDocuments,scanTeamAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments,toAutoMemoryRef,validateStructuredAutoMemoryDocument}from"./chunk-GNQGC2DJ.js";import{AgentOutputMessageCapture,DEFAULT_OTLP_ENDPOINT,DEFAULT_TELEMETRY_TARGET,GOAL_DEFAULT_TOKEN_BUDGET,GOAL_INFEASIBLE_NEXT_STEP,GOAL_NO_PROGRESS_TURN_LIMIT,GOAL_PAUSE_REASON_NO_PROGRESS,GOAL_PAUSE_REASON_SESSION_TOKEN_LIMIT,GOAL_PAUSE_REASON_STOP_HOOK_CAP,GOAL_PAUSE_REASON_USER_INTERRUPT,GOAL_PROPOSAL_REASON_MAX_CHARACTERS,GOAL_STATE_VERSION,GoalConflictError,GoalInvalidTransitionError,PAUSED_GOAL_SYSTEM_REMINDER,addAgentInputMessageAttributes,addToolArgumentsAttributes,addToolCallResultAttributes,addUserPromptAttributes,elapsedActiveTime,goalActiveTimeBudgetReason,goalPauseReasonForFailure,goalPauseReasonForVerifierFailure,goalRequiresExactPermit,goalStateEventFromSnapshot,goalTokenBudgetReason,goalTurnBudgetReason,isGoalActiveTimeBudgetSpent,isGoalTokenBudgetSpent,isGoalTurnBudgetSpent,isRepeatedBlockerProposal,parseGoalStateRecordPayloadV2,reduceGoalControl,reduceGoalSpend,reduceGoalTurnFinished,validateGoalProposalReason}from"./chunk-F63ESLTI.js";import{parse,require_dist,sanitizeValue,stringify}from"./chunk-KLC3OD2M.js";import{canUseRipgrep}from"./chunk-K6EQXZMK.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{buildModelIdContext,resolveModelId}from"./chunk-BEKROCWN.js";import{SHARED_RECORD_SLOT,defangEnvelopeTags,deriveSessionName,flattenPeerLabel,patchSessionRecord,unregisterSession}from"./chunk-BYU42MLK.js";import{LEADER_NAME,MAX_TEAMMATES,assignTeammateColor,classifyShutdownResponse,findMemberByName,formatAgentId,generateUniqueTeammateName,sanitizeName,writeTeamFile}from"./chunk-JWQXU3SR.js";import{normalizeImageGenerationBaseUrl}from"./chunk-JVJS2YFU.js";import{restoreSessionSources}from"./chunk-G5PYYZMM.js";import{isTruthy}from"./chunk-D7XCQWP2.js";import{glob,globSync}from"./chunk-OBOU4ZZM.js";import{ToolMode,buildExecDeclaration,getToolExposure,isCodeModeToolCallAllowed,isDeferredToolBridgeAvailable,isDirectToolBridgeAvailable,planCodeModeBindings}from"./chunk-4VUT7DCY.js";import{EXCLUDED_TOOLS_FOR_SUBAGENTS,READ_ONLY_INSPECTION_TOOLS,SHELL_TOOL_NAMES,buildPermissionRules,buildSubagentPlanToolBlockedResult,getExcludedToolUnavailableMessage,getLeaderOnlyToolUnavailableMessage,getPlanRequiredTeammatePreApprovalMessage,getSubagentPlanToolUnavailableMessage,getToolNameAliases,hasAmbiguousMcpGrant,isLeaderOnlyToolUnavailableInSubagent,isPlanLifecycleToolUnavailableInSubagent,isPlanRequiredTeammateAwaitingApproval,isPlanRequiredTeammateContext,isPlanRequiredTeammatePreApprovalAllowedTool,isSubagentLikeExecutionContext,isToolExcludedForCurrentContext,matchesAgentToolBlocklist,matchesRule,matchesToolPattern,parseRule,parseRules,require_picomatch,resolveToolName,shouldUsePlanOnlyReminderInSubagentContext,splitCompoundCommand,splitCompoundCommandSegments,toolConfigAllowsSkill,toolMatchesRuleToolName}from"./chunk-FQQMMFT6.js";import{APPROVAL_MODES,ApprovalMode}from"./chunk-JZK2WGXA.js";import{executeSandbox}from"./chunk-BQTFBDPK.js";import{admitShellSandbox,assertShellSandboxCwd,probeShellSandbox}from"./chunk-PPHCG6Q5.js";import{resolveNetworkTarget}from"./chunk-JKXBHBE3.js";import{isOmniDeliveryActive}from"./chunk-OW4QBRSR.js";import{MediaResourceRegistry,evaluateMediaPolicyToolCall,isMediaPolicyToolHiddenFromModel,resolveMediaPolicyModelAccess}from"./chunk-S2ZKZXHX.js";import{AskUserQuestionTool,TrustedUserAnswers,assembleSystemPrompt,getArenaSystemReminder,getCompressionPrompt,getCoreSystemPrompt,getCustomSystemPrompt,getManualPlanExitSystemReminder,getOutputStyleTurnReminder,getPlanModeSystemReminder,resolveEffectiveOutputStyle,resolveInteractionMode,resolveMainSessionOutputStyle}from"./chunk-PXXU2KWH.js";import{NO_EXEC_CONFIG,findGitRoot,getCachedGitBranch,getGitBranch,getRecentGitStatus,isGitRepository}from"./chunk-EBMCWXGZ.js";import{ShellExecutionService,getShellAbortReasonKind,getShellContextEnvVars,getShellPagerEnv,isSignalTermination,normalizePathEnvForWindows}from"./chunk-3X7DP5W3.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{promptIdContext,todoWorkChainContext}from"./chunk-MWGB5RCF.js";import{SHELL_SELF_KILL_REJECTION,buildOutsideWorkspaceWarning,buildShellExecWarnings,classifyAwkCommandSafety,classifySedCommandSafety,detectSelfKillCommand,escapeShellArg,getCommandRoot,getCommandRoots,getShellConfiguration,hasShellPatternExpansion,hasShellSubstitution,isShellCommandReadOnly,normalizeMonitorCommand,shouldDefaultToNodePty,splitCommands,stripShellWrapper}from"./chunk-XWEXQT3X.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{require_shell_quote}from"./chunk-TL3SF2GA.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{BaseTokenStorage,KeychainTokenStorage}from"./chunk-4GP3PH7Z.js";import{isInternalSecretEnvVar,sanitizeChildEnv}from"./chunk-LFKUPU57.js";import{carryIncompleteArgumentsMarker,supportsOpenAIPrefixCaching,toolCallArgumentsWereIncomplete}from"./chunk-T2F7KYYR.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX}from"./chunk-SW54YEPK.js";import{DashScopeOpenAICompatibleProvider,selectDashScopeThinkingKnob}from"./chunk-U2FJSKS3.js";import{assertHookExecutionOwner,captureHookExecutionOwner,childLaunchDepth,getCurrentAgentChat,getCurrentAgentConfiguredToolAllowlist,getCurrentAgentDepth,getCurrentAgentDisallowedTools,getCurrentAgentId,getHookExecutionOwner,getRuntimeContentGenerator,isTopLevelSession,resolveHookExecutionOwner,runOutsideAgentContext,runWithAgentChat,runWithAgentConfiguredToolAllowlist,runWithAgentContext,runWithAgentDisallowedTools,runWithHookExecutionOwner,runWithRuntimeContentGenerator,spawnBlockReason}from"./chunk-7J2TOJMG.js";import{getTeammateContext,isTeammate,runOutsideTeammateIdentity,runWithTeammateIdentity}from"./chunk-AGEDDL7Z.js";import{getResponsesMessage,sameResponsesMessage}from"./chunk-2NJJHZ52.js";import{openBrowserSecurely,shouldAttemptBrowserLaunch}from"./chunk-3YWXKSOI.js";import{beginRetryWait,bindRetryWaitObserver,delay,isUnattendedMode,retryWithBackoff,runWithRetryWaitObserver}from"./chunk-2PMQL4KE.js";import{InMemoryImagePayloadStore,InvalidStreamError,REATTACH_BOUNDARY_METADATA,buildReattachParts,countAllInlineImages,getToolCallPreparations,hasImagePayloadReferences,isFlushedToolCallPark,isRetryableStatuslessUpstreamError,isRetryableStreamTransportError,replaceImagePayloadsInPlace,setToolCallPreparations}from"./chunk-V3XYE727.js";import{getThoughtSummary}from"./chunk-BRPC43OM.js";import{ModelsConfig,captureReasoningSnapshot,getBuiltinDeepSeekReasoning,getRequestModel,isImageGenerationCapable,resolveProviderProtocol,resolveReasoningCapabilities,resolveReasoningForModel,stripRuntimeSnapshotPrefix,validateReasoningCapabilities}from"./chunk-XYBEQRSZ.js";import{QUOTA_EXHAUSTED_PREFIX,classifyRetryError,formatQuotaExhaustedMessage,getHeaderValue,getRateLimitErrorDetails,getRateLimitRetryDelayMs,isApiError,isFallbackEligible,isQuotaExhaustedError,isRateLimitError,isRetryableUpstreamError,isStructuredError}from"./chunk-WZDBBDRD.js";import{combineAbortSignals,createAbortController,createChildAbortController}from"./chunk-476F6QIM.js";import{ResponsesHttpError}from"./chunk-4R67LXKL.js";import{addDaemonRequestAttribute}from"./chunk-VTDSLBET.js";import{ApiRetryEvent,COMBINED_PASS_TOLERANCE_FACTOR,ContentRetryEvent,ContentRetryFailureEvent,DiscoveredMCPTool,ExtensionDisableEvent,ExtensionEnableEvent,ExtensionInstallEvent,ExtensionUninstallEvent,ExtensionUpdateEvent,FULL_OUTPUT_DIGEST_LABEL,HookCallEvent,LoopDetectedEvent,LoopDetectionDisabledEvent,MemoryDreamEvent,MemoryExtractEvent,MemoryMigrationEvent,MemoryRecallDeliveryEvent,MemoryRecallEvent,MemoryRecallModeTransitionEvent,NextSpeakerCheckEvent,PREVIEW_SIZE_CHARS,RipgrepFallbackEvent,StartSessionEvent,SubagentExecutionEvent,TOOL_OUTPUT_TRUNCATED_PREFIX,ToolCallEvent,ToolResultSizeEvent,UiTelemetryService,attachToolOutputProvenance,collectText,effectiveAppResourceMaxBytes,effectiveAppResourceTimeoutMs,formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,getMCPServerStatus,getQualifiedVisionModelId,getToolOutputProvenance,isAlreadyTruncated,isChatRecordingSuppressed,isFullTurnVisionCapable,isImagePart,isSkipSelectorOnUniqueStrongHitEnabled,logApiRetry,logArenaAgentCompleted,logArenaSessionEnded,logArenaSessionStarted,logChatCompression,logContentRetry,logContentRetryFailure,logExtensionDisable,logExtensionEnable,logExtensionInstallEvent,logExtensionUninstall,logExtensionUpdateEvent,logGoalState,logHookCall,logLoopDetected,logLoopDetectionDisabled,logMemoryDream,logMemoryExtract,logMemoryMigration,logMemoryRecall,logMemoryRecallDelivery,logMemoryRecallModeTransition,logNextSpeakerCheck,logRipgrepFallback,logSessionEnd,logStartSession,logSubagentExecution,logToolCall,logToolResultSize,makeArenaAgentCompletedEvent,makeArenaSessionEndedEvent,makeArenaSessionStartedEvent,makeChatCompressionEvent,measureToolOutput,memoryAge,memoryFreshnessText,normalizeParts,normalizeToolResultCallId,persistAndTruncateToolResult,recordMCPServerLastError,removeMCPServerStatus,runVisionBridge,runWithChatRecordingSuppressed,selectVisionBridgeModel,shouldRunVisionBridge,subagentIdentityContext,subagentNameContext,truncateLlmContent,truncateToolOutput,uiTelemetryService,updateMCPServerStatus,updateToolOutputBudget}from"./chunk-DR3HLUJ5.js";import{_recoverObjectsFromLine,exists,parseLineTolerant,read,readLines,readLinesWithIntegrity,writeLine,writeLineSync}from"./chunk-UQFTXKEB.js";import{Mutex}from"./chunk-HDGTWJ24.js";import{extractCodeModeImageContent,getCurrentToolCallSource,runWithToolCallRuntime,runWithToolCallSource,runWithoutToolCallRuntime}from"./chunk-W5NWIGKO.js";import{runSideQuery}from"./chunk-6C4YRBLR.js";import{FileExclusions,FileReadOpenError,LOCAL_CONTEXT_FILENAME,digestFileReadSource,getAllMemoryFilenames,isUtf8CompatibleEncoding,loadIconvLite,readFileHandleBytes,readFileWithLineAndLimit,readTextCursorWindowFromHandle,readTextRangeFromHandle,setMemoryFilename}from"./chunk-JU2HHQR5.js";import{AUTO_MEMORY_INDEX_FILENAME,AUTO_MEMORY_PINNED_DIRNAME,TEAM_AUTO_MEMORY_DIRNAME,getAutoMemoryConsolidationLockPath,getAutoMemoryExtractCursorPath,getAutoMemoryIndexPath,getAutoMemoryMetadataPath,getAutoMemoryRoot,getAutoMemoryTrustedAnchor,getMemoryBaseDir,getMemoryRootTrustedAnchor,getProjectAutoMemoryRoots,getTeamAutoMemoryIndexPath,getTeamAutoMemoryRoot,getUserAutoMemoryConsolidationLockPath,getUserAutoMemoryIndexPath,getUserAutoMemoryMetadataPath,getUserAutoMemoryRoot,isAnyAutoMemPath,isAutoMemPath,isManagedMemoryPath,isTeamAutoMemPath,isUserAutoMemPath}from"./chunk-37KFLBKZ.js";import{getSystemEncoding}from"./chunk-7U7CWMP7.js";import{getInvocationContext,runWithInvocationContext}from"./chunk-SLD7H2FA.js";import{normalizeMcpToolName,sanitizeToolNameForProvider}from"./chunk-7DOOXUDG.js";import{clampInlineMediaPart}from"./chunk-P3RLMP7L.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,TOKEN_TO_CHAR_RATIO,estimateContentChars,getFunctionResponseParts,resolveCompactionTuning,resolveSlimmingConfig,sanitizeMimeForPlaceholder,slimCompactionInput}from"./chunk-R54OXALA.js";import{AUTH_ENV_MAPPINGS,DEFAULT_MODELS,DEFAULT_QWEN_EMBEDDING_MODEL,MODEL_GENERATION_CONFIG_FIELDS,QWEN_OAUTH_ALLOWED_MODELS,createContentGenerator,resetPreloadedContentGenerator,resolveContentGeneratorConfigWithSources}from"./chunk-7WS2EYMQ.js";import{CATALOG_MODALITIES,DEFAULT_TOKEN_LIMIT,MIN_AUTO_DETECTED_CONTEXT_WINDOW,MODELS_DEV_URL,MODEL_CATALOG_PROJECTION_VERSION,MODEL_CATALOG_URL_ENV,OUTPUT_TOKEN_CEILING,REASONING_EFFORT_TIERS,clampOutputTokensToWindow,clampReasoningEffort,defaultModalities,defaultOutputCeiling,getGptReasoningCapabilities,getModelCatalogCachePath,hasExplicitOutputLimit,isModelCatalogDisabled,isModelCatalogKey,isTieredEffortWireModel,knownTokenLimit,normalize,normalizeReasoningEffort,parseModelCatalog,parsePositiveIntegerEnvValue,reasoningEffortsForCapability,setGeneratorReasoningEffort,tokenLimit,versionSpellingAlias}from"./chunk-TAAJ7TDB.js";import{DEFAULT_QWEN_MODEL}from"./chunk-4ZBZL23U.js";import{getOrCreateMcpDispatcher,loadUndici,preloadRuntimeFetchModule,redactProxyError,setResolvedProxyUrlForRuntimeFetch}from"./chunk-ZZZAYAJW.js";import{safeJsonStringify}from"./chunk-XMANRGPK.js";import{DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT,TOOL_FAILURE_KIND_ATTRIBUTE,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_FAILURE_KIND_CANCELLED,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_FAILURE_KIND_POST_HOOK_STOPPED,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_FAILURE_KIND_TIMEOUT,TOOL_FAILURE_KIND_TOOL_ERROR,TOOL_FAILURE_KIND_TOOL_EXCEPTION,endHookSpan,endInteractionSpan,endSubagentSpan,endToolBlockedOnUserSpan,endToolExecutionSpan,endToolSpan,getActiveInteractionSpan,initializeTelemetry,isPerformanceMonitoringActive,isTelemetrySdkInitialized,isValidSensitiveSpanAttributeMaxLength,recordCpuUsage,recordInteractionActivity,recordMemoryUsage,redactUrlCredentials,refreshSessionContext,runInSubagentSpanContext,runInToolSpanContext,safeSetStatus,shutdownTelemetry,startHookSpan,startInteractionSpan,startSubagentSpan,startToolBlockedOnUserSpan,startToolExecutionSpan,startToolSpan,truncateSpanError}from"./chunk-XHV5HLJS.js";import{STRUCTURED_OUTPUT_REDACTED_ARGS}from"./chunk-BWU6AH5O.js";import{atomicWriteFile,atomicWriteFileSync,atomicWriteJSON,renameWithRetry}from"./chunk-BMHYEQTI.js";import{require_src}from"./chunk-GU22I6TY.js";import{normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-4YLXNRRH.js";import{BUBBLE_APPROVAL_MODE,FORK_AGENT,FORK_DEFAULT_MAX_TURNS,FORK_PLACEHOLDER_RESULT,FORK_SUBAGENT_TYPE,SubagentError,SubagentErrorCode,buildAvailableSkillsReminder,buildChangedAgentsReminder,buildChangedMcpToolsReminder,buildChangedSkillsReminder,buildChildMessage,buildDeferredToolsReminder,buildForkExecutionAllowlist,buildForkedMessages,buildFunctionResponseParts,buildMcpServerInstructionsReminder,buildMcpServerInstructionsReminderFromEntries,buildPinnedWorktreeNotice,buildWorktreeNotice,formatDateForContext,getDirectoryContextString,getInitialChatHistory,getStartupContextLength,isSystemReminderContent,normalizeForkTurns,registerForkDisplayImageForCache,resolveForkExecutionAllowedTools,runInForkContext,selectForkHistory,stripSystemReminderBlocks,validateForkToolList,wrapSystemReminder}from"./chunk-65UCR6OZ.js";import{SESSION_SKILL_MANAGER,SKILLS_ACTIVATED_OPENER,clearLoadedSkillTracking,collectAvailableSkillEntries,renderAvailableSkillsBlock,sessionSkillManager}from"./chunk-CN2TQ3PU.js";import{DefaultHookOutput,HOOKS_CONFIG_FIELDS,HookEventName,PermissionRequestHookOutput,PostToolBatchHookOutput,PostToolUseFailureHookOutput,PostToolUseHookOutput,PreToolUseHookOutput,StopHookOutput,UserPromptExpansionHookOutput,createHookOutput,escapeSystemReminderTags,escapeXml,escapeXmlElementText,escapeXmlWithinBudget,getHookKey,isBlockingHookOutput,isToolArtifactLike,toUpdatedToolInput}from"./chunk-6GTPLW7K.js";import{DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES,QwenIgnoreParser,formatQwenIgnoreFileNames,require_ignore}from"./chunk-5DTFN37U.js";import{WorkspaceContext,isPathWithinRoot}from"./chunk-2YUBAWQ6.js";import{AgentStatistics,BaseDeclarativeTool,BaseToolInvocation,CONCURRENCY_SAFE_KINDS,StructuredToolError,hasCycleInSchema,isShellProgressData}from"./chunk-O5EKX7LG.js";import{AGENT_HOST_TOOL_NAMES,ToolDisplayNames,ToolDisplayNamesMigration,ToolNames,ToolNamesMigration,canonicalToolName,resolveBuiltinToolName,resolveRegisteredToolName}from"./chunk-2UNFJQ2D.js";import{createDebugLogger,isDebugLogFileEnabled,registerSessionModel,registerSessionProjectDir,sessionIdContext,setDebugLogSession,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import{SpanStatusCode,context,init_esm,trace}from"./chunk-I4H7NUVP.js";import{SKILL_PROVIDER_CONFIG_DIRS,Storage}from"./chunk-EPODBRBP.js";import{PATH_ARG_KEYS,QWEN_DIR,expandHomeDir,getProjectHash,isSubpath,isSubpaths,makeRelative,resolvePath,shortenPath,tildeifyPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{FatalConfigError,UnauthorizedError,getErrorMessage,getErrorStatus,getErrorType,isAbortError,isNodeError,toFriendlyError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__commonJS,__export,__name,__require,__toESM}from"./chunk-KBWJGX7I.js";var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs77=__require("fs");function checkPathExt(path82,options2){var pathext=options2.pathExt!==void 0?options2.pathExt:process.env.PATHEXT;if(!pathext){return true}pathext=pathext.split(";");if(pathext.indexOf("")!==-1){return true}for(var i=0;i<pathext.length;i++){var p2=pathext[i].toLowerCase();if(p2&&path82.substr(-p2.length).toLowerCase()===p2){return true}}return false}__name(checkPathExt,"checkPathExt");function checkStat(stat14,path82,options2){if(!stat14.isSymbolicLink()&&!stat14.isFile()){return false}return checkPathExt(path82,options2)}__name(checkStat,"checkStat");function isexe(path82,options2,cb){fs77.stat(path82,function(er2,stat14){cb(er2,er2?false:checkStat(stat14,path82,options2))})}__name(isexe,"isexe");function sync(path82,options2){return checkStat(fs77.statSync(path82),path82,options2)}__name(sync,"sync")}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs77=__require("fs");function isexe(path82,options2,cb){fs77.stat(path82,function(er2,stat14){cb(er2,er2?false:checkStat(stat14,options2))})}__name(isexe,"isexe");function sync(path82,options2){return checkStat(fs77.statSync(path82),options2)}__name(sync,"sync");function checkStat(stat14,options2){return stat14.isFile()&&checkMode(stat14,options2)}__name(checkStat,"checkStat");function checkMode(stat14,options2){var mod=stat14.mode;var uid=stat14.uid;var gid=stat14.gid;var myUid=options2.uid!==void 0?options2.uid:process.getuid&&process.getuid();var myGid=options2.gid!==void 0?options2.gid:process.getgid&&process.getgid();var u2=parseInt("100",8);var g2=parseInt("010",8);var o=parseInt("001",8);var ug=u2|g2;var ret=mod&o||mod&g2&&gid===myGid||mod&u2&&uid===myUid||mod&ug&&myUid===0;return ret}__name(checkMode,"checkMode")}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports2,module2){init_esbuild_shims();var fs77=__require("fs");var core;if(process.platform==="win32"||globalThis.TESTING_WINDOWS){core=require_windows()}else{core=require_mode()}module2.exports=isexe;isexe.sync=sync;function isexe(path82,options2,cb){if(typeof options2==="function"){cb=options2;options2={}}if(!cb){if(typeof Promise!=="function"){throw new TypeError("callback not provided")}return new Promise(function(resolve34,reject){isexe(path82,options2||{},function(er2,is2){if(er2){reject(er2)}else{resolve34(is2)}})})}core(path82,options2||{},function(er2,is2){if(er2){if(er2.code==="EACCES"||options2&&options2.ignoreErrors){er2=null;is2=false}}cb(er2,is2)})}__name(isexe,"isexe");function sync(path82,options2){try{return core.sync(path82,options2||{})}catch(er2){if(options2&&options2.ignoreErrors||er2.code==="EACCES"){return false}else{throw er2}}}__name(sync,"sync")}});var require_which=__commonJS({"node_modules/cross-spawn/node_modules/which/which.js"(exports2,module2){init_esbuild_shims();var isWindows2=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";var path82=__require("path");var COLON=isWindows2?";":":";var isexe=require_isexe();var getNotFoundError=__name(cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),"getNotFoundError");var getPathInfo=__name((cmd,opt)=>{const colon=opt.colon||COLON;const pathEnv=cmd.match(/\//)||isWindows2&&cmd.match(/\\/)?[""]:[...isWindows2?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)];const pathExtExe=isWindows2?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"";const pathExt=isWindows2?pathExtExe.split(colon):[""];if(isWindows2){if(cmd.indexOf(".")!==-1&&pathExt[0]!=="")pathExt.unshift("")}return{pathEnv,pathExt,pathExtExe}},"getPathInfo");var which=__name((cmd,opt,cb)=>{if(typeof opt==="function"){cb=opt;opt={}}if(!opt)opt={};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];const step=__name(i=>new Promise((resolve34,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve34(found):reject(getNotFoundError(cmd));const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path82.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve34(subStep(p2,i,0))}),"step");const subStep=__name((p2,i,ii2)=>new Promise((resolve34,reject)=>{if(ii2===pathExt.length)return resolve34(step(i+1));const ext=pathExt[ii2];isexe(p2+ext,{pathExt:pathExtExe},(er2,is2)=>{if(!er2&&is2){if(opt.all)found.push(p2+ext);else return resolve34(p2+ext)}return resolve34(subStep(p2,i,ii2+1))})}),"subStep");return cb?step(0).then(res=>cb(null,res),cb):step(0)},"which");var whichSync=__name((cmd,opt)=>{opt=opt||{};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];for(let i=0;i<pathEnv.length;i++){const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path82.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j2=0;j2<pathExt.length;j2++){const cur=p2+pathExt[j2];try{const is2=isexe.sync(cur,{pathExt:pathExtExe});if(is2){if(opt.all)found.push(cur);else return cur}}catch(ex){}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)},"whichSync");module2.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports2,module2){"use strict";init_esbuild_shims();var pathKey=__name((options2={})=>{const environment=options2.env||process.env;const platform2=options2.platform||process.platform;if(platform2!=="win32"){return"PATH"}return Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"},"pathKey");module2.exports=pathKey;module2.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2,module2){"use strict";init_esbuild_shims();var path82=__require("path");var which=require_which();var getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){const env=parsed.options.env||process.env;const cwd=process.cwd();const hasCustomCwd=parsed.options.cwd!=null;const shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd){try{process.chdir(parsed.options.cwd)}catch(err){}}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path82.delimiter:void 0})}catch(e){}finally{if(shouldSwitchCwd){process.chdir(cwd)}}if(resolved){resolved=path82.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)}return resolved}__name(resolveCommandAttempt,"resolveCommandAttempt");function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,true)}__name(resolveCommand,"resolveCommand");module2.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports2,module2){"use strict";init_esbuild_shims();var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){arg=arg.replace(metaCharsRegExp,"^$1");return arg}__name(escapeCommand,"escapeCommand");function escapeArgument(arg,doubleEscapeMetaChars){arg=`${arg}`;arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"');arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1");arg=`"${arg}"`;arg=arg.replace(metaCharsRegExp,"^$1");if(doubleEscapeMetaChars){arg=arg.replace(metaCharsRegExp,"^$1")}return arg}__name(escapeArgument,"escapeArgument");module2.exports.command=escapeCommand;module2.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports2,module2){"use strict";init_esbuild_shims();var shebangRegex=require_shebang_regex();module2.exports=(string7="")=>{const match=string7.match(shebangRegex);if(!match){return null}const[path82,argument]=match[0].replace(/#! ?/,"").split(" ");const binary=path82.split("/").pop();if(binary==="env"){return argument}return argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports2,module2){"use strict";init_esbuild_shims();var fs77=__require("fs");var shebangCommand=require_shebang_command();function readShebang(command){const size=150;const buffer=Buffer.alloc(size);let fd;try{fd=fs77.openSync(command,"r");fs77.readSync(fd,buffer,0,size,0);fs77.closeSync(fd)}catch(e){}return shebangCommand(buffer.toString())}__name(readShebang,"readShebang");module2.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports2,module2){"use strict";init_esbuild_shims();var path82=__require("path");var resolveCommand=require_resolveCommand();var escape3=require_escape();var readShebang=require_readShebang();var isWin=process.platform==="win32";var isExecutableRegExp=/\.(?:com|exe)$/i;var isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);const shebang=parsed.file&&readShebang(parsed.file);if(shebang){parsed.args.unshift(parsed.file);parsed.command=shebang;return resolveCommand(parsed)}return parsed.file}__name(detectShebang,"detectShebang");function parseNonShell(parsed){if(!isWin){return parsed}const commandFile=detectShebang(parsed);const needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){const needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path82.normalize(parsed.command);parsed.command=escape3.command(parsed.command);parsed.args=parsed.args.map(arg=>escape3.argument(arg,needsDoubleEscapeMetaChars));const shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`];parsed.command=process.env.comspec||"cmd.exe";parsed.options.windowsVerbatimArguments=true}return parsed}__name(parseNonShell,"parseNonShell");function parse14(command,args,options2){if(args&&!Array.isArray(args)){options2=args;args=null}args=args?args.slice(0):[];options2=Object.assign({},options2);const parsed={command,args,options:options2,file:void 0,original:{command,args}};return options2.shell?parsed:parseNonShell(parsed)}__name(parse14,"parse");module2.exports=parse14}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports2,module2){"use strict";init_esbuild_shims();var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}__name(notFoundError,"notFoundError");function hookChildProcess(cp,parsed){if(!isWin){return}const originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){const err=verifyENOENT(arg1,parsed);if(err){return originalEmit.call(cp,"error",err)}}return originalEmit.apply(cp,arguments)}}__name(hookChildProcess,"hookChildProcess");function verifyENOENT(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawn")}return null}__name(verifyENOENT,"verifyENOENT");function verifyENOENTSync(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawnSync")}return null}__name(verifyENOENTSync,"verifyENOENTSync");module2.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports2,module2){"use strict";init_esbuild_shims();var cp=__require("child_process");var parse14=require_parse();var enoent=require_enoent();function spawn7(command,args,options2){const parsed=parse14(command,args,options2);const spawned=cp.spawn(parsed.command,parsed.args,parsed.options);enoent.hookChildProcess(spawned,parsed);return spawned}__name(spawn7,"spawn");function spawnSync3(command,args,options2){const parsed=parse14(command,args,options2);const result=cp.spawnSync(parsed.command,parsed.args,parsed.options);result.error=result.error||enoent.verifyENOENTSync(result.status,parsed);return result}__name(spawnSync3,"spawnSync");module2.exports=spawn7;module2.exports.spawn=spawn7;module2.exports.sync=spawnSync3;module2.exports._parse=parse14;module2.exports._enoent=enoent}});var require_levenshtein=__commonJS({"node_modules/fast-levenshtein/levenshtein.js"(exports2,module2){init_esbuild_shims();(function(){"use strict";var collator;try{collator=typeof Intl!=="undefined"&&typeof Intl.Collator!=="undefined"?Intl.Collator("generic",{sensitivity:"base"}):null}catch(err){console.log("Collator could not be initialized and wouldn't be used")}var prevRow=[],str2Char=[];var Levenshtein={get:__name(function(str1,str2,options2){var useCollator=options2&&collator&&options2.useCollator;var str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i,j2,tmp;for(i=0;i<str2Len;++i){prevRow[i]=i;str2Char[i]=str2.charCodeAt(i)}prevRow[str2Len]=str2Len;var strCmp;if(useCollator){for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=0===collator.compare(str1.charAt(i),String.fromCharCode(str2Char[j2]));nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}else{for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=str1.charCodeAt(i)===str2Char[j2];nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}return nextCol},"get")};if(typeof define!=="undefined"&&define!==null&&define.amd){define(function(){return Levenshtein})}else if(typeof module2!=="undefined"&&module2!==null&&typeof exports2!=="undefined"&&module2.exports===exports2){module2.exports=Levenshtein}else if(typeof self!=="undefined"&&typeof self.postMessage==="function"&&typeof self.importScripts==="function"){self.Levenshtein=Levenshtein}else if(typeof window!=="undefined"&&window!==null){window.Levenshtein=Levenshtein}})()}});var require_parser=__commonJS({"node_modules/@iarna/toml/lib/parser.js"(exports2,module2){"use strict";init_esbuild_shims();var ParserEND=1114112;var ParserError=class _ParserError extends Error{static{__name(this,"ParserError")}constructor(msg,filename,linenumber){super("[ParserError] "+msg,filename,linenumber);this.name="ParserError";this.code="ParserError";if(Error.captureStackTrace)Error.captureStackTrace(this,_ParserError)}};var State=class{static{__name(this,"State")}constructor(parser2){this.parser=parser2;this.buf="";this.returned=null;this.result=null;this.resultTable=null;this.resultArr=null}};var Parser3=class{static{__name(this,"Parser")}constructor(){this.pos=0;this.col=0;this.line=0;this.obj={};this.ctx=this.obj;this.stack=[];this._buf="";this.char=null;this.ii=0;this.state=new State(this.parseStart)}parse(str){if(str.length===0||str.length==null)return;this._buf=String(str);this.ii=-1;this.char=-1;let getNext;while(getNext===false||this.nextChar()){getNext=this.runOne()}this._buf=null}nextChar(){if(this.char===10){++this.line;this.col=-1}++this.ii;this.char=this._buf.codePointAt(this.ii);++this.pos;++this.col;return this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=ParserEND;let last;do{last=this.state.parser;this.runOne()}while(this.state.parser!==last);this.ctx=null;this.state=null;this._buf=null;return this.obj}next(fn){if(typeof fn!=="function")throw new ParserError("Tried to set state to non-existent state: "+JSON.stringify(fn));this.state.parser=fn}goto(fn){this.next(fn);return this.runOne()}call(fn,returnWith){if(returnWith)this.next(returnWith);this.stack.push(this.state);this.state=new State(fn)}callNow(fn,returnWith){this.call(fn,returnWith);return this.runOne()}return(value){if(this.stack.length===0)throw this.error(new ParserError("Stack underflow"));if(value===void 0)value=this.state.buf;this.state=this.stack.pop();this.state.returned=value}returnNow(value){this.return(value);return this.runOne()}consume(){if(this.char===ParserEND)throw this.error(new ParserError("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(err){err.line=this.line;err.col=this.col;err.pos=this.pos;return err}parseStart(){throw new ParserError("Must declare a parseStart method")}};Parser3.END=ParserEND;Parser3.Error=ParserError;module2.exports=Parser3}});var require_create_datetime=__commonJS({"node_modules/@iarna/toml/lib/create-datetime.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=value=>{const date6=new Date(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_format_num=__commonJS({"node_modules/@iarna/toml/lib/format-num.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(d,num)=>{num=String(num);while(num.length<d)num="0"+num;return num}}});var require_create_datetime_float=__commonJS({"node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var FloatingDateTime=class extends Date{static{__name(this,"FloatingDateTime")}constructor(value){super(value+"Z");this.isFloating=true}toISOString(){const date6=`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`;const time5=`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`;return`${date6}T${time5}`}};module2.exports=value=>{const date6=new FloatingDateTime(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_date=__commonJS({"node_modules/@iarna/toml/lib/create-date.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var DateTime=globalThis.Date;var Date2=class extends DateTime{static{__name(this,"Date")}constructor(value){super(value);this.isDate=true}toISOString(){return`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`}};module2.exports=value=>{const date6=new Date2(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_time=__commonJS({"node_modules/@iarna/toml/lib/create-time.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var Time=class extends Date{static{__name(this,"Time")}constructor(value){super(`0000-01-01T${value}Z`);this.isTime=true}toISOString(){return`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`}};module2.exports=value=>{const date6=new Time(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_toml_parser=__commonJS({"node_modules/@iarna/toml/lib/toml-parser.js"(exports,module){"use strict";init_esbuild_shims();module.exports=makeParserClass(require_parser());module.exports.makeParserClass=makeParserClass;var TomlError=class _TomlError extends Error{static{__name(this,"TomlError")}constructor(msg){super(msg);this.name="TomlError";if(Error.captureStackTrace)Error.captureStackTrace(this,_TomlError);this.fromTOML=true;this.wrapped=null}};TomlError.wrap=err=>{const terr=new TomlError(err.message);terr.code=err.code;terr.wrapped=err;return terr};module.exports.TomlError=TomlError;var createDateTime=require_create_datetime();var createDateTimeFloat=require_create_datetime_float();var createDate=require_create_date();var createTime=require_create_time();var CTRL_I=9;var CTRL_J=10;var CTRL_M=13;var CTRL_CHAR_BOUNDARY=31;var CHAR_SP=32;var CHAR_QUOT=34;var CHAR_NUM=35;var CHAR_APOS=39;var CHAR_PLUS=43;var CHAR_COMMA=44;var CHAR_HYPHEN=45;var CHAR_PERIOD=46;var CHAR_0=48;var CHAR_1=49;var CHAR_7=55;var CHAR_9=57;var CHAR_COLON=58;var CHAR_EQUALS=61;var CHAR_A=65;var CHAR_E=69;var CHAR_F=70;var CHAR_T=84;var CHAR_U=85;var CHAR_Z=90;var CHAR_LOWBAR=95;var CHAR_a=97;var CHAR_b=98;var CHAR_e=101;var CHAR_f=102;var CHAR_i=105;var CHAR_l=108;var CHAR_n=110;var CHAR_o=111;var CHAR_r=114;var CHAR_s=115;var CHAR_t=116;var CHAR_u=117;var CHAR_x=120;var CHAR_z=122;var CHAR_LCUB=123;var CHAR_RCUB=125;var CHAR_LSQB=91;var CHAR_BSOL=92;var CHAR_RSQB=93;var CHAR_DEL=127;var SURROGATE_FIRST=55296;var SURROGATE_LAST=57343;var escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:"\n",[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(cp){return cp>=CHAR_0&&cp<=CHAR_9}__name(isDigit,"isDigit");function isHexit(cp){return cp>=CHAR_A&&cp<=CHAR_F||cp>=CHAR_a&&cp<=CHAR_f||cp>=CHAR_0&&cp<=CHAR_9}__name(isHexit,"isHexit");function isBit(cp){return cp===CHAR_1||cp===CHAR_0}__name(isBit,"isBit");function isOctit(cp){return cp>=CHAR_0&&cp<=CHAR_7}__name(isOctit,"isOctit");function isAlphaNumQuoteHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_APOS||cp===CHAR_QUOT||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumQuoteHyphen,"isAlphaNumQuoteHyphen");function isAlphaNumHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumHyphen,"isAlphaNumHyphen");var _type=Symbol("type");var _declared=Symbol("declared");var hasOwnProperty=Object.prototype.hasOwnProperty;var defineProperty=Object.defineProperty;var descriptor={configurable:true,enumerable:true,writable:true,value:void 0};function hasKey(obj,key){if(hasOwnProperty.call(obj,key))return true;if(key==="__proto__")defineProperty(obj,"__proto__",descriptor);return false}__name(hasKey,"hasKey");var INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}__name(InlineTable,"InlineTable");function isInlineTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_TABLE}__name(isInlineTable,"isInlineTable");var TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:false,writable:true}})}__name(Table,"Table");function isTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===TABLE}__name(isTable,"isTable");var _contentType=Symbol("content-type");var INLINE_LIST=Symbol("inline-list");function InlineList(type){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:type}})}__name(InlineList,"InlineList");function isInlineList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_LIST}__name(isInlineList,"isInlineList");var LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}__name(List,"List");function isList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===LIST}__name(isList,"isList");var _custom;try{const utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(_2){}var _inspect=_custom||"inspect";var BoxedBigInt=class{static{__name(this,"BoxedBigInt")}constructor(value){try{this.value=globalThis.BigInt.asIntN(64,value)}catch(_2){this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}};var INTEGER=Symbol("integer");function Integer(value){let num=Number(value);if(Object.is(num,-0))num=0;if(globalThis.BigInt&&!Number.isSafeInteger(num)){return new BoxedBigInt(value)}else{return Object.defineProperties(new Number(num),{isNaN:{value:__name(function(){return isNaN(this)},"value")},[_type]:{value:INTEGER},[_inspect]:{value:__name(()=>`[Integer: ${value}]`,"value")}})}}__name(Integer,"Integer");function isInteger(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INTEGER}__name(isInteger,"isInteger");var FLOAT=Symbol("float");function Float(value){return Object.defineProperties(new Number(value),{[_type]:{value:FLOAT},[_inspect]:{value:__name(()=>`[Float: ${value}]`,"value")}})}__name(Float,"Float");function isFloat(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===FLOAT}__name(isFloat,"isFloat");function tomlType(value){const type=typeof value;if(type==="object"){if(value===null)return"null";if(value instanceof Date)return"datetime";if(_type in value){switch(value[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}}return type}__name(tomlType,"tomlType");function makeParserClass(Parser3){class TOMLParser extends Parser3{static{__name(this,"TOMLParser")}constructor(){super();this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===Parser3.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===Parser3.END){return null}else if(this.char===CHAR_LSQB){return this.call(this.parseTableOrList)}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(isAlphaNumQuoteHyphen(this.char)){return this.callNow(this.parseAssignStatement)}else{throw this.error(new TomlError(`Unknown character "${this.char}"`))}}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(this.char===CHAR_NUM){return this.goto(this.parseComment)}else if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}else{throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(kv){let target=this.ctx;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(key){if(this.state.resultTable){this.state.resultTable.push(key)}else{this.state.resultTable=[key]}return this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD){return this.next(this.parseAssignKeywordPostDot)}else if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.goto(this.parseAssignEqual)}}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}}parseAssignEqual(){if(this.char===CHAR_EQUALS){return this.next(this.parseAssignPreValue)}else{throw this.error(new TomlError('Invalid character, expected "="'))}}parseAssignPreValue(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseValue,this.recordAssignValue)}}recordAssignValue(value){return this.returnNow({key:this.state.resultTable,value})}parseComment(){do{if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}}while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB){this.next(this.parseList)}else{return this.goto(this.parseTable)}}parseTable(){this.ctx=this.obj;return this.goto(this.parseTableNext)}parseTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseTableMore)}}parseTableMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(hasKey(this.ctx,keyword)&&(!isTable(this.ctx[keyword])||this.ctx[keyword][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}else{this.ctx=this.ctx[keyword]=this.ctx[keyword]||Table();this.ctx[_declared]=true}return this.next(this.parseWhitespaceToEOL)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else{throw this.error(new TomlError("Can't redefine existing key"))}return this.next(this.parseTableNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseList(){this.ctx=this.obj;return this.goto(this.parseListNext)}parseListNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseListMore)}}parseListMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(!hasKey(this.ctx,keyword)){this.ctx[keyword]=List()}if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isList(this.ctx[keyword])){const next=Table();this.ctx[keyword].push(next);this.ctx=next}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListEnd)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isInlineTable(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline table"))}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseListEnd(keyword){if(this.char===CHAR_RSQB){return this.next(this.parseWhitespaceToEOL)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseValue(){if(this.char===Parser3.END){throw this.error(new TomlError("Key without value"))}else if(this.char===CHAR_QUOT){return this.next(this.parseDoubleString)}if(this.char===CHAR_APOS){return this.next(this.parseSingleString)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){return this.goto(this.parseNumberSign)}else if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else if(isDigit(this.char)){return this.goto(this.parseNumberOrDateTime)}else if(this.char===CHAR_t||this.char===CHAR_f){return this.goto(this.parseBoolean)}else if(this.char===CHAR_LSQB){return this.call(this.parseInlineList,this.recordValue)}else if(this.char===CHAR_LCUB){return this.call(this.parseInlineTable,this.recordValue)}else{throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}}recordValue(value){return this.returnNow(value)}parseInf(){if(this.char===CHAR_n){return this.next(this.parseInf2)}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseInf2(){if(this.char===CHAR_f){if(this.state.buf==="-"){return this.return(-Infinity)}else{return this.return(Infinity)}}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseNan(){if(this.char===CHAR_a){return this.next(this.parseNan2)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseNan2(){if(this.char===CHAR_n){return this.return(NaN)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseKeyword(){if(this.char===CHAR_QUOT){return this.next(this.parseBasicString)}else if(this.char===CHAR_APOS){return this.next(this.parseLiteralString)}else{return this.goto(this.parseBareKey)}}parseBareKey(){do{if(this.char===Parser3.END){throw this.error(new TomlError("Key ended without value"))}else if(isAlphaNumHyphen(this.char)){this.consume()}else if(this.state.buf.length===0){throw this.error(new TomlError("Empty bare keys are not allowed"))}else{return this.returnNow()}}while(this.nextChar())}parseSingleString(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiStringMaybe)}else{return this.goto(this.parseLiteralString)}}parseLiteralString(){do{if(this.char===CHAR_APOS){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiStringMaybe(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiString)}else{return this.returnNow()}}parseLiteralMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseLiteralMultiStringContent)}else{return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiEnd(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd2)}else{this.state.buf+="'";return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiEnd2(){if(this.char===CHAR_APOS){return this.return()}else{this.state.buf+="''";return this.goto(this.parseLiteralMultiStringContent)}}parseDoubleString(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiStringMaybe)}else{return this.goto(this.parseBasicString)}}parseBasicString(){do{if(this.char===CHAR_BSOL){return this.call(this.parseEscape,this.recordEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}recordEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseBasicString)}parseMultiStringMaybe(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiString)}else{return this.returnNow()}}parseMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseMultiStringContent)}else{return this.goto(this.parseMultiStringContent)}}parseMultiStringContent(){do{if(this.char===CHAR_BSOL){return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}errorControlCharInString(){let displayCode="\\u00";if(this.char<16){displayCode+="0"}displayCode+=this.char.toString(16);return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))}recordMultiEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseMultiStringContent)}parseMultiEnd(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd2)}else{this.state.buf+='"';return this.goto(this.parseMultiStringContent)}}parseMultiEnd2(){if(this.char===CHAR_QUOT){return this.return()}else{this.state.buf+='""';return this.goto(this.parseMultiStringContent)}}parseMultiEscape(){if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else if(this.char===CHAR_SP||this.char===CTRL_I){return this.next(this.parsePreMultiTrim)}else{return this.goto(this.parseEscape)}}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else{throw this.error(new TomlError("Can't escape whitespace"))}}parseMultiTrim(){if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else{return this.returnNow()}}parseEscape(){if(this.char in escapes){return this.return(escapes[this.char])}else if(this.char===CHAR_u){return this.call(this.parseSmallUnicode,this.parseUnicodeReturn)}else if(this.char===CHAR_U){return this.call(this.parseLargeUnicode,this.parseUnicodeReturn)}else{throw this.error(new TomlError("Unknown escape character: "+this.char))}}parseUnicodeReturn(char){try{const codePoint=parseInt(char,16);if(codePoint>=SURROGATE_FIRST&&codePoint<=SURROGATE_LAST){throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"))}return this.returnNow(String.fromCodePoint(codePoint))}catch(err){throw this.error(TomlError.wrap(err))}}parseSmallUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=4)return this.return()}}parseLargeUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=8)return this.return()}}parseNumberSign(){this.consume();return this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else{return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}}parseNumberIntegerStart(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberIntegerExponentOrDecimal)}else{return this.goto(this.parseNumberInteger)}}parseNumberIntegerExponentOrDecimal(){if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Integer(this.state.buf))}}parseNumberInteger(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Float(this.state.buf))}}parseNumberExponentSign(){if(isDigit(this.char)){return this.goto(this.parseNumberExponent)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.call(this.parseNoUnder,this.parseNumberExponent)}else{throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}}parseNumberExponent(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else{return this.returnNow(Float(this.state.buf))}}parseNumberOrDateTime(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberBaseOrDateTime)}else{return this.goto(this.parseNumberOrDateTimeOnly)}}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberInteger)}else if(isDigit(this.char)){this.consume();if(this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{return this.returnNow(Integer(this.state.buf))}}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char)){return this.consume()}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{throw this.error(new TomlError("Expected digit while parsing year part of a date"))}}else{if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else{throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}}}parseNumberBaseOrDateTime(){if(this.char===CHAR_b){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)}else if(this.char===CHAR_o){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)}else if(this.char===CHAR_x){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)}else if(this.char===CHAR_PERIOD){return this.goto(this.parseNumberInteger)}else if(isDigit(this.char)){return this.goto(this.parseDateTimeOnly)}else{return this.returnNow(Integer(this.state.buf))}}parseIntegerHex(){if(isHexit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerOct(){if(isOctit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerBin(){if(isBit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseDateTime(){if(this.state.buf.length<4){throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2){throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseDateDay)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2){throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseStartTimeHour)}else if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result+"-"+this.state.buf))}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseStartTimeHour(){if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result))}else{return this.goto(this.parseTimeHour)}}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result+="T"+this.state.buf;this.state.buf="";return this.next(this.parseTimeMin)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeSec)}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeZoneOrFraction)}}else{throw this.error(new TomlError("Incomplete datetime"))}}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeMin)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeSec)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){return this.next(this.parseOnlyTimeFractionMaybe)}}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeFractionMaybe(){this.state.result+=":"+this.state.buf;if(this.char===CHAR_PERIOD){this.state.buf="";this.next(this.parseOnlyTimeFraction)}else{return this.return(createTime(this.state.result))}}parseOnlyTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD){this.consume();this.next(this.parseDateTimeFraction)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseDateTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.state.buf.length===1){throw this.error(new TomlError("Expected digit in milliseconds"))}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneHour(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseTimeZoneSep(){if(this.char===CHAR_COLON){this.consume();this.next(this.parseTimeZoneMin)}else{throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}}parseTimeZoneMin(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseBoolean(){if(this.char===CHAR_t){this.consume();return this.next(this.parseTrue_r)}else if(this.char===CHAR_f){this.consume();return this.next(this.parseFalse_a)}}parseTrue_r(){if(this.char===CHAR_r){this.consume();return this.next(this.parseTrue_u)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_u(){if(this.char===CHAR_u){this.consume();return this.next(this.parseTrue_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_e(){if(this.char===CHAR_e){return this.return(true)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_a(){if(this.char===CHAR_a){this.consume();return this.next(this.parseFalse_l)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_l(){if(this.char===CHAR_l){this.consume();return this.next(this.parseFalse_s)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_s(){if(this.char===CHAR_s){this.consume();return this.next(this.parseFalse_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_e(){if(this.char===CHAR_e){return this.return(false)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_RSQB){return this.return(this.state.resultArr||InlineList())}else{return this.callNow(this.parseValue,this.recordInlineListValue)}}recordInlineListValue(value){if(this.state.resultArr){const listType=this.state.resultArr[_contentType];const valueType=tomlType(value);if(listType!==valueType){throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))}}else{this.state.resultArr=InlineList(tomlType(value))}if(isFloat(value)||isInteger(value)){this.state.resultArr.push(value.valueOf())}else{this.state.resultArr.push(value)}return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineList)}else if(this.char===CHAR_RSQB){return this.goto(this.parseInlineList)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_RCUB){return this.return(this.state.resultTable||InlineTable())}else{if(!this.state.resultTable)this.state.resultTable=InlineTable();return this.callNow(this.parseAssign,this.recordInlineTableValue)}}recordInlineTableValue(kv){let target=this.state.resultTable;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineTable)}else if(this.char===CHAR_RCUB){return this.goto(this.parseInlineTable)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}}return TOMLParser}__name(makeParserClass,"makeParserClass")}});var require_parse_pretty_error=__commonJS({"node_modules/@iarna/toml/parse-pretty-error.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=prettyError;function prettyError(err,buf){if(err.pos==null||err.line==null)return err;let msg=err.message;msg+=` at row ${err.line+1}, col ${err.col+1}, pos ${err.pos}:
|
|
3
|
+
import{isBidiControlChar,stripDisplayControlChars,stripTerminalControlSequences,truncateNotificationLabel}from"./chunk-R2EHHA2C.js";import{SshWorkspaceClient,SshWorkspaceError}from"./chunk-ZLZF2ZDD.js";import{ExecutionCleanupError,MANAGED_RUNTIME_TOOL_NAMES,ManagedRuntimeOutcomeUnknownError}from"./chunk-JUPGJYC2.js";import{AjvJsonSchemaValidator,CallToolResultSchema,CompleteResultSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,CreateTaskResultSchema,ElicitRequestSchema,ElicitResultSchema,EmptyResultSchema,ErrorCode,GetPromptResultSchema,InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION,ListChangedOptionsBaseSchema,ListPromptsResultSchema,ListResourceTemplatesResultSchema,ListResourcesResultSchema,ListToolsResultSchema,McpError,PromptListChangedNotificationSchema,Protocol,ReadBuffer,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SUPPORTED_PROTOCOL_VERSIONS,ToolListChangedNotificationSchema,assertClientRequestTaskCapability,assertToolsCallTaskCapability,getLiteralValue,getObjectShape,isInitializedNotification,isJSONRPCRequest,isJSONRPCResultResponse,mergeCapabilities,safeParse,serializeMessage}from"./chunk-YK7NDQKM.js";import{EMPTY_COMMIT_PREFIX_HASH,HARNESS_DURABLE_WAIT_BOUNDARY,HARNESS_MODEL_START_PHASES,HARNESS_TURN_COMPLETE_BOUNDARY,LITE_READ_BUF_SIZE,LocalJsonlManagedSessionJournalStore,LocalManagedSessionAuthority,LocalManagedSessionResourceStore,MAX_SNAPSHOTS,ManagedSessionCommitRejectedError,ManagedSessionConflictError,ManagedSessionUncommittedTailError,SessionTranscriptChangedError,SessionTranscriptIdentityUnavailableError,SessionWriterError,SessionWriterLease,SessionWriterLostError,SessionWriterUnavailableError,activationAlreadyInstalledError,assertManagedSessionRestoreBundle,createAwaitActionHarnessCheckpoint,createAwaitAgentHarnessCheckpoint,createAwaitCommandHarnessCheckpoint,createAwaitRuntimeHarnessCheckpoint,createConsumedAgentWaitHarnessCheckpoint,createConsumedCommandWaitHarnessCheckpoint,createConsumedRuntimeResultsHarnessCheckpoint,createHookStoppedRuntimeHarnessCheckpoint,createInitialHarnessCheckpoint,createModelOutputCommittedHarnessCheckpoint,createNextTurnReadyHarnessCheckpoint,createResultsReadyHarnessCheckpoint,createTurnSettledHarnessCheckpoint,encodeHarnessCheckpointV1,harnessCommandLockOf,harnessCommandLocked,isManagedExecutionTranscriptSync,isManagedOwnerRecord,isManagedSessionTranscriptSync,localManagedSessionKey,managedSessionResourceRoot,managedToolDigest,managedToolFailureMessage,managedToolResponseParts,parseHarnessCheckpointV1,publishManagedMessageBody,readLastJsonStringFieldSync,readLastMatchingLineFieldSync,readManagedBranchCheckpoint,readManagedExecutionEvidenceSync,readManagedMessageBody,readManagedSessionLog,readManagedSessionSourceSync,readManagedSessionTitleInfoSync,readSessionTitleInfoFromFileSync,tryParseHarnessCheckpointV1}from"./chunk-DD4SV4AJ.js";import{require_main,resolveEnvVarsInObject}from"./chunk-OGI5HG6N.js";import{isShellResultDisplay,mapShellResultText,shellResultText}from"./chunk-T7CHK6C2.js";import{SessionExecutionEngineAccumulator,SessionExecutionEngineError,assertSessionExecutionEngine}from"./chunk-VZDZ34KK.js";import{NEVER,ZodIssueCode,any,array,boolean,coerce_exports,literal,looseObject,number,object,string,url}from"./chunk-PT7NZBDY.js";import{external_exports}from"./chunk-TWP72VRH.js";import{MANAGED_SESSION_FORMAT_VERSION,MANAGED_SESSION_HEADER_SUBTYPE,MANAGED_SESSION_LIMITS,ManagedSessionAppendUnsettledError,ManagedSessionRecordError,assertManagedSessionDurableRef,collectPendingBranchToolCalls,managedSessionReaderFacingBody,parseBranchCheckpointPayload,resolveBranchPoints,resolveCompletedTurnBranchCandidateFromRecords,safeErrorValue,updatePendingBranchToolCalls,validateManagedReaderFacingRecord}from"./chunk-XKVETIZH.js";import{require_content_type}from"./chunk-PHIPLV2I.js";import{consumeUnread,forwardApproval,getInboxPath,readInbox,sendStructuredMessage,wrapConfirmWithBadge,writeMessage}from"./chunk-WK2IBT6D.js";import{claimTask,listTasks,onTasksUpdated,unassignTeammateTasks}from"./chunk-UYEWRLGD.js";import{AGENT_WORKTREE_SLUG_PATTERN,GitWorktreeService,MAX_DIFF_SIZE_BYTES,clearRuntimeStatus,generateAgentWorktreeSlug,gitEnv,gitRemoteEnv,loadSimpleGit,readRuntimeStatus,worktreeBranchForSlug,worktreeHasWork,writeRuntimeStatus,writeWorktreeSessionMarker}from"./chunk-LLX4BCWK.js";import{hasVerifiableInode,openNoFollow,openSyncNoFollow}from"./chunk-QXQGUM3Y.js";import{SessionArtifactSnapshotAccumulator,deleteArtifactSnapshot,getWebPreviewSnapshotId,isSessionArtifactRecord,rebuildSessionArtifactSnapshot,remapSessionArtifactPayloadForFork,retainArtifactSnapshot,selectActiveSideArtifactRecordUuids}from"./chunk-AG3SSCAF.js";import{aggregateTranscriptRecordFragments,isInternalCodeModeToolResult,isTranscriptConversationRecord,isUserPromptSubmitContextPartText,prepareTranscriptRecords,projectUserTranscriptForDisplay,selectTranscriptLeaf,stripGeneratedAttachmentTokens,validateTranscriptRecord,walkTranscriptUuidChain,wrapUserPromptSubmitContext}from"./chunk-BMSATZXW.js";import{CronScheduler,DEFAULT_RECURRING_MAX_AGE_DAYS,closeFileWatcher,normalizeRecurringMaxAge}from"./chunk-57RLZJ6C.js";import{loadSkillsFromDir,parsePriorityField,readBundledReference,resolveBundledReferenceSurface,toolSearchBridgeSentence,validateConfig,validateSymlinkTarget}from"./chunk-GWYQTKSR.js";import{SKILL_FILE_NAME,assertRealProjectSkillPath,getArchivedSkillsRoot,getPendingSkillsRoot,getProjectSkillsRoot,isProjectSkillPath,maybeRunAutoSkillCurator}from"./chunk-XQJOZDV7.js";import{SKILL_NAME_PATTERN,SkillError,SkillErrorCode,authoredSkillName,parseAllowedToolsField,parseModelField,parsePathsField,parseUserInvocableField,qualifySkillName,skillRestrictionNames,validateSkillName}from"./chunk-CV2UAEZA.js";import{AUTO_MEMORY_SCHEMA_VERSION,AUTO_MEMORY_SCOPES,AUTO_MEMORY_TREE_CATEGORIES,AUTO_MEMORY_TYPES,MAX_USAGE_SCENARIO_CHARS,createAutoMemoryTreeSnapshot,listTrustedMemoryMarkdownFiles,normalizeAutoMemoryKeyword,parseAutoMemoryTopicDocument,renderAutoMemoryFocusedSubtree,rereadAutoMemoryDocument,resolveTrustedMemoryFile,resolveTrustedMemoryRoot,sanitizeAutoMemoryPromptField,scanAllAutoMemoryTopicDocuments,scanAllAutoMemoryTopicDocumentsFromRoot,scanAllUserAutoMemoryTopicDocuments,scanAutoMemorySnapshot,scanAutoMemoryTopicDocuments,scanTeamAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments,toAutoMemoryRef,validateStructuredAutoMemoryDocument}from"./chunk-GNQGC2DJ.js";import{AgentOutputMessageCapture,DEFAULT_OTLP_ENDPOINT,DEFAULT_TELEMETRY_TARGET,GOAL_DEFAULT_TOKEN_BUDGET,GOAL_INFEASIBLE_NEXT_STEP,GOAL_NO_PROGRESS_TURN_LIMIT,GOAL_PAUSE_REASON_NO_PROGRESS,GOAL_PAUSE_REASON_SESSION_TOKEN_LIMIT,GOAL_PAUSE_REASON_STOP_HOOK_CAP,GOAL_PAUSE_REASON_USER_INTERRUPT,GOAL_PROPOSAL_REASON_MAX_CHARACTERS,GOAL_STATE_VERSION,GoalConflictError,GoalInvalidTransitionError,PAUSED_GOAL_SYSTEM_REMINDER,addAgentInputMessageAttributes,addToolArgumentsAttributes,addToolCallResultAttributes,addUserPromptAttributes,elapsedActiveTime,goalActiveTimeBudgetReason,goalPauseReasonForFailure,goalPauseReasonForVerifierFailure,goalRequiresExactPermit,goalStateEventFromSnapshot,goalTokenBudgetReason,goalTurnBudgetReason,isGoalActiveTimeBudgetSpent,isGoalTokenBudgetSpent,isGoalTurnBudgetSpent,isRepeatedBlockerProposal,parseGoalStateRecordPayloadV2,reduceGoalControl,reduceGoalSpend,reduceGoalTurnFinished,validateGoalProposalReason}from"./chunk-F63ESLTI.js";import{parse,require_dist,sanitizeValue,stringify}from"./chunk-KLC3OD2M.js";import{canUseRipgrep}from"./chunk-K6EQXZMK.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{buildModelIdContext,resolveModelId}from"./chunk-BEKROCWN.js";import{SHARED_RECORD_SLOT,defangEnvelopeTags,deriveSessionName,flattenPeerLabel,patchSessionRecord,unregisterSession}from"./chunk-BYU42MLK.js";import{LEADER_NAME,MAX_TEAMMATES,assignTeammateColor,classifyShutdownResponse,findMemberByName,formatAgentId,generateUniqueTeammateName,sanitizeName,writeTeamFile}from"./chunk-JWQXU3SR.js";import{normalizeImageGenerationBaseUrl}from"./chunk-JVJS2YFU.js";import{restoreSessionSources}from"./chunk-G5PYYZMM.js";import{isTruthy}from"./chunk-D7XCQWP2.js";import{glob,globSync}from"./chunk-OBOU4ZZM.js";import{ToolMode,buildExecDeclaration,getToolExposure,isCodeModeToolCallAllowed,isDeferredToolBridgeAvailable,isDirectToolBridgeAvailable,planCodeModeBindings}from"./chunk-4VUT7DCY.js";import{EXCLUDED_TOOLS_FOR_SUBAGENTS,READ_ONLY_INSPECTION_TOOLS,SHELL_TOOL_NAMES,buildPermissionRules,buildSubagentPlanToolBlockedResult,getExcludedToolUnavailableMessage,getLeaderOnlyToolUnavailableMessage,getPlanRequiredTeammatePreApprovalMessage,getSubagentPlanToolUnavailableMessage,getToolNameAliases,hasAmbiguousMcpGrant,isLeaderOnlyToolUnavailableInSubagent,isPlanLifecycleToolUnavailableInSubagent,isPlanRequiredTeammateAwaitingApproval,isPlanRequiredTeammateContext,isPlanRequiredTeammatePreApprovalAllowedTool,isSubagentLikeExecutionContext,isToolExcludedForCurrentContext,matchesAgentToolBlocklist,matchesRule,matchesToolPattern,parseRule,parseRules,require_picomatch,resolveToolName,shouldUsePlanOnlyReminderInSubagentContext,splitCompoundCommand,splitCompoundCommandSegments,toolConfigAllowsSkill,toolMatchesRuleToolName}from"./chunk-FQQMMFT6.js";import{APPROVAL_MODES,ApprovalMode}from"./chunk-JZK2WGXA.js";import{executeSandbox}from"./chunk-BQTFBDPK.js";import{admitShellSandbox,assertShellSandboxCwd,probeShellSandbox}from"./chunk-PPHCG6Q5.js";import{resolveNetworkTarget}from"./chunk-JKXBHBE3.js";import{isOmniDeliveryActive}from"./chunk-6UZ65Z2P.js";import{MediaResourceRegistry,evaluateMediaPolicyToolCall,isMediaPolicyToolHiddenFromModel,resolveMediaPolicyModelAccess}from"./chunk-S2ZKZXHX.js";import{AskUserQuestionTool,TrustedUserAnswers,assembleSystemPrompt,getArenaSystemReminder,getCompressionPrompt,getCoreSystemPrompt,getCustomSystemPrompt,getManualPlanExitSystemReminder,getOutputStyleTurnReminder,getPlanModeSystemReminder,resolveEffectiveOutputStyle,resolveInteractionMode,resolveMainSessionOutputStyle}from"./chunk-PXXU2KWH.js";import{NO_EXEC_CONFIG,findGitRoot,getCachedGitBranch,getGitBranch,getRecentGitStatus,isGitRepository}from"./chunk-EBMCWXGZ.js";import{ShellExecutionService,getShellAbortReasonKind,getShellContextEnvVars,getShellPagerEnv,isSignalTermination,normalizePathEnvForWindows}from"./chunk-3X7DP5W3.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{promptIdContext,todoWorkChainContext}from"./chunk-MWGB5RCF.js";import{SHELL_SELF_KILL_REJECTION,buildOutsideWorkspaceWarning,buildShellExecWarnings,classifyAwkCommandSafety,classifySedCommandSafety,detectSelfKillCommand,escapeShellArg,getCommandRoot,getCommandRoots,getShellConfiguration,hasShellPatternExpansion,hasShellSubstitution,isShellCommandReadOnly,normalizeMonitorCommand,shouldDefaultToNodePty,splitCommands,stripShellWrapper}from"./chunk-XWEXQT3X.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{require_shell_quote}from"./chunk-TL3SF2GA.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{BaseTokenStorage,KeychainTokenStorage}from"./chunk-4GP3PH7Z.js";import{isInternalSecretEnvVar,sanitizeChildEnv}from"./chunk-LFKUPU57.js";import{carryIncompleteArgumentsMarker,supportsOpenAIPrefixCaching,toolCallArgumentsWereIncomplete}from"./chunk-T2F7KYYR.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX}from"./chunk-SW54YEPK.js";import{DashScopeOpenAICompatibleProvider,selectDashScopeThinkingKnob}from"./chunk-RHEMFKMX.js";import{assertHookExecutionOwner,captureHookExecutionOwner,childLaunchDepth,getCurrentAgentChat,getCurrentAgentConfiguredToolAllowlist,getCurrentAgentDepth,getCurrentAgentDisallowedTools,getCurrentAgentId,getHookExecutionOwner,getRuntimeContentGenerator,isTopLevelSession,resolveHookExecutionOwner,runOutsideAgentContext,runWithAgentChat,runWithAgentConfiguredToolAllowlist,runWithAgentContext,runWithAgentDisallowedTools,runWithHookExecutionOwner,runWithRuntimeContentGenerator,spawnBlockReason}from"./chunk-7J2TOJMG.js";import{getTeammateContext,isTeammate,runOutsideTeammateIdentity,runWithTeammateIdentity}from"./chunk-AGEDDL7Z.js";import{getResponsesMessage,sameResponsesMessage}from"./chunk-2NJJHZ52.js";import{openBrowserSecurely,shouldAttemptBrowserLaunch}from"./chunk-3YWXKSOI.js";import{beginRetryWait,bindRetryWaitObserver,delay,isUnattendedMode,retryWithBackoff,runWithRetryWaitObserver}from"./chunk-2PMQL4KE.js";import{InMemoryImagePayloadStore,InvalidStreamError,REATTACH_BOUNDARY_METADATA,buildReattachParts,countAllInlineImages,getToolCallPreparations,hasImagePayloadReferences,isFlushedToolCallPark,isRetryableStatuslessUpstreamError,isRetryableStreamTransportError,replaceImagePayloadsInPlace,setToolCallPreparations}from"./chunk-V3XYE727.js";import{getThoughtSummary}from"./chunk-BRPC43OM.js";import{ModelsConfig,captureReasoningSnapshot,getBuiltinDeepSeekReasoning,getRequestModel,isImageGenerationCapable,resolveProviderProtocol,resolveReasoningCapabilities,resolveReasoningForModel,stripRuntimeSnapshotPrefix,validateReasoningCapabilities}from"./chunk-DIHJELGW.js";import{QUOTA_EXHAUSTED_PREFIX,classifyRetryError,formatQuotaExhaustedMessage,getHeaderValue,getRateLimitErrorDetails,getRateLimitRetryDelayMs,isApiError,isFallbackEligible,isQuotaExhaustedError,isRateLimitError,isRetryableUpstreamError,isStructuredError}from"./chunk-WZDBBDRD.js";import{combineAbortSignals,createAbortController,createChildAbortController}from"./chunk-476F6QIM.js";import{ResponsesHttpError}from"./chunk-4R67LXKL.js";import{addDaemonRequestAttribute}from"./chunk-VTDSLBET.js";import{ApiRetryEvent,COMBINED_PASS_TOLERANCE_FACTOR,ContentRetryEvent,ContentRetryFailureEvent,DiscoveredMCPTool,ExtensionDisableEvent,ExtensionEnableEvent,ExtensionInstallEvent,ExtensionUninstallEvent,ExtensionUpdateEvent,FULL_OUTPUT_DIGEST_LABEL,HookCallEvent,LoopDetectedEvent,LoopDetectionDisabledEvent,MemoryDreamEvent,MemoryExtractEvent,MemoryMigrationEvent,MemoryRecallDeliveryEvent,MemoryRecallEvent,MemoryRecallModeTransitionEvent,NextSpeakerCheckEvent,PREVIEW_SIZE_CHARS,RipgrepFallbackEvent,StartSessionEvent,SubagentExecutionEvent,TOOL_OUTPUT_TRUNCATED_PREFIX,ToolCallEvent,ToolResultSizeEvent,UiTelemetryService,attachToolOutputProvenance,collectText,effectiveAppResourceMaxBytes,effectiveAppResourceTimeoutMs,formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,getMCPServerStatus,getQualifiedVisionModelId,getToolOutputProvenance,isAlreadyTruncated,isChatRecordingSuppressed,isFullTurnVisionCapable,isImagePart,isSkipSelectorOnUniqueStrongHitEnabled,logApiRetry,logArenaAgentCompleted,logArenaSessionEnded,logArenaSessionStarted,logChatCompression,logContentRetry,logContentRetryFailure,logExtensionDisable,logExtensionEnable,logExtensionInstallEvent,logExtensionUninstall,logExtensionUpdateEvent,logGoalState,logHookCall,logLoopDetected,logLoopDetectionDisabled,logMemoryDream,logMemoryExtract,logMemoryMigration,logMemoryRecall,logMemoryRecallDelivery,logMemoryRecallModeTransition,logNextSpeakerCheck,logRipgrepFallback,logSessionEnd,logStartSession,logSubagentExecution,logToolCall,logToolResultSize,makeArenaAgentCompletedEvent,makeArenaSessionEndedEvent,makeArenaSessionStartedEvent,makeChatCompressionEvent,measureToolOutput,memoryAge,memoryFreshnessText,normalizeParts,normalizeToolResultCallId,persistAndTruncateToolResult,recordMCPServerLastError,removeMCPServerStatus,runVisionBridge,runWithChatRecordingSuppressed,selectVisionBridgeModel,shouldRunVisionBridge,subagentIdentityContext,subagentNameContext,truncateLlmContent,truncateToolOutput,uiTelemetryService,updateMCPServerStatus,updateToolOutputBudget}from"./chunk-DR3HLUJ5.js";import{_recoverObjectsFromLine,exists,parseLineTolerant,read,readLines,readLinesWithIntegrity,writeLine,writeLineSync}from"./chunk-UQFTXKEB.js";import{Mutex}from"./chunk-HDGTWJ24.js";import{extractCodeModeImageContent,getCurrentToolCallSource,runWithToolCallRuntime,runWithToolCallSource,runWithoutToolCallRuntime}from"./chunk-W5NWIGKO.js";import{runSideQuery}from"./chunk-6C4YRBLR.js";import{FileExclusions,FileReadOpenError,LOCAL_CONTEXT_FILENAME,digestFileReadSource,getAllMemoryFilenames,isUtf8CompatibleEncoding,loadIconvLite,readFileHandleBytes,readFileWithLineAndLimit,readTextCursorWindowFromHandle,readTextRangeFromHandle,setMemoryFilename}from"./chunk-JU2HHQR5.js";import{AUTO_MEMORY_INDEX_FILENAME,AUTO_MEMORY_PINNED_DIRNAME,TEAM_AUTO_MEMORY_DIRNAME,getAutoMemoryConsolidationLockPath,getAutoMemoryExtractCursorPath,getAutoMemoryIndexPath,getAutoMemoryMetadataPath,getAutoMemoryRoot,getAutoMemoryTrustedAnchor,getMemoryBaseDir,getMemoryRootTrustedAnchor,getProjectAutoMemoryRoots,getTeamAutoMemoryIndexPath,getTeamAutoMemoryRoot,getUserAutoMemoryConsolidationLockPath,getUserAutoMemoryIndexPath,getUserAutoMemoryMetadataPath,getUserAutoMemoryRoot,isAnyAutoMemPath,isAutoMemPath,isManagedMemoryPath,isTeamAutoMemPath,isUserAutoMemPath}from"./chunk-37KFLBKZ.js";import{getSystemEncoding}from"./chunk-7U7CWMP7.js";import{getInvocationContext,runWithInvocationContext}from"./chunk-SLD7H2FA.js";import{normalizeMcpToolName,sanitizeToolNameForProvider}from"./chunk-7DOOXUDG.js";import{clampInlineMediaPart}from"./chunk-P3RLMP7L.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,TOKEN_TO_CHAR_RATIO,estimateContentChars,getFunctionResponseParts,resolveCompactionTuning,resolveSlimmingConfig,sanitizeMimeForPlaceholder,slimCompactionInput}from"./chunk-R54OXALA.js";import{AUTH_ENV_MAPPINGS,DEFAULT_MODELS,DEFAULT_QWEN_EMBEDDING_MODEL,MODEL_GENERATION_CONFIG_FIELDS,QWEN_OAUTH_ALLOWED_MODELS,createContentGenerator,resetPreloadedContentGenerator,resolveContentGeneratorConfigWithSources}from"./chunk-PWHD4NK3.js";import{CATALOG_MODALITIES,DEFAULT_TOKEN_LIMIT,MIN_AUTO_DETECTED_CONTEXT_WINDOW,MODELS_DEV_URL,MODEL_CATALOG_PROJECTION_VERSION,MODEL_CATALOG_URL_ENV,OUTPUT_TOKEN_CEILING,REASONING_EFFORT_TIERS,clampOutputTokensToWindow,clampReasoningEffort,defaultModalities,defaultOutputCeiling,getGptReasoningCapabilities,getModelCatalogCachePath,hasExplicitOutputLimit,isModelCatalogDisabled,isModelCatalogKey,isTieredEffortWireModel,knownTokenLimit,normalize,normalizeReasoningEffort,parseModelCatalog,parsePositiveIntegerEnvValue,reasoningEffortsForCapability,setGeneratorReasoningEffort,tokenLimit,versionSpellingAlias}from"./chunk-TAAJ7TDB.js";import{DEFAULT_QWEN_MODEL}from"./chunk-4ZBZL23U.js";import{getOrCreateMcpDispatcher,loadUndici,preloadRuntimeFetchModule,redactProxyError,setResolvedProxyUrlForRuntimeFetch}from"./chunk-ZZZAYAJW.js";import{safeJsonStringify}from"./chunk-XMANRGPK.js";import{DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT,TOOL_FAILURE_KIND_ATTRIBUTE,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_FAILURE_KIND_CANCELLED,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_FAILURE_KIND_POST_HOOK_STOPPED,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_FAILURE_KIND_TIMEOUT,TOOL_FAILURE_KIND_TOOL_ERROR,TOOL_FAILURE_KIND_TOOL_EXCEPTION,endHookSpan,endInteractionSpan,endSubagentSpan,endToolBlockedOnUserSpan,endToolExecutionSpan,endToolSpan,getActiveInteractionSpan,initializeTelemetry,isPerformanceMonitoringActive,isTelemetrySdkInitialized,isValidSensitiveSpanAttributeMaxLength,recordCpuUsage,recordInteractionActivity,recordMemoryUsage,redactUrlCredentials,refreshSessionContext,runInSubagentSpanContext,runInToolSpanContext,safeSetStatus,shutdownTelemetry,startHookSpan,startInteractionSpan,startSubagentSpan,startToolBlockedOnUserSpan,startToolExecutionSpan,startToolSpan,truncateSpanError}from"./chunk-XHV5HLJS.js";import{STRUCTURED_OUTPUT_REDACTED_ARGS}from"./chunk-BWU6AH5O.js";import{atomicWriteFile,atomicWriteFileSync,atomicWriteJSON,renameWithRetry}from"./chunk-BMHYEQTI.js";import{require_src}from"./chunk-GU22I6TY.js";import{normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-4YLXNRRH.js";import{BUBBLE_APPROVAL_MODE,FORK_AGENT,FORK_DEFAULT_MAX_TURNS,FORK_PLACEHOLDER_RESULT,FORK_SUBAGENT_TYPE,SubagentError,SubagentErrorCode,buildAvailableSkillsReminder,buildChangedAgentsReminder,buildChangedMcpToolsReminder,buildChangedSkillsReminder,buildChildMessage,buildDeferredToolsReminder,buildForkExecutionAllowlist,buildForkedMessages,buildFunctionResponseParts,buildMcpServerInstructionsReminder,buildMcpServerInstructionsReminderFromEntries,buildPinnedWorktreeNotice,buildWorktreeNotice,formatDateForContext,getDirectoryContextString,getInitialChatHistory,getStartupContextLength,isSystemReminderContent,normalizeForkTurns,registerForkDisplayImageForCache,resolveForkExecutionAllowedTools,runInForkContext,selectForkHistory,stripSystemReminderBlocks,validateForkToolList,wrapSystemReminder}from"./chunk-65UCR6OZ.js";import{SESSION_SKILL_MANAGER,SKILLS_ACTIVATED_OPENER,clearLoadedSkillTracking,collectAvailableSkillEntries,renderAvailableSkillsBlock,sessionSkillManager}from"./chunk-CN2TQ3PU.js";import{DefaultHookOutput,HOOKS_CONFIG_FIELDS,HookEventName,PermissionRequestHookOutput,PostToolBatchHookOutput,PostToolUseFailureHookOutput,PostToolUseHookOutput,PreToolUseHookOutput,StopHookOutput,UserPromptExpansionHookOutput,createHookOutput,escapeSystemReminderTags,escapeXml,escapeXmlElementText,escapeXmlWithinBudget,getHookKey,isBlockingHookOutput,isToolArtifactLike,toUpdatedToolInput}from"./chunk-6GTPLW7K.js";import{DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES,QwenIgnoreParser,formatQwenIgnoreFileNames,require_ignore}from"./chunk-5DTFN37U.js";import{WorkspaceContext,isPathWithinRoot}from"./chunk-2YUBAWQ6.js";import{AgentStatistics,BaseDeclarativeTool,BaseToolInvocation,CONCURRENCY_SAFE_KINDS,StructuredToolError,hasCycleInSchema,isShellProgressData}from"./chunk-O5EKX7LG.js";import{AGENT_HOST_TOOL_NAMES,ToolDisplayNames,ToolDisplayNamesMigration,ToolNames,ToolNamesMigration,canonicalToolName,resolveBuiltinToolName,resolveRegisteredToolName}from"./chunk-2UNFJQ2D.js";import{createDebugLogger,isDebugLogFileEnabled,registerSessionModel,registerSessionProjectDir,sessionIdContext,setDebugLogSession,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import{SpanStatusCode,context,init_esm,trace}from"./chunk-I4H7NUVP.js";import{SKILL_PROVIDER_CONFIG_DIRS,Storage}from"./chunk-EPODBRBP.js";import{PATH_ARG_KEYS,QWEN_DIR,expandHomeDir,getProjectHash,isSubpath,isSubpaths,makeRelative,resolvePath,shortenPath,tildeifyPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{FatalConfigError,UnauthorizedError,getErrorMessage,getErrorStatus,getErrorType,isAbortError,isNodeError,toFriendlyError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__commonJS,__export,__name,__require,__toESM}from"./chunk-KBWJGX7I.js";var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs77=__require("fs");function checkPathExt(path82,options2){var pathext=options2.pathExt!==void 0?options2.pathExt:process.env.PATHEXT;if(!pathext){return true}pathext=pathext.split(";");if(pathext.indexOf("")!==-1){return true}for(var i=0;i<pathext.length;i++){var p2=pathext[i].toLowerCase();if(p2&&path82.substr(-p2.length).toLowerCase()===p2){return true}}return false}__name(checkPathExt,"checkPathExt");function checkStat(stat14,path82,options2){if(!stat14.isSymbolicLink()&&!stat14.isFile()){return false}return checkPathExt(path82,options2)}__name(checkStat,"checkStat");function isexe(path82,options2,cb){fs77.stat(path82,function(er2,stat14){cb(er2,er2?false:checkStat(stat14,path82,options2))})}__name(isexe,"isexe");function sync(path82,options2){return checkStat(fs77.statSync(path82),path82,options2)}__name(sync,"sync")}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs77=__require("fs");function isexe(path82,options2,cb){fs77.stat(path82,function(er2,stat14){cb(er2,er2?false:checkStat(stat14,options2))})}__name(isexe,"isexe");function sync(path82,options2){return checkStat(fs77.statSync(path82),options2)}__name(sync,"sync");function checkStat(stat14,options2){return stat14.isFile()&&checkMode(stat14,options2)}__name(checkStat,"checkStat");function checkMode(stat14,options2){var mod=stat14.mode;var uid=stat14.uid;var gid=stat14.gid;var myUid=options2.uid!==void 0?options2.uid:process.getuid&&process.getuid();var myGid=options2.gid!==void 0?options2.gid:process.getgid&&process.getgid();var u2=parseInt("100",8);var g2=parseInt("010",8);var o=parseInt("001",8);var ug=u2|g2;var ret=mod&o||mod&g2&&gid===myGid||mod&u2&&uid===myUid||mod&ug&&myUid===0;return ret}__name(checkMode,"checkMode")}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports2,module2){init_esbuild_shims();var fs77=__require("fs");var core;if(process.platform==="win32"||globalThis.TESTING_WINDOWS){core=require_windows()}else{core=require_mode()}module2.exports=isexe;isexe.sync=sync;function isexe(path82,options2,cb){if(typeof options2==="function"){cb=options2;options2={}}if(!cb){if(typeof Promise!=="function"){throw new TypeError("callback not provided")}return new Promise(function(resolve34,reject){isexe(path82,options2||{},function(er2,is2){if(er2){reject(er2)}else{resolve34(is2)}})})}core(path82,options2||{},function(er2,is2){if(er2){if(er2.code==="EACCES"||options2&&options2.ignoreErrors){er2=null;is2=false}}cb(er2,is2)})}__name(isexe,"isexe");function sync(path82,options2){try{return core.sync(path82,options2||{})}catch(er2){if(options2&&options2.ignoreErrors||er2.code==="EACCES"){return false}else{throw er2}}}__name(sync,"sync")}});var require_which=__commonJS({"node_modules/cross-spawn/node_modules/which/which.js"(exports2,module2){init_esbuild_shims();var isWindows2=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";var path82=__require("path");var COLON=isWindows2?";":":";var isexe=require_isexe();var getNotFoundError=__name(cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),"getNotFoundError");var getPathInfo=__name((cmd,opt)=>{const colon=opt.colon||COLON;const pathEnv=cmd.match(/\//)||isWindows2&&cmd.match(/\\/)?[""]:[...isWindows2?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)];const pathExtExe=isWindows2?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"";const pathExt=isWindows2?pathExtExe.split(colon):[""];if(isWindows2){if(cmd.indexOf(".")!==-1&&pathExt[0]!=="")pathExt.unshift("")}return{pathEnv,pathExt,pathExtExe}},"getPathInfo");var which=__name((cmd,opt,cb)=>{if(typeof opt==="function"){cb=opt;opt={}}if(!opt)opt={};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];const step=__name(i=>new Promise((resolve34,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve34(found):reject(getNotFoundError(cmd));const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path82.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve34(subStep(p2,i,0))}),"step");const subStep=__name((p2,i,ii2)=>new Promise((resolve34,reject)=>{if(ii2===pathExt.length)return resolve34(step(i+1));const ext=pathExt[ii2];isexe(p2+ext,{pathExt:pathExtExe},(er2,is2)=>{if(!er2&&is2){if(opt.all)found.push(p2+ext);else return resolve34(p2+ext)}return resolve34(subStep(p2,i,ii2+1))})}),"subStep");return cb?step(0).then(res=>cb(null,res),cb):step(0)},"which");var whichSync=__name((cmd,opt)=>{opt=opt||{};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];for(let i=0;i<pathEnv.length;i++){const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path82.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j2=0;j2<pathExt.length;j2++){const cur=p2+pathExt[j2];try{const is2=isexe.sync(cur,{pathExt:pathExtExe});if(is2){if(opt.all)found.push(cur);else return cur}}catch(ex){}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)},"whichSync");module2.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports2,module2){"use strict";init_esbuild_shims();var pathKey=__name((options2={})=>{const environment=options2.env||process.env;const platform2=options2.platform||process.platform;if(platform2!=="win32"){return"PATH"}return Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"},"pathKey");module2.exports=pathKey;module2.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2,module2){"use strict";init_esbuild_shims();var path82=__require("path");var which=require_which();var getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){const env=parsed.options.env||process.env;const cwd=process.cwd();const hasCustomCwd=parsed.options.cwd!=null;const shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd){try{process.chdir(parsed.options.cwd)}catch(err){}}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path82.delimiter:void 0})}catch(e){}finally{if(shouldSwitchCwd){process.chdir(cwd)}}if(resolved){resolved=path82.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)}return resolved}__name(resolveCommandAttempt,"resolveCommandAttempt");function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,true)}__name(resolveCommand,"resolveCommand");module2.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports2,module2){"use strict";init_esbuild_shims();var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){arg=arg.replace(metaCharsRegExp,"^$1");return arg}__name(escapeCommand,"escapeCommand");function escapeArgument(arg,doubleEscapeMetaChars){arg=`${arg}`;arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"');arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1");arg=`"${arg}"`;arg=arg.replace(metaCharsRegExp,"^$1");if(doubleEscapeMetaChars){arg=arg.replace(metaCharsRegExp,"^$1")}return arg}__name(escapeArgument,"escapeArgument");module2.exports.command=escapeCommand;module2.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports2,module2){"use strict";init_esbuild_shims();var shebangRegex=require_shebang_regex();module2.exports=(string7="")=>{const match=string7.match(shebangRegex);if(!match){return null}const[path82,argument]=match[0].replace(/#! ?/,"").split(" ");const binary=path82.split("/").pop();if(binary==="env"){return argument}return argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports2,module2){"use strict";init_esbuild_shims();var fs77=__require("fs");var shebangCommand=require_shebang_command();function readShebang(command){const size=150;const buffer=Buffer.alloc(size);let fd;try{fd=fs77.openSync(command,"r");fs77.readSync(fd,buffer,0,size,0);fs77.closeSync(fd)}catch(e){}return shebangCommand(buffer.toString())}__name(readShebang,"readShebang");module2.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports2,module2){"use strict";init_esbuild_shims();var path82=__require("path");var resolveCommand=require_resolveCommand();var escape3=require_escape();var readShebang=require_readShebang();var isWin=process.platform==="win32";var isExecutableRegExp=/\.(?:com|exe)$/i;var isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);const shebang=parsed.file&&readShebang(parsed.file);if(shebang){parsed.args.unshift(parsed.file);parsed.command=shebang;return resolveCommand(parsed)}return parsed.file}__name(detectShebang,"detectShebang");function parseNonShell(parsed){if(!isWin){return parsed}const commandFile=detectShebang(parsed);const needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){const needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path82.normalize(parsed.command);parsed.command=escape3.command(parsed.command);parsed.args=parsed.args.map(arg=>escape3.argument(arg,needsDoubleEscapeMetaChars));const shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`];parsed.command=process.env.comspec||"cmd.exe";parsed.options.windowsVerbatimArguments=true}return parsed}__name(parseNonShell,"parseNonShell");function parse14(command,args,options2){if(args&&!Array.isArray(args)){options2=args;args=null}args=args?args.slice(0):[];options2=Object.assign({},options2);const parsed={command,args,options:options2,file:void 0,original:{command,args}};return options2.shell?parsed:parseNonShell(parsed)}__name(parse14,"parse");module2.exports=parse14}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports2,module2){"use strict";init_esbuild_shims();var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}__name(notFoundError,"notFoundError");function hookChildProcess(cp,parsed){if(!isWin){return}const originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){const err=verifyENOENT(arg1,parsed);if(err){return originalEmit.call(cp,"error",err)}}return originalEmit.apply(cp,arguments)}}__name(hookChildProcess,"hookChildProcess");function verifyENOENT(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawn")}return null}__name(verifyENOENT,"verifyENOENT");function verifyENOENTSync(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawnSync")}return null}__name(verifyENOENTSync,"verifyENOENTSync");module2.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports2,module2){"use strict";init_esbuild_shims();var cp=__require("child_process");var parse14=require_parse();var enoent=require_enoent();function spawn7(command,args,options2){const parsed=parse14(command,args,options2);const spawned=cp.spawn(parsed.command,parsed.args,parsed.options);enoent.hookChildProcess(spawned,parsed);return spawned}__name(spawn7,"spawn");function spawnSync3(command,args,options2){const parsed=parse14(command,args,options2);const result=cp.spawnSync(parsed.command,parsed.args,parsed.options);result.error=result.error||enoent.verifyENOENTSync(result.status,parsed);return result}__name(spawnSync3,"spawnSync");module2.exports=spawn7;module2.exports.spawn=spawn7;module2.exports.sync=spawnSync3;module2.exports._parse=parse14;module2.exports._enoent=enoent}});var require_levenshtein=__commonJS({"node_modules/fast-levenshtein/levenshtein.js"(exports2,module2){init_esbuild_shims();(function(){"use strict";var collator;try{collator=typeof Intl!=="undefined"&&typeof Intl.Collator!=="undefined"?Intl.Collator("generic",{sensitivity:"base"}):null}catch(err){console.log("Collator could not be initialized and wouldn't be used")}var prevRow=[],str2Char=[];var Levenshtein={get:__name(function(str1,str2,options2){var useCollator=options2&&collator&&options2.useCollator;var str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i,j2,tmp;for(i=0;i<str2Len;++i){prevRow[i]=i;str2Char[i]=str2.charCodeAt(i)}prevRow[str2Len]=str2Len;var strCmp;if(useCollator){for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=0===collator.compare(str1.charAt(i),String.fromCharCode(str2Char[j2]));nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}else{for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=str1.charCodeAt(i)===str2Char[j2];nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}return nextCol},"get")};if(typeof define!=="undefined"&&define!==null&&define.amd){define(function(){return Levenshtein})}else if(typeof module2!=="undefined"&&module2!==null&&typeof exports2!=="undefined"&&module2.exports===exports2){module2.exports=Levenshtein}else if(typeof self!=="undefined"&&typeof self.postMessage==="function"&&typeof self.importScripts==="function"){self.Levenshtein=Levenshtein}else if(typeof window!=="undefined"&&window!==null){window.Levenshtein=Levenshtein}})()}});var require_parser=__commonJS({"node_modules/@iarna/toml/lib/parser.js"(exports2,module2){"use strict";init_esbuild_shims();var ParserEND=1114112;var ParserError=class _ParserError extends Error{static{__name(this,"ParserError")}constructor(msg,filename,linenumber){super("[ParserError] "+msg,filename,linenumber);this.name="ParserError";this.code="ParserError";if(Error.captureStackTrace)Error.captureStackTrace(this,_ParserError)}};var State=class{static{__name(this,"State")}constructor(parser2){this.parser=parser2;this.buf="";this.returned=null;this.result=null;this.resultTable=null;this.resultArr=null}};var Parser3=class{static{__name(this,"Parser")}constructor(){this.pos=0;this.col=0;this.line=0;this.obj={};this.ctx=this.obj;this.stack=[];this._buf="";this.char=null;this.ii=0;this.state=new State(this.parseStart)}parse(str){if(str.length===0||str.length==null)return;this._buf=String(str);this.ii=-1;this.char=-1;let getNext;while(getNext===false||this.nextChar()){getNext=this.runOne()}this._buf=null}nextChar(){if(this.char===10){++this.line;this.col=-1}++this.ii;this.char=this._buf.codePointAt(this.ii);++this.pos;++this.col;return this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=ParserEND;let last;do{last=this.state.parser;this.runOne()}while(this.state.parser!==last);this.ctx=null;this.state=null;this._buf=null;return this.obj}next(fn){if(typeof fn!=="function")throw new ParserError("Tried to set state to non-existent state: "+JSON.stringify(fn));this.state.parser=fn}goto(fn){this.next(fn);return this.runOne()}call(fn,returnWith){if(returnWith)this.next(returnWith);this.stack.push(this.state);this.state=new State(fn)}callNow(fn,returnWith){this.call(fn,returnWith);return this.runOne()}return(value){if(this.stack.length===0)throw this.error(new ParserError("Stack underflow"));if(value===void 0)value=this.state.buf;this.state=this.stack.pop();this.state.returned=value}returnNow(value){this.return(value);return this.runOne()}consume(){if(this.char===ParserEND)throw this.error(new ParserError("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(err){err.line=this.line;err.col=this.col;err.pos=this.pos;return err}parseStart(){throw new ParserError("Must declare a parseStart method")}};Parser3.END=ParserEND;Parser3.Error=ParserError;module2.exports=Parser3}});var require_create_datetime=__commonJS({"node_modules/@iarna/toml/lib/create-datetime.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=value=>{const date6=new Date(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_format_num=__commonJS({"node_modules/@iarna/toml/lib/format-num.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(d,num)=>{num=String(num);while(num.length<d)num="0"+num;return num}}});var require_create_datetime_float=__commonJS({"node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var FloatingDateTime=class extends Date{static{__name(this,"FloatingDateTime")}constructor(value){super(value+"Z");this.isFloating=true}toISOString(){const date6=`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`;const time5=`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`;return`${date6}T${time5}`}};module2.exports=value=>{const date6=new FloatingDateTime(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_date=__commonJS({"node_modules/@iarna/toml/lib/create-date.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var DateTime=globalThis.Date;var Date2=class extends DateTime{static{__name(this,"Date")}constructor(value){super(value);this.isDate=true}toISOString(){return`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`}};module2.exports=value=>{const date6=new Date2(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_time=__commonJS({"node_modules/@iarna/toml/lib/create-time.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var Time=class extends Date{static{__name(this,"Time")}constructor(value){super(`0000-01-01T${value}Z`);this.isTime=true}toISOString(){return`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`}};module2.exports=value=>{const date6=new Time(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_toml_parser=__commonJS({"node_modules/@iarna/toml/lib/toml-parser.js"(exports,module){"use strict";init_esbuild_shims();module.exports=makeParserClass(require_parser());module.exports.makeParserClass=makeParserClass;var TomlError=class _TomlError extends Error{static{__name(this,"TomlError")}constructor(msg){super(msg);this.name="TomlError";if(Error.captureStackTrace)Error.captureStackTrace(this,_TomlError);this.fromTOML=true;this.wrapped=null}};TomlError.wrap=err=>{const terr=new TomlError(err.message);terr.code=err.code;terr.wrapped=err;return terr};module.exports.TomlError=TomlError;var createDateTime=require_create_datetime();var createDateTimeFloat=require_create_datetime_float();var createDate=require_create_date();var createTime=require_create_time();var CTRL_I=9;var CTRL_J=10;var CTRL_M=13;var CTRL_CHAR_BOUNDARY=31;var CHAR_SP=32;var CHAR_QUOT=34;var CHAR_NUM=35;var CHAR_APOS=39;var CHAR_PLUS=43;var CHAR_COMMA=44;var CHAR_HYPHEN=45;var CHAR_PERIOD=46;var CHAR_0=48;var CHAR_1=49;var CHAR_7=55;var CHAR_9=57;var CHAR_COLON=58;var CHAR_EQUALS=61;var CHAR_A=65;var CHAR_E=69;var CHAR_F=70;var CHAR_T=84;var CHAR_U=85;var CHAR_Z=90;var CHAR_LOWBAR=95;var CHAR_a=97;var CHAR_b=98;var CHAR_e=101;var CHAR_f=102;var CHAR_i=105;var CHAR_l=108;var CHAR_n=110;var CHAR_o=111;var CHAR_r=114;var CHAR_s=115;var CHAR_t=116;var CHAR_u=117;var CHAR_x=120;var CHAR_z=122;var CHAR_LCUB=123;var CHAR_RCUB=125;var CHAR_LSQB=91;var CHAR_BSOL=92;var CHAR_RSQB=93;var CHAR_DEL=127;var SURROGATE_FIRST=55296;var SURROGATE_LAST=57343;var escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:"\n",[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(cp){return cp>=CHAR_0&&cp<=CHAR_9}__name(isDigit,"isDigit");function isHexit(cp){return cp>=CHAR_A&&cp<=CHAR_F||cp>=CHAR_a&&cp<=CHAR_f||cp>=CHAR_0&&cp<=CHAR_9}__name(isHexit,"isHexit");function isBit(cp){return cp===CHAR_1||cp===CHAR_0}__name(isBit,"isBit");function isOctit(cp){return cp>=CHAR_0&&cp<=CHAR_7}__name(isOctit,"isOctit");function isAlphaNumQuoteHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_APOS||cp===CHAR_QUOT||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumQuoteHyphen,"isAlphaNumQuoteHyphen");function isAlphaNumHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumHyphen,"isAlphaNumHyphen");var _type=Symbol("type");var _declared=Symbol("declared");var hasOwnProperty=Object.prototype.hasOwnProperty;var defineProperty=Object.defineProperty;var descriptor={configurable:true,enumerable:true,writable:true,value:void 0};function hasKey(obj,key){if(hasOwnProperty.call(obj,key))return true;if(key==="__proto__")defineProperty(obj,"__proto__",descriptor);return false}__name(hasKey,"hasKey");var INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}__name(InlineTable,"InlineTable");function isInlineTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_TABLE}__name(isInlineTable,"isInlineTable");var TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:false,writable:true}})}__name(Table,"Table");function isTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===TABLE}__name(isTable,"isTable");var _contentType=Symbol("content-type");var INLINE_LIST=Symbol("inline-list");function InlineList(type){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:type}})}__name(InlineList,"InlineList");function isInlineList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_LIST}__name(isInlineList,"isInlineList");var LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}__name(List,"List");function isList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===LIST}__name(isList,"isList");var _custom;try{const utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(_2){}var _inspect=_custom||"inspect";var BoxedBigInt=class{static{__name(this,"BoxedBigInt")}constructor(value){try{this.value=globalThis.BigInt.asIntN(64,value)}catch(_2){this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}};var INTEGER=Symbol("integer");function Integer(value){let num=Number(value);if(Object.is(num,-0))num=0;if(globalThis.BigInt&&!Number.isSafeInteger(num)){return new BoxedBigInt(value)}else{return Object.defineProperties(new Number(num),{isNaN:{value:__name(function(){return isNaN(this)},"value")},[_type]:{value:INTEGER},[_inspect]:{value:__name(()=>`[Integer: ${value}]`,"value")}})}}__name(Integer,"Integer");function isInteger(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INTEGER}__name(isInteger,"isInteger");var FLOAT=Symbol("float");function Float(value){return Object.defineProperties(new Number(value),{[_type]:{value:FLOAT},[_inspect]:{value:__name(()=>`[Float: ${value}]`,"value")}})}__name(Float,"Float");function isFloat(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===FLOAT}__name(isFloat,"isFloat");function tomlType(value){const type=typeof value;if(type==="object"){if(value===null)return"null";if(value instanceof Date)return"datetime";if(_type in value){switch(value[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}}return type}__name(tomlType,"tomlType");function makeParserClass(Parser3){class TOMLParser extends Parser3{static{__name(this,"TOMLParser")}constructor(){super();this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===Parser3.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===Parser3.END){return null}else if(this.char===CHAR_LSQB){return this.call(this.parseTableOrList)}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(isAlphaNumQuoteHyphen(this.char)){return this.callNow(this.parseAssignStatement)}else{throw this.error(new TomlError(`Unknown character "${this.char}"`))}}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(this.char===CHAR_NUM){return this.goto(this.parseComment)}else if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}else{throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(kv){let target=this.ctx;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(key){if(this.state.resultTable){this.state.resultTable.push(key)}else{this.state.resultTable=[key]}return this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD){return this.next(this.parseAssignKeywordPostDot)}else if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.goto(this.parseAssignEqual)}}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}}parseAssignEqual(){if(this.char===CHAR_EQUALS){return this.next(this.parseAssignPreValue)}else{throw this.error(new TomlError('Invalid character, expected "="'))}}parseAssignPreValue(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseValue,this.recordAssignValue)}}recordAssignValue(value){return this.returnNow({key:this.state.resultTable,value})}parseComment(){do{if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}}while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB){this.next(this.parseList)}else{return this.goto(this.parseTable)}}parseTable(){this.ctx=this.obj;return this.goto(this.parseTableNext)}parseTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseTableMore)}}parseTableMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(hasKey(this.ctx,keyword)&&(!isTable(this.ctx[keyword])||this.ctx[keyword][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}else{this.ctx=this.ctx[keyword]=this.ctx[keyword]||Table();this.ctx[_declared]=true}return this.next(this.parseWhitespaceToEOL)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else{throw this.error(new TomlError("Can't redefine existing key"))}return this.next(this.parseTableNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseList(){this.ctx=this.obj;return this.goto(this.parseListNext)}parseListNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseListMore)}}parseListMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(!hasKey(this.ctx,keyword)){this.ctx[keyword]=List()}if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isList(this.ctx[keyword])){const next=Table();this.ctx[keyword].push(next);this.ctx=next}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListEnd)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isInlineTable(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline table"))}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseListEnd(keyword){if(this.char===CHAR_RSQB){return this.next(this.parseWhitespaceToEOL)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseValue(){if(this.char===Parser3.END){throw this.error(new TomlError("Key without value"))}else if(this.char===CHAR_QUOT){return this.next(this.parseDoubleString)}if(this.char===CHAR_APOS){return this.next(this.parseSingleString)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){return this.goto(this.parseNumberSign)}else if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else if(isDigit(this.char)){return this.goto(this.parseNumberOrDateTime)}else if(this.char===CHAR_t||this.char===CHAR_f){return this.goto(this.parseBoolean)}else if(this.char===CHAR_LSQB){return this.call(this.parseInlineList,this.recordValue)}else if(this.char===CHAR_LCUB){return this.call(this.parseInlineTable,this.recordValue)}else{throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}}recordValue(value){return this.returnNow(value)}parseInf(){if(this.char===CHAR_n){return this.next(this.parseInf2)}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseInf2(){if(this.char===CHAR_f){if(this.state.buf==="-"){return this.return(-Infinity)}else{return this.return(Infinity)}}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseNan(){if(this.char===CHAR_a){return this.next(this.parseNan2)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseNan2(){if(this.char===CHAR_n){return this.return(NaN)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseKeyword(){if(this.char===CHAR_QUOT){return this.next(this.parseBasicString)}else if(this.char===CHAR_APOS){return this.next(this.parseLiteralString)}else{return this.goto(this.parseBareKey)}}parseBareKey(){do{if(this.char===Parser3.END){throw this.error(new TomlError("Key ended without value"))}else if(isAlphaNumHyphen(this.char)){this.consume()}else if(this.state.buf.length===0){throw this.error(new TomlError("Empty bare keys are not allowed"))}else{return this.returnNow()}}while(this.nextChar())}parseSingleString(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiStringMaybe)}else{return this.goto(this.parseLiteralString)}}parseLiteralString(){do{if(this.char===CHAR_APOS){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiStringMaybe(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiString)}else{return this.returnNow()}}parseLiteralMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseLiteralMultiStringContent)}else{return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiEnd(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd2)}else{this.state.buf+="'";return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiEnd2(){if(this.char===CHAR_APOS){return this.return()}else{this.state.buf+="''";return this.goto(this.parseLiteralMultiStringContent)}}parseDoubleString(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiStringMaybe)}else{return this.goto(this.parseBasicString)}}parseBasicString(){do{if(this.char===CHAR_BSOL){return this.call(this.parseEscape,this.recordEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}recordEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseBasicString)}parseMultiStringMaybe(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiString)}else{return this.returnNow()}}parseMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseMultiStringContent)}else{return this.goto(this.parseMultiStringContent)}}parseMultiStringContent(){do{if(this.char===CHAR_BSOL){return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}errorControlCharInString(){let displayCode="\\u00";if(this.char<16){displayCode+="0"}displayCode+=this.char.toString(16);return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))}recordMultiEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseMultiStringContent)}parseMultiEnd(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd2)}else{this.state.buf+='"';return this.goto(this.parseMultiStringContent)}}parseMultiEnd2(){if(this.char===CHAR_QUOT){return this.return()}else{this.state.buf+='""';return this.goto(this.parseMultiStringContent)}}parseMultiEscape(){if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else if(this.char===CHAR_SP||this.char===CTRL_I){return this.next(this.parsePreMultiTrim)}else{return this.goto(this.parseEscape)}}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else{throw this.error(new TomlError("Can't escape whitespace"))}}parseMultiTrim(){if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else{return this.returnNow()}}parseEscape(){if(this.char in escapes){return this.return(escapes[this.char])}else if(this.char===CHAR_u){return this.call(this.parseSmallUnicode,this.parseUnicodeReturn)}else if(this.char===CHAR_U){return this.call(this.parseLargeUnicode,this.parseUnicodeReturn)}else{throw this.error(new TomlError("Unknown escape character: "+this.char))}}parseUnicodeReturn(char){try{const codePoint=parseInt(char,16);if(codePoint>=SURROGATE_FIRST&&codePoint<=SURROGATE_LAST){throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"))}return this.returnNow(String.fromCodePoint(codePoint))}catch(err){throw this.error(TomlError.wrap(err))}}parseSmallUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=4)return this.return()}}parseLargeUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=8)return this.return()}}parseNumberSign(){this.consume();return this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else{return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}}parseNumberIntegerStart(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberIntegerExponentOrDecimal)}else{return this.goto(this.parseNumberInteger)}}parseNumberIntegerExponentOrDecimal(){if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Integer(this.state.buf))}}parseNumberInteger(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Float(this.state.buf))}}parseNumberExponentSign(){if(isDigit(this.char)){return this.goto(this.parseNumberExponent)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.call(this.parseNoUnder,this.parseNumberExponent)}else{throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}}parseNumberExponent(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else{return this.returnNow(Float(this.state.buf))}}parseNumberOrDateTime(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberBaseOrDateTime)}else{return this.goto(this.parseNumberOrDateTimeOnly)}}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberInteger)}else if(isDigit(this.char)){this.consume();if(this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{return this.returnNow(Integer(this.state.buf))}}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char)){return this.consume()}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{throw this.error(new TomlError("Expected digit while parsing year part of a date"))}}else{if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else{throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}}}parseNumberBaseOrDateTime(){if(this.char===CHAR_b){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)}else if(this.char===CHAR_o){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)}else if(this.char===CHAR_x){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)}else if(this.char===CHAR_PERIOD){return this.goto(this.parseNumberInteger)}else if(isDigit(this.char)){return this.goto(this.parseDateTimeOnly)}else{return this.returnNow(Integer(this.state.buf))}}parseIntegerHex(){if(isHexit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerOct(){if(isOctit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerBin(){if(isBit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseDateTime(){if(this.state.buf.length<4){throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2){throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseDateDay)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2){throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseStartTimeHour)}else if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result+"-"+this.state.buf))}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseStartTimeHour(){if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result))}else{return this.goto(this.parseTimeHour)}}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result+="T"+this.state.buf;this.state.buf="";return this.next(this.parseTimeMin)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeSec)}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeZoneOrFraction)}}else{throw this.error(new TomlError("Incomplete datetime"))}}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeMin)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeSec)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){return this.next(this.parseOnlyTimeFractionMaybe)}}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeFractionMaybe(){this.state.result+=":"+this.state.buf;if(this.char===CHAR_PERIOD){this.state.buf="";this.next(this.parseOnlyTimeFraction)}else{return this.return(createTime(this.state.result))}}parseOnlyTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD){this.consume();this.next(this.parseDateTimeFraction)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseDateTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.state.buf.length===1){throw this.error(new TomlError("Expected digit in milliseconds"))}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneHour(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseTimeZoneSep(){if(this.char===CHAR_COLON){this.consume();this.next(this.parseTimeZoneMin)}else{throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}}parseTimeZoneMin(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseBoolean(){if(this.char===CHAR_t){this.consume();return this.next(this.parseTrue_r)}else if(this.char===CHAR_f){this.consume();return this.next(this.parseFalse_a)}}parseTrue_r(){if(this.char===CHAR_r){this.consume();return this.next(this.parseTrue_u)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_u(){if(this.char===CHAR_u){this.consume();return this.next(this.parseTrue_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_e(){if(this.char===CHAR_e){return this.return(true)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_a(){if(this.char===CHAR_a){this.consume();return this.next(this.parseFalse_l)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_l(){if(this.char===CHAR_l){this.consume();return this.next(this.parseFalse_s)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_s(){if(this.char===CHAR_s){this.consume();return this.next(this.parseFalse_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_e(){if(this.char===CHAR_e){return this.return(false)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_RSQB){return this.return(this.state.resultArr||InlineList())}else{return this.callNow(this.parseValue,this.recordInlineListValue)}}recordInlineListValue(value){if(this.state.resultArr){const listType=this.state.resultArr[_contentType];const valueType=tomlType(value);if(listType!==valueType){throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))}}else{this.state.resultArr=InlineList(tomlType(value))}if(isFloat(value)||isInteger(value)){this.state.resultArr.push(value.valueOf())}else{this.state.resultArr.push(value)}return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineList)}else if(this.char===CHAR_RSQB){return this.goto(this.parseInlineList)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_RCUB){return this.return(this.state.resultTable||InlineTable())}else{if(!this.state.resultTable)this.state.resultTable=InlineTable();return this.callNow(this.parseAssign,this.recordInlineTableValue)}}recordInlineTableValue(kv){let target=this.state.resultTable;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineTable)}else if(this.char===CHAR_RCUB){return this.goto(this.parseInlineTable)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}}return TOMLParser}__name(makeParserClass,"makeParserClass")}});var require_parse_pretty_error=__commonJS({"node_modules/@iarna/toml/parse-pretty-error.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=prettyError;function prettyError(err,buf){if(err.pos==null||err.line==null)return err;let msg=err.message;msg+=` at row ${err.line+1}, col ${err.col+1}, pos ${err.pos}:
|
|
4
4
|
`;if(buf&&buf.split){const lines=buf.split(/\n/);const lineNumWidth=String(Math.min(lines.length,err.line+3)).length;let linePadding=" ";while(linePadding.length<lineNumWidth)linePadding+=" ";for(let ii2=Math.max(0,err.line-1);ii2<Math.min(lines.length,err.line+2);++ii2){let lineNum=String(ii2+1);if(lineNum.length<lineNumWidth)lineNum=" "+lineNum;if(err.line===ii2){msg+=lineNum+"> "+lines[ii2]+"\n";msg+=linePadding+" ";for(let hh=0;hh<err.col;++hh){msg+=" "}msg+="^\n"}else{msg+=lineNum+": "+lines[ii2]+"\n"}}}err.message=msg+"\n";return err}__name(prettyError,"prettyError")}});var require_parse_string=__commonJS({"node_modules/@iarna/toml/parse-string.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=parseString;var TOMLParser=require_toml_parser();var prettyError=require_parse_pretty_error();function parseString(str){if(globalThis.Buffer&&globalThis.Buffer.isBuffer(str)){str=str.toString("utf8")}const parser2=new TOMLParser;try{parser2.parse(str);return parser2.finish()}catch(err){throw prettyError(err,str)}}__name(parseString,"parseString")}});var require_parse_async=__commonJS({"node_modules/@iarna/toml/parse-async.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=parseAsync5;var TOMLParser=require_toml_parser();var prettyError=require_parse_pretty_error();function parseAsync5(str,opts){if(!opts)opts={};const index=0;const blocksize=opts.blocksize||40960;const parser2=new TOMLParser;return new Promise((resolve34,reject)=>{setImmediate(parseAsyncNext,index,blocksize,resolve34,reject)});function parseAsyncNext(index2,blocksize2,resolve34,reject){if(index2>=str.length){try{return resolve34(parser2.finish())}catch(err){return reject(prettyError(err,str))}}try{parser2.parse(str.slice(index2,index2+blocksize2));setImmediate(parseAsyncNext,index2+blocksize2,blocksize2,resolve34,reject)}catch(err){reject(prettyError(err,str))}}__name(parseAsyncNext,"parseAsyncNext")}__name(parseAsync5,"parseAsync")}});var require_parse_stream=__commonJS({"node_modules/@iarna/toml/parse-stream.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=parseStream;var stream=__require("stream");var TOMLParser=require_toml_parser();function parseStream(stm){if(stm){return parseReadable(stm)}else{return parseTransform(stm)}}__name(parseStream,"parseStream");function parseReadable(stm){const parser2=new TOMLParser;stm.setEncoding("utf8");return new Promise((resolve34,reject)=>{let readable;let ended=false;let errored=false;function finish(){ended=true;if(readable)return;try{resolve34(parser2.finish())}catch(err){reject(err)}}__name(finish,"finish");function error3(err){errored=true;reject(err)}__name(error3,"error");stm.once("end",finish);stm.once("error",error3);readNext();function readNext(){readable=true;let data2;while((data2=stm.read())!==null){try{parser2.parse(data2)}catch(err){return error3(err)}}readable=false;if(ended)return finish();if(errored)return;stm.once("readable",readNext)}__name(readNext,"readNext")})}__name(parseReadable,"parseReadable");function parseTransform(){const parser2=new TOMLParser;return new stream.Transform({objectMode:true,transform(chunk,encoding,cb){try{parser2.parse(chunk.toString(encoding))}catch(err){this.emit("error",err)}cb()},flush(cb){try{this.push(parser2.finish())}catch(err){this.emit("error",err)}cb()}})}__name(parseTransform,"parseTransform")}});var require_parse2=__commonJS({"node_modules/@iarna/toml/parse.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=require_parse_string();module2.exports.async=require_parse_async();module2.exports.stream=require_parse_stream();module2.exports.prettyError=require_parse_pretty_error()}});var require_stringify=__commonJS({"node_modules/@iarna/toml/stringify.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=stringify2;module2.exports.value=stringifyInline;function stringify2(obj){if(obj===null)throw typeError("null");if(obj===void 0)throw typeError("undefined");if(typeof obj!=="object")throw typeError(typeof obj);if(typeof obj.toJSON==="function")obj=obj.toJSON();if(obj==null)return null;const type=tomlType2(obj);if(type!=="table")throw typeError(type);return stringifyObject("","",obj)}__name(stringify2,"stringify");function typeError(type){return new Error("Can only stringify objects, not "+type)}__name(typeError,"typeError");function arrayOneTypeError(){return new Error("Array values can't have mixed types")}__name(arrayOneTypeError,"arrayOneTypeError");function getInlineKeys(obj){return Object.keys(obj).filter(key=>isInline(obj[key]))}__name(getInlineKeys,"getInlineKeys");function getComplexKeys(obj){return Object.keys(obj).filter(key=>!isInline(obj[key]))}__name(getComplexKeys,"getComplexKeys");function toJSON(obj){let nobj=Array.isArray(obj)?[]:Object.prototype.hasOwnProperty.call(obj,"__proto__")?{["__proto__"]:void 0}:{};for(let prop of Object.keys(obj)){if(obj[prop]&&typeof obj[prop].toJSON==="function"&&!("toISOString"in obj[prop])){nobj[prop]=obj[prop].toJSON()}else{nobj[prop]=obj[prop]}}return nobj}__name(toJSON,"toJSON");function stringifyObject(prefix,indent,obj){obj=toJSON(obj);var inlineKeys;var complexKeys;inlineKeys=getInlineKeys(obj);complexKeys=getComplexKeys(obj);var result=[];var inlineIndent=indent||"";inlineKeys.forEach(key=>{var type=tomlType2(obj[key]);if(type!=="undefined"&&type!=="null"){result.push(inlineIndent+stringifyKey(key)+" = "+stringifyAnyInline(obj[key],true))}});if(result.length>0)result.push("");var complexIndent=prefix&&inlineKeys.length>0?indent+" ":"";complexKeys.forEach(key=>{result.push(stringifyComplex(prefix,complexIndent,key,obj[key]))});return result.join("\n")}__name(stringifyObject,"stringifyObject");function isInline(value){switch(tomlType2(value)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return true;case"array":return value.length===0||tomlType2(value[0])!=="table";case"table":return Object.keys(value).length===0;default:return false}}__name(isInline,"isInline");function tomlType2(value){if(value===void 0){return"undefined"}else if(value===null){return"null"}else if(typeof value==="bigint"||Number.isInteger(value)&&!Object.is(value,-0)){return"integer"}else if(typeof value==="number"){return"float"}else if(typeof value==="boolean"){return"boolean"}else if(typeof value==="string"){return"string"}else if("toISOString"in value){return isNaN(value)?"undefined":"datetime"}else if(Array.isArray(value)){return"array"}else{return"table"}}__name(tomlType2,"tomlType");function stringifyKey(key){var keyStr=String(key);if(/^[-A-Za-z0-9_]+$/.test(keyStr)){return keyStr}else{return stringifyBasicString(keyStr)}}__name(stringifyKey,"stringifyKey");function stringifyBasicString(str){return'"'+escapeString(str).replace(/"/g,'\\"')+'"'}__name(stringifyBasicString,"stringifyBasicString");function stringifyLiteralString(str){return"'"+str+"'"}__name(stringifyLiteralString,"stringifyLiteralString");function numpad(num,str){while(str.length<num)str="0"+str;return str}__name(numpad,"numpad");function escapeString(str){return str.replace(/\\/g,"\\\\").replace(/[\b]/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/([\u0000-\u001f\u007f])/,c=>"\\u"+numpad(4,c.codePointAt(0).toString(16)))}__name(escapeString,"escapeString");function stringifyMultilineString(str){let escaped=str.split(/\n/).map(str2=>{return escapeString(str2).replace(/"(?="")/g,'\\"')}).join("\n");if(escaped.slice(-1)==='"')escaped+="\\\n";return'"""\n'+escaped+'"""'}__name(stringifyMultilineString,"stringifyMultilineString");function stringifyAnyInline(value,multilineOk){let type=tomlType2(value);if(type==="string"){if(multilineOk&&/\n/.test(value)){type="string-multiline"}else if(!/[\b\t\n\f\r']/.test(value)&&/"/.test(value)){type="string-literal"}}return stringifyInline(value,type)}__name(stringifyAnyInline,"stringifyAnyInline");function stringifyInline(value,type){if(!type)type=tomlType2(value);switch(type){case"string-multiline":return stringifyMultilineString(value);case"string":return stringifyBasicString(value);case"string-literal":return stringifyLiteralString(value);case"integer":return stringifyInteger(value);case"float":return stringifyFloat(value);case"boolean":return stringifyBoolean(value);case"datetime":return stringifyDatetime(value);case"array":return stringifyInlineArray(value.filter(_2=>tomlType2(_2)!=="null"&&tomlType2(_2)!=="undefined"&&tomlType2(_2)!=="nan"));case"table":return stringifyInlineTable(value);default:throw typeError(type)}}__name(stringifyInline,"stringifyInline");function stringifyInteger(value){return String(value).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}__name(stringifyInteger,"stringifyInteger");function stringifyFloat(value){if(value===Infinity){return"inf"}else if(value===-Infinity){return"-inf"}else if(Object.is(value,NaN)){return"nan"}else if(Object.is(value,-0)){return"-0.0"}var chunks=String(value).split(".");var int3=chunks[0];var dec=chunks[1]||0;return stringifyInteger(int3)+"."+dec}__name(stringifyFloat,"stringifyFloat");function stringifyBoolean(value){return String(value)}__name(stringifyBoolean,"stringifyBoolean");function stringifyDatetime(value){return value.toISOString()}__name(stringifyDatetime,"stringifyDatetime");function isNumber(type){return type==="float"||type==="integer"}__name(isNumber,"isNumber");function arrayType(values){var contentType2=tomlType2(values[0]);if(values.every(_2=>tomlType2(_2)===contentType2))return contentType2;if(values.every(_2=>isNumber(tomlType2(_2))))return"float";return"mixed"}__name(arrayType,"arrayType");function validateArray(values){const type=arrayType(values);if(type==="mixed"){throw arrayOneTypeError()}return type}__name(validateArray,"validateArray");function stringifyInlineArray(values){values=toJSON(values);const type=validateArray(values);var result="[";var stringified=values.map(_2=>stringifyInline(_2,type));if(stringified.join(", ").length>60||/\n/.test(stringified)){result+="\n "+stringified.join(",\n ")+"\n"}else{result+=" "+stringified.join(", ")+(stringified.length>0?" ":"")}return result+"]"}__name(stringifyInlineArray,"stringifyInlineArray");function stringifyInlineTable(value){value=toJSON(value);var result=[];Object.keys(value).forEach(key=>{result.push(stringifyKey(key)+" = "+stringifyAnyInline(value[key],false))});return"{ "+result.join(", ")+(result.length>0?" ":"")+"}"}__name(stringifyInlineTable,"stringifyInlineTable");function stringifyComplex(prefix,indent,key,value){var valueType=tomlType2(value);if(valueType==="array"){return stringifyArrayOfTables(prefix,indent,key,value)}else if(valueType==="table"){return stringifyComplexTable(prefix,indent,key,value)}else{throw typeError(valueType)}}__name(stringifyComplex,"stringifyComplex");function stringifyArrayOfTables(prefix,indent,key,values){values=toJSON(values);validateArray(values);var firstValueType=tomlType2(values[0]);if(firstValueType!=="table")throw typeError(firstValueType);var fullKey=prefix+stringifyKey(key);var result="";values.forEach(table=>{if(result.length>0)result+="\n";result+=indent+"[["+fullKey+"]]\n";result+=stringifyObject(fullKey+".",indent,table)});return result}__name(stringifyArrayOfTables,"stringifyArrayOfTables");function stringifyComplexTable(prefix,indent,key,value){var fullKey=prefix+stringifyKey(key);var result="";if(getInlineKeys(value).length>0){result+=indent+"["+fullKey+"]\n"}return result+stringifyObject(fullKey+".",indent,value)}__name(stringifyComplexTable,"stringifyComplexTable")}});var require_toml=__commonJS({"node_modules/@iarna/toml/toml.js"(exports2){"use strict";init_esbuild_shims();exports2.parse=require_parse2();exports2.stringify=require_stringify()}});var require_pend=__commonJS({"node_modules/pend/index.js"(exports2,module2){init_esbuild_shims();module2.exports=Pend;function Pend(){this.pending=0;this.max=Infinity;this.listeners=[];this.waiting=[];this.error=null}__name(Pend,"Pend");Pend.prototype.go=function(fn){if(this.pending<this.max){pendGo(this,fn)}else{this.waiting.push(fn)}};Pend.prototype.wait=function(cb){if(this.pending===0){cb(this.error)}else{this.listeners.push(cb)}};Pend.prototype.hold=function(){return pendHold(this)};function pendHold(self2){self2.pending+=1;var called=false;return onCb;function onCb(err){if(called)throw new Error("callback called twice");called=true;self2.error=self2.error||err;self2.pending-=1;if(self2.waiting.length>0&&self2.pending<self2.max){pendGo(self2,self2.waiting.shift())}else if(self2.pending===0){var listeners=self2.listeners;self2.listeners=[];listeners.forEach(cbListener)}}__name(onCb,"onCb");function cbListener(listener){listener(self2.error)}__name(cbListener,"cbListener")}__name(pendHold,"pendHold");function pendGo(self2,fn){fn(pendHold(self2))}__name(pendGo,"pendGo")}});var require_fd_slicer=__commonJS({"node_modules/fd-slicer/index.js"(exports2){init_esbuild_shims();var fs77=__require("fs");var util=__require("util");var stream=__require("stream");var Readable2=stream.Readable;var Writable=stream.Writable;var PassThrough3=stream.PassThrough;var Pend=require_pend();var EventEmitter7=__require("events").EventEmitter;exports2.createFromBuffer=createFromBuffer;exports2.createFromFd=createFromFd;exports2.BufferSlicer=BufferSlicer;exports2.FdSlicer=FdSlicer;util.inherits(FdSlicer,EventEmitter7);function FdSlicer(fd,options2){options2=options2||{};EventEmitter7.call(this);this.fd=fd;this.pend=new Pend;this.pend.max=1;this.refCount=0;this.autoClose=!!options2.autoClose}__name(FdSlicer,"FdSlicer");FdSlicer.prototype.read=function(buffer,offset2,length,position,callback){var self2=this;self2.pend.go(function(cb){fs77.read(self2.fd,buffer,offset2,length,position,function(err,bytesRead,buffer2){cb();callback(err,bytesRead,buffer2)})})};FdSlicer.prototype.write=function(buffer,offset2,length,position,callback){var self2=this;self2.pend.go(function(cb){fs77.write(self2.fd,buffer,offset2,length,position,function(err,written,buffer2){cb();callback(err,written,buffer2)})})};FdSlicer.prototype.createReadStream=function(options2){return new ReadStream(this,options2)};FdSlicer.prototype.createWriteStream=function(options2){return new WriteStream(this,options2)};FdSlicer.prototype.ref=function(){this.refCount+=1};FdSlicer.prototype.unref=function(){var self2=this;self2.refCount-=1;if(self2.refCount>0)return;if(self2.refCount<0)throw new Error("invalid unref");if(self2.autoClose){fs77.close(self2.fd,onCloseDone)}function onCloseDone(err){if(err){self2.emit("error",err)}else{self2.emit("close")}}__name(onCloseDone,"onCloseDone")};util.inherits(ReadStream,Readable2);function ReadStream(context2,options2){options2=options2||{};Readable2.call(this,options2);this.context=context2;this.context.ref();this.start=options2.start||0;this.endOffset=options2.end;this.pos=this.start;this.destroyed=false}__name(ReadStream,"ReadStream");ReadStream.prototype._read=function(n){var self2=this;if(self2.destroyed)return;var toRead=Math.min(self2._readableState.highWaterMark,n);if(self2.endOffset!=null){toRead=Math.min(toRead,self2.endOffset-self2.pos)}if(toRead<=0){self2.destroyed=true;self2.push(null);self2.context.unref();return}self2.context.pend.go(function(cb){if(self2.destroyed)return cb();var buffer=new Buffer(toRead);fs77.read(self2.context.fd,buffer,0,toRead,self2.pos,function(err,bytesRead){if(err){self2.destroy(err)}else if(bytesRead===0){self2.destroyed=true;self2.push(null);self2.context.unref()}else{self2.pos+=bytesRead;self2.push(buffer.slice(0,bytesRead))}cb()})})};ReadStream.prototype.destroy=function(err){if(this.destroyed)return;err=err||new Error("stream destroyed");this.destroyed=true;this.emit("error",err);this.context.unref()};util.inherits(WriteStream,Writable);function WriteStream(context2,options2){options2=options2||{};Writable.call(this,options2);this.context=context2;this.context.ref();this.start=options2.start||0;this.endOffset=options2.end==null?Infinity:+options2.end;this.bytesWritten=0;this.pos=this.start;this.destroyed=false;this.on("finish",this.destroy.bind(this))}__name(WriteStream,"WriteStream");WriteStream.prototype._write=function(buffer,encoding,callback){var self2=this;if(self2.destroyed)return;if(self2.pos+buffer.length>self2.endOffset){var err=new Error("maximum file length exceeded");err.code="ETOOBIG";self2.destroy();callback(err);return}self2.context.pend.go(function(cb){if(self2.destroyed)return cb();fs77.write(self2.context.fd,buffer,0,buffer.length,self2.pos,function(err2,bytes){if(err2){self2.destroy();cb();callback(err2)}else{self2.bytesWritten+=bytes;self2.pos+=bytes;self2.emit("progress");cb();callback()}})})};WriteStream.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this.context.unref()};util.inherits(BufferSlicer,EventEmitter7);function BufferSlicer(buffer,options2){EventEmitter7.call(this);options2=options2||{};this.refCount=0;this.buffer=buffer;this.maxChunkSize=options2.maxChunkSize||Number.MAX_SAFE_INTEGER}__name(BufferSlicer,"BufferSlicer");BufferSlicer.prototype.read=function(buffer,offset2,length,position,callback){var end=position+length;var delta=end-this.buffer.length;var written=delta>0?delta:length;this.buffer.copy(buffer,offset2,position,end);setImmediate(function(){callback(null,written)})};BufferSlicer.prototype.write=function(buffer,offset2,length,position,callback){buffer.copy(this.buffer,position,offset2,offset2+length);setImmediate(function(){callback(null,length,buffer)})};BufferSlicer.prototype.createReadStream=function(options2){options2=options2||{};var readStream=new PassThrough3(options2);readStream.destroyed=false;readStream.start=options2.start||0;readStream.endOffset=options2.end;readStream.pos=readStream.endOffset||this.buffer.length;var entireSlice=this.buffer.slice(readStream.start,readStream.pos);var offset2=0;while(true){var nextOffset=offset2+this.maxChunkSize;if(nextOffset>=entireSlice.length){if(offset2<entireSlice.length){readStream.write(entireSlice.slice(offset2,entireSlice.length))}break}readStream.write(entireSlice.slice(offset2,nextOffset));offset2=nextOffset}readStream.end();readStream.destroy=function(){readStream.destroyed=true};return readStream};BufferSlicer.prototype.createWriteStream=function(options2){var bufferSlicer=this;options2=options2||{};var writeStream=new Writable(options2);writeStream.start=options2.start||0;writeStream.endOffset=options2.end==null?this.buffer.length:+options2.end;writeStream.bytesWritten=0;writeStream.pos=writeStream.start;writeStream.destroyed=false;writeStream._write=function(buffer,encoding,callback){if(writeStream.destroyed)return;var end=writeStream.pos+buffer.length;if(end>writeStream.endOffset){var err=new Error("maximum file length exceeded");err.code="ETOOBIG";writeStream.destroyed=true;callback(err);return}buffer.copy(bufferSlicer.buffer,writeStream.pos,0,buffer.length);writeStream.bytesWritten+=buffer.length;writeStream.pos=end;writeStream.emit("progress");callback()};writeStream.destroy=function(){writeStream.destroyed=true};return writeStream};BufferSlicer.prototype.ref=function(){this.refCount+=1};BufferSlicer.prototype.unref=function(){this.refCount-=1;if(this.refCount<0){throw new Error("invalid unref")}};function createFromBuffer(buffer,options2){return new BufferSlicer(buffer,options2)}__name(createFromBuffer,"createFromBuffer");function createFromFd(fd,options2){return new FdSlicer(fd,options2)}__name(createFromFd,"createFromFd")}});var require_buffer_crc32=__commonJS({"node_modules/buffer-crc32/index.js"(exports2,module2){init_esbuild_shims();var Buffer3=__require("buffer").Buffer;var CRC_TABLE=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array!=="undefined"){CRC_TABLE=new Int32Array(CRC_TABLE)}function ensureBuffer(input){if(Buffer3.isBuffer(input)){return input}var hasNewBufferAPI=typeof Buffer3.alloc==="function"&&typeof Buffer3.from==="function";if(typeof input==="number"){return hasNewBufferAPI?Buffer3.alloc(input):new Buffer3(input)}else if(typeof input==="string"){return hasNewBufferAPI?Buffer3.from(input):new Buffer3(input)}else{throw new Error("input must be buffer, number, or string, received "+typeof input)}}__name(ensureBuffer,"ensureBuffer");function bufferizeInt(num){var tmp=ensureBuffer(4);tmp.writeInt32BE(num,0);return tmp}__name(bufferizeInt,"bufferizeInt");function _crc32(buf,previous){buf=ensureBuffer(buf);if(Buffer3.isBuffer(previous)){previous=previous.readUInt32BE(0)}var crc=~~previous^-1;for(var n=0;n<buf.length;n++){crc=CRC_TABLE[(crc^buf[n])&255]^crc>>>8}return crc^-1}__name(_crc32,"_crc32");function crc32(){return bufferizeInt(_crc32.apply(null,arguments))}__name(crc32,"crc32");crc32.signed=function(){return _crc32.apply(null,arguments)};crc32.unsigned=function(){return _crc32.apply(null,arguments)>>>0};module2.exports=crc32}});var require_yauzl=__commonJS({"packages/core/node_modules/yauzl/index.js"(exports2){init_esbuild_shims();var fs77=__require("fs");var zlib=__require("zlib");var fd_slicer=require_fd_slicer();var crc32=require_buffer_crc32();var util=__require("util");var EventEmitter7=__require("events").EventEmitter;var Transform=__require("stream").Transform;var PassThrough3=__require("stream").PassThrough;var Writable=__require("stream").Writable;exports2.open=open6;exports2.fromFd=fromFd;exports2.fromBuffer=fromBuffer;exports2.fromRandomAccessReader=fromRandomAccessReader;exports2.dosDateTimeToDate=dosDateTimeToDate;exports2.validateFileName=validateFileName;exports2.ZipFile=ZipFile;exports2.Entry=Entry;exports2.RandomAccessReader=RandomAccessReader;function open6(path82,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};if(options2.autoClose==null)options2.autoClose=true;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;if(callback==null)callback=defaultCallback;fs77.open(path82,"r",function(err,fd){if(err)return callback(err);fromFd(fd,options2,function(err2,zipfile){if(err2)fs77.close(fd,defaultCallback);callback(err2,zipfile)})})}__name(open6,"open");function fromFd(fd,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};if(options2.autoClose==null)options2.autoClose=false;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;if(callback==null)callback=defaultCallback;fs77.fstat(fd,function(err,stats){if(err)return callback(err);var reader=fd_slicer.createFromFd(fd,{autoClose:true});fromRandomAccessReader(reader,stats.size,options2,callback)})}__name(fromFd,"fromFd");function fromBuffer(buffer,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};options2.autoClose=false;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;var reader=fd_slicer.createFromBuffer(buffer,{maxChunkSize:65536});fromRandomAccessReader(reader,buffer.length,options2,callback)}__name(fromBuffer,"fromBuffer");function fromRandomAccessReader(reader,totalSize,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};if(options2.autoClose==null)options2.autoClose=true;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;var decodeStrings=!!options2.decodeStrings;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;if(callback==null)callback=defaultCallback;if(typeof totalSize!=="number")throw new Error("expected totalSize parameter to be a number");if(totalSize>Number.MAX_SAFE_INTEGER){throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.")}reader.ref();var eocdrWithoutCommentSize=22;var maxCommentSize=65535;var bufferSize=Math.min(eocdrWithoutCommentSize+maxCommentSize,totalSize);var buffer=newBuffer(bufferSize);var bufferReadStart=totalSize-buffer.length;readAndAssertNoEof(reader,buffer,0,bufferSize,bufferReadStart,function(err){if(err)return callback(err);for(var i=bufferSize-eocdrWithoutCommentSize;i>=0;i-=1){if(buffer.readUInt32LE(i)!==101010256)continue;var eocdrBuffer=buffer.slice(i);var diskNumber=eocdrBuffer.readUInt16LE(4);if(diskNumber!==0){return callback(new Error("multi-disk zip files are not supported: found disk number: "+diskNumber))}var entryCount=eocdrBuffer.readUInt16LE(10);var centralDirectoryOffset=eocdrBuffer.readUInt32LE(16);var commentLength=eocdrBuffer.readUInt16LE(20);var expectedCommentLength=eocdrBuffer.length-eocdrWithoutCommentSize;if(commentLength!==expectedCommentLength){return callback(new Error("invalid comment length. expected: "+expectedCommentLength+". found: "+commentLength))}var comment=decodeStrings?decodeBuffer(eocdrBuffer,22,eocdrBuffer.length,false):eocdrBuffer.slice(22);if(!(entryCount===65535||centralDirectoryOffset===4294967295)){return callback(null,new ZipFile(reader,centralDirectoryOffset,totalSize,entryCount,comment,options2.autoClose,options2.lazyEntries,decodeStrings,options2.validateEntrySizes,options2.strictFileNames))}var zip64EocdlBuffer=newBuffer(20);var zip64EocdlOffset=bufferReadStart+i-zip64EocdlBuffer.length;readAndAssertNoEof(reader,zip64EocdlBuffer,0,zip64EocdlBuffer.length,zip64EocdlOffset,function(err2){if(err2)return callback(err2);if(zip64EocdlBuffer.readUInt32LE(0)!==117853008){return callback(new Error("invalid zip64 end of central directory locator signature"))}var zip64EocdrOffset=readUInt64LE(zip64EocdlBuffer,8);var zip64EocdrBuffer=newBuffer(56);readAndAssertNoEof(reader,zip64EocdrBuffer,0,zip64EocdrBuffer.length,zip64EocdrOffset,function(err3){if(err3)return callback(err3);if(zip64EocdrBuffer.readUInt32LE(0)!==101075792){return callback(new Error("invalid zip64 end of central directory record signature"))}entryCount=readUInt64LE(zip64EocdrBuffer,32);centralDirectoryOffset=readUInt64LE(zip64EocdrBuffer,48);return callback(null,new ZipFile(reader,centralDirectoryOffset,totalSize,entryCount,comment,options2.autoClose,options2.lazyEntries,decodeStrings,options2.validateEntrySizes,options2.strictFileNames))})});return}callback(new Error("end of central directory record signature not found"))})}__name(fromRandomAccessReader,"fromRandomAccessReader");util.inherits(ZipFile,EventEmitter7);function ZipFile(reader,centralDirectoryOffset,fileSize,entryCount,comment,autoClose,lazyEntries,decodeStrings,validateEntrySizes,strictFileNames){var self2=this;EventEmitter7.call(self2);self2.reader=reader;self2.reader.on("error",function(err){emitError(self2,err)});self2.reader.once("close",function(){self2.emit("close")});self2.readEntryCursor=centralDirectoryOffset;self2.fileSize=fileSize;self2.entryCount=entryCount;self2.comment=comment;self2.entriesRead=0;self2.autoClose=!!autoClose;self2.lazyEntries=!!lazyEntries;self2.decodeStrings=!!decodeStrings;self2.validateEntrySizes=!!validateEntrySizes;self2.strictFileNames=!!strictFileNames;self2.isOpen=true;self2.emittedError=false;if(!self2.lazyEntries)self2._readEntry()}__name(ZipFile,"ZipFile");ZipFile.prototype.close=function(){if(!this.isOpen)return;this.isOpen=false;this.reader.unref()};function emitErrorAndAutoClose(self2,err){if(self2.autoClose)self2.close();emitError(self2,err)}__name(emitErrorAndAutoClose,"emitErrorAndAutoClose");function emitError(self2,err){if(self2.emittedError)return;self2.emittedError=true;self2.emit("error",err)}__name(emitError,"emitError");ZipFile.prototype.readEntry=function(){if(!this.lazyEntries)throw new Error("readEntry() called without lazyEntries:true");this._readEntry()};ZipFile.prototype._readEntry=function(){var self2=this;if(self2.entryCount===self2.entriesRead){setImmediate(function(){if(self2.autoClose)self2.close();if(self2.emittedError)return;self2.emit("end")});return}if(self2.emittedError)return;var buffer=newBuffer(46);readAndAssertNoEof(self2.reader,buffer,0,buffer.length,self2.readEntryCursor,function(err){if(err)return emitErrorAndAutoClose(self2,err);if(self2.emittedError)return;var entry=new Entry;var signature=buffer.readUInt32LE(0);if(signature!==33639248)return emitErrorAndAutoClose(self2,new Error("invalid central directory file header signature: 0x"+signature.toString(16)));entry.versionMadeBy=buffer.readUInt16LE(4);entry.versionNeededToExtract=buffer.readUInt16LE(6);entry.generalPurposeBitFlag=buffer.readUInt16LE(8);entry.compressionMethod=buffer.readUInt16LE(10);entry.lastModFileTime=buffer.readUInt16LE(12);entry.lastModFileDate=buffer.readUInt16LE(14);entry.crc32=buffer.readUInt32LE(16);entry.compressedSize=buffer.readUInt32LE(20);entry.uncompressedSize=buffer.readUInt32LE(24);entry.fileNameLength=buffer.readUInt16LE(28);entry.extraFieldLength=buffer.readUInt16LE(30);entry.fileCommentLength=buffer.readUInt16LE(32);entry.internalFileAttributes=buffer.readUInt16LE(36);entry.externalFileAttributes=buffer.readUInt32LE(38);entry.relativeOffsetOfLocalHeader=buffer.readUInt32LE(42);if(entry.generalPurposeBitFlag&64)return emitErrorAndAutoClose(self2,new Error("strong encryption is not supported"));self2.readEntryCursor+=46;buffer=newBuffer(entry.fileNameLength+entry.extraFieldLength+entry.fileCommentLength);readAndAssertNoEof(self2.reader,buffer,0,buffer.length,self2.readEntryCursor,function(err2){if(err2)return emitErrorAndAutoClose(self2,err2);if(self2.emittedError)return;var isUtf8=(entry.generalPurposeBitFlag&2048)!==0;entry.fileName=self2.decodeStrings?decodeBuffer(buffer,0,entry.fileNameLength,isUtf8):buffer.slice(0,entry.fileNameLength);var fileCommentStart=entry.fileNameLength+entry.extraFieldLength;var extraFieldBuffer=buffer.slice(entry.fileNameLength,fileCommentStart);entry.extraFields=[];var i=0;while(i<extraFieldBuffer.length-3){var headerId=extraFieldBuffer.readUInt16LE(i+0);var dataSize=extraFieldBuffer.readUInt16LE(i+2);var dataStart=i+4;var dataEnd=dataStart+dataSize;if(dataEnd>extraFieldBuffer.length)return emitErrorAndAutoClose(self2,new Error("extra field length exceeds extra field buffer size"));var dataBuffer=newBuffer(dataSize);extraFieldBuffer.copy(dataBuffer,0,dataStart,dataEnd);entry.extraFields.push({id:headerId,data:dataBuffer});i=dataEnd}entry.fileComment=self2.decodeStrings?decodeBuffer(buffer,fileCommentStart,fileCommentStart+entry.fileCommentLength,isUtf8):buffer.slice(fileCommentStart,fileCommentStart+entry.fileCommentLength);entry.comment=entry.fileComment;self2.readEntryCursor+=buffer.length;self2.entriesRead+=1;if(entry.uncompressedSize===4294967295||entry.compressedSize===4294967295||entry.relativeOffsetOfLocalHeader===4294967295){var zip64EiefBuffer=null;for(var i=0;i<entry.extraFields.length;i++){var extraField=entry.extraFields[i];if(extraField.id===1){zip64EiefBuffer=extraField.data;break}}if(zip64EiefBuffer==null){return emitErrorAndAutoClose(self2,new Error("expected zip64 extended information extra field"))}var index=0;if(entry.uncompressedSize===4294967295){if(index+8>zip64EiefBuffer.length){return emitErrorAndAutoClose(self2,new Error("zip64 extended information extra field does not include uncompressed size"))}entry.uncompressedSize=readUInt64LE(zip64EiefBuffer,index);index+=8}if(entry.compressedSize===4294967295){if(index+8>zip64EiefBuffer.length){return emitErrorAndAutoClose(self2,new Error("zip64 extended information extra field does not include compressed size"))}entry.compressedSize=readUInt64LE(zip64EiefBuffer,index);index+=8}if(entry.relativeOffsetOfLocalHeader===4294967295){if(index+8>zip64EiefBuffer.length){return emitErrorAndAutoClose(self2,new Error("zip64 extended information extra field does not include relative header offset"))}entry.relativeOffsetOfLocalHeader=readUInt64LE(zip64EiefBuffer,index);index+=8}}if(self2.decodeStrings){for(var i=0;i<entry.extraFields.length;i++){var extraField=entry.extraFields[i];if(extraField.id===28789){if(extraField.data.length<6){continue}if(extraField.data.readUInt8(0)!==1){continue}var oldNameCrc32=extraField.data.readUInt32LE(1);if(crc32.unsigned(buffer.slice(0,entry.fileNameLength))!==oldNameCrc32){continue}entry.fileName=decodeBuffer(extraField.data,5,extraField.data.length,true);break}}}if(self2.validateEntrySizes&&entry.compressionMethod===0){var expectedCompressedSize=entry.uncompressedSize;if(entry.isEncrypted()){expectedCompressedSize+=12}if(entry.compressedSize!==expectedCompressedSize){var msg="compressed/uncompressed size mismatch for stored file: "+entry.compressedSize+" != "+entry.uncompressedSize;return emitErrorAndAutoClose(self2,new Error(msg))}}if(self2.decodeStrings){if(!self2.strictFileNames){entry.fileName=entry.fileName.replace(/\\/g,"/")}var errorMessage=validateFileName(entry.fileName,self2.validateFileNameOptions);if(errorMessage!=null)return emitErrorAndAutoClose(self2,new Error(errorMessage))}self2.emit("entry",entry);if(!self2.lazyEntries)self2._readEntry()})})};ZipFile.prototype.openReadStream=function(entry,options2,callback){var self2=this;var relativeStart=0;var relativeEnd=entry.compressedSize;if(callback==null){callback=options2;options2={}}else{if(options2.decrypt!=null){if(!entry.isEncrypted()){throw new Error("options.decrypt can only be specified for encrypted entries")}if(options2.decrypt!==false)throw new Error("invalid options.decrypt value: "+options2.decrypt);if(entry.isCompressed()){if(options2.decompress!==false)throw new Error("entry is encrypted and compressed, and options.decompress !== false")}}if(options2.decompress!=null){if(!entry.isCompressed()){throw new Error("options.decompress can only be specified for compressed entries")}if(!(options2.decompress===false||options2.decompress===true)){throw new Error("invalid options.decompress value: "+options2.decompress)}}if(options2.start!=null||options2.end!=null){if(entry.isCompressed()&&options2.decompress!==false){throw new Error("start/end range not allowed for compressed entry without options.decompress === false")}if(entry.isEncrypted()&&options2.decrypt!==false){throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false")}}if(options2.start!=null){relativeStart=options2.start;if(relativeStart<0)throw new Error("options.start < 0");if(relativeStart>entry.compressedSize)throw new Error("options.start > entry.compressedSize")}if(options2.end!=null){relativeEnd=options2.end;if(relativeEnd<0)throw new Error("options.end < 0");if(relativeEnd>entry.compressedSize)throw new Error("options.end > entry.compressedSize");if(relativeEnd<relativeStart)throw new Error("options.end < options.start")}}if(!self2.isOpen)return callback(new Error("closed"));if(entry.isEncrypted()){if(options2.decrypt!==false)return callback(new Error("entry is encrypted, and options.decrypt !== false"))}self2.reader.ref();var buffer=newBuffer(30);readAndAssertNoEof(self2.reader,buffer,0,buffer.length,entry.relativeOffsetOfLocalHeader,function(err){try{if(err)return callback(err);var signature=buffer.readUInt32LE(0);if(signature!==67324752){return callback(new Error("invalid local file header signature: 0x"+signature.toString(16)))}var fileNameLength=buffer.readUInt16LE(26);var extraFieldLength=buffer.readUInt16LE(28);var localFileHeaderEnd=entry.relativeOffsetOfLocalHeader+buffer.length+fileNameLength+extraFieldLength;var decompress;if(entry.compressionMethod===0){decompress=false}else if(entry.compressionMethod===8){decompress=options2.decompress!=null?options2.decompress:true}else{return callback(new Error("unsupported compression method: "+entry.compressionMethod))}var fileDataStart=localFileHeaderEnd;var fileDataEnd=fileDataStart+entry.compressedSize;if(entry.compressedSize!==0){if(fileDataEnd>self2.fileSize){return callback(new Error("file data overflows file bounds: "+fileDataStart+" + "+entry.compressedSize+" > "+self2.fileSize))}}var readStream=self2.reader.createReadStream({start:fileDataStart+relativeStart,end:fileDataStart+relativeEnd});var endpointStream=readStream;if(decompress){var destroyed=false;var inflateFilter=zlib.createInflateRaw();readStream.on("error",function(err2){setImmediate(function(){if(!destroyed)inflateFilter.emit("error",err2)})});readStream.pipe(inflateFilter);if(self2.validateEntrySizes){endpointStream=new AssertByteCountStream(entry.uncompressedSize);inflateFilter.on("error",function(err2){setImmediate(function(){if(!destroyed)endpointStream.emit("error",err2)})});inflateFilter.pipe(endpointStream)}else{endpointStream=inflateFilter}endpointStream.destroy=function(){destroyed=true;if(inflateFilter!==endpointStream)inflateFilter.unpipe(endpointStream);readStream.unpipe(inflateFilter);readStream.destroy()}}callback(null,endpointStream)}finally{self2.reader.unref()}})};function Entry(){}__name(Entry,"Entry");Entry.prototype.getLastModDate=function(){return dosDateTimeToDate(this.lastModFileDate,this.lastModFileTime)};Entry.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!==0};Entry.prototype.isCompressed=function(){return this.compressionMethod===8};function dosDateTimeToDate(date6,time5){var day=date6&31;var month=(date6>>5&15)-1;var year=(date6>>9&127)+1980;var millisecond=0;var second=(time5&31)*2;var minute=time5>>5&63;var hour=time5>>11&31;return new Date(year,month,day,hour,minute,second,millisecond)}__name(dosDateTimeToDate,"dosDateTimeToDate");function validateFileName(fileName){if(fileName.indexOf("\\")!==-1){return"invalid characters in fileName: "+fileName}if(/^[a-zA-Z]:/.test(fileName)||/^\//.test(fileName)){return"absolute path: "+fileName}if(fileName.split("/").indexOf("..")!==-1){return"invalid relative path: "+fileName}return null}__name(validateFileName,"validateFileName");function readAndAssertNoEof(reader,buffer,offset2,length,position,callback){if(length===0){return setImmediate(function(){callback(null,newBuffer(0))})}reader.read(buffer,offset2,length,position,function(err,bytesRead){if(err)return callback(err);if(bytesRead<length){return callback(new Error("unexpected EOF"))}callback()})}__name(readAndAssertNoEof,"readAndAssertNoEof");util.inherits(AssertByteCountStream,Transform);function AssertByteCountStream(byteCount){Transform.call(this);this.actualByteCount=0;this.expectedByteCount=byteCount}__name(AssertByteCountStream,"AssertByteCountStream");AssertByteCountStream.prototype._transform=function(chunk,encoding,cb){this.actualByteCount+=chunk.length;if(this.actualByteCount>this.expectedByteCount){var msg="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return cb(new Error(msg))}cb(null,chunk)};AssertByteCountStream.prototype._flush=function(cb){if(this.actualByteCount<this.expectedByteCount){var msg="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return cb(new Error(msg))}cb()};util.inherits(RandomAccessReader,EventEmitter7);function RandomAccessReader(){EventEmitter7.call(this);this.refCount=0}__name(RandomAccessReader,"RandomAccessReader");RandomAccessReader.prototype.ref=function(){this.refCount+=1};RandomAccessReader.prototype.unref=function(){var self2=this;self2.refCount-=1;if(self2.refCount>0)return;if(self2.refCount<0)throw new Error("invalid unref");self2.close(onCloseDone);function onCloseDone(err){if(err)return self2.emit("error",err);self2.emit("close")}__name(onCloseDone,"onCloseDone")};RandomAccessReader.prototype.createReadStream=function(options2){var start=options2.start;var end=options2.end;if(start===end){var emptyStream=new PassThrough3;setImmediate(function(){emptyStream.end()});return emptyStream}var stream=this._readStreamForRange(start,end);var destroyed=false;var refUnrefFilter=new RefUnrefFilter(this);stream.on("error",function(err){setImmediate(function(){if(!destroyed)refUnrefFilter.emit("error",err)})});refUnrefFilter.destroy=function(){stream.unpipe(refUnrefFilter);refUnrefFilter.unref();stream.destroy()};var byteCounter=new AssertByteCountStream(end-start);refUnrefFilter.on("error",function(err){setImmediate(function(){if(!destroyed)byteCounter.emit("error",err)})});byteCounter.destroy=function(){destroyed=true;refUnrefFilter.unpipe(byteCounter);refUnrefFilter.destroy()};return stream.pipe(refUnrefFilter).pipe(byteCounter)};RandomAccessReader.prototype._readStreamForRange=function(start,end){throw new Error("not implemented")};RandomAccessReader.prototype.read=function(buffer,offset2,length,position,callback){var readStream=this.createReadStream({start:position,end:position+length});var writeStream=new Writable;var written=0;writeStream._write=function(chunk,encoding,cb){chunk.copy(buffer,offset2+written,0,chunk.length);written+=chunk.length;cb()};writeStream.on("finish",callback);readStream.on("error",function(error3){callback(error3)});readStream.pipe(writeStream)};RandomAccessReader.prototype.close=function(callback){setImmediate(callback)};util.inherits(RefUnrefFilter,PassThrough3);function RefUnrefFilter(context2){PassThrough3.call(this);this.context=context2;this.context.ref();this.unreffedYet=false}__name(RefUnrefFilter,"RefUnrefFilter");RefUnrefFilter.prototype._flush=function(cb){this.unref();cb()};RefUnrefFilter.prototype.unref=function(cb){if(this.unreffedYet)return;this.unreffedYet=true;this.context.unref()};var cp437="\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";function decodeBuffer(buffer,start,end,isUtf8){if(isUtf8){return buffer.toString("utf8",start,end)}else{var result="";for(var i=start;i<end;i++){result+=cp437[buffer[i]]}return result}}__name(decodeBuffer,"decodeBuffer");function readUInt64LE(buffer,offset2){var lower32=buffer.readUInt32LE(offset2);var upper32=buffer.readUInt32LE(offset2+4);return upper32*4294967296+lower32}__name(readUInt64LE,"readUInt64LE");var newBuffer;if(typeof Buffer.allocUnsafe==="function"){newBuffer=__name(function(len){return Buffer.allocUnsafe(len)},"newBuffer")}else{newBuffer=__name(function(len){return new Buffer(len)},"newBuffer")}function defaultCallback(err){if(err)throw err}__name(defaultCallback,"defaultCallback")}});var require_kleur=__commonJS({"node_modules/kleur/index.js"(exports2,module2){"use strict";init_esbuild_shims();var{FORCE_COLOR,NODE_DISABLE_COLORS,TERM}=process.env;var $2={enabled:!NODE_DISABLE_COLORS&&TERM!=="dumb"&&FORCE_COLOR!=="0",reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(arr,str){let i=0,tmp,beg="",end="";for(;i<arr.length;i++){tmp=arr[i];beg+=tmp.open;end+=tmp.close;if(str.includes(tmp.close)){str=str.replace(tmp.rgx,tmp.close+tmp.open)}}return beg+str+end}__name(run,"run");function chain(has,keys){let ctx={has,keys};ctx.reset=$2.reset.bind(ctx);ctx.bold=$2.bold.bind(ctx);ctx.dim=$2.dim.bind(ctx);ctx.italic=$2.italic.bind(ctx);ctx.underline=$2.underline.bind(ctx);ctx.inverse=$2.inverse.bind(ctx);ctx.hidden=$2.hidden.bind(ctx);ctx.strikethrough=$2.strikethrough.bind(ctx);ctx.black=$2.black.bind(ctx);ctx.red=$2.red.bind(ctx);ctx.green=$2.green.bind(ctx);ctx.yellow=$2.yellow.bind(ctx);ctx.blue=$2.blue.bind(ctx);ctx.magenta=$2.magenta.bind(ctx);ctx.cyan=$2.cyan.bind(ctx);ctx.white=$2.white.bind(ctx);ctx.gray=$2.gray.bind(ctx);ctx.grey=$2.grey.bind(ctx);ctx.bgBlack=$2.bgBlack.bind(ctx);ctx.bgRed=$2.bgRed.bind(ctx);ctx.bgGreen=$2.bgGreen.bind(ctx);ctx.bgYellow=$2.bgYellow.bind(ctx);ctx.bgBlue=$2.bgBlue.bind(ctx);ctx.bgMagenta=$2.bgMagenta.bind(ctx);ctx.bgCyan=$2.bgCyan.bind(ctx);ctx.bgWhite=$2.bgWhite.bind(ctx);return ctx}__name(chain,"chain");function init(open6,close){let blk={open:`\x1B[${open6}m`,close:`\x1B[${close}m`,rgx:new RegExp(`\\x1b\\[${close}m`,"g")};return function(txt){if(this!==void 0&&this.has!==void 0){this.has.includes(open6)||(this.has.push(open6),this.keys.push(blk));return txt===void 0?this:$2.enabled?run(this.keys,txt+""):txt+""}return txt===void 0?chain([open6],[blk]):$2.enabled?run([blk],txt+""):txt+""}}__name(init,"init");module2.exports=$2}});var require_action=__commonJS({"node_modules/prompts/dist/util/action.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(key,isSelect)=>{if(key.meta&&key.name!=="escape")return;if(key.ctrl){if(key.name==="a")return"first";if(key.name==="c")return"abort";if(key.name==="d")return"abort";if(key.name==="e")return"last";if(key.name==="g")return"reset"}if(isSelect){if(key.name==="j")return"down";if(key.name==="k")return"up"}if(key.name==="return")return"submit";if(key.name==="enter")return"submit";if(key.name==="backspace")return"delete";if(key.name==="delete")return"deleteForward";if(key.name==="abort")return"abort";if(key.name==="escape")return"exit";if(key.name==="tab")return"next";if(key.name==="pagedown")return"nextPage";if(key.name==="pageup")return"prevPage";if(key.name==="home")return"home";if(key.name==="end")return"end";if(key.name==="up")return"up";if(key.name==="down")return"down";if(key.name==="right")return"right";if(key.name==="left")return"left";return false}}});var require_strip=__commonJS({"node_modules/prompts/dist/util/strip.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=str=>{const pattern=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|");const RGX=new RegExp(pattern,"g");return typeof str==="string"?str.replace(RGX,""):str}}});var require_src2=__commonJS({"node_modules/sisteransi/src/index.js"(exports2,module2){"use strict";init_esbuild_shims();var ESC="\x1B";var CSI=`${ESC}[`;var beep="\x07";var cursor={to(x,y){if(!y)return`${CSI}${x+1}G`;return`${CSI}${y+1};${x+1}H`},move(x,y){let ret="";if(x<0)ret+=`${CSI}${-x}D`;else if(x>0)ret+=`${CSI}${x}C`;if(y<0)ret+=`${CSI}${-y}A`;else if(y>0)ret+=`${CSI}${y}B`;return ret},up:__name((count=1)=>`${CSI}${count}A`,"up"),down:__name((count=1)=>`${CSI}${count}B`,"down"),forward:__name((count=1)=>`${CSI}${count}C`,"forward"),backward:__name((count=1)=>`${CSI}${count}D`,"backward"),nextLine:__name((count=1)=>`${CSI}E`.repeat(count),"nextLine"),prevLine:__name((count=1)=>`${CSI}F`.repeat(count),"prevLine"),left:`${CSI}G`,hide:`${CSI}?25l`,show:`${CSI}?25h`,save:`${ESC}7`,restore:`${ESC}8`};var scroll={up:__name((count=1)=>`${CSI}S`.repeat(count),"up"),down:__name((count=1)=>`${CSI}T`.repeat(count),"down")};var erase={screen:`${CSI}2J`,up:__name((count=1)=>`${CSI}1J`.repeat(count),"up"),down:__name((count=1)=>`${CSI}J`.repeat(count),"down"),line:`${CSI}2K`,lineEnd:`${CSI}K`,lineStart:`${CSI}1K`,lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");if(count)clear+=cursor.left;return clear}};module2.exports={cursor,scroll,erase,beep}}});var require_clear=__commonJS({"node_modules/prompts/dist/util/clear.js"(exports2,module2){"use strict";init_esbuild_shims();function _createForOfIteratorHelper(o,allowArrayLike){var it2=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it2){if(Array.isArray(o)||(it2=_unsupportedIterableToArray2(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it2)o=it2;var i=0;var F2=__name(function F3(){},"F");return{s:F2,n:__name(function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},"n"),e:__name(function e(_e2){throw _e2},"e"),f:F2}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:__name(function s3(){it2=it2.call(o)},"s"),n:__name(function n(){var step=it2.next();normalCompletion=step.done;return step},"n"),e:__name(function e(_e2){didErr=true;err=_e2},"e"),f:__name(function f2(){try{if(!normalCompletion&&it2.return!=null)it2.return()}finally{if(didErr)throw err}},"f")}}__name(_createForOfIteratorHelper,"_createForOfIteratorHelper");function _unsupportedIterableToArray2(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray2(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray2(o,minLen)}__name(_unsupportedIterableToArray2,"_unsupportedIterableToArray");function _arrayLikeToArray2(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}__name(_arrayLikeToArray2,"_arrayLikeToArray");var strip=require_strip();var _require=require_src2();var erase=_require.erase;var cursor=_require.cursor;var width=__name(str=>[...strip(str)].length,"width");module2.exports=function(prompt,perLine){if(!perLine)return erase.line+cursor.to(0);let rows=0;const lines=prompt.split(/\r?\n/);var _iterator=_createForOfIteratorHelper(lines),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){let line=_step.value;rows+=1+Math.floor(Math.max(width(line)-1,0)/perLine)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return erase.lines(rows)}}});var require_figures=__commonJS({"node_modules/prompts/dist/util/figures.js"(exports2,module2){"use strict";init_esbuild_shims();var main={arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",radioOn:"\u25C9",radioOff:"\u25EF",tick:"\u2714",cross:"\u2716",ellipsis:"\u2026",pointerSmall:"\u203A",line:"\u2500",pointer:"\u276F"};var win={arrowUp:main.arrowUp,arrowDown:main.arrowDown,arrowLeft:main.arrowLeft,arrowRight:main.arrowRight,radioOn:"(*)",radioOff:"( )",tick:"\u221A",cross:"\xD7",ellipsis:"...",pointerSmall:"\xBB",line:"\u2500",pointer:">"};var figures=process.platform==="win32"?win:main;module2.exports=figures}});var require_style=__commonJS({"node_modules/prompts/dist/util/style.js"(exports2,module2){"use strict";init_esbuild_shims();var c=require_kleur();var figures=require_figures();var styles=Object.freeze({password:{scale:1,render:__name(input=>"*".repeat(input.length),"render")},emoji:{scale:2,render:__name(input=>"\u{1F603}".repeat(input.length),"render")},invisible:{scale:0,render:__name(input=>"","render")},default:{scale:1,render:__name(input=>`${input}`,"render")}});var render=__name(type=>styles[type]||styles.default,"render");var symbols=Object.freeze({aborted:c.red(figures.cross),done:c.green(figures.tick),exited:c.yellow(figures.cross),default:c.cyan("?")});var symbol=__name((done,aborted3,exited)=>aborted3?symbols.aborted:exited?symbols.exited:done?symbols.done:symbols.default,"symbol");var delimiter2=__name(completing=>c.gray(completing?figures.ellipsis:figures.pointerSmall),"delimiter");var item=__name((expandable,expanded)=>c.gray(expandable?expanded?figures.pointerSmall:"+":figures.line),"item");module2.exports={styles,render,symbols,symbol,delimiter:delimiter2,item}}});var require_lines=__commonJS({"node_modules/prompts/dist/util/lines.js"(exports2,module2){"use strict";init_esbuild_shims();var strip=require_strip();module2.exports=function(msg,perLine){let lines=String(strip(msg)||"").split(/\r?\n/);if(!perLine)return lines.length;return lines.map(l=>Math.ceil(l.length/perLine)).reduce((a,b2)=>a+b2)}}});var require_wrap=__commonJS({"node_modules/prompts/dist/util/wrap.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(msg,opts={})=>{const tab=Number.isSafeInteger(parseInt(opts.margin))?new Array(parseInt(opts.margin)).fill(" ").join(""):opts.margin||"";const width=opts.width;return(msg||"").split(/\r?\n/g).map(line=>line.split(/\s+/g).reduce((arr,w2)=>{if(w2.length+tab.length>=width||arr[arr.length-1].length+w2.length+1<width)arr[arr.length-1]+=` ${w2}`;else arr.push(`${tab}${w2}`);return arr},[tab]).join("\n")).join("\n")}}});var require_entriesToDisplay=__commonJS({"node_modules/prompts/dist/util/entriesToDisplay.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(cursor,total,maxVisible)=>{maxVisible=maxVisible||total;let startIndex=Math.min(total-maxVisible,cursor-Math.floor(maxVisible/2));if(startIndex<0)startIndex=0;let endIndex=Math.min(startIndex+maxVisible,total);return{startIndex,endIndex}}}});var require_util2=__commonJS({"node_modules/prompts/dist/util/index.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports={action:require_action(),clear:require_clear(),style:require_style(),strip:require_strip(),figures:require_figures(),lines:require_lines(),wrap:require_wrap(),entriesToDisplay:require_entriesToDisplay()}}});var require_prompt=__commonJS({"node_modules/prompts/dist/elements/prompt.js"(exports2,module2){"use strict";init_esbuild_shims();var readline2=__require("readline");var _require=require_util2();var action=_require.action;var EventEmitter7=__require("events");var _require2=require_src2();var beep=_require2.beep;var cursor=_require2.cursor;var color=require_kleur();var Prompt=class extends EventEmitter7{static{__name(this,"Prompt")}constructor(opts={}){super();this.firstRender=true;this.in=opts.stdin||process.stdin;this.out=opts.stdout||process.stdout;this.onRender=(opts.onRender||(()=>void 0)).bind(this);const rl=readline2.createInterface({input:this.in,escapeCodeTimeout:50});readline2.emitKeypressEvents(this.in,rl);if(this.in.isTTY)this.in.setRawMode(true);const isSelect=["SelectPrompt","MultiselectPrompt"].indexOf(this.constructor.name)>-1;const keypress=__name((str,key)=>{let a=action(key,isSelect);if(a===false){this._&&this._(str,key)}else if(typeof this[a]==="function"){this[a](key)}else{this.bell()}},"keypress");this.close=()=>{this.out.write(cursor.show);this.in.removeListener("keypress",keypress);if(this.in.isTTY)this.in.setRawMode(false);rl.close();this.emit(this.aborted?"abort":this.exited?"exit":"submit",this.value);this.closed=true};this.in.on("keypress",keypress)}fire(){this.emit("state",{value:this.value,aborted:!!this.aborted,exited:!!this.exited})}bell(){this.out.write(beep)}render(){this.onRender(color);if(this.firstRender)this.firstRender=false}};module2.exports=Prompt}});var require_text=__commonJS({"node_modules/prompts/dist/elements/text.js"(exports2,module2){"use strict";init_esbuild_shims();function asyncGeneratorStep(gen,resolve34,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value}catch(error3){reject(error3);return}if(info.done){resolve34(value)}else{Promise.resolve(value).then(_next,_throw)}}__name(asyncGeneratorStep,"asyncGeneratorStep");function _asyncToGenerator(fn){return function(){var self2=this,args=arguments;return new Promise(function(resolve34,reject){var gen=fn.apply(self2,args);function _next(value){asyncGeneratorStep(gen,resolve34,reject,_next,_throw,"next",value)}__name(_next,"_next");function _throw(err){asyncGeneratorStep(gen,resolve34,reject,_next,_throw,"throw",err)}__name(_throw,"_throw");_next(void 0)})}}__name(_asyncToGenerator,"_asyncToGenerator");var color=require_kleur();var Prompt=require_prompt();var _require=require_src2();var erase=_require.erase;var cursor=_require.cursor;var _require2=require_util2();var style=_require2.style;var clear=_require2.clear;var lines=_require2.lines;var figures=_require2.figures;var TextPrompt=class extends Prompt{static{__name(this,"TextPrompt")}constructor(opts={}){super(opts);this.transform=style.render(opts.style);this.scale=this.transform.scale;this.msg=opts.message;this.initial=opts.initial||``;this.validator=opts.validate||(()=>true);this.value=``;this.errorMsg=opts.error||`Please Enter A Valid Value`;this.cursor=Number(!!this.initial);this.cursorOffset=0;this.clear=clear(``,this.out.columns);this.render()}set value(v2){if(!v2&&this.initial){this.placeholder=true;this.rendered=color.gray(this.transform.render(this.initial))}else{this.placeholder=false;this.rendered=this.transform.render(v2)}this._value=v2;this.fire()}get value(){return this._value}reset(){this.value=``;this.cursor=Number(!!this.initial);this.cursorOffset=0;this.fire();this.render()}exit(){this.abort()}abort(){this.value=this.value||this.initial;this.done=this.aborted=true;this.error=false;this.red=false;this.fire();this.render();this.out.write("\n");this.close()}validate(){var _this=this;return _asyncToGenerator(function*(){let valid=yield _this.validator(_this.value);if(typeof valid===`string`){_this.errorMsg=valid;valid=false}_this.error=!valid})()}submit(){var _this2=this;return _asyncToGenerator(function*(){_this2.value=_this2.value||_this2.initial;_this2.cursorOffset=0;_this2.cursor=_this2.rendered.length;yield _this2.validate();if(_this2.error){_this2.red=true;_this2.fire();_this2.render();return}_this2.done=true;_this2.aborted=false;_this2.fire();_this2.render();_this2.out.write("\n");_this2.close()})()}next(){if(!this.placeholder)return this.bell();this.value=this.initial;this.cursor=this.rendered.length;this.fire();this.render()}moveCursor(n){if(this.placeholder)return;this.cursor=this.cursor+n;this.cursorOffset+=n}_(c,key){let s1=this.value.slice(0,this.cursor);let s22=this.value.slice(this.cursor);this.value=`${s1}${c}${s22}`;this.red=false;this.cursor=this.placeholder?0:s1.length+1;this.render()}delete(){if(this.isCursorAtStart())return this.bell();let s1=this.value.slice(0,this.cursor-1);let s22=this.value.slice(this.cursor);this.value=`${s1}${s22}`;this.red=false;if(this.isCursorAtStart()){this.cursorOffset=0}else{this.cursorOffset++;this.moveCursor(-1)}this.render()}deleteForward(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();let s1=this.value.slice(0,this.cursor);let s22=this.value.slice(this.cursor+1);this.value=`${s1}${s22}`;this.red=false;if(this.isCursorAtEnd()){this.cursorOffset=0}else{this.cursorOffset++}this.render()}first(){this.cursor=0;this.render()}last(){this.cursor=this.value.length;this.render()}left(){if(this.cursor<=0||this.placeholder)return this.bell();this.moveCursor(-1);this.render()}right(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();this.moveCursor(1);this.render()}isCursorAtStart(){return this.cursor===0||this.placeholder&&this.cursor===1}isCursorAtEnd(){return this.cursor===this.rendered.length||this.placeholder&&this.cursor===this.rendered.length+1}render(){if(this.closed)return;if(!this.firstRender){if(this.outputError)this.out.write(cursor.down(lines(this.outputError,this.out.columns)-1)+clear(this.outputError,this.out.columns));this.out.write(clear(this.outputText,this.out.columns))}super.render();this.outputError="";this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.red?color.red(this.rendered):this.rendered].join(` `);if(this.error){this.outputError+=this.errorMsg.split(`
|
|
5
5
|
`).reduce((a,l,i)=>a+`
|
|
6
6
|
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,``)}this.out.write(erase.line+cursor.to(0)+this.outputText+cursor.save+this.outputError+cursor.restore+cursor.move(this.cursorOffset,0))}};module2.exports=TextPrompt}});var require_select=__commonJS({"node_modules/prompts/dist/elements/select.js"(exports2,module2){"use strict";init_esbuild_shims();var color=require_kleur();var Prompt=require_prompt();var _require=require_util2();var style=_require.style;var clear=_require.clear;var figures=_require.figures;var wrap=_require.wrap;var entriesToDisplay=_require.entriesToDisplay;var _require2=require_src2();var cursor=_require2.cursor;var SelectPrompt=class extends Prompt{static{__name(this,"SelectPrompt")}constructor(opts={}){super(opts);this.msg=opts.message;this.hint=opts.hint||"- Use arrow-keys. Return to submit.";this.warn=opts.warn||"- This option is disabled";this.cursor=opts.initial||0;this.choices=opts.choices.map((ch,idx)=>{if(typeof ch==="string")ch={title:ch,value:idx};return{title:ch&&(ch.title||ch.value||ch),value:ch&&(ch.value===void 0?idx:ch.value),description:ch&&ch.description,selected:ch&&ch.selected,disabled:ch&&ch.disabled}});this.optionsPerPage=opts.optionsPerPage||10;this.value=(this.choices[this.cursor]||{}).value;this.clear=clear("",this.out.columns);this.render()}moveCursor(n){this.cursor=n;this.value=this.choices[n].value;this.fire()}reset(){this.moveCursor(0);this.fire();this.render()}exit(){this.abort()}abort(){this.done=this.aborted=true;this.fire();this.render();this.out.write("\n");this.close()}submit(){if(!this.selection.disabled){this.done=true;this.aborted=false;this.fire();this.render();this.out.write("\n");this.close()}else this.bell()}first(){this.moveCursor(0);this.render()}last(){this.moveCursor(this.choices.length-1);this.render()}up(){if(this.cursor===0){this.moveCursor(this.choices.length-1)}else{this.moveCursor(this.cursor-1)}this.render()}down(){if(this.cursor===this.choices.length-1){this.moveCursor(0)}else{this.moveCursor(this.cursor+1)}this.render()}next(){this.moveCursor((this.cursor+1)%this.choices.length);this.render()}_(c,key){if(c===" ")return this.submit()}get selection(){return this.choices[this.cursor]}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render();let _entriesToDisplay=entriesToDisplay(this.cursor,this.choices.length,this.optionsPerPage),startIndex=_entriesToDisplay.startIndex,endIndex=_entriesToDisplay.endIndex;this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(false),this.done?this.selection.title:this.selection.disabled?color.yellow(this.warn):color.gray(this.hint)].join(" ");if(!this.done){this.outputText+="\n";for(let i=startIndex;i<endIndex;i++){let title,prefix,desc="",v2=this.choices[i];if(i===startIndex&&startIndex>0){prefix=figures.arrowUp}else if(i===endIndex-1&&endIndex<this.choices.length){prefix=figures.arrowDown}else{prefix=" "}if(v2.disabled){title=this.cursor===i?color.gray().underline(v2.title):color.strikethrough().gray(v2.title);prefix=(this.cursor===i?color.bold().gray(figures.pointer)+" ":" ")+prefix}else{title=this.cursor===i?color.cyan().underline(v2.title):v2.title;prefix=(this.cursor===i?color.cyan(figures.pointer)+" ":" ")+prefix;if(v2.description&&this.cursor===i){desc=` - ${v2.description}`;if(prefix.length+title.length+desc.length>=this.out.columns||v2.description.split(/\r?\n/).length>1){desc="\n"+wrap(v2.description,{margin:3,width:this.out.columns})}}}this.outputText+=`${prefix} ${title}${color.gray(desc)}
|
|
@@ -180,7 +180,7 @@ ${SESSION_START_CONTEXT_SENTINEL_END}`}__name(buildSessionStartContextBlock,"bui
|
|
|
180
180
|
${SESSION_START_CONTEXT_SENTINEL_START}
|
|
181
181
|
${SESSION_START_CONTEXT_HEADER}:
|
|
182
182
|
`);if(startIndex===-1){return systemInstruction}const endIndex=systemInstruction.indexOf(`
|
|
183
|
-
${SESSION_START_CONTEXT_SENTINEL_END}`,startIndex);if(endIndex===-1){return systemInstruction}return systemInstruction.slice(0,startIndex)}__name(stripTrailingSessionStartContextBlock,"stripTrailingSessionStartContextBlock");var LlmChat=class{constructor(config3,generationConfig={},history=[],chatRecordingService,telemetryService){this.config=config3;this.generationConfig=generationConfig;this.history=history;this.chatRecordingService=chatRecordingService;this.telemetryService=telemetryService;validateHistory(history);this.redactApprovedPlansFromLoadedHistory();this.markToolResultsInjected(this.history)}static{__name(this,"LlmChat")}sendPromise=Promise.resolve();lastPromptTokenCount=0;lastPromptTokenCountIsEstimated=false;injectedToolResults=new WeakSet;lastOutputTokenCount=0;lastCachedContentTokenCount=0;tokenCountsRouteKey=void 0;tokenCountsByRouteKey=new Map;consecutiveFailures=0;hardRescueFailureCount=0;pendingPartialAssistantTurnIndex=null;pendingPartialAssistantRecord=null;lastObservedClosedFinishReason;imagePayloadStore=new InMemoryImagePayloadStore;userContentPushCount=0;manualPlanExitNoticesEnabled=false;completedToolCallIds=[];setCompletedToolCallIds(toolCallIds){this.completedToolCallIds=[...new Set(toolCallIds)].filter(id=>completedToolCallBoundary(this.history,[id])>0)}getCompletedToolCallIds(){return[...this.completedToolCallIds]}getHistoryForRecovery(){const boundary=completedToolCallBoundary(this.history,this.completedToolCallIds);return this.history.slice(boundary).map(copyContentContainer)}isForkedChat=false;clearPendingPartialState(){this.pendingPartialAssistantTurnIndex=null;this.pendingPartialAssistantRecord=null}popPendingPartialAssistantTurn(){const idx=this.pendingPartialAssistantTurnIndex;if(idx===null)return;if(this.history.length>idx&&this.history[idx]?.role==="model"){this.history.splice(idx,1)}else{debugLogger21.warn(`[PARTIAL_POP] Splice skipped: idx=${idx}, historyLength=${this.history.length}, roleAtIdx=${this.history[idx]?.role??"undefined"}`)}this.clearPendingPartialState()}markToolResultsInjected(contents){for(const content of contents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(provenance)this.injectedToolResults.add(provenance)}}enableManualPlanExitNotices(){this.manualPlanExitNoticesEnabled=true}currentRouteKey(){return this.config.getModelRouteIdentity?.()??""}adoptTokenCountsForRoute(targetRouteKey){if(this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0&&this.tokenCountsByRouteKey.size===0){return}targetRouteKey??=this.currentRouteKey();if(this.tokenCountsRouteKey===targetRouteKey){return}const retained=this.tokenCountsByRouteKey.get(targetRouteKey);if(retained){this.tokenCountsByRouteKey.delete(targetRouteKey);this.retainCurrentTokenCounts();debugLogger21.debug(`[token-counts] restoring retained counts for route ${targetRouteKey}`);this.lastPromptTokenCount=retained.promptTokenCount;this.lastPromptTokenCountIsEstimated=retained.promptTokenCountIsEstimated;this.lastOutputTokenCount=retained.outputTokenCount;this.lastCachedContentTokenCount=retained.cachedContentTokenCount;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(retained.promptTokenCount);this.telemetryService?.setLastCachedContentTokenCount(retained.cachedContentTokenCount);return}debugLogger21.debug(`[token-counts] route changed; retaining counts recorded for ${this.tokenCountsRouteKey??"unknown"} (now ${targetRouteKey})`);this.retainCurrentTokenCounts();this.lastPromptTokenCount=0;this.lastPromptTokenCountIsEstimated=false;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(0);this.telemetryService?.setLastCachedContentTokenCount(0)}retainCurrentTokenCounts(){if(this.tokenCountsRouteKey===void 0||this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0){return}if(this.tokenCountsByRouteKey.size>=MAX_RETAINED_ROUTE_COUNTS){const oldestKey=this.tokenCountsByRouteKey.keys().next().value;if(oldestKey!==void 0){this.tokenCountsByRouteKey.delete(oldestKey)}}this.tokenCountsByRouteKey.set(this.tokenCountsRouteKey,{promptTokenCount:this.lastPromptTokenCount,promptTokenCountIsEstimated:this.lastPromptTokenCountIsEstimated,outputTokenCount:this.lastOutputTokenCount,cachedContentTokenCount:this.lastCachedContentTokenCount})}getLastPromptTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastPromptTokenCount}getLastOutputTokenCount(){this.adoptTokenCountsForRoute();return this.lastOutputTokenCount}getLastCachedContentTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastCachedContentTokenCount}getRequestHistory(currentUserContent){const curatedHistory=extractCuratedHistory(this.history);const{maxRecentImages,imagePayloadThreshold}=resolveCompactionTuning(this.config.getChatCompression());let replaced=[];if(countAllInlineImages(curatedHistory)>=imagePayloadThreshold){const skipEntry=currentUserContent?curatedHistory.find(c=>c===currentUserContent||c.role==="user"&¤tUserContent.parts?.some(p2=>c.parts?.includes(p2))):void 0;replaced=replaceImagePayloadsInPlace(curatedHistory,this.imagePayloadStore,skipEntry)}const requestHistory=curatedHistory.map(copyContentContainer);const reattachParts=buildReattachParts(replaced,maxRecentImages,requestHistory,this.imagePayloadStore);if(reattachParts.length>0){const last=requestHistory.at(-1);if(last?.role==="user"){last.parts=[...last.parts??[],...reattachParts]}else{requestHistory.push({role:"user",parts:reattachParts})}}return appendAutoMemoryContext(requestHistory,this.config.getAutoMemoryContext?.()??"")}getRequestHistoryForRoute(currentUserContent,supportedModalities){return slimCompactionInput(this.getRequestHistory(currentUserContent),supportedModalities).slimmedHistory}setLastPromptTokenCount(count,isEstimated=false){this.lastPromptTokenCount=count;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.telemetryService?.setLastCachedContentTokenCount(0);this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}isLastPromptTokenCountEstimated(){this.adoptTokenCountsForRoute();return this.lastPromptTokenCountIsEstimated}promptCountIsEstimateDerived(){return this.lastPromptTokenCount===0||this.lastPromptTokenCountIsEstimated}seedResumeTokenCounts(promptTokenCount,outputTokenCount,isEstimated=false){this.lastPromptTokenCount=Number.isFinite(promptTokenCount)?Math.max(0,promptTokenCount):0;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=Number.isFinite(outputTokenCount)?Math.max(0,outputTokenCount):0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}async tryCompress(promptId,force=false,signal,options2){this.adoptTokenCountsForRoute(options2?.requestRouteKey);const originalTokenCountOverride=options2?.originalTokenCountOverride;const originalTokenCountIsEstimated=originalTokenCountOverride!==void 0?originalTokenCountOverride.isEstimated:options2?.precomputedEffectiveTokens!==void 0||this.promptCountIsEstimateDerived();const originalTokenCount=originalTokenCountOverride!==void 0?originalTokenCountOverride.count:originalTokenCountIsEstimated?options2?.precomputedEffectiveTokens??estimateContentTokens(options2?.pendingUserMessage?[...this.getHistoryShallow(true),options2.pendingUserMessage]:this.getHistoryShallow(true),resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate):this.lastPromptTokenCount;debugLogger21.debug(`[compaction] token-count provenance: prompt_id=${promptId}, originalTokenCount=${originalTokenCount}, estimated=${originalTokenCountIsEstimated}`);const service=new ChatCompressionService;const{newHistory,info}=await service.compress(this,{promptId,force,config:this.config,consecutiveFailures:this.consecutiveFailures,originalTokenCount,pendingUserMessage:options2?.pendingUserMessage,precomputedEffectiveTokens:options2?.precomputedEffectiveTokens,observedServerCeiling:options2?.observedServerCeiling,observedServerCeilingKind:options2?.observedServerCeilingKind,requestRouteKey:options2?.requestRouteKey,requestGenerationConfig:options2?.requestGenerationConfig,trigger:options2?.trigger,customInstructions:options2?.customInstructions,requestPayloadTooLarge:options2?.requestPayloadTooLarge,signal});info.originalTokenCountIsEstimated=originalTokenCountIsEstimated;this.adoptTokenCountsForRoute(options2?.requestRouteKey);if(info.compressionStatus===1&&newHistory){info.newTokenCountIsEstimated??=true;if(!options2?.deferChatCompressionRecord){this.chatRecordingService?.recordChatCompression({info,compressedHistory:options2?.pendingUserMessage?[...newHistory,options2.pendingUserMessage]:newHistory,summaryPrefixLength:newHistory.length,completedToolCallIds:this.completedToolCallIds})}this.setHistory(newHistory,this.completedToolCallIds);debugLogger21.debug("[FILE_READ_CACHE] clear after auto tryCompress");this.config.getFileReadCache().clear();try{await this.config.getExecutionEnvironment?.()?.invalidateReadCache()}catch(error3){debugLogger21.warn("Execution cache invalidation after compression failed",error3)}this.tokenCountsByRouteKey.clear();this.setLastPromptTokenCount(info.newTokenCount,info.newTokenCountIsEstimated);if(options2?.requestRouteKey&&this.tokenCountsRouteKey!==options2.requestRouteKey){this.retainCurrentTokenCounts();this.tokenCountsRouteKey=options2.requestRouteKey;this.tokenCountsByRouteKey.delete(options2.requestRouteKey)}this.telemetryService?.setLastPromptTokenCount(info.newTokenCount);this.consecutiveFailures=0;this.hardRescueFailureCount=0}else if(isCompressionFailureStatus(info.compressionStatus)){if(!force){this.consecutiveFailures+=1;if(this.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger21.warn(`[compaction] circuit breaker tripped after ${this.consecutiveFailures} consecutive failures (cheap-gate path); auto-compaction will NOOP until a successful force compaction resets the counter.`)}}}return info}compressFast(){this.adoptTokenCountsForRoute();const beforeEstimate=estimateContentTokens(this.history);const projectRoot=this.config.getProjectRoot();const targetDir=this.config.getTargetDir?.()??projectRoot;const mcResult=microcompactHistory(this.history,null,this.config.getClearContextOnIdle(),{force:true,preserveReadFileResult:__name(filePath=>isManagedMemoryPath(filePath,projectRoot,targetDir),"preserveReadFileResult")});const mcMeta=mcResult.meta;const newHistory=mcResult.history.map(c=>c.role==="model"?stripThoughtPartsFromContent(c):c).filter(c=>c!==null);const afterEstimate=estimateContentTokens(newHistory);if(afterEstimate>=beforeEstimate){const apiBaseline2=this.lastPromptTokenCount||beforeEstimate;return{info:{originalTokenCount:apiBaseline2,newTokenCount:apiBaseline2,originalTokenCountIsEstimated:this.promptCountIsEstimateDerived(),compressionStatus:5}}}const reduction=beforeEstimate-afterEstimate;const apiBaseline=this.lastPromptTokenCount||beforeEstimate;const baselineIsEstimated=this.promptCountIsEstimateDerived();const adjustedTokenCount=Math.max(0,apiBaseline-reduction);debugLogger21.debug(`[compaction] fast token-count provenance: originalTokenCount=${apiBaseline}, estimated=${baselineIsEstimated}`);const info={originalTokenCount:apiBaseline,newTokenCount:adjustedTokenCount,originalTokenCountIsEstimated:baselineIsEstimated,newTokenCountIsEstimated:true,compressionStatus:1,triggerReason:"manual"};this.chatRecordingService?.recordChatCompression({info,compressedHistory:newHistory,completedToolCallIds:this.completedToolCallIds});logChatCompression(this.config,makeChatCompressionEvent({tokens_before:info.originalTokenCount,tokens_after:info.newTokenCount}));this.setHistory(newHistory,this.completedToolCallIds);this.lastPromptTokenCount=adjustedTokenCount;this.lastPromptTokenCountIsEstimated=true;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.clear();this.telemetryService?.setLastPromptTokenCount(adjustedTokenCount);this.telemetryService?.setLastCachedContentTokenCount(0);this.consecutiveFailures=0;return{info,microcompactMeta:mcMeta}}setSystemInstruction(sysInstr){this.generationConfig.systemInstruction=sysInstr}setSessionStartContext(extraInstruction){const trimmed=extraInstruction.trim();if(!trimmed){return}const current2=this.generationConfig.systemInstruction;let baseInstruction="";if(typeof current2==="string"){baseInstruction=stripTrailingSessionStartContextBlock(current2)}else if(current2){baseInstruction=getCustomSystemPrompt(current2);baseInstruction=stripTrailingSessionStartContextBlock(baseInstruction)}const contextBlock=buildSessionStartContextBlock(trimmed);this.generationConfig.systemInstruction=`${baseInstruction}${contextBlock}`}applySessionStartContext(extraInstruction,_source){const trimmed=extraInstruction.trim();if(!trimmed){return}this.setSessionStartContext(trimmed)}async sendPreparedMessageStream(prepared,promptId,signal,onPreparedRequest){signal.throwIfAborted();if(hasImagePayloadReferences(prepared.history))throw new LlmRequestPreparationError("Saved image payloads are unavailable.");return this.sendMessageStream(`${prepared.routeSelector}\0`,{message:[],config:{...prepared.request.config,abortSignal:signal}},promptId,void 0,{preparedRequest:prepared,onPreparedRequest,retractDeliveredOutputOnRetry:true,disableModelFallbacks:true})}async sendMessageStream(model,params,prompt_id,goalContext,options2){const managedSessionBlock=this.config.getManagedSessionBlock?.();if(managedSessionBlock)throw managedSessionBlock;const turnGoalContext=goalContext?{...goalContext}:void 0;const fullTurnRoute=model.endsWith("\0");const exactRoute=fullTurnRoute?await this.config.getBaseLlmClient().resolveForModel(model.slice(0,-1),{failClosed:true}):void 0;if(exactRoute){model=exactRoute.model}const requestRouteKey=this.config.getModelRouteIdentity(model,exactRoute?.contentGeneratorConfig);this.adoptTokenCountsForRoute(requestRouteKey);const requestModalities=exactRoute?.contentGeneratorConfig.modalities??this.config.getEffectiveInputModalities();await this.sendPromise;let streamDoneResolver;const streamDonePromise=new Promise(resolve34=>{streamDoneResolver=resolve34});this.sendPromise=streamDonePromise;this.clearPendingPartialState();let compressionInfo;let requestContents;let userContentAdded=false;let manualPlanExitNoticeVersion;let manualPlanExitNoticeText;const cgConfigForThresholds=exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig();const parsedEnvMaxTokensForClamp=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const explicitOutputCeiling=params.config?.maxOutputTokens??cgConfigForThresholds?.samplingParams?.max_tokens??parsedEnvMaxTokensForClamp;const outputCeiling=explicitOutputCeiling??defaultOutputCeiling(model);const contextWindowForClamp=cgConfigForThresholds?.contextWindowSize??DEFAULT_TOKEN_LIMIT;let promptTokensForClamp=0;const previousGenerationConfig=options2?.preparedRequest?this.generationConfig:void 0;let currentUserContent;try{if(options2?.preparedRequest){const saved=options2.preparedRequest;if(saved.request.model!==model||saved.providerPin!==llmPreparedProviderPin(exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig()))throw new LlmRequestPreparationError("Saved model route changed.");this.setHistory(structuredClone(saved.history),saved.completedToolCallIds);this.generationConfig=structuredClone(saved.request.config);requestContents=structuredClone(saved.request.contents);currentUserContent=this.history.at(-1);promptTokensForClamp=saved.promptTokensForClamp;compressionInfo={originalTokenCount:promptTokensForClamp,newTokenCount:promptTokensForClamp,compressionStatus:5}}else{let userContent=createUserContent(params.message);userContent={...userContent,parts:userContent.parts?.map(part=>part.functionResponse&&!getToolOutputProvenance(part)?attachToolOutputProvenance([part],{callId:part.functionResponse.id??"",toolName:part.functionResponse.name??"",promptId:prompt_id,toolType:part.functionResponse.name?.startsWith("mcp__")?"mcp":"native"})[0]:part)};const toolOutputBudget=this.config.getToolOutputBatchBudget?.();if(toolOutputBudget!==void 0&&Number.isFinite(toolOutputBudget)&&userContent.parts){const[guarded]=enforceFunctionResponseBudget([{callId:"send-boundary",toolName:"tool-response-batch",responseParts:userContent.parts}],toolOutputBudget);if(guarded.responseParts!==userContent.parts){debugLogger21.warn(`Tool response send guard reduced an unfinalized batch to ${toolOutputBudget} characters.`);userContent={...userContent,parts:guarded.responseParts}}}const{hard}=computeThresholds(contextWindowForClamp,this.config.getAutoCompactThreshold());const imageTokenEstimate=resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate;const effectiveTokens=estimatePromptTokens(this.lastPromptTokenCount>0?[]:this.getHistoryShallow(true),userContent,this.lastPromptTokenCount,this.lastOutputTokenCount,imageTokenEstimate);const isHardTier=effectiveTokens>=hard;const shouldForceFromHard=!exactRoute&&isHardTier&&this.hardRescueFailureCount<MAX_CONSECUTIVE_FAILURES;const historyBeforeHardRescue=shouldForceFromHard?this.getHistoryShallow():void 0;const completedToolCallIdsBeforeHardRescue=this.completedToolCallIds;const lastPromptTokenCountBeforeHardRescue=this.lastPromptTokenCount;const lastPromptTokenCountWasEstimatedBeforeHardRescue=this.lastPromptTokenCountIsEstimated;const lastOutputTokenCountBeforeHardRescue=this.lastOutputTokenCount;const lastCachedContentTokenCountBeforeHardRescue=this.lastCachedContentTokenCount;const tokenCountsRouteKeyBeforeHardRescue=this.tokenCountsRouteKey;const retainedTokenCountsBeforeHardRescue=new Map(this.tokenCountsByRouteKey);const hardRescueFailureCountBeforeHardRescue=this.hardRescueFailureCount;if(shouldForceFromHard){debugLogger21.warn(`[compaction] hard-tier rescue triggered: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, hardRescueAttempt=${this.hardRescueFailureCount+1}, consecutiveFailures=${this.consecutiveFailures}.`)}else if(isHardTier&&!exactRoute){debugLogger21.warn(`[compaction] hard-tier rescue skipped after ${this.hardRescueFailureCount} failed attempts; relying on reactive overflow recovery. prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}.`)}markApiHistoryPrompt(userContent,options2?.promptId);if(exactRoute||isHardTier&&!shouldForceFromHard){compressionInfo={originalTokenCount:effectiveTokens,newTokenCount:effectiveTokens,compressionStatus:5}}else{compressionInfo=await this.tryCompress(prompt_id,shouldForceFromHard,params.config?.abortSignal,{pendingUserMessage:userContent,precomputedEffectiveTokens:effectiveTokens,requestGenerationConfig:params.config,requestRouteKey,deferChatCompressionRecord:shouldForceFromHard,trigger:shouldForceFromHard?"auto":void 0})}const localPromptTokensAfterCompression=shouldForceFromHard?estimatePromptTokens(this.lastPromptTokenCount>0?[]:this.getHistoryShallow(true),userContent,this.lastPromptTokenCount,this.lastOutputTokenCount,imageTokenEstimate):0;if(shouldStopAfterHardRescue(shouldForceFromHard,hard,localPromptTokensAfterCompression)){const message=getHardRescueFailureMessage(effectiveTokens,hard,compressionInfo,localPromptTokensAfterCompression);if(shouldForceFromHard){this.hardRescueFailureCount=hardRescueFailureCountBeforeHardRescue+1}if(compressionInfo.compressionStatus===1&&historyBeforeHardRescue){this.setHistory(historyBeforeHardRescue,completedToolCallIdsBeforeHardRescue);this.lastPromptTokenCount=lastPromptTokenCountBeforeHardRescue;this.lastPromptTokenCountIsEstimated=lastPromptTokenCountWasEstimatedBeforeHardRescue;this.lastOutputTokenCount=lastOutputTokenCountBeforeHardRescue;this.lastCachedContentTokenCount=lastCachedContentTokenCountBeforeHardRescue;this.tokenCountsRouteKey=tokenCountsRouteKeyBeforeHardRescue;this.tokenCountsByRouteKey.clear();for(const[retainedRouteKey,retainedCounts]of retainedTokenCountsBeforeHardRescue){this.tokenCountsByRouteKey.set(retainedRouteKey,retainedCounts)}this.telemetryService?.setLastPromptTokenCount(lastPromptTokenCountBeforeHardRescue);this.telemetryService?.setLastCachedContentTokenCount(lastCachedContentTokenCountBeforeHardRescue)}const compressionStatus=CompressionStatus[compressionInfo.compressionStatus]??String(compressionInfo.compressionStatus);debugLogger21.warn(`[compaction] hard-tier rescue stopped oversized prompt: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, localPromptTokensAfterCompression=${localPromptTokensAfterCompression}, compressionStatus=${compressionStatus}, newTokenCount=${compressionInfo.newTokenCount}, hardRescueFailureCount=${this.hardRescueFailureCount}, consecutiveFailures=${this.consecutiveFailures}. ${message}`);throw new Error(message)}if(shouldForceFromHard&&compressionInfo.compressionStatus===1){this.chatRecordingService?.recordChatCompression({info:compressionInfo,compressedHistory:[...this.getHistoryShallow(),userContent],summaryPrefixLength:this.getHistoryShallow().length,completedToolCallIds:this.completedToolCallIds})}if(this.manualPlanExitNoticesEnabled){const notice=this.config.takePendingManualPlanExitNotice();if(notice){manualPlanExitNoticeVersion=notice.version;manualPlanExitNoticeText=getManualPlanExitSystemReminder(notice.currentMode);userContent={...userContent,parts:[...userContent.parts??[],{text:manualPlanExitNoticeText}]}}}if(Array.isArray(params.message)){params.message[userContentPushSnapshotKey]=this.userContentPushCount}this.history.push(userContent);this.syncReviewedSchemasForContent(userContent);currentUserContent=userContent;userContentAdded=true;this.userContentPushCount++;const inlineRepair=repairOrphanedToolUseTurns(this.history,ORPHAN_TOOL_USE_REPAIR_REASON);if(inlineRepair.injected.length>0){debugLogger21.warn(`[REPAIR] sendMessageStream inline pass synthesized ${inlineRepair.injected.length} functionResponse(s): `+inlineRepair.injected.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}if(inlineRepair.droppedDuplicates.length>0){debugLogger21.warn(`[REPAIR] sendMessageStream inline pass dropped ${inlineRepair.droppedDuplicates.length} duplicate functionResponse(s): `+inlineRepair.droppedDuplicates.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}requestContents=this.getRequestHistoryForRoute(currentUserContent,requestModalities);promptTokensForClamp=this.lastPromptTokenCount>0?estimatePromptTokens([],userContent,this.lastPromptTokenCount,this.lastOutputTokenCount,imageTokenEstimate,true):effectiveTokens;if(this.promptCountIsEstimateDerived()){promptTokensForClamp+=ESTIMATE_CLAMP_OVERHEAD_PAD;debugLogger21.debug(`[clamp] estimate-derived prompt count; padded by ${ESTIMATE_CLAMP_OVERHEAD_PAD}: promptTokensForClamp=${promptTokensForClamp}, count=${this.lastPromptTokenCount}`)}const clampedMaxOutputTokens=clampOutputTokensToWindow(outputCeiling,contextWindowForClamp,promptTokensForClamp);params={...params,config:{...params.config,maxOutputTokens:clampedMaxOutputTokens}}}}catch(error3){if(userContentAdded){this.history.pop();if(currentUserContent){this.syncReviewedSchemasForContent(currentUserContent)}this.userContentPushCount--}if(manualPlanExitNoticeVersion!==void 0){this.config.restorePendingManualPlanExitNotice(manualPlanExitNoticeVersion)}if(previousGenerationConfig)this.generationConfig=previousGenerationConfig;streamDoneResolver();throw error3}const self2=this;return(async function*(){let successfulRecoveries=0;let activeRecoveryUser;let pendingTransportPrefix=[];const sleepInhibitorHandle=acquireSleepInhibitor(self2.config,"Qwen Code is streaming a model response");try{if(compressionInfo.compressionStatus===1){yield{type:"compressed",info:compressionInfo}}let lastError=new Error("Request failed after all retries.");let rateLimitRetryCount=0;let transientInvalidStreamRetryCount=0;let protocolTagLeakRetryCount=0;const totalInvalidStreamRetryCount=__name(()=>transientInvalidStreamRetryCount+protocolTagLeakRetryCount,"totalInvalidStreamRetryCount");const rearmQuietAcceptanceIfBudgetSpent=__name(()=>{if(transientInvalidStreamRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt=true}},"rearmQuietAcceptanceIfBudgetSpent");let streamReplayRetryCount=0;let transportContinuationCount=0;let transportContinuationText="";let transportContinuationParts=[];let transportAttemptParts=[];let transportContinuationPrefix=[];let reactiveCompressionAttempted=false;let omniMediaDegradeAttempts=0;let suppressNextRetryEvent=false;let streamYieldedAnyChunk=false;const cgConfig=exactRoute?.contentGeneratorConfig??self2.config.getContentGeneratorConfig();const requestOverrides=exactRoute?{contentGenerator:exactRoute.contentGenerator,contentGeneratorConfig:exactRoute.contentGeneratorConfig,retryAuthType:exactRoute.retryAuthType,retryErrorCodes:exactRoute.retryErrorCodes,allowPersistentRetry:options2?.preparedRequest?.allowPersistentRetry===true}:void 0;const maxRateLimitRetries=cgConfig?.maxRetries??RATE_LIMIT_RETRY_OPTIONS.maxRetries;const retryInitialDelayMs=cgConfig?.retryInitialDelayMs??RATE_LIMIT_RETRY_OPTIONS.initialDelayMs;const retryMaxDelayMs=cgConfig?.retryMaxDelayMs??RATE_LIMIT_RETRY_OPTIONS.maxDelayMs;const extraRetryErrorCodes=cgConfig?.retryErrorCodes;let maxTokensEscalated=false;const parsedEnvMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const hasUserMaxTokensOverride=cgConfig?.samplingParams?.max_tokens!==void 0&&cgConfig?.samplingParams?.max_tokens!==null||parsedEnvMaxTokens!==void 0;const effectiveInitialMaxOutputTokens=params.config?.maxOutputTokens??outputCeiling;const escalatedLimit=clampOutputTokensToWindow(OUTPUT_TOKEN_CEILING,contextWindowForClamp,promptTokensForClamp);const shouldEscalateMaxOutputTokens=effectiveInitialMaxOutputTokens<escalatedLimit;let lastFinishReason;const buildAttemptContents=__name(()=>transportContinuationPrefix.length>0?[...requestContents,{role:"model",parts:transportContinuationPrefix},createUserContent([{text:buildRecoveryMessageFromText(TRANSPORT_CONTINUATION_MESSAGE,getPlainTextFromParts(transportContinuationPrefix))}])]:requestContents,"buildAttemptContents");const resetTransportContinuation=__name(()=>{transportContinuationCount=0;transportContinuationText="";transportContinuationParts=[];transportAttemptParts=[];transportContinuationPrefix=[];pendingTransportPrefix=[]},"resetTransportContinuation");const foldTransportAttemptText=__name(()=>{transportContinuationParts=mergeDeliveredParts(transportContinuationParts,consolidateModelResponseParts(transportAttemptParts));transportContinuationText=getPlainTextFromParts(transportContinuationParts);transportAttemptParts=[]},"foldTransportAttemptText");let acceptQuietToolResultCompletionOnNextAttempt=false;for(;;){transportAttemptParts=[];let streamEstablished=false;let streamYieldedChunk=false;let streamYieldedContentChunk=false;let streamYieldedFunctionCall=false;try{if(suppressNextRetryEvent){suppressNextRetryEvent=false}else if(rateLimitRetryCount>0||totalInvalidStreamRetryCount()>0||streamReplayRetryCount>0||transportContinuationCount>0){resetTransportContinuation();yield{type:"retry"}}const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt;acceptQuietToolResultCompletionOnNextAttempt=false;const stream=await self2.makeApiCallAndProcessStream(model,buildAttemptContents(),params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,transportContinuationPrefix.length>0?transportContinuationPrefix:void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp);streamEstablished=true;pendingTransportPrefix=[];lastFinishReason=void 0;self2.lastObservedClosedFinishReason=void 0;for await(const chunk of stream){if(isFlushedToolCallPark(chunk)&&!streamYieldedContentChunk&&transportContinuationText.trim().length===0){continue}if(hasCandidateOutput(chunk)){streamYieldedChunk=true;streamYieldedAnyChunk=true}if(hasNonThoughtCandidateParts(chunk)){streamYieldedContentChunk=true}const chunkParts=chunk.candidates?.[0]?.content?.parts;transportAttemptParts.push(...(chunkParts??[]).filter(isPlainTextPart).map(part=>({...part})));if(chunkParts?.some(part=>part.functionCall)){streamYieldedFunctionCall=true}const fr2=chunk.candidates?.[0]?.finishReason;if(fr2)lastFinishReason=fr2;yield{type:"chunk",value:chunk}}lastError=null;transportContinuationPrefix=[];break}catch(error3){if(error3 instanceof LlmRequestPreparationError)throw error3;lastError=error3;if(params.config?.abortSignal?.aborted)throw error3;foldTransportAttemptText();const classification=classifyRetryError(error3,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isQuotaExhaustedError(error3)){debugLogger21.warn("Quota exhausted mid-stream, fast-failing",{retryPath:"stream",retryDecision:"fail-fast",errorKind:classification.kind,classificationReason:classification.reason});throw new Error(formatQuotaExhaustedMessage(error3),{cause:error3})}if(error3 instanceof ResponsesHttpError&&error3.headers.get("x-should-retry")==="false"){throw error3}const isRateLimit=isRateLimitError(error3,extraRetryErrorCodes);if(isRateLimit){const details=getRateLimitErrorDetails(error3);const diagnosticFields={classificationDiagnosis:classification.diagnosis,errorKind:classification.kind,classificationReason:classification.reason,...details};if(rateLimitRetryCount<maxRateLimitRetries){self2.popPendingPartialAssistantTurn();rateLimitRetryCount++;const delayMs=getRateLimitRetryDelayMs(rateLimitRetryCount,{...RATE_LIMIT_RETRY_OPTIONS,initialDelayMs:retryInitialDelayMs,maxDelayMs:retryMaxDelayMs,error:error3});const message=parseAndFormatApiError(error3 instanceof Error?error3.message:String(error3));debugLogger21.warn("Rate limit retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,retryDelayMs:delayMs,...diagnosticFields});const{promise:delayPromise,skip}=delay2(delayMs,params.config?.abortSignal);resetTransportContinuation();yield{type:"retry",retryInfo:{message,attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,delayMs,skipDelay:skip}};await delayPromise;rearmQuietAcceptanceIfBudgetSpent();continue}debugLogger21.warn("Rate limit retry exhausted",{retryPath:"stream",retryDecision:"exhausted",attempts:rateLimitRetryCount,maxRetries:maxRateLimitRetries,...diagnosticFields})}const contextOverflow=getContextLengthExceededInfo(error3);const requestPayloadOverflow=getRequestPayloadTooLargeInfo(error3);const isServerStreamError=streamEstablished&&!isRateLimit&&(classification.kind==="http"||classification.kind==="sse-provider")&&classification.diagnosis==="retryable"&&classification.statusCode!==void 0&&classification.statusCode>=500&&classification.statusCode<600;const isContinuableStreamCut=isRetryableStreamTransportError(classification)||isRetryableStatuslessUpstreamError(classification)&&!contextOverflow.isExceeded&&!requestPayloadOverflow.isTooLarge;const isReplayableStreamError=isContinuableStreamCut||isServerStreamError;const replayAdmitsDeliveredContent=options2?.retractDeliveredOutputOnRetry===true;if(isReplayableStreamError&&(replayAdmitsDeliveredContent||!streamYieldedContentChunk&&transportContinuationText.trim().length===0)&&streamReplayRetryCount<STREAM_RETRY_CONFIG.maxRetries){self2.popPendingPartialAssistantTurn();streamReplayRetryCount++;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*streamReplayRetryCount;debugLogger21.warn(isServerStreamError?"Server stream retry scheduled":"Transport stream retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,retryDelayMs:delayMs,yieldedNonContentChunks:streamYieldedChunk,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}});yield{type:"retry"};resetTransportContinuation();suppressNextRetryEvent=true;await delay2(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}const attemptFinishReason=lastFinishReason??self2.lastObservedClosedFinishReason;const attemptClosedWithOwnOutput=attemptFinishReason!==void 0&&CLOSED_FINISH_REASONS.has(attemptFinishReason)&&streamYieldedContentChunk;const canContinueAfterTransportCut=isContinuableStreamCut&&!replayAdmitsDeliveredContent&&!attemptClosedWithOwnOutput&&!streamYieldedFunctionCall&&transportContinuationText.trim().length>0&&transportContinuationCount<STREAM_RETRY_CONFIG.maxContinuationRetries;if(canContinueAfterTransportCut){self2.popPendingPartialAssistantTurn();transportContinuationCount++;transportContinuationPrefix=transportContinuationParts;pendingTransportPrefix=transportContinuationPrefix;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*transportContinuationCount;debugLogger21.warn("Transport stream continuation scheduled",{retryPath:"stream",retryDecision:"continue",attempt:transportContinuationCount,maxRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,retryDelayMs:delayMs,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,deliveredChars:transportContinuationText.length});yield{type:"retry",isContinuation:true};suppressNextRetryEvent=true;await delay2(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}if(isReplayableStreamError){debugLogger21.warn(isServerStreamError?"Server stream retry not taken":"Transport stream retry not taken",{retryPath:"stream",retryDecision:attemptClosedWithOwnOutput?"skipped_terminal_finish_reason":streamYieldedContentChunk||transportContinuationText.trim().length>0?"skipped_after_content":"exhausted",attempts:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,continuationAttempts:transportContinuationCount,maxContinuationRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}})}if(contextOverflow.isExceeded||requestPayloadOverflow.isTooLarge){const omniDegradeMaxAttempts=self2.config.getOmniProcessingConfig?.()?.limits.maxTransportPasses??0;if(contextOverflow.isExceeded&&!exactRoute&&omniMediaDegradeAttempts<omniDegradeMaxAttempts){const degradeAttempt=omniMediaDegradeAttempts++;let degradeOutcome;try{const{degradeOmniMediaAfterServerReject}=await import("./reactive-degrade-KSNGHMBN.js");degradeOutcome=await degradeOmniMediaAfterServerReject(self2.config,self2.history,degradeAttempt,{signal:params.config?.abortSignal,observedLimitTokens:contextOverflow.limitTokens})}catch(degradeError){if(params.config?.abortSignal?.aborted||isAbortError(degradeError)){throw degradeError}debugLogger21.warn("Omni media degradation fallback failed.",degradeError)}if(degradeOutcome&°radeOutcome.replacedParts>0){self2.popPendingPartialAssistantTurn();requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger21.warn(`Server input limit exceeded; degraded ${degradeOutcome.degradedResources} omni media resource(s) in place (attempt ${degradeAttempt+1}/${omniDegradeMaxAttempts}); retrying.`);resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}}let attemptedPayloadRecovery=false;let payloadRecoveryNoop=false;let payloadRecoveryThrew=false;if(!exactRoute&&!reactiveCompressionAttempted){reactiveCompressionAttempted=true;attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge;const reactiveOriginalTokenCountIsEstimated=contextOverflow.actualTokens===void 0;const reactiveOriginalTokenCount=contextOverflow.actualTokens??contextOverflow.limitTokens??(requestPayloadOverflow.isTooLarge?estimateContentTokens(self2.getHistoryShallow(true),resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate):cgConfig?.contextWindowSize??DEFAULT_TOKEN_LIMIT);debugLogger21.warn(requestPayloadOverflow.isTooLarge?"Request body rejected with HTTP 413; attempting reactive compression.":"Context length exceeded; attempting reactive compression.");if(!streamYieldedFunctionCall){pendingTransportPrefix=transportContinuationParts}try{const reactiveInfo=await self2.tryCompress(prompt_id,true,params.config?.abortSignal,{originalTokenCountOverride:{count:reactiveOriginalTokenCount,isEstimated:reactiveOriginalTokenCountIsEstimated},precomputedEffectiveTokens:reactiveOriginalTokenCount,observedServerCeiling:contextOverflow.limitTokens,observedServerCeilingKind:contextOverflow.limitKind,requestGenerationConfig:params.config,requestRouteKey,trigger:"auto",requestPayloadTooLarge:requestPayloadOverflow.isTooLarge});if(reactiveInfo.compressionStatus===1){self2.popPendingPartialAssistantTurn();const noticeText=manualPlanExitNoticeText;if(noticeText&&!self2.history.some(content=>content.parts?.some(part=>part.text?.includes(noticeText)))){const lastContent=self2.history.at(-1);if(lastContent?.role==="user"){lastContent.parts=[...lastContent.parts??[],{text:noticeText}]}else{self2.history.push(createUserContent([{text:noticeText}]))}}requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger21.info(`Reactive compression succeeded: ${reactiveInfo.originalTokenCount} -> ${reactiveInfo.newTokenCount} tokens.`);yield{type:"compressed",info:reactiveInfo};resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}if(reactiveInfo.compressionStatus===5){payloadRecoveryNoop=true}debugLogger21.warn(requestPayloadOverflow.isTooLarge?`Reactive compression did not recover request payload overflow: status=${reactiveInfo.compressionStatus}.`:`Reactive compression did not recover context overflow: status=${reactiveInfo.compressionStatus}.`);if(isCompressionFailureStatus(reactiveInfo.compressionStatus)){if(requestPayloadOverflow.isTooLarge&&reactiveInfo.compressionStatus===7){payloadRecoveryThrew=true}self2.consecutiveFailures+=1;if(self2.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger21.warn(`[compaction] circuit breaker tripped after ${self2.consecutiveFailures} consecutive failures (reactive overflow path); auto-compaction will NOOP on the cheap-gate until a successful force compaction resets the counter.`)}}}catch(compressionError){if(params.config?.abortSignal?.aborted||isAbortError(compressionError)){throw compressionError}payloadRecoveryThrew=requestPayloadOverflow.isTooLarge;debugLogger21.warn("Reactive compression failed.",compressionError)}}else{attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge&&reactiveCompressionAttempted&&!exactRoute;debugLogger21.warn(requestPayloadOverflow.isTooLarge?"Reactive compression already attempted; propagating the request payload overflow error to caller.":"Reactive compression already attempted; propagating the context overflow error to caller.")}if(attemptedPayloadRecovery){if(payloadRecoveryThrew){debugLogger21.warn("Request payload overflow recovery failed transiently; propagating the original 413 so the next send can retry recovery.")}else{debugLogger21.warn("Request payload overflow recovery exhausted; surfacing actionable 413 error.");const actionableError=new Error(payloadRecoveryNoop?REQUEST_PAYLOAD_TOO_LARGE_NOOP_MESSAGE:REQUEST_PAYLOAD_TOO_LARGE_RECOVERY_MESSAGE,{cause:error3});const payloadStatus=requestPayloadOverflow.status;if(payloadStatus!==void 0){Object.assign(actionableError,{status:payloadStatus})}lastError=actionableError}}break}if(error3 instanceof InvalidStreamError&&(error3.type==="NO_TOOL_RESULT_PROGRESS_MAX_TOKENS"||error3.type==="NO_RESPONSE_TEXT"&&lastFinishReason===FinishReason.MAX_TOKENS)&&!maxTokensEscalated&&!hasUserMaxTokensOverride&&shouldEscalateMaxOutputTokens){lastError=null;lastFinishReason=FinishReason.MAX_TOKENS;break}const isInvalidStreamError=error3 instanceof InvalidStreamError;const maxInvalidStreamRetries=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const invalidStreamRetryCount=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount:transientInvalidStreamRetryCount;if(isInvalidStreamError&&invalidStreamRetryCount<maxInvalidStreamRetries){self2.popPendingPartialAssistantTurn();const nextInvalidStreamRetryCount=invalidStreamRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount=nextInvalidStreamRetryCount}else{transientInvalidStreamRetryCount=nextInvalidStreamRetryCount}rearmQuietAcceptanceIfBudgetSpent();const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextInvalidStreamRetryCount;debugLogger21.warn(`Invalid stream [${error3.type}] (retry ${nextInvalidStreamRetryCount}/${maxInvalidStreamRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextInvalidStreamRetryCount-1,error3.type,delayMs,model));yield{type:"retry"};await delay2(delayMs,params.config?.abortSignal).promise;continue}break}}const rollbackRecoveryAttempt=__name(()=>{const expectedIdx=self2.pendingPartialAssistantTurnIndex;const lastIdx=self2.history.length-1;if(expectedIdx!==null&&self2.history.length>0&&self2.history[lastIdx]?.role==="model"){if(expectedIdx!==lastIdx){debugLogger21.warn(`[RECOVERY_POP] Marker/last-index mismatch: marker=${expectedIdx}, lastIdx=${lastIdx}, historyLength=${self2.history.length}. Popping last entry as best-effort rollback \u2014 investigate any history mutation between processStreamResponse's partial push and this catch.`)}self2.history.pop();self2.clearPendingPartialState()}if(self2.history.length>0&&self2.history[self2.history.length-1].role==="user"){self2.history.pop()}},"rollbackRecoveryAttempt");const streamWithInvalidStreamRetries=__name(async function*(buildAttempt,retryEvent={type:"retry"}){let transientRetryCount=0;let protocolTagLeakRetryCount2=0;let acceptQuietToolResultCompletionOnNextAttempt2=false;for(;;){const attemptState=buildAttempt();try{const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt2;acceptQuietToolResultCompletionOnNextAttempt2=false;const stream=await self2.makeApiCallAndProcessStream(model,attemptState.requestContents,attemptState.params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp,retryEvent.isContinuation===true);for await(const chunk of stream){yield{type:"chunk",value:chunk}}return}catch(error3){if(attemptState.params.config?.abortSignal?.aborted)throw error3;attemptState.rollback();if(!(error3 instanceof InvalidStreamError))throw error3;const maxContinuationRetries=error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const continuationRetryCount=error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount2:transientRetryCount;if(continuationRetryCount>=maxContinuationRetries){throw error3}const nextContinuationRetryCount=continuationRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount2=nextContinuationRetryCount}else{transientRetryCount=nextContinuationRetryCount}if(transientRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt2=true}const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextContinuationRetryCount;debugLogger21.warn(`Invalid stream [${error3.type}] during output continuation (retry ${nextContinuationRetryCount}/${maxContinuationRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextContinuationRetryCount-1,error3.type,delayMs,model));yield retryEvent;await delay2(delayMs,attemptState.params.config?.abortSignal).promise}}},"streamWithInvalidStreamRetries");if(lastError===null&&lastFinishReason===FinishReason.MAX_TOKENS&&!maxTokensEscalated&&!hasUserMaxTokensOverride){maxTokensEscalated=true;let recoveryFinishReason=lastFinishReason;let recoveryParams=params;if(shouldEscalateMaxOutputTokens){debugLogger21.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens. Escalating to ${escalatedLimit} tokens.`);if(self2.history.length>0&&self2.history[self2.history.length-1].role==="model"){self2.history.pop()}yield{type:"retry",maxOutputTokensEscalated:escalatedLimit};const escalatedParams={...params,config:{...params.config,maxOutputTokens:escalatedLimit}};recoveryParams=escalatedParams;recoveryFinishReason=void 0;for await(const event of streamWithInvalidStreamRetries(()=>({requestContents,params:escalatedParams,rollback:__name(()=>self2.popPendingPartialAssistantTurn(),"rollback")}))){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}}else{debugLogger21.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens; skipping no-op escalation to ${escalatedLimit} tokens and running recovery.`)}let recoveryCount=0;while(recoveryFinishReason===FinishReason.MAX_TOKENS&&recoveryCount<MAX_OUTPUT_RECOVERY_ATTEMPTS){const lastEntry=self2.history[self2.history.length-1];const hasFunctionCall=lastEntry?.role==="model"&&lastEntry.parts?.some(p2=>p2.functionCall)===true;if(hasFunctionCall){debugLogger21.info("Skipping recovery: truncated turn contains functionCall; deferring to tool scheduler fallback.");break}recoveryCount++;debugLogger21.info(`Output still truncated after max_tokens handling. Recovery attempt ${recoveryCount}/${MAX_OUTPUT_RECOVERY_ATTEMPTS}.`);const recoveryUserContent=createUserContent([{text:buildOutputRecoveryMessage(lastEntry)}]);yield{type:"retry",isContinuation:true};recoveryFinishReason=void 0;const recoveryImageTokenEstimate=resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate;const countBasedRecoveryEstimate=self2.lastPromptTokenCount>0?estimatePromptTokens([],recoveryUserContent,self2.lastPromptTokenCount,self2.lastOutputTokenCount,recoveryImageTokenEstimate,true):0;self2.history.push(recoveryUserContent);const recoveryContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);self2.history.pop();const walkRecoveryEstimate=estimateContentTokens(recoveryContents,recoveryImageTokenEstimate)+ESTIMATE_CLAMP_OVERHEAD_PAD;const recoveryPromptEstimate=Math.max(countBasedRecoveryEstimate,walkRecoveryEstimate);const recoveryCeiling=recoveryParams.config?.maxOutputTokens??outputCeiling;const iterationParams={...recoveryParams,config:{...recoveryParams.config,maxOutputTokens:clampOutputTokensToWindow(recoveryCeiling,contextWindowForClamp,recoveryPromptEstimate)}};try{for await(const event of streamWithInvalidStreamRetries(()=>{self2.history.push(recoveryUserContent);activeRecoveryUser=recoveryUserContent;return{requestContents:self2.getRequestHistoryForRoute(currentUserContent,requestModalities),params:iterationParams,rollback:rollbackRecoveryAttempt}},{type:"retry",isContinuation:true})){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}successfulRecoveries++;activeRecoveryUser=void 0}catch(recoveryError){if(recoveryError instanceof LlmRequestPreparationError)throw recoveryError;if(params.config?.abortSignal?.aborted)throw recoveryError;rollbackRecoveryAttempt();debugLogger21.warn(`Recovery attempt ${recoveryCount} failed: ${recoveryError}`);yield{type:"chunk",value:{candidates:[{content:{role:"model",parts:[]},finishReason:FinishReason.STOP}]}};break}}}if(lastError){if(lastError instanceof InvalidStreamError){const totalAttempts=totalInvalidStreamRetryCount()+1;logContentRetryFailure(self2.config,new ContentRetryFailureEvent(totalAttempts,lastError.type,model))}const fallbackModels=exactRoute||options2?.disableModelFallbacks?[]:self2.config.getModelFallbacks();if(fallbackModels.length>0&&!isUnattendedMode()&&!streamYieldedAnyChunk){let currentErrorClassification=classifyRetryError(lastError,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isFallbackEligible(currentErrorClassification)){let fallbackSucceeded=false;let fallbackIndex=0;let currentModel=model;let currentResolvedModel=cgConfig?.model??model;let fallbackStreamYieldedAnyChunk=false;for(const fallbackModelId of fallbackModels){if(fallbackModelId===model||fallbackModelId===currentModel){debugLogger21.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": same as current model.`);continue}let fallbackGenerator;let fallbackConfig;let fallbackRetryAuthType;let fallbackRetryErrorCodes;let resolvedFallbackModel;let fallbackModalities;try{const resolved=await self2.config.getBaseLlmClient().resolveForModel(fallbackModelId,{failClosed:true});fallbackGenerator=resolved.contentGenerator;fallbackConfig=resolved.contentGeneratorConfig;fallbackRetryAuthType=resolved.retryAuthType;fallbackRetryErrorCodes=resolved.retryErrorCodes;resolvedFallbackModel=resolved.model;fallbackModalities=resolved.contentGeneratorConfig?.modalities}catch(resolveError){if(isAbortError(resolveError))throw resolveError;const resolveErrorMessage=resolveError instanceof Error?resolveError.message:String(resolveError);debugLogger21.warn(`[FALLBACK] Failed to resolve fallback model "${fallbackModelId}": ${resolveErrorMessage}. Trying next fallback.`);continue}if(resolvedFallbackModel===currentResolvedModel){debugLogger21.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": resolved model "${resolvedFallbackModel}" matches the current model.`);continue}fallbackIndex++;debugLogger21.warn(`[FALLBACK] Model "${currentModel}" exhausted retries (reason: ${currentErrorClassification.reason}, status: ${currentErrorClassification.statusCode??"unknown"}). Switching to fallback model "${fallbackModelId}" (${fallbackIndex}/${fallbackModels.length}).`);yield{type:"model_fallback",info:{fromModel:currentModel,toModel:resolvedFallbackModel,statusCode:currentErrorClassification.statusCode,fallbackIndex}};self2.popPendingPartialAssistantTurn();let currentFallbackYieldedAnyChunk=false;try{const fallbackRequestContents=self2.getRequestHistoryForRoute(currentUserContent,fallbackModalities??{});for await(const event of self2.makeFallbackStream(resolvedFallbackModel,fallbackRequestContents,params,prompt_id,fallbackGenerator,fallbackRetryAuthType,fallbackRetryErrorCodes,requestRouteKey,turnGoalContext,options2?.onPreparedRequest,promptTokensForClamp,fallbackConfig)){const emittedUserVisibleOutput=event.type!=="chunk"||hasCandidateOutput(event.value);if(emittedUserVisibleOutput){currentFallbackYieldedAnyChunk=true;fallbackStreamYieldedAnyChunk=true}yield event}lastError=null;fallbackSucceeded=true;debugLogger21.info(`[FALLBACK] Successfully completed request with fallback model "${resolvedFallbackModel}".`);return}catch(fallbackError){if(fallbackError instanceof LlmRequestPreparationError)throw fallbackError;if(params.config?.abortSignal?.aborted||isAbortError(fallbackError)){throw fallbackError}lastError=fallbackError;if(currentFallbackYieldedAnyChunk){self2.popPendingPartialAssistantTurn();debugLogger21.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" failed after emitting output. Popped the partial assistant turn and stopped the fallback chain to avoid duplicating user-visible output.`);break}const fallbackClassification=classifyRetryError(fallbackError,{authType:fallbackRetryAuthType,extraRetryErrorCodes:fallbackRetryErrorCodes});const canTryNextFallback=isFallbackEligible(fallbackClassification);debugLogger21.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" also failed (reason: ${fallbackClassification.reason}, status: ${fallbackClassification.statusCode??"unknown"}). ${canTryNextFallback?"Checking remaining fallbacks.":"Stopping fallback chain."}`);currentModel=resolvedFallbackModel;currentResolvedModel=resolvedFallbackModel;currentErrorClassification=fallbackClassification;if(!canTryNextFallback){debugLogger21.warn(`[FALLBACK] Error from "${resolvedFallbackModel}" is not fallback-eligible (${fallbackClassification.reason}). Stopping fallback chain.`);break}}}if(!fallbackSucceeded){if(!fallbackStreamYieldedAnyChunk){self2.popPendingPartialAssistantTurn()}debugLogger21.warn("[FALLBACK] Fallback chain exhausted without success. Throwing last error.")}}else{debugLogger21.warn(`[FALLBACK] Fallback chain skipped: primary error is not fallback-eligible (reason: ${currentErrorClassification.reason}, diagnosis: ${currentErrorClassification.diagnosis}, status: ${currentErrorClassification.statusCode??"unknown"}, error: ${lastError instanceof Error?lastError.message:String(lastError)}).`)}}else if(fallbackModels.length>0&&!isUnattendedMode()&&streamYieldedAnyChunk){debugLogger21.warn("[FALLBACK] Fallback chain skipped because the primary model already emitted user-visible output.")}if(lastError){throw lastError}}}finally{if(params.config?.abortSignal?.aborted&&pendingTransportPrefix.length>0){const parts=pendingTransportPrefix;self2.history.push({role:"model",parts});self2.pendingPartialAssistantTurnIndex=self2.history.length-1;self2.pendingPartialAssistantRecord={model,message:parts,contextWindowSize:self2.config.getContentGeneratorConfig()?.contextWindowSize,...turnGoalContext?{goalContext:{...turnGoalContext}}:{}}}const recoveryIndex=activeRecoveryUser?self2.history.indexOf(activeRecoveryUser):-1;if(recoveryIndex===self2.history.length-1&&recoveryIndex>=0){self2.history.pop()}else if(recoveryIndex>=0&&recoveryIndex===self2.history.length-2&&self2.history.at(-1)?.role==="model"){successfulRecoveries++}if(successfulRecoveries>0){self2.coalesceRecoveryPairs(successfulRecoveries)}if(previousGenerationConfig)self2.generationConfig=previousGenerationConfig;sleepInhibitorHandle.release();streamDoneResolver();if(self2.pendingPartialAssistantRecord){try{self2.chatRecordingService?.recordAssistantTurn(self2.pendingPartialAssistantRecord)}catch(recordErr){debugLogger21.error("[PARTIAL_FLUSH] Failed to persist deferred JSONL record: "+(recordErr instanceof Error?recordErr.message:String(recordErr)))}self2.clearPendingPartialState()}}})()}async makeApiCallAndProcessStream(model,requestContents,params,prompt_id,overrides,routeKey=this.currentRouteKey(),goalContext,transportContinuationPrefix,acceptQuietToolResultCompletion=false,onPreparedRequest,promptTokensForClamp=0,continuationInFlight=false){const generator=overrides?.contentGenerator??this.config.getContentGenerator();const request={model,contents:requestContents,config:{...this.generationConfig,...params.config},...transportContinuationPrefix!==void 0&&{continuationInFlight:true}};const actualConfig=overrides?.contentGeneratorConfig??this.config.getContentGeneratorConfig();if(onPreparedRequest){const{abortSignal:_signal,httpOptions:_http,...config3}=request.config??{};try{const prepared={request:{model,contents:requestContents,config:config3},history:this.history,completedToolCallIds:[...this.completedToolCallIds],routeSelector:`${actualConfig?.authType??""}:${model}`,providerPin:llmPreparedProviderPin(actualConfig),promptTokensForClamp,allowPersistentRetry:overrides?.allowPersistentRetry??!overrides};const overBudget=onPreparedRequest.maxSnapshotBytes!==void 0&&Buffer.byteLength(JSON.stringify(prepared))>onPreparedRequest.maxSnapshotBytes;await onPreparedRequest(overBudget?prepared:structuredClone(prepared),continuationInFlight||transportContinuationPrefix!==void 0||hasImagePayloadReferences(this.history))}catch(cause){throw new LlmRequestPreparationError(cause)}}params.config?.abortSignal?.throwIfAborted();const apiCall=__name(()=>{params.config?.abortSignal?.throwIfAborted();const groups=new Map;for(const content of requestContents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(!provenance||this.injectedToolResults.has(provenance))continue;const parts=groups.get(provenance)??[];parts.push(part);groups.set(provenance,parts)}for(const[provenance,parts]of groups){this.injectedToolResults.add(provenance);try{const injected=measureToolOutput(parts,this.config);logToolResultSize(this.config,new ToolResultSizeEvent(provenance.toolName,provenance.toolType,"injection",provenance.rawSize?.chars,injected.chars,provenance.rawSize?.estimatedTokens,injected.estimatedTokens,provenance.truncated,Number.isFinite(provenance.budget)?provenance.budget:void 0,provenance.budgetSource,provenance.callId,provenance.promptId||prompt_id))}catch{}}return generator.generateContentStream(request,prompt_id)},"apiCall");const cgConfig=this.config.getContentGeneratorConfig();const authType=overrides?.retryAuthType??cgConfig?.authType;const extraRetryErrorCodes=overrides?.retryErrorCodes??cgConfig?.retryErrorCodes;const persistentMode=(overrides?.allowPersistentRetry??!overrides)&&isUnattendedMode();const streamResponse=await retryWithBackoff(apiCall,{shouldRetryOnError:__name(error3=>{if(error3 instanceof ResponsesHttpError){return error3.shouldRetry(extraRetryErrorCodes)}if(error3 instanceof Error){if(isSchemaDepthError(error3.message))return false;if(isInvalidArgumentError(error3.message))return false}const status=getErrorStatus(error3);if(status===400){return classifyRetryError(error3,{authType,extraRetryErrorCodes}).kind==="transport"}if(status===429)return true;if(status&&status>=500&&status<600)return true;return isRetryableUpstreamError(error3,extraRetryErrorCodes)},"shouldRetryOnError"),authType,extraRetryErrorCodes,persistentMode,signal:params.config?.abortSignal,...persistentMode?{heartbeatFn:__name(info=>{process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info.attempt}, retry in ${Math.ceil(info.remainingMs/1e3)}s
|
|
183
|
+
${SESSION_START_CONTEXT_SENTINEL_END}`,startIndex);if(endIndex===-1){return systemInstruction}return systemInstruction.slice(0,startIndex)}__name(stripTrailingSessionStartContextBlock,"stripTrailingSessionStartContextBlock");var LlmChat=class{constructor(config3,generationConfig={},history=[],chatRecordingService,telemetryService){this.config=config3;this.generationConfig=generationConfig;this.history=history;this.chatRecordingService=chatRecordingService;this.telemetryService=telemetryService;validateHistory(history);this.redactApprovedPlansFromLoadedHistory();this.markToolResultsInjected(this.history)}static{__name(this,"LlmChat")}sendPromise=Promise.resolve();lastPromptTokenCount=0;lastPromptTokenCountIsEstimated=false;injectedToolResults=new WeakSet;lastOutputTokenCount=0;lastCachedContentTokenCount=0;tokenCountsRouteKey=void 0;tokenCountsByRouteKey=new Map;consecutiveFailures=0;hardRescueFailureCount=0;pendingPartialAssistantTurnIndex=null;pendingPartialAssistantRecord=null;lastObservedClosedFinishReason;imagePayloadStore=new InMemoryImagePayloadStore;userContentPushCount=0;manualPlanExitNoticesEnabled=false;completedToolCallIds=[];setCompletedToolCallIds(toolCallIds){this.completedToolCallIds=[...new Set(toolCallIds)].filter(id=>completedToolCallBoundary(this.history,[id])>0)}getCompletedToolCallIds(){return[...this.completedToolCallIds]}getHistoryForRecovery(){const boundary=completedToolCallBoundary(this.history,this.completedToolCallIds);return this.history.slice(boundary).map(copyContentContainer)}isForkedChat=false;clearPendingPartialState(){this.pendingPartialAssistantTurnIndex=null;this.pendingPartialAssistantRecord=null}popPendingPartialAssistantTurn(){const idx=this.pendingPartialAssistantTurnIndex;if(idx===null)return;if(this.history.length>idx&&this.history[idx]?.role==="model"){this.history.splice(idx,1)}else{debugLogger21.warn(`[PARTIAL_POP] Splice skipped: idx=${idx}, historyLength=${this.history.length}, roleAtIdx=${this.history[idx]?.role??"undefined"}`)}this.clearPendingPartialState()}markToolResultsInjected(contents){for(const content of contents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(provenance)this.injectedToolResults.add(provenance)}}enableManualPlanExitNotices(){this.manualPlanExitNoticesEnabled=true}currentRouteKey(){return this.config.getModelRouteIdentity?.()??""}adoptTokenCountsForRoute(targetRouteKey){if(this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0&&this.tokenCountsByRouteKey.size===0){return}targetRouteKey??=this.currentRouteKey();if(this.tokenCountsRouteKey===targetRouteKey){return}const retained=this.tokenCountsByRouteKey.get(targetRouteKey);if(retained){this.tokenCountsByRouteKey.delete(targetRouteKey);this.retainCurrentTokenCounts();debugLogger21.debug(`[token-counts] restoring retained counts for route ${targetRouteKey}`);this.lastPromptTokenCount=retained.promptTokenCount;this.lastPromptTokenCountIsEstimated=retained.promptTokenCountIsEstimated;this.lastOutputTokenCount=retained.outputTokenCount;this.lastCachedContentTokenCount=retained.cachedContentTokenCount;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(retained.promptTokenCount);this.telemetryService?.setLastCachedContentTokenCount(retained.cachedContentTokenCount);return}debugLogger21.debug(`[token-counts] route changed; retaining counts recorded for ${this.tokenCountsRouteKey??"unknown"} (now ${targetRouteKey})`);this.retainCurrentTokenCounts();this.lastPromptTokenCount=0;this.lastPromptTokenCountIsEstimated=false;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(0);this.telemetryService?.setLastCachedContentTokenCount(0)}retainCurrentTokenCounts(){if(this.tokenCountsRouteKey===void 0||this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0){return}if(this.tokenCountsByRouteKey.size>=MAX_RETAINED_ROUTE_COUNTS){const oldestKey=this.tokenCountsByRouteKey.keys().next().value;if(oldestKey!==void 0){this.tokenCountsByRouteKey.delete(oldestKey)}}this.tokenCountsByRouteKey.set(this.tokenCountsRouteKey,{promptTokenCount:this.lastPromptTokenCount,promptTokenCountIsEstimated:this.lastPromptTokenCountIsEstimated,outputTokenCount:this.lastOutputTokenCount,cachedContentTokenCount:this.lastCachedContentTokenCount})}getLastPromptTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastPromptTokenCount}getLastOutputTokenCount(){this.adoptTokenCountsForRoute();return this.lastOutputTokenCount}getLastCachedContentTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastCachedContentTokenCount}getRequestHistory(currentUserContent){const curatedHistory=extractCuratedHistory(this.history);const{maxRecentImages,imagePayloadThreshold}=resolveCompactionTuning(this.config.getChatCompression());let replaced=[];if(countAllInlineImages(curatedHistory)>=imagePayloadThreshold){const skipEntry=currentUserContent?curatedHistory.find(c=>c===currentUserContent||c.role==="user"&¤tUserContent.parts?.some(p2=>c.parts?.includes(p2))):void 0;replaced=replaceImagePayloadsInPlace(curatedHistory,this.imagePayloadStore,skipEntry)}const requestHistory=curatedHistory.map(copyContentContainer);const reattachParts=buildReattachParts(replaced,maxRecentImages,requestHistory,this.imagePayloadStore);if(reattachParts.length>0){const last=requestHistory.at(-1);if(last?.role==="user"){last.parts=[...last.parts??[],...reattachParts]}else{requestHistory.push({role:"user",parts:reattachParts})}}return appendAutoMemoryContext(requestHistory,this.config.getAutoMemoryContext?.()??"")}getRequestHistoryForRoute(currentUserContent,supportedModalities){return slimCompactionInput(this.getRequestHistory(currentUserContent),supportedModalities).slimmedHistory}setLastPromptTokenCount(count,isEstimated=false){this.lastPromptTokenCount=count;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.telemetryService?.setLastCachedContentTokenCount(0);this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}isLastPromptTokenCountEstimated(){this.adoptTokenCountsForRoute();return this.lastPromptTokenCountIsEstimated}promptCountIsEstimateDerived(){return this.lastPromptTokenCount===0||this.lastPromptTokenCountIsEstimated}seedResumeTokenCounts(promptTokenCount,outputTokenCount,isEstimated=false){this.lastPromptTokenCount=Number.isFinite(promptTokenCount)?Math.max(0,promptTokenCount):0;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=Number.isFinite(outputTokenCount)?Math.max(0,outputTokenCount):0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}async tryCompress(promptId,force=false,signal,options2){this.adoptTokenCountsForRoute(options2?.requestRouteKey);const originalTokenCountOverride=options2?.originalTokenCountOverride;const originalTokenCountIsEstimated=originalTokenCountOverride!==void 0?originalTokenCountOverride.isEstimated:options2?.precomputedEffectiveTokens!==void 0||this.promptCountIsEstimateDerived();const originalTokenCount=originalTokenCountOverride!==void 0?originalTokenCountOverride.count:originalTokenCountIsEstimated?options2?.precomputedEffectiveTokens??estimateContentTokens(options2?.pendingUserMessage?[...this.getHistoryShallow(true),options2.pendingUserMessage]:this.getHistoryShallow(true),resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate):this.lastPromptTokenCount;debugLogger21.debug(`[compaction] token-count provenance: prompt_id=${promptId}, originalTokenCount=${originalTokenCount}, estimated=${originalTokenCountIsEstimated}`);const service=new ChatCompressionService;const{newHistory,info}=await service.compress(this,{promptId,force,config:this.config,consecutiveFailures:this.consecutiveFailures,originalTokenCount,pendingUserMessage:options2?.pendingUserMessage,precomputedEffectiveTokens:options2?.precomputedEffectiveTokens,observedServerCeiling:options2?.observedServerCeiling,observedServerCeilingKind:options2?.observedServerCeilingKind,requestRouteKey:options2?.requestRouteKey,requestGenerationConfig:options2?.requestGenerationConfig,trigger:options2?.trigger,customInstructions:options2?.customInstructions,requestPayloadTooLarge:options2?.requestPayloadTooLarge,signal});info.originalTokenCountIsEstimated=originalTokenCountIsEstimated;this.adoptTokenCountsForRoute(options2?.requestRouteKey);if(info.compressionStatus===1&&newHistory){info.newTokenCountIsEstimated??=true;if(!options2?.deferChatCompressionRecord){this.chatRecordingService?.recordChatCompression({info,compressedHistory:options2?.pendingUserMessage?[...newHistory,options2.pendingUserMessage]:newHistory,summaryPrefixLength:newHistory.length,completedToolCallIds:this.completedToolCallIds})}this.setHistory(newHistory,this.completedToolCallIds);debugLogger21.debug("[FILE_READ_CACHE] clear after auto tryCompress");this.config.getFileReadCache().clear();try{await this.config.getExecutionEnvironment?.()?.invalidateReadCache()}catch(error3){debugLogger21.warn("Execution cache invalidation after compression failed",error3)}this.tokenCountsByRouteKey.clear();this.setLastPromptTokenCount(info.newTokenCount,info.newTokenCountIsEstimated);if(options2?.requestRouteKey&&this.tokenCountsRouteKey!==options2.requestRouteKey){this.retainCurrentTokenCounts();this.tokenCountsRouteKey=options2.requestRouteKey;this.tokenCountsByRouteKey.delete(options2.requestRouteKey)}this.telemetryService?.setLastPromptTokenCount(info.newTokenCount);this.consecutiveFailures=0;this.hardRescueFailureCount=0}else if(isCompressionFailureStatus(info.compressionStatus)){if(!force){this.consecutiveFailures+=1;if(this.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger21.warn(`[compaction] circuit breaker tripped after ${this.consecutiveFailures} consecutive failures (cheap-gate path); auto-compaction will NOOP until a successful force compaction resets the counter.`)}}}return info}compressFast(){this.adoptTokenCountsForRoute();const beforeEstimate=estimateContentTokens(this.history);const projectRoot=this.config.getProjectRoot();const targetDir=this.config.getTargetDir?.()??projectRoot;const mcResult=microcompactHistory(this.history,null,this.config.getClearContextOnIdle(),{force:true,preserveReadFileResult:__name(filePath=>isManagedMemoryPath(filePath,projectRoot,targetDir),"preserveReadFileResult")});const mcMeta=mcResult.meta;const newHistory=mcResult.history.map(c=>c.role==="model"?stripThoughtPartsFromContent(c):c).filter(c=>c!==null);const afterEstimate=estimateContentTokens(newHistory);if(afterEstimate>=beforeEstimate){const apiBaseline2=this.lastPromptTokenCount||beforeEstimate;return{info:{originalTokenCount:apiBaseline2,newTokenCount:apiBaseline2,originalTokenCountIsEstimated:this.promptCountIsEstimateDerived(),compressionStatus:5}}}const reduction=beforeEstimate-afterEstimate;const apiBaseline=this.lastPromptTokenCount||beforeEstimate;const baselineIsEstimated=this.promptCountIsEstimateDerived();const adjustedTokenCount=Math.max(0,apiBaseline-reduction);debugLogger21.debug(`[compaction] fast token-count provenance: originalTokenCount=${apiBaseline}, estimated=${baselineIsEstimated}`);const info={originalTokenCount:apiBaseline,newTokenCount:adjustedTokenCount,originalTokenCountIsEstimated:baselineIsEstimated,newTokenCountIsEstimated:true,compressionStatus:1,triggerReason:"manual"};this.chatRecordingService?.recordChatCompression({info,compressedHistory:newHistory,completedToolCallIds:this.completedToolCallIds});logChatCompression(this.config,makeChatCompressionEvent({tokens_before:info.originalTokenCount,tokens_after:info.newTokenCount}));this.setHistory(newHistory,this.completedToolCallIds);this.lastPromptTokenCount=adjustedTokenCount;this.lastPromptTokenCountIsEstimated=true;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.clear();this.telemetryService?.setLastPromptTokenCount(adjustedTokenCount);this.telemetryService?.setLastCachedContentTokenCount(0);this.consecutiveFailures=0;return{info,microcompactMeta:mcMeta}}setSystemInstruction(sysInstr){this.generationConfig.systemInstruction=sysInstr}setSessionStartContext(extraInstruction){const trimmed=extraInstruction.trim();if(!trimmed){return}const current2=this.generationConfig.systemInstruction;let baseInstruction="";if(typeof current2==="string"){baseInstruction=stripTrailingSessionStartContextBlock(current2)}else if(current2){baseInstruction=getCustomSystemPrompt(current2);baseInstruction=stripTrailingSessionStartContextBlock(baseInstruction)}const contextBlock=buildSessionStartContextBlock(trimmed);this.generationConfig.systemInstruction=`${baseInstruction}${contextBlock}`}applySessionStartContext(extraInstruction,_source){const trimmed=extraInstruction.trim();if(!trimmed){return}this.setSessionStartContext(trimmed)}async sendPreparedMessageStream(prepared,promptId,signal,onPreparedRequest){signal.throwIfAborted();if(hasImagePayloadReferences(prepared.history))throw new LlmRequestPreparationError("Saved image payloads are unavailable.");return this.sendMessageStream(`${prepared.routeSelector}\0`,{message:[],config:{...prepared.request.config,abortSignal:signal}},promptId,void 0,{preparedRequest:prepared,onPreparedRequest,retractDeliveredOutputOnRetry:true,disableModelFallbacks:true})}async sendMessageStream(model,params,prompt_id,goalContext,options2){const managedSessionBlock=this.config.getManagedSessionBlock?.();if(managedSessionBlock)throw managedSessionBlock;const turnGoalContext=goalContext?{...goalContext}:void 0;const fullTurnRoute=model.endsWith("\0");const exactRoute=fullTurnRoute?await this.config.getBaseLlmClient().resolveForModel(model.slice(0,-1),{failClosed:true}):void 0;if(exactRoute){model=exactRoute.model}const requestRouteKey=this.config.getModelRouteIdentity(model,exactRoute?.contentGeneratorConfig);this.adoptTokenCountsForRoute(requestRouteKey);const requestModalities=exactRoute?.contentGeneratorConfig.modalities??this.config.getEffectiveInputModalities();await this.sendPromise;let streamDoneResolver;const streamDonePromise=new Promise(resolve34=>{streamDoneResolver=resolve34});this.sendPromise=streamDonePromise;this.clearPendingPartialState();let compressionInfo;let requestContents;let userContentAdded=false;let manualPlanExitNoticeVersion;let manualPlanExitNoticeText;const cgConfigForThresholds=exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig();const parsedEnvMaxTokensForClamp=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const explicitOutputCeiling=params.config?.maxOutputTokens??cgConfigForThresholds?.samplingParams?.max_tokens??parsedEnvMaxTokensForClamp;const outputCeiling=explicitOutputCeiling??defaultOutputCeiling(model);const contextWindowForClamp=cgConfigForThresholds?.contextWindowSize??DEFAULT_TOKEN_LIMIT;let promptTokensForClamp=0;const previousGenerationConfig=options2?.preparedRequest?this.generationConfig:void 0;let currentUserContent;try{if(options2?.preparedRequest){const saved=options2.preparedRequest;if(saved.request.model!==model||saved.providerPin!==llmPreparedProviderPin(exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig()))throw new LlmRequestPreparationError("Saved model route changed.");this.setHistory(structuredClone(saved.history),saved.completedToolCallIds);this.generationConfig=structuredClone(saved.request.config);requestContents=structuredClone(saved.request.contents);currentUserContent=this.history.at(-1);promptTokensForClamp=saved.promptTokensForClamp;compressionInfo={originalTokenCount:promptTokensForClamp,newTokenCount:promptTokensForClamp,compressionStatus:5}}else{let userContent=createUserContent(params.message);userContent={...userContent,parts:userContent.parts?.map(part=>part.functionResponse&&!getToolOutputProvenance(part)?attachToolOutputProvenance([part],{callId:part.functionResponse.id??"",toolName:part.functionResponse.name??"",promptId:prompt_id,toolType:part.functionResponse.name?.startsWith("mcp__")?"mcp":"native"})[0]:part)};const toolOutputBudget=this.config.getToolOutputBatchBudget?.();if(toolOutputBudget!==void 0&&Number.isFinite(toolOutputBudget)&&userContent.parts){const[guarded]=enforceFunctionResponseBudget([{callId:"send-boundary",toolName:"tool-response-batch",responseParts:userContent.parts}],toolOutputBudget);if(guarded.responseParts!==userContent.parts){debugLogger21.warn(`Tool response send guard reduced an unfinalized batch to ${toolOutputBudget} characters.`);userContent={...userContent,parts:guarded.responseParts}}}const{hard}=computeThresholds(contextWindowForClamp,this.config.getAutoCompactThreshold());const imageTokenEstimate=resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate;const effectiveTokens=estimatePromptTokens(this.lastPromptTokenCount>0?[]:this.getHistoryShallow(true),userContent,this.lastPromptTokenCount,this.lastOutputTokenCount,imageTokenEstimate);const isHardTier=effectiveTokens>=hard;const shouldForceFromHard=!exactRoute&&isHardTier&&this.hardRescueFailureCount<MAX_CONSECUTIVE_FAILURES;const historyBeforeHardRescue=shouldForceFromHard?this.getHistoryShallow():void 0;const completedToolCallIdsBeforeHardRescue=this.completedToolCallIds;const lastPromptTokenCountBeforeHardRescue=this.lastPromptTokenCount;const lastPromptTokenCountWasEstimatedBeforeHardRescue=this.lastPromptTokenCountIsEstimated;const lastOutputTokenCountBeforeHardRescue=this.lastOutputTokenCount;const lastCachedContentTokenCountBeforeHardRescue=this.lastCachedContentTokenCount;const tokenCountsRouteKeyBeforeHardRescue=this.tokenCountsRouteKey;const retainedTokenCountsBeforeHardRescue=new Map(this.tokenCountsByRouteKey);const hardRescueFailureCountBeforeHardRescue=this.hardRescueFailureCount;if(shouldForceFromHard){debugLogger21.warn(`[compaction] hard-tier rescue triggered: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, hardRescueAttempt=${this.hardRescueFailureCount+1}, consecutiveFailures=${this.consecutiveFailures}.`)}else if(isHardTier&&!exactRoute){debugLogger21.warn(`[compaction] hard-tier rescue skipped after ${this.hardRescueFailureCount} failed attempts; relying on reactive overflow recovery. prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}.`)}markApiHistoryPrompt(userContent,options2?.promptId);if(exactRoute||isHardTier&&!shouldForceFromHard){compressionInfo={originalTokenCount:effectiveTokens,newTokenCount:effectiveTokens,compressionStatus:5}}else{compressionInfo=await this.tryCompress(prompt_id,shouldForceFromHard,params.config?.abortSignal,{pendingUserMessage:userContent,precomputedEffectiveTokens:effectiveTokens,requestGenerationConfig:params.config,requestRouteKey,deferChatCompressionRecord:shouldForceFromHard,trigger:shouldForceFromHard?"auto":void 0})}const localPromptTokensAfterCompression=shouldForceFromHard?estimatePromptTokens(this.lastPromptTokenCount>0?[]:this.getHistoryShallow(true),userContent,this.lastPromptTokenCount,this.lastOutputTokenCount,imageTokenEstimate):0;if(shouldStopAfterHardRescue(shouldForceFromHard,hard,localPromptTokensAfterCompression)){const message=getHardRescueFailureMessage(effectiveTokens,hard,compressionInfo,localPromptTokensAfterCompression);if(shouldForceFromHard){this.hardRescueFailureCount=hardRescueFailureCountBeforeHardRescue+1}if(compressionInfo.compressionStatus===1&&historyBeforeHardRescue){this.setHistory(historyBeforeHardRescue,completedToolCallIdsBeforeHardRescue);this.lastPromptTokenCount=lastPromptTokenCountBeforeHardRescue;this.lastPromptTokenCountIsEstimated=lastPromptTokenCountWasEstimatedBeforeHardRescue;this.lastOutputTokenCount=lastOutputTokenCountBeforeHardRescue;this.lastCachedContentTokenCount=lastCachedContentTokenCountBeforeHardRescue;this.tokenCountsRouteKey=tokenCountsRouteKeyBeforeHardRescue;this.tokenCountsByRouteKey.clear();for(const[retainedRouteKey,retainedCounts]of retainedTokenCountsBeforeHardRescue){this.tokenCountsByRouteKey.set(retainedRouteKey,retainedCounts)}this.telemetryService?.setLastPromptTokenCount(lastPromptTokenCountBeforeHardRescue);this.telemetryService?.setLastCachedContentTokenCount(lastCachedContentTokenCountBeforeHardRescue)}const compressionStatus=CompressionStatus[compressionInfo.compressionStatus]??String(compressionInfo.compressionStatus);debugLogger21.warn(`[compaction] hard-tier rescue stopped oversized prompt: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, localPromptTokensAfterCompression=${localPromptTokensAfterCompression}, compressionStatus=${compressionStatus}, newTokenCount=${compressionInfo.newTokenCount}, hardRescueFailureCount=${this.hardRescueFailureCount}, consecutiveFailures=${this.consecutiveFailures}. ${message}`);throw new Error(message)}if(shouldForceFromHard&&compressionInfo.compressionStatus===1){this.chatRecordingService?.recordChatCompression({info:compressionInfo,compressedHistory:[...this.getHistoryShallow(),userContent],summaryPrefixLength:this.getHistoryShallow().length,completedToolCallIds:this.completedToolCallIds})}if(this.manualPlanExitNoticesEnabled){const notice=this.config.takePendingManualPlanExitNotice();if(notice){manualPlanExitNoticeVersion=notice.version;manualPlanExitNoticeText=getManualPlanExitSystemReminder(notice.currentMode);userContent={...userContent,parts:[...userContent.parts??[],{text:manualPlanExitNoticeText}]}}}if(Array.isArray(params.message)){params.message[userContentPushSnapshotKey]=this.userContentPushCount}this.history.push(userContent);this.syncReviewedSchemasForContent(userContent);currentUserContent=userContent;userContentAdded=true;this.userContentPushCount++;const inlineRepair=repairOrphanedToolUseTurns(this.history,ORPHAN_TOOL_USE_REPAIR_REASON);if(inlineRepair.injected.length>0){debugLogger21.warn(`[REPAIR] sendMessageStream inline pass synthesized ${inlineRepair.injected.length} functionResponse(s): `+inlineRepair.injected.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}if(inlineRepair.droppedDuplicates.length>0){debugLogger21.warn(`[REPAIR] sendMessageStream inline pass dropped ${inlineRepair.droppedDuplicates.length} duplicate functionResponse(s): `+inlineRepair.droppedDuplicates.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}requestContents=this.getRequestHistoryForRoute(currentUserContent,requestModalities);promptTokensForClamp=this.lastPromptTokenCount>0?estimatePromptTokens([],userContent,this.lastPromptTokenCount,this.lastOutputTokenCount,imageTokenEstimate,true):effectiveTokens;if(this.promptCountIsEstimateDerived()){promptTokensForClamp+=ESTIMATE_CLAMP_OVERHEAD_PAD;debugLogger21.debug(`[clamp] estimate-derived prompt count; padded by ${ESTIMATE_CLAMP_OVERHEAD_PAD}: promptTokensForClamp=${promptTokensForClamp}, count=${this.lastPromptTokenCount}`)}const clampedMaxOutputTokens=clampOutputTokensToWindow(outputCeiling,contextWindowForClamp,promptTokensForClamp);params={...params,config:{...params.config,maxOutputTokens:clampedMaxOutputTokens}}}}catch(error3){if(userContentAdded){this.history.pop();if(currentUserContent){this.syncReviewedSchemasForContent(currentUserContent)}this.userContentPushCount--}if(manualPlanExitNoticeVersion!==void 0){this.config.restorePendingManualPlanExitNotice(manualPlanExitNoticeVersion)}if(previousGenerationConfig)this.generationConfig=previousGenerationConfig;streamDoneResolver();throw error3}const self2=this;return(async function*(){let successfulRecoveries=0;let activeRecoveryUser;let pendingTransportPrefix=[];const sleepInhibitorHandle=acquireSleepInhibitor(self2.config,"Qwen Code is streaming a model response");try{if(compressionInfo.compressionStatus===1){yield{type:"compressed",info:compressionInfo}}let lastError=new Error("Request failed after all retries.");let rateLimitRetryCount=0;let transientInvalidStreamRetryCount=0;let protocolTagLeakRetryCount=0;const totalInvalidStreamRetryCount=__name(()=>transientInvalidStreamRetryCount+protocolTagLeakRetryCount,"totalInvalidStreamRetryCount");const rearmQuietAcceptanceIfBudgetSpent=__name(()=>{if(transientInvalidStreamRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt=true}},"rearmQuietAcceptanceIfBudgetSpent");let streamReplayRetryCount=0;let transportContinuationCount=0;let transportContinuationText="";let transportContinuationParts=[];let transportAttemptParts=[];let transportContinuationPrefix=[];let reactiveCompressionAttempted=false;let omniMediaDegradeAttempts=0;let suppressNextRetryEvent=false;let streamYieldedAnyChunk=false;const cgConfig=exactRoute?.contentGeneratorConfig??self2.config.getContentGeneratorConfig();const requestOverrides=exactRoute?{contentGenerator:exactRoute.contentGenerator,contentGeneratorConfig:exactRoute.contentGeneratorConfig,retryAuthType:exactRoute.retryAuthType,retryErrorCodes:exactRoute.retryErrorCodes,allowPersistentRetry:options2?.preparedRequest?.allowPersistentRetry===true}:void 0;const maxRateLimitRetries=cgConfig?.maxRetries??RATE_LIMIT_RETRY_OPTIONS.maxRetries;const retryInitialDelayMs=cgConfig?.retryInitialDelayMs??RATE_LIMIT_RETRY_OPTIONS.initialDelayMs;const retryMaxDelayMs=cgConfig?.retryMaxDelayMs??RATE_LIMIT_RETRY_OPTIONS.maxDelayMs;const extraRetryErrorCodes=cgConfig?.retryErrorCodes;let maxTokensEscalated=false;const parsedEnvMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const hasUserMaxTokensOverride=cgConfig?.samplingParams?.max_tokens!==void 0&&cgConfig?.samplingParams?.max_tokens!==null||parsedEnvMaxTokens!==void 0;const effectiveInitialMaxOutputTokens=params.config?.maxOutputTokens??outputCeiling;const escalatedLimit=clampOutputTokensToWindow(OUTPUT_TOKEN_CEILING,contextWindowForClamp,promptTokensForClamp);const shouldEscalateMaxOutputTokens=effectiveInitialMaxOutputTokens<escalatedLimit;let lastFinishReason;const buildAttemptContents=__name(()=>transportContinuationPrefix.length>0?[...requestContents,{role:"model",parts:transportContinuationPrefix},createUserContent([{text:buildRecoveryMessageFromText(TRANSPORT_CONTINUATION_MESSAGE,getPlainTextFromParts(transportContinuationPrefix))}])]:requestContents,"buildAttemptContents");const resetTransportContinuation=__name(()=>{transportContinuationCount=0;transportContinuationText="";transportContinuationParts=[];transportAttemptParts=[];transportContinuationPrefix=[];pendingTransportPrefix=[]},"resetTransportContinuation");const foldTransportAttemptText=__name(()=>{transportContinuationParts=mergeDeliveredParts(transportContinuationParts,consolidateModelResponseParts(transportAttemptParts));transportContinuationText=getPlainTextFromParts(transportContinuationParts);transportAttemptParts=[]},"foldTransportAttemptText");let acceptQuietToolResultCompletionOnNextAttempt=false;for(;;){transportAttemptParts=[];let streamEstablished=false;let streamYieldedChunk=false;let streamYieldedContentChunk=false;let streamYieldedFunctionCall=false;try{if(suppressNextRetryEvent){suppressNextRetryEvent=false}else if(rateLimitRetryCount>0||totalInvalidStreamRetryCount()>0||streamReplayRetryCount>0||transportContinuationCount>0){resetTransportContinuation();yield{type:"retry"}}const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt;acceptQuietToolResultCompletionOnNextAttempt=false;const stream=await self2.makeApiCallAndProcessStream(model,buildAttemptContents(),params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,transportContinuationPrefix.length>0?transportContinuationPrefix:void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp);streamEstablished=true;pendingTransportPrefix=[];lastFinishReason=void 0;self2.lastObservedClosedFinishReason=void 0;for await(const chunk of stream){if(isFlushedToolCallPark(chunk)&&!streamYieldedContentChunk&&transportContinuationText.trim().length===0){continue}if(hasCandidateOutput(chunk)){streamYieldedChunk=true;streamYieldedAnyChunk=true}if(hasNonThoughtCandidateParts(chunk)){streamYieldedContentChunk=true}const chunkParts=chunk.candidates?.[0]?.content?.parts;transportAttemptParts.push(...(chunkParts??[]).filter(isPlainTextPart).map(part=>({...part})));if(chunkParts?.some(part=>part.functionCall)){streamYieldedFunctionCall=true}const fr2=chunk.candidates?.[0]?.finishReason;if(fr2)lastFinishReason=fr2;yield{type:"chunk",value:chunk}}lastError=null;transportContinuationPrefix=[];break}catch(error3){if(error3 instanceof LlmRequestPreparationError)throw error3;lastError=error3;if(params.config?.abortSignal?.aborted)throw error3;foldTransportAttemptText();const classification=classifyRetryError(error3,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isQuotaExhaustedError(error3)){debugLogger21.warn("Quota exhausted mid-stream, fast-failing",{retryPath:"stream",retryDecision:"fail-fast",errorKind:classification.kind,classificationReason:classification.reason});throw new Error(formatQuotaExhaustedMessage(error3),{cause:error3})}if(error3 instanceof ResponsesHttpError&&error3.headers.get("x-should-retry")==="false"){throw error3}const isRateLimit=isRateLimitError(error3,extraRetryErrorCodes);if(isRateLimit){const details=getRateLimitErrorDetails(error3);const diagnosticFields={classificationDiagnosis:classification.diagnosis,errorKind:classification.kind,classificationReason:classification.reason,...details};if(rateLimitRetryCount<maxRateLimitRetries){self2.popPendingPartialAssistantTurn();rateLimitRetryCount++;const delayMs=getRateLimitRetryDelayMs(rateLimitRetryCount,{...RATE_LIMIT_RETRY_OPTIONS,initialDelayMs:retryInitialDelayMs,maxDelayMs:retryMaxDelayMs,error:error3});const message=parseAndFormatApiError(error3 instanceof Error?error3.message:String(error3));debugLogger21.warn("Rate limit retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,retryDelayMs:delayMs,...diagnosticFields});const{promise:delayPromise,skip}=delay2(delayMs,params.config?.abortSignal);resetTransportContinuation();yield{type:"retry",retryInfo:{message,attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,delayMs,skipDelay:skip}};await delayPromise;rearmQuietAcceptanceIfBudgetSpent();continue}debugLogger21.warn("Rate limit retry exhausted",{retryPath:"stream",retryDecision:"exhausted",attempts:rateLimitRetryCount,maxRetries:maxRateLimitRetries,...diagnosticFields})}const contextOverflow=getContextLengthExceededInfo(error3);const requestPayloadOverflow=getRequestPayloadTooLargeInfo(error3);const isServerStreamError=streamEstablished&&!isRateLimit&&(classification.kind==="http"||classification.kind==="sse-provider")&&classification.diagnosis==="retryable"&&classification.statusCode!==void 0&&classification.statusCode>=500&&classification.statusCode<600;const isContinuableStreamCut=isRetryableStreamTransportError(classification)||isRetryableStatuslessUpstreamError(classification)&&!contextOverflow.isExceeded&&!requestPayloadOverflow.isTooLarge;const isReplayableStreamError=isContinuableStreamCut||isServerStreamError;const replayAdmitsDeliveredContent=options2?.retractDeliveredOutputOnRetry===true;if(isReplayableStreamError&&(replayAdmitsDeliveredContent||!streamYieldedContentChunk&&transportContinuationText.trim().length===0)&&streamReplayRetryCount<STREAM_RETRY_CONFIG.maxRetries){self2.popPendingPartialAssistantTurn();streamReplayRetryCount++;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*streamReplayRetryCount;debugLogger21.warn(isServerStreamError?"Server stream retry scheduled":"Transport stream retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,retryDelayMs:delayMs,yieldedNonContentChunks:streamYieldedChunk,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}});yield{type:"retry"};resetTransportContinuation();suppressNextRetryEvent=true;await delay2(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}const attemptFinishReason=lastFinishReason??self2.lastObservedClosedFinishReason;const attemptClosedWithOwnOutput=attemptFinishReason!==void 0&&CLOSED_FINISH_REASONS.has(attemptFinishReason)&&streamYieldedContentChunk;const canContinueAfterTransportCut=isContinuableStreamCut&&!replayAdmitsDeliveredContent&&!attemptClosedWithOwnOutput&&!streamYieldedFunctionCall&&transportContinuationText.trim().length>0&&transportContinuationCount<STREAM_RETRY_CONFIG.maxContinuationRetries;if(canContinueAfterTransportCut){self2.popPendingPartialAssistantTurn();transportContinuationCount++;transportContinuationPrefix=transportContinuationParts;pendingTransportPrefix=transportContinuationPrefix;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*transportContinuationCount;debugLogger21.warn("Transport stream continuation scheduled",{retryPath:"stream",retryDecision:"continue",attempt:transportContinuationCount,maxRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,retryDelayMs:delayMs,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,deliveredChars:transportContinuationText.length});yield{type:"retry",isContinuation:true};suppressNextRetryEvent=true;await delay2(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}if(isReplayableStreamError){debugLogger21.warn(isServerStreamError?"Server stream retry not taken":"Transport stream retry not taken",{retryPath:"stream",retryDecision:attemptClosedWithOwnOutput?"skipped_terminal_finish_reason":streamYieldedContentChunk||transportContinuationText.trim().length>0?"skipped_after_content":"exhausted",attempts:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,continuationAttempts:transportContinuationCount,maxContinuationRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}})}if(contextOverflow.isExceeded||requestPayloadOverflow.isTooLarge){const omniDegradeMaxAttempts=self2.config.getOmniProcessingConfig?.()?.limits.maxTransportPasses??0;if(contextOverflow.isExceeded&&!exactRoute&&omniMediaDegradeAttempts<omniDegradeMaxAttempts){const degradeAttempt=omniMediaDegradeAttempts++;let degradeOutcome;try{const{degradeOmniMediaAfterServerReject}=await import("./reactive-degrade-MNMTTHO5.js");degradeOutcome=await degradeOmniMediaAfterServerReject(self2.config,self2.history,degradeAttempt,{signal:params.config?.abortSignal,observedLimitTokens:contextOverflow.limitTokens})}catch(degradeError){if(params.config?.abortSignal?.aborted||isAbortError(degradeError)){throw degradeError}debugLogger21.warn("Omni media degradation fallback failed.",degradeError)}if(degradeOutcome&°radeOutcome.replacedParts>0){self2.popPendingPartialAssistantTurn();requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger21.warn(`Server input limit exceeded; degraded ${degradeOutcome.degradedResources} omni media resource(s) in place (attempt ${degradeAttempt+1}/${omniDegradeMaxAttempts}); retrying.`);resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}}let attemptedPayloadRecovery=false;let payloadRecoveryNoop=false;let payloadRecoveryThrew=false;if(!exactRoute&&!reactiveCompressionAttempted){reactiveCompressionAttempted=true;attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge;const reactiveOriginalTokenCountIsEstimated=contextOverflow.actualTokens===void 0;const reactiveOriginalTokenCount=contextOverflow.actualTokens??contextOverflow.limitTokens??(requestPayloadOverflow.isTooLarge?estimateContentTokens(self2.getHistoryShallow(true),resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate):cgConfig?.contextWindowSize??DEFAULT_TOKEN_LIMIT);debugLogger21.warn(requestPayloadOverflow.isTooLarge?"Request body rejected with HTTP 413; attempting reactive compression.":"Context length exceeded; attempting reactive compression.");if(!streamYieldedFunctionCall){pendingTransportPrefix=transportContinuationParts}try{const reactiveInfo=await self2.tryCompress(prompt_id,true,params.config?.abortSignal,{originalTokenCountOverride:{count:reactiveOriginalTokenCount,isEstimated:reactiveOriginalTokenCountIsEstimated},precomputedEffectiveTokens:reactiveOriginalTokenCount,observedServerCeiling:contextOverflow.limitTokens,observedServerCeilingKind:contextOverflow.limitKind,requestGenerationConfig:params.config,requestRouteKey,trigger:"auto",requestPayloadTooLarge:requestPayloadOverflow.isTooLarge});if(reactiveInfo.compressionStatus===1){self2.popPendingPartialAssistantTurn();const noticeText=manualPlanExitNoticeText;if(noticeText&&!self2.history.some(content=>content.parts?.some(part=>part.text?.includes(noticeText)))){const lastContent=self2.history.at(-1);if(lastContent?.role==="user"){lastContent.parts=[...lastContent.parts??[],{text:noticeText}]}else{self2.history.push(createUserContent([{text:noticeText}]))}}requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger21.info(`Reactive compression succeeded: ${reactiveInfo.originalTokenCount} -> ${reactiveInfo.newTokenCount} tokens.`);yield{type:"compressed",info:reactiveInfo};resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}if(reactiveInfo.compressionStatus===5){payloadRecoveryNoop=true}debugLogger21.warn(requestPayloadOverflow.isTooLarge?`Reactive compression did not recover request payload overflow: status=${reactiveInfo.compressionStatus}.`:`Reactive compression did not recover context overflow: status=${reactiveInfo.compressionStatus}.`);if(isCompressionFailureStatus(reactiveInfo.compressionStatus)){if(requestPayloadOverflow.isTooLarge&&reactiveInfo.compressionStatus===7){payloadRecoveryThrew=true}self2.consecutiveFailures+=1;if(self2.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger21.warn(`[compaction] circuit breaker tripped after ${self2.consecutiveFailures} consecutive failures (reactive overflow path); auto-compaction will NOOP on the cheap-gate until a successful force compaction resets the counter.`)}}}catch(compressionError){if(params.config?.abortSignal?.aborted||isAbortError(compressionError)){throw compressionError}payloadRecoveryThrew=requestPayloadOverflow.isTooLarge;debugLogger21.warn("Reactive compression failed.",compressionError)}}else{attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge&&reactiveCompressionAttempted&&!exactRoute;debugLogger21.warn(requestPayloadOverflow.isTooLarge?"Reactive compression already attempted; propagating the request payload overflow error to caller.":"Reactive compression already attempted; propagating the context overflow error to caller.")}if(attemptedPayloadRecovery){if(payloadRecoveryThrew){debugLogger21.warn("Request payload overflow recovery failed transiently; propagating the original 413 so the next send can retry recovery.")}else{debugLogger21.warn("Request payload overflow recovery exhausted; surfacing actionable 413 error.");const actionableError=new Error(payloadRecoveryNoop?REQUEST_PAYLOAD_TOO_LARGE_NOOP_MESSAGE:REQUEST_PAYLOAD_TOO_LARGE_RECOVERY_MESSAGE,{cause:error3});const payloadStatus=requestPayloadOverflow.status;if(payloadStatus!==void 0){Object.assign(actionableError,{status:payloadStatus})}lastError=actionableError}}break}if(error3 instanceof InvalidStreamError&&(error3.type==="NO_TOOL_RESULT_PROGRESS_MAX_TOKENS"||error3.type==="NO_RESPONSE_TEXT"&&lastFinishReason===FinishReason.MAX_TOKENS)&&!maxTokensEscalated&&!hasUserMaxTokensOverride&&shouldEscalateMaxOutputTokens){lastError=null;lastFinishReason=FinishReason.MAX_TOKENS;break}const isInvalidStreamError=error3 instanceof InvalidStreamError;const maxInvalidStreamRetries=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const invalidStreamRetryCount=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount:transientInvalidStreamRetryCount;if(isInvalidStreamError&&invalidStreamRetryCount<maxInvalidStreamRetries){self2.popPendingPartialAssistantTurn();const nextInvalidStreamRetryCount=invalidStreamRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount=nextInvalidStreamRetryCount}else{transientInvalidStreamRetryCount=nextInvalidStreamRetryCount}rearmQuietAcceptanceIfBudgetSpent();const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextInvalidStreamRetryCount;debugLogger21.warn(`Invalid stream [${error3.type}] (retry ${nextInvalidStreamRetryCount}/${maxInvalidStreamRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextInvalidStreamRetryCount-1,error3.type,delayMs,model));yield{type:"retry"};await delay2(delayMs,params.config?.abortSignal).promise;continue}break}}const rollbackRecoveryAttempt=__name(()=>{const expectedIdx=self2.pendingPartialAssistantTurnIndex;const lastIdx=self2.history.length-1;if(expectedIdx!==null&&self2.history.length>0&&self2.history[lastIdx]?.role==="model"){if(expectedIdx!==lastIdx){debugLogger21.warn(`[RECOVERY_POP] Marker/last-index mismatch: marker=${expectedIdx}, lastIdx=${lastIdx}, historyLength=${self2.history.length}. Popping last entry as best-effort rollback \u2014 investigate any history mutation between processStreamResponse's partial push and this catch.`)}self2.history.pop();self2.clearPendingPartialState()}if(self2.history.length>0&&self2.history[self2.history.length-1].role==="user"){self2.history.pop()}},"rollbackRecoveryAttempt");const streamWithInvalidStreamRetries=__name(async function*(buildAttempt,retryEvent={type:"retry"}){let transientRetryCount=0;let protocolTagLeakRetryCount2=0;let acceptQuietToolResultCompletionOnNextAttempt2=false;for(;;){const attemptState=buildAttempt();try{const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt2;acceptQuietToolResultCompletionOnNextAttempt2=false;const stream=await self2.makeApiCallAndProcessStream(model,attemptState.requestContents,attemptState.params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp,retryEvent.isContinuation===true);for await(const chunk of stream){yield{type:"chunk",value:chunk}}return}catch(error3){if(attemptState.params.config?.abortSignal?.aborted)throw error3;attemptState.rollback();if(!(error3 instanceof InvalidStreamError))throw error3;const maxContinuationRetries=error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const continuationRetryCount=error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount2:transientRetryCount;if(continuationRetryCount>=maxContinuationRetries){throw error3}const nextContinuationRetryCount=continuationRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount2=nextContinuationRetryCount}else{transientRetryCount=nextContinuationRetryCount}if(transientRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt2=true}const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextContinuationRetryCount;debugLogger21.warn(`Invalid stream [${error3.type}] during output continuation (retry ${nextContinuationRetryCount}/${maxContinuationRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextContinuationRetryCount-1,error3.type,delayMs,model));yield retryEvent;await delay2(delayMs,attemptState.params.config?.abortSignal).promise}}},"streamWithInvalidStreamRetries");if(lastError===null&&lastFinishReason===FinishReason.MAX_TOKENS&&!maxTokensEscalated&&!hasUserMaxTokensOverride){maxTokensEscalated=true;let recoveryFinishReason=lastFinishReason;let recoveryParams=params;if(shouldEscalateMaxOutputTokens){debugLogger21.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens. Escalating to ${escalatedLimit} tokens.`);if(self2.history.length>0&&self2.history[self2.history.length-1].role==="model"){self2.history.pop()}yield{type:"retry",maxOutputTokensEscalated:escalatedLimit};const escalatedParams={...params,config:{...params.config,maxOutputTokens:escalatedLimit}};recoveryParams=escalatedParams;recoveryFinishReason=void 0;for await(const event of streamWithInvalidStreamRetries(()=>({requestContents,params:escalatedParams,rollback:__name(()=>self2.popPendingPartialAssistantTurn(),"rollback")}))){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}}else{debugLogger21.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens; skipping no-op escalation to ${escalatedLimit} tokens and running recovery.`)}let recoveryCount=0;while(recoveryFinishReason===FinishReason.MAX_TOKENS&&recoveryCount<MAX_OUTPUT_RECOVERY_ATTEMPTS){const lastEntry=self2.history[self2.history.length-1];const hasFunctionCall=lastEntry?.role==="model"&&lastEntry.parts?.some(p2=>p2.functionCall)===true;if(hasFunctionCall){debugLogger21.info("Skipping recovery: truncated turn contains functionCall; deferring to tool scheduler fallback.");break}recoveryCount++;debugLogger21.info(`Output still truncated after max_tokens handling. Recovery attempt ${recoveryCount}/${MAX_OUTPUT_RECOVERY_ATTEMPTS}.`);const recoveryUserContent=createUserContent([{text:buildOutputRecoveryMessage(lastEntry)}]);yield{type:"retry",isContinuation:true};recoveryFinishReason=void 0;const recoveryImageTokenEstimate=resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate;const countBasedRecoveryEstimate=self2.lastPromptTokenCount>0?estimatePromptTokens([],recoveryUserContent,self2.lastPromptTokenCount,self2.lastOutputTokenCount,recoveryImageTokenEstimate,true):0;self2.history.push(recoveryUserContent);const recoveryContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);self2.history.pop();const walkRecoveryEstimate=estimateContentTokens(recoveryContents,recoveryImageTokenEstimate)+ESTIMATE_CLAMP_OVERHEAD_PAD;const recoveryPromptEstimate=Math.max(countBasedRecoveryEstimate,walkRecoveryEstimate);const recoveryCeiling=recoveryParams.config?.maxOutputTokens??outputCeiling;const iterationParams={...recoveryParams,config:{...recoveryParams.config,maxOutputTokens:clampOutputTokensToWindow(recoveryCeiling,contextWindowForClamp,recoveryPromptEstimate)}};try{for await(const event of streamWithInvalidStreamRetries(()=>{self2.history.push(recoveryUserContent);activeRecoveryUser=recoveryUserContent;return{requestContents:self2.getRequestHistoryForRoute(currentUserContent,requestModalities),params:iterationParams,rollback:rollbackRecoveryAttempt}},{type:"retry",isContinuation:true})){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}successfulRecoveries++;activeRecoveryUser=void 0}catch(recoveryError){if(recoveryError instanceof LlmRequestPreparationError)throw recoveryError;if(params.config?.abortSignal?.aborted)throw recoveryError;rollbackRecoveryAttempt();debugLogger21.warn(`Recovery attempt ${recoveryCount} failed: ${recoveryError}`);yield{type:"chunk",value:{candidates:[{content:{role:"model",parts:[]},finishReason:FinishReason.STOP}]}};break}}}if(lastError){if(lastError instanceof InvalidStreamError){const totalAttempts=totalInvalidStreamRetryCount()+1;logContentRetryFailure(self2.config,new ContentRetryFailureEvent(totalAttempts,lastError.type,model))}const fallbackModels=exactRoute||options2?.disableModelFallbacks?[]:self2.config.getModelFallbacks();if(fallbackModels.length>0&&!isUnattendedMode()&&!streamYieldedAnyChunk){let currentErrorClassification=classifyRetryError(lastError,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isFallbackEligible(currentErrorClassification)){let fallbackSucceeded=false;let fallbackIndex=0;let currentModel=model;let currentResolvedModel=cgConfig?.model??model;let fallbackStreamYieldedAnyChunk=false;for(const fallbackModelId of fallbackModels){if(fallbackModelId===model||fallbackModelId===currentModel){debugLogger21.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": same as current model.`);continue}let fallbackGenerator;let fallbackConfig;let fallbackRetryAuthType;let fallbackRetryErrorCodes;let resolvedFallbackModel;let fallbackModalities;try{const resolved=await self2.config.getBaseLlmClient().resolveForModel(fallbackModelId,{failClosed:true});fallbackGenerator=resolved.contentGenerator;fallbackConfig=resolved.contentGeneratorConfig;fallbackRetryAuthType=resolved.retryAuthType;fallbackRetryErrorCodes=resolved.retryErrorCodes;resolvedFallbackModel=resolved.model;fallbackModalities=resolved.contentGeneratorConfig?.modalities}catch(resolveError){if(isAbortError(resolveError))throw resolveError;const resolveErrorMessage=resolveError instanceof Error?resolveError.message:String(resolveError);debugLogger21.warn(`[FALLBACK] Failed to resolve fallback model "${fallbackModelId}": ${resolveErrorMessage}. Trying next fallback.`);continue}if(resolvedFallbackModel===currentResolvedModel){debugLogger21.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": resolved model "${resolvedFallbackModel}" matches the current model.`);continue}fallbackIndex++;debugLogger21.warn(`[FALLBACK] Model "${currentModel}" exhausted retries (reason: ${currentErrorClassification.reason}, status: ${currentErrorClassification.statusCode??"unknown"}). Switching to fallback model "${fallbackModelId}" (${fallbackIndex}/${fallbackModels.length}).`);yield{type:"model_fallback",info:{fromModel:currentModel,toModel:resolvedFallbackModel,statusCode:currentErrorClassification.statusCode,fallbackIndex}};self2.popPendingPartialAssistantTurn();let currentFallbackYieldedAnyChunk=false;try{const fallbackRequestContents=self2.getRequestHistoryForRoute(currentUserContent,fallbackModalities??{});for await(const event of self2.makeFallbackStream(resolvedFallbackModel,fallbackRequestContents,params,prompt_id,fallbackGenerator,fallbackRetryAuthType,fallbackRetryErrorCodes,requestRouteKey,turnGoalContext,options2?.onPreparedRequest,promptTokensForClamp,fallbackConfig)){const emittedUserVisibleOutput=event.type!=="chunk"||hasCandidateOutput(event.value);if(emittedUserVisibleOutput){currentFallbackYieldedAnyChunk=true;fallbackStreamYieldedAnyChunk=true}yield event}lastError=null;fallbackSucceeded=true;debugLogger21.info(`[FALLBACK] Successfully completed request with fallback model "${resolvedFallbackModel}".`);return}catch(fallbackError){if(fallbackError instanceof LlmRequestPreparationError)throw fallbackError;if(params.config?.abortSignal?.aborted||isAbortError(fallbackError)){throw fallbackError}lastError=fallbackError;if(currentFallbackYieldedAnyChunk){self2.popPendingPartialAssistantTurn();debugLogger21.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" failed after emitting output. Popped the partial assistant turn and stopped the fallback chain to avoid duplicating user-visible output.`);break}const fallbackClassification=classifyRetryError(fallbackError,{authType:fallbackRetryAuthType,extraRetryErrorCodes:fallbackRetryErrorCodes});const canTryNextFallback=isFallbackEligible(fallbackClassification);debugLogger21.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" also failed (reason: ${fallbackClassification.reason}, status: ${fallbackClassification.statusCode??"unknown"}). ${canTryNextFallback?"Checking remaining fallbacks.":"Stopping fallback chain."}`);currentModel=resolvedFallbackModel;currentResolvedModel=resolvedFallbackModel;currentErrorClassification=fallbackClassification;if(!canTryNextFallback){debugLogger21.warn(`[FALLBACK] Error from "${resolvedFallbackModel}" is not fallback-eligible (${fallbackClassification.reason}). Stopping fallback chain.`);break}}}if(!fallbackSucceeded){if(!fallbackStreamYieldedAnyChunk){self2.popPendingPartialAssistantTurn()}debugLogger21.warn("[FALLBACK] Fallback chain exhausted without success. Throwing last error.")}}else{debugLogger21.warn(`[FALLBACK] Fallback chain skipped: primary error is not fallback-eligible (reason: ${currentErrorClassification.reason}, diagnosis: ${currentErrorClassification.diagnosis}, status: ${currentErrorClassification.statusCode??"unknown"}, error: ${lastError instanceof Error?lastError.message:String(lastError)}).`)}}else if(fallbackModels.length>0&&!isUnattendedMode()&&streamYieldedAnyChunk){debugLogger21.warn("[FALLBACK] Fallback chain skipped because the primary model already emitted user-visible output.")}if(lastError){throw lastError}}}finally{if(params.config?.abortSignal?.aborted&&pendingTransportPrefix.length>0){const parts=pendingTransportPrefix;self2.history.push({role:"model",parts});self2.pendingPartialAssistantTurnIndex=self2.history.length-1;self2.pendingPartialAssistantRecord={model,message:parts,contextWindowSize:self2.config.getContentGeneratorConfig()?.contextWindowSize,...turnGoalContext?{goalContext:{...turnGoalContext}}:{}}}const recoveryIndex=activeRecoveryUser?self2.history.indexOf(activeRecoveryUser):-1;if(recoveryIndex===self2.history.length-1&&recoveryIndex>=0){self2.history.pop()}else if(recoveryIndex>=0&&recoveryIndex===self2.history.length-2&&self2.history.at(-1)?.role==="model"){successfulRecoveries++}if(successfulRecoveries>0){self2.coalesceRecoveryPairs(successfulRecoveries)}if(previousGenerationConfig)self2.generationConfig=previousGenerationConfig;sleepInhibitorHandle.release();streamDoneResolver();if(self2.pendingPartialAssistantRecord){try{self2.chatRecordingService?.recordAssistantTurn(self2.pendingPartialAssistantRecord)}catch(recordErr){debugLogger21.error("[PARTIAL_FLUSH] Failed to persist deferred JSONL record: "+(recordErr instanceof Error?recordErr.message:String(recordErr)))}self2.clearPendingPartialState()}}})()}async makeApiCallAndProcessStream(model,requestContents,params,prompt_id,overrides,routeKey=this.currentRouteKey(),goalContext,transportContinuationPrefix,acceptQuietToolResultCompletion=false,onPreparedRequest,promptTokensForClamp=0,continuationInFlight=false){const generator=overrides?.contentGenerator??this.config.getContentGenerator();const request={model,contents:requestContents,config:{...this.generationConfig,...params.config},...transportContinuationPrefix!==void 0&&{continuationInFlight:true}};const actualConfig=overrides?.contentGeneratorConfig??this.config.getContentGeneratorConfig();if(onPreparedRequest){const{abortSignal:_signal,httpOptions:_http,...config3}=request.config??{};try{const prepared={request:{model,contents:requestContents,config:config3},history:this.history,completedToolCallIds:[...this.completedToolCallIds],routeSelector:`${actualConfig?.authType??""}:${model}`,providerPin:llmPreparedProviderPin(actualConfig),promptTokensForClamp,allowPersistentRetry:overrides?.allowPersistentRetry??!overrides};const overBudget=onPreparedRequest.maxSnapshotBytes!==void 0&&Buffer.byteLength(JSON.stringify(prepared))>onPreparedRequest.maxSnapshotBytes;await onPreparedRequest(overBudget?prepared:structuredClone(prepared),continuationInFlight||transportContinuationPrefix!==void 0||hasImagePayloadReferences(this.history))}catch(cause){throw new LlmRequestPreparationError(cause)}}params.config?.abortSignal?.throwIfAborted();const apiCall=__name(()=>{params.config?.abortSignal?.throwIfAborted();const groups=new Map;for(const content of requestContents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(!provenance||this.injectedToolResults.has(provenance))continue;const parts=groups.get(provenance)??[];parts.push(part);groups.set(provenance,parts)}for(const[provenance,parts]of groups){this.injectedToolResults.add(provenance);try{const injected=measureToolOutput(parts,this.config);logToolResultSize(this.config,new ToolResultSizeEvent(provenance.toolName,provenance.toolType,"injection",provenance.rawSize?.chars,injected.chars,provenance.rawSize?.estimatedTokens,injected.estimatedTokens,provenance.truncated,Number.isFinite(provenance.budget)?provenance.budget:void 0,provenance.budgetSource,provenance.callId,provenance.promptId||prompt_id))}catch{}}return generator.generateContentStream(request,prompt_id)},"apiCall");const cgConfig=this.config.getContentGeneratorConfig();const authType=overrides?.retryAuthType??cgConfig?.authType;const extraRetryErrorCodes=overrides?.retryErrorCodes??cgConfig?.retryErrorCodes;const persistentMode=(overrides?.allowPersistentRetry??!overrides)&&isUnattendedMode();const streamResponse=await retryWithBackoff(apiCall,{shouldRetryOnError:__name(error3=>{if(error3 instanceof ResponsesHttpError){return error3.shouldRetry(extraRetryErrorCodes)}if(error3 instanceof Error){if(isSchemaDepthError(error3.message))return false;if(isInvalidArgumentError(error3.message))return false}const status=getErrorStatus(error3);if(status===400){return classifyRetryError(error3,{authType,extraRetryErrorCodes}).kind==="transport"}if(status===429)return true;if(status&&status>=500&&status<600)return true;return isRetryableUpstreamError(error3,extraRetryErrorCodes)},"shouldRetryOnError"),authType,extraRetryErrorCodes,persistentMode,signal:params.config?.abortSignal,...persistentMode?{heartbeatFn:__name(info=>{process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info.attempt}, retry in ${Math.ceil(info.remainingMs/1e3)}s
|
|
184
184
|
`)},"heartbeatFn")}:{},onRetry:__name(info=>{logApiRetry(this.config,new ApiRetryEvent({model,promptId:prompt_id,attemptNumber:info.attempt,error:info.error,statusCode:info.errorStatus,retryDelayMs:info.delayMs,subagentName:subagentNameContext.getStore()}))},"onRetry")});return this.processStreamResponse(model,rejectDegradedPlaceholderResponse(streamResponse),routeKey,goalContext,transportContinuationPrefix,acceptQuietToolResultCompletion,params.config?.abortSignal,{authType,extraRetryErrorCodes})}async*makeFallbackStream(model,requestContents,params,prompt_id,contentGenerator,retryAuthType,retryErrorCodes,routeKey,goalContext,onPreparedRequest,promptTokensForClamp=0,contentGeneratorConfig){const stream=await this.makeApiCallAndProcessStream(model,requestContents,params,prompt_id,{contentGenerator,contentGeneratorConfig,retryAuthType,retryErrorCodes},routeKey,goalContext,void 0,false,onPreparedRequest,promptTokensForClamp);for await(const chunk of stream){yield{type:"chunk",value:chunk}}}getHistory(curated=false){const history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}getHistoryTail(count,curated=false){if(count<=0)return[];const history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history.slice(-count))}getHistoryShallow(curated=false){const history=curated?extractCuratedHistory(this.history):this.history;return history.map(copyContentContainer)}getHistoryForForkWindow(){const history=this.history.slice(getStartupContextLength(this.history));return extractCuratedHistory(history).map(copyContentContainer)}getHistoryTailShallow(count,curated=false){if(count<=0)return[];const history=curated?extractCuratedHistory(this.history):this.history;return history.slice(-count).map(copyContentContainer)}getLastHistoryEntry(){return this.getHistoryTail(1)[0]}peekLastHistoryEntry(){return this.history.at(-1)}findLastHistoryEntry(predicate){for(let i=this.history.length-1;i>=0;i--){const entry=this.history[i];if(predicate(entry)){return entry}}return void 0}getLastModelMessageText(){for(let i=this.history.length-1;i>=0;i--){const message=this.history[i];if(message?.role!=="model")continue;const text=message.parts?.filter(part=>typeof part.text==="string"&&!part.thought).map(part=>part.text).join("")??"";return text||void 0}return void 0}getHistoryLength(){return this.history.length}getUserContentPushCount(){return this.userContentPushCount}getHistoryFunctionResponseIds(){const ids=new Set;for(const entry of this.history){if(entry.role!=="user")continue;for(const part of entry.parts??[]){const id=part.functionResponse?.id;if(id)ids.add(id)}}return ids}getHistoryToolCallFingerprints(){const fingerprintsById=new Map;const respondedIds=new Set;for(const entry of this.history){if(entry.role==="user"){for(const part of entry.parts??[]){const id=part.functionResponse?.id;if(id)respondedIds.add(id)}continue}for(const part of entry.parts??[]){const functionCall=part.functionCall;if(functionCall?.id&&!fingerprintsById.has(functionCall.id)){fingerprintsById.set(functionCall.id,getFunctionCallFingerprint(functionCall))}}}const handled=new Map;for(const id of respondedIds){const fingerprint2=fingerprintsById.get(id);if(fingerprint2!==void 0)handled.set(id,fingerprint2)}return handled}clearHistory(){this.history=[];this.completedToolCallIds=[];if(!this.isForkedChat){this.config.getToolRegistry()?.clearReviewedDeclarations?.()}this.clearPendingPartialState()}addHistory(content){this.history.push(content);this.syncReviewedSchemasForContent(content);if(this.pendingPartialAssistantTurnIndex!==null||this.pendingPartialAssistantRecord!==null){debugLogger21.error("[INVARIANT_VIOLATION] addHistory called while a partial-push marker is active \u2014 clearing it.")}this.clearPendingPartialState()}syncReviewedSchemasForContent(content){if(!this.isForkedChat&&content.parts?.some(part=>part.functionResponse?.name===ToolNames.TOOL_SEARCH)){this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}}redactApprovedPlanFromHistory(callId,replacement,expectedPlan){for(let i=this.history.length-1;i>=0;i--){const entry=this.history[i];if(entry?.role!=="model"||!entry.parts)continue;const partIdx=entry.parts.findIndex(part2=>part2.functionCall?.id===callId&&canonicalPlanToolName(part2.functionCall.name)===ToolNames.EXIT_PLAN_MODE);if(partIdx===-1)continue;const part=entry.parts[partIdx];const functionCall=part.functionCall;const plan=(functionCall.args??{})["plan"];if(typeof plan!=="string"){return false}if(expectedPlan!==void 0&&plan!==expectedPlan){return false}const newParts=[...entry.parts];newParts[partIdx]={...part,functionCall:{...functionCall,args:{...functionCall.args,plan:replacement}}};this.history[i]={...entry,parts:newParts};return true}return false}redactApprovedPlansFromLoadedHistory(){const hasPlanCall=this.history.some(entry=>entry?.parts?.some(part=>canonicalPlanToolName(part.functionCall?.name)===ToolNames.EXIT_PLAN_MODE));if(!hasPlanCall)return;let planPath;let savedPlan;try{planPath=this.config.getPlanFilePath();savedPlan=fs12.readFileSync(planPath,"utf-8")}catch(err){debugLogger21.debug(`Skipping load-side plan redaction, plan file unavailable: ${err}`);return}const redacted=redactApprovedPlansInHistory(this.history,savedPlan,planPath);if(redacted){this.history=redacted}else{debugLogger21.debug(`Load-side plan redaction left history unchanged: no approved exit_plan_mode call matches the plan file at ${planPath}.`)}}setHistory(history,completedToolCallIds){this.history=history;this.markToolResultsInjected(this.history);this.setCompletedToolCallIds(completedToolCallIds);this.clearPendingPartialState();this.redactApprovedPlansFromLoadedHistory();if(!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"setHistory");this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}}truncateHistory(keepCount){const prevLen=this.history.length;this.history=this.history.slice(0,keepCount);this.setCompletedToolCallIds(this.completedToolCallIds);if(this.history.length<prevLen&&!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"truncateHistory");this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}this.clearPendingPartialState()}stripThoughtsFromHistory(){this.history=this.history.map(stripThoughtPartsFromContent).filter(content=>content!==null);this.setCompletedToolCallIds(this.completedToolCallIds);this.clearPendingPartialState()}stripOrphanedUserEntriesFromHistory(){const strippedEntries=[];const boundary=completedToolCallBoundary(this.history,this.completedToolCallIds);while(this.history.length>boundary&&this.history[this.history.length-1].role==="user"){const lastEntry=this.history[this.history.length-1];if(lastEntry&&isSystemReminderContent(lastEntry)){break}if(lastEntry&&isAgentEnvelopeContent(lastEntry)){break}strippedEntries.unshift(this.history.pop())}if(strippedEntries.length>0&&!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"stripOrphanedUserEntries");this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}this.clearPendingPartialState();return strippedEntries}repairOrphanedToolUseTurns(reason,options2){return repairOrphanedToolUseTurns(this.history,reason,options2)}setTools(tools){this.generationConfig.tools=tools}getGenerationConfig(){return{...this.generationConfig}}async maybeIncludeSchemaDepthContext(error3){if(isSchemaDepthError(error3.message)||isInvalidArgumentError(error3.message)){const toolRegistry=this.config.getToolRegistry();await toolRegistry.warmAll();const tools=toolRegistry.getAllTools();const cyclicSchemaTools=[];for(const tool of tools){if(tool.schema.parametersJsonSchema&&hasCycleInSchema(tool.schema.parametersJsonSchema)||tool.schema.parameters&&hasCycleInSchema(tool.schema.parameters)){cyclicSchemaTools.push(tool.displayName)}}if(cyclicSchemaTools.length>0){const extraDetails=`
|
|
185
185
|
|
|
186
186
|
This error was probably caused by cyclic schema references in one of the following tools, try disabling them with excludeTools:
|
|
@@ -552,14 +552,14 @@ ${text}`:text;return next}__name(appendResponseText,"appendResponseText");functi
|
|
|
552
552
|
${details.prompt}`,renderPromptAsPlainText:true};case"mcp":return{type:"info",title:`Hook requested confirmation to run ${details.toolName}`,prompt:`${reason}
|
|
553
553
|
|
|
554
554
|
MCP Server: ${details.serverName}
|
|
555
|
-
Tool: ${details.toolName}`,renderPromptAsPlainText:true,hideAlwaysAllow:true,onConfirm:details.onConfirm};default:return details}}__name(withPreToolUseAskReason,"withPreToolUseAskReason");function isConcurrencySafe(call,hookReplacedInput){return isToolCallConcurrencySafe(call.request.name,call.tool.kind,call.request.args,hookReplacedInput?void 0:call.request.source)}__name(isConcurrencySafe,"isConcurrencySafe");function partitionByConcurrencySafety(items,isSafe){return items.reduce((batches,item)=>{const safe=isSafe(item);const lastBatch=batches[batches.length-1];if(safe&&lastBatch?.concurrent){lastBatch.calls.push(item)}else{batches.push({concurrent:safe,calls:[item]})}return batches},[])}__name(partitionByConcurrencySafety,"partitionByConcurrencySafety");function partitionToolCalls(calls,hookReplacedInputCallIds){return partitionByConcurrencySafety(calls,call=>isConcurrencySafe(call,hookReplacedInputCallIds.has(call.request.callId)))}__name(partitionToolCalls,"partitionToolCalls");function producerInputDropsStructuredContent(input){if(input===null||input===void 0||typeof input==="string"){return false}const contentToProcess=Array.isArray(input)&&input.length===1?input[0]:input;if(typeof contentToProcess==="string")return false;const hasOnlyKeys2=__name((part,...keys)=>Object.entries(part).every(([key,value])=>value===void 0||keys.includes(key)),"hasOnlyKeys");if(Array.isArray(contentToProcess)){return contentToProcess.some(part=>{if(typeof part==="string")return false;if(part.text!==void 0)return!hasOnlyKeys2(part,"text");if(part.inlineData!==void 0){return!hasOnlyKeys2(part,"inlineData")}if(part.fileData!==void 0)return!hasOnlyKeys2(part,"fileData");return true})}if(contentToProcess.functionResponse!==void 0){return Boolean(contentToProcess.functionResponse.response?.["content"])}if(contentToProcess.inlineData!==void 0||contentToProcess.fileData!==void 0){return!hasOnlyKeys2(contentToProcess,"inlineData","fileData")}if(contentToProcess.text!==void 0){return!hasOnlyKeys2(contentToProcess,"text")}return true}__name(producerInputDropsStructuredContent,"producerInputDropsStructuredContent");function producerContentEqual(toolName,callId,input,output){if(producerInputDropsStructuredContent(input))return false;return isDeepStrictEqual3(convertToFunctionResponseParts(toolName,callId,input??""),Array.isArray(output)?output.map(part=>typeof part==="string"?part:Object.fromEntries(Object.entries(part))):output)}__name(producerContentEqual,"producerContentEqual");var CoreToolScheduler=class _CoreToolScheduler{static{__name(this,"CoreToolScheduler")}schedulerOptions;get toolRegistry(){return this.config.getToolRegistry()}toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;invocationReleases=new Map;onToolCallsUpdate;getPreferredEditor;config;onEditorClose;chatRecordingService;onToolResultFullTurnModel;shouldObserveProducer;hasSkillToolOverride;isToolExecutionAllowed;isFinalizingToolCalls=false;postToolBatchEnabledForBatch=false;postToolBatchSpanCallId;postToolBatchConfigWarned=false;isScheduling=false;validationRetryCounts=new Map;autoModeFallbackCallIds=new Set;toolSpans=new Map;blockedSpans=new Map;callIdToBatch=new Map;callIdToPostToolBatchSignal=new Map;preToolUseIds=new Map;preToolUseAsks=new Map;preToolUseSessionHookIds=new Map;hookReplacedInputCallIds=new Set;preToolUseContexts=new Map;nestedHookContexts=new Map;failureContextsForParent=new Map;hookContextSink;askUserQuestionResponseClaims=new Set;runtimeContentGeneratorViews=new Map;hookOwners=new Map;requestQueue=[];nestedToolScheduler;nestedToolCalls=[];nestedSequence=0;nestedFlushScheduled=false;nestedQueue=[];nestedResolvers=new Map;constructor(options2){this.schedulerOptions=options2;this.config=options2.config;this.outputUpdateHandler=options2.outputUpdateHandler;this.onAllToolCallsComplete=options2.onAllToolCallsComplete;this.onToolCallsUpdate=options2.onToolCallsUpdate;this.getPreferredEditor=options2.getPreferredEditor;this.onEditorClose=options2.onEditorClose;this.chatRecordingService=options2.chatRecordingService;this.onToolResultFullTurnModel=options2.onToolResultFullTurnModel;this.shouldObserveProducer=options2.shouldObserveProducer??(()=>true);this.hasSkillToolOverride=options2.hasSkillTool;this.isToolExecutionAllowed=options2.isToolExecutionAllowed}getOrCreateNestedToolScheduler(){if(this.nestedToolScheduler)return this.nestedToolScheduler;this.nestedToolScheduler=new _CoreToolScheduler({...this.schedulerOptions,modToolCheck:void 0,onAllToolCallsComplete:__name(async calls=>{for(const call of calls){const resolver=this.nestedResolvers.get(call.request.callId);if(!resolver)continue;this.nestedResolvers.delete(call.request.callId);try{resolver.onResult?.(call.response)}catch(error3){resolver.reject(error3);continue}if(call.status==="success"){const content=extractCodeModeImageContent(call.response.responseParts);resolver.resolve({callId:call.request.callId,name:call.request.name,status:"success",output:extractCodeModeToolOutput(call.response.responseParts),...content?{content}:{}})}else{resolver.reject(call.response.error??new Error(extractCodeModeToolOutput(call.response.responseParts)||`Tool ${call.request.name} failed.`))}}},"onAllToolCallsComplete"),onToolCallsUpdate:__name(calls=>{this.nestedToolCalls=calls;this.notifyToolCallsUpdate()},"onToolCallsUpdate")});this.nestedToolScheduler.hookContextSink=(request,context2)=>{const parentCallId=request.parentCallId;if(!parentCallId||!this.toolCalls.some(call=>call.request.callId===parentCallId&&call.status==="executing")){return}const contexts=this.nestedHookContexts.get(parentCallId)??[];contexts.push(context2);this.nestedHookContexts.set(parentCallId,contexts)};return this.nestedToolScheduler}dispatchCodeModeTool(name,args,parent,signal,onResult){const allowedNames=parent.codeModeAllowedToolNames?new Set(parent.codeModeAllowedToolNames):void 0;if(!isCodeModeToolCallAllowed(name,"code_mode",allowedNames)){return Promise.reject(new Error(`Tool "${name}" is not callable from exec.`))}const callId=`${parent.callId}:code:${++this.nestedSequence}`;const request={callId,name,args,isClientInitiated:true,prompt_id:parent.prompt_id,response_id:parent.response_id,parentCallId:parent.callId,source:"code_mode",goalContext:parent.goalContext};return new Promise((resolve34,reject)=>{this.nestedQueue.push({request,signal,resolve:resolve34,reject,onResult});if(this.nestedFlushScheduled)return;this.nestedFlushScheduled=true;setTimeout(()=>this.flushNestedQueue(),CODE_MODE_BATCH_WINDOW_MS)})}flushNestedQueue(){this.nestedFlushScheduled=false;const entries=this.nestedQueue.splice(0);if(entries.length===0)return;const active=entries.filter(entry=>!entry.signal.aborted);for(const entry of entries){if(entry.signal.aborted)entry.reject(entry.signal.reason)}if(active.length===0)return;const batchController=new AbortController;const abortBatch=__name(event=>{const aborted3=event.currentTarget;batchController.abort(aborted3.reason)},"abortBatch");for(const entry of active){entry.signal.addEventListener("abort",abortBatch,{once:true});this.nestedResolvers.set(entry.request.callId,{resolve:entry.resolve,reject:entry.reject,onResult:entry.onResult})}void runWithoutToolCallRuntime(()=>this.getOrCreateNestedToolScheduler().schedule(active.map(entry=>entry.request),batchController.signal)).catch(error3=>{for(const entry of active){this.nestedResolvers.delete(entry.request.callId);entry.reject(error3)}}).finally(()=>{for(const entry of active){entry.signal.removeEventListener("abort",abortBatch)}})}get memoryMonitor(){return this.config.getMemoryPressureMonitor?.()}compactResultDisplayForInteractiveHistory(resultDisplay){return typeof this.config.isInteractive==="function"&&this.config.isInteractive()?compactToolResultDisplayForHistory(resultDisplay):resultDisplay}async processToolResultImages(responseParts,signal,executionOrigin){if(executionOrigin?.kind==="fixed_policy"){return{responseParts}}let modelOverride;const notices=[];let omniProcessed=responseParts;if(this.config.isOmniEnabled?.()){const{processToolResultOmniMedia}=await import("./tool-result-media-XSFON2ZQ.js");omniProcessed=await processToolResultOmniMedia(responseParts,this.config,signal)}const processedParts=await bridgeToolResultImages({config:this.config,responseParts:omniProcessed,signal,onFullTurnModel:__name(model=>{if(!this.onToolResultFullTurnModel?.(model))return false;modelOverride=model;return true},"onFullTurnModel"),onVisionBridgeNotice:__name(notice=>notices.push(notice),"onVisionBridgeNotice")});return{responseParts:processedParts,...modelOverride!==void 0?{modelOverride}:{},...notices.length>0?{visionBridgeNotice:notices.join("\n")}:{}}}setStatusInternal(targetCallId,newStatus,auxiliaryData,executionStatus){this.toolCalls=this.toolCalls.map(currentCall=>{if(currentCall.request.callId!==targetCallId||currentCall.status==="success"||currentCall.status==="error"||currentCall.status==="cancelled"){return currentCall}const existingStartTime=currentCall.startTime;const toolInstance=currentCall.tool;const invocation=currentCall.invocation;if(invocation?.release&&(newStatus==="success"||newStatus==="error"||newStatus==="cancelled")){this.invocationReleases.set(targetCallId,Promise.resolve().then(()=>invocation.release()).catch(error3=>{debugLogger44.warn("Tool invocation resource cleanup failed:",error3)}))}const outcome=currentCall.outcome;switch(newStatus){case"success":{this.clearRetryCountsForTool(currentCall.request.name);const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,tool:toolInstance,invocation,status:"success",response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"error":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,status:"error",tool:toolInstance,invocation,response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"awaiting_approval":return{request:currentCall.request,tool:toolInstance,status:"awaiting_approval",confirmationDetails:auxiliaryData,startTime:existingStartTime,outcome,invocation};case"scheduled":return{request:currentCall.request,tool:toolInstance,status:"scheduled",startTime:existingStartTime,outcome,invocation};case"cancelled":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;let resultDisplay=void 0;if(currentCall.status==="awaiting_approval"){const waitingCall=currentCall;if(waitingCall.confirmationDetails.type==="edit"){resultDisplay={fileDiff:waitingCall.confirmationDetails.fileDiff,fileName:waitingCall.confirmationDetails.fileName,filePath:waitingCall.confirmationDetails.filePath,originalContent:waitingCall.confirmationDetails.originalContent,newContent:waitingCall.confirmationDetails.newContent}}else if(waitingCall.confirmationDetails.type==="plan"){resultDisplay={type:"plan_summary",message:"Plan was rejected. Remaining in plan mode.",plan:waitingCall.confirmationDetails.plan,rejected:true}}}else if(currentCall.status==="executing"){const executingCall=currentCall;if(executingCall.liveOutput!==void 0){resultDisplay=executingCall.liveOutput}}const preservedResultDisplay=this.compactResultDisplayForInteractiveHistory(resultDisplay);const response=isToolCallResponseInfo(auxiliaryData)?{...auxiliaryData,executionStatus:auxiliaryData.executionStatus??executionStatus??"not_started",resultDisplay:auxiliaryData.resultDisplay??preservedResultDisplay}:{...createCancelledResponse(currentCall.request,String(auxiliaryData),executionStatus??"not_started"),resultDisplay:preservedResultDisplay};return{request:currentCall.request,tool:toolInstance,invocation,status:"cancelled",response,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"validating":return{request:currentCall.request,tool:toolInstance,status:"validating",startTime:existingStartTime,outcome,invocation};case"executing":return{request:currentCall.request,tool:toolInstance,status:"executing",startTime:existingStartTime,executionStartTime:Date.now(),outcome,invocation};default:{const exhaustiveCheck=newStatus;return exhaustiveCheck}}});this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger44.warn(`setStatusInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}setArgsInternal(targetCallId,args){let invocationError;let argsUpdated=false;this.toolCalls=this.toolCalls.map(call=>{if(call.request.callId!==targetCallId||call.status==="success"||call.status==="error"||call.status==="cancelled"){return call}const invocationOrError=runInRequestGoalContext(call.request,()=>this.buildInvocation(call.tool,args,targetCallId,call.request.prompt_id,call.request.executionOrigin?.kind==="client"));if(invocationOrError instanceof Error){invocationError=invocationOrError;const response=createErrorResponse(call.request,invocationOrError,"invalid_tool_params","not_started");return{request:{...call.request,args},status:"error",tool:call.tool,response}}argsUpdated=true;return{...call,request:{...call.request,args},invocation:invocationOrError}});if(invocationError){this.finalizeBlockedSpan(targetCallId,"error","system");const toolSpan=this.toolSpans.get(targetCallId);if(toolSpan){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,invocationError.message)}this.finalizeToolSpan(targetCallId);this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger44.warn(`setArgsInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)});return false}return argsUpdated}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}cancelPreExecutionIfAborted(callId,signal,toolSpan=this.toolSpans.get(callId)){if(!signal.aborted)return false;this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(callId,"aborted","system");if(toolSpan){setToolSpanCancelled(toolSpan)}this.finalizeToolSpan(callId);return true}finalizeToolSpan(callId,force=false){this.preToolUseIds.delete(callId);this.preToolUseAsks.delete(callId);this.preToolUseSessionHookIds.delete(callId);this.hookReplacedInputCallIds.delete(callId);this.autoModeFallbackCallIds.delete(callId);this.runtimeContentGeneratorViews.delete(callId);if(callId===this.postToolBatchSpanCallId&&!force)return;const span=this.toolSpans.get(callId);if(!span)return;this.toolSpans.delete(callId);endToolSpan(span);this.releaseBatchListenerIfDrained(callId)}finalizeBlockedSpan(callId,decision,source){const span=this.blockedSpans.get(callId);if(!span)return;this.blockedSpans.delete(callId);endToolBlockedOnUserSpan(span,{decision,source})}releaseBatchListenerIfDrained(callId){const batch=this.callIdToBatch.get(callId);if(!batch)return;this.callIdToBatch.delete(callId);batch.callIds.delete(callId);this.releaseIdleBatchListener(batch)}releaseIdleBatchListener(batch){if(batch.preparing)return;for(const id of batch.callIds){if(this.toolSpans.has(id)||this.blockedSpans.has(id))return}batch.signal.removeEventListener("abort",batch.onAbort)}getBlockedSource(){return this.config.getIdeMode?.()?"ide":"cli"}drainSpansForBatch(callIds){const ids=Array.from(callIds);setTimeout(()=>{for(const callId of ids){try{const call=this.toolCalls.find(c=>c.request.callId===callId);if(call?.status!=="awaiting_approval"&&call?.status!=="scheduled"){continue}this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");if(this.blockedSpans.has(callId)){this.finalizeBlockedSpan(callId,"aborted","system")}const span=this.toolSpans.get(callId);if(span){setToolSpanCancelled(span);this.finalizeToolSpan(callId,true)}this.callIdToPostToolBatchSignal.delete(callId);this.autoModeFallbackCallIds.delete(callId)}catch(e){debugLogger44.warn(`drainSpansForBatch: failed to drain ${callId}: ${e instanceof Error?e.message:String(e)}`)}}},0)}postToolUseFailureEndMeta=__name(r=>r.hookError?{success:false,error:r.hookError}:{success:true,hasAdditionalContext:!!r.additionalContext},"postToolUseFailureEndMeta");openToolSpan(reqInfo,tool,batchState){const existing=this.toolSpans.get(reqInfo.callId);if(existing)return existing;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=startToolSpan(canonicalName,{"tool.call_id":reqInfo.callId,"gen_ai.tool.call.id":reqInfo.providerCallId??reqInfo.callId,call_id:reqInfo.callId,tool_name:canonicalName,...reqInfo.parentCallId?{"tool.parent_call_id":reqInfo.parentCallId}:{},...reqInfo.source?{"tool.source":reqInfo.source}:{}},tool.description,reqInfo.prompt_id);this.toolSpans.set(reqInfo.callId,toolSpan);batchState.callIds.add(reqInfo.callId);this.callIdToBatch.set(reqInfo.callId,batchState);return toolSpan}async withHookSpan(opts,fn,toEndMeta){const hookSpan=startHookSpan(opts);let endMeta={success:false};try{const result=await fn();endMeta=toEndMeta(result);return result}catch(err){endMeta={success:false,error:err instanceof Error?err.message:String(err)};throw err}finally{endHookSpan(hookSpan,endMeta)}}buildInvocation(tool,args,callId,promptId,notifyOnCompletion=false){try{const invocation=tool.build(structuredClone(args));const notificationAware=invocation;notificationAware.setCompletionNotificationEnabled?.(notifyOnCompletion);if(callId){const maybeAware=invocation;if(typeof maybeAware.setCallId==="function"){maybeAware.setCallId(callId)}}if(promptId){const maybeAware=invocation;if(typeof maybeAware.setPromptId==="function"){maybeAware.setPromptId(promptId)}}return invocation}catch(e){if(e instanceof Error){return e}return new Error(String(e))}}async getToolNotFoundMessage(unknownToolName,topN=3){const skillTool=await this.toolRegistry.ensureTool(ToolNames.SKILL);if(skillTool&&"getAvailableSkillNames"in skillTool){const availableSkillNames=skillTool.getAvailableSkillNames();if(availableSkillNames.includes(unknownToolName)){return`"${unknownToolName}" is a skill name, not a tool name. To use this skill, invoke the "${ToolNames.SKILL}" tool with parameter: skill: "${unknownToolName}"`}}const mcpMessage=this.getMcpToolUnavailableMessage(unknownToolName);if(mcpMessage){return mcpMessage}const optInToolMessage=await getOptInToolNotFoundMessage(this.config,unknownToolName,async canonicalName=>Boolean(await this.toolRegistry.ensureTool(canonicalName)));if(optInToolMessage){return optInToolMessage}const suggestion=this.getToolSuggestion(unknownToolName,topN);return`Tool "${unknownToolName}" not found in registry. Tools must use the exact names that are registered.${suggestion}`}getMcpToolUnavailableMessage(unknownToolName){if(!unknownToolName.startsWith("mcp__")){return null}const prefixOf=__name(server=>sanitizeToolNameForProvider(`mcp__${server}__`),"prefixOf");const byPrefixLengthDesc=__name((a,b2)=>prefixOf(b2).length-prefixOf(a).length,"byPrefixLengthDesc");const candidates=Array.from(new Set([...this.config.getMcpServerNames?.()??[],...this.config.getRecentlyRemovedMcpServers?.()??[]])).sort(byPrefixLengthDesc);const serverHit=candidates.find(s3=>unknownToolName.startsWith(prefixOf(s3)));if(!serverHit){return`Tool "${unknownToolName}" not found: no MCP server providing it is currently configured. If you recently removed or renamed an MCP server, its tools are no longer available.`}switch(this.config.getMcpServerUnavailableReason?.(serverHit)){case"removed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" was removed during this session, so its tools were unloaded. Re-add it to your settings to use this tool again.`;case"not_allowed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is not in the allow-list (mcp.allowed / --allowed-mcp-server-names), so its tools are not loaded. Add it to mcp.allowed to use this tool.`;case"excluded":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is excluded (mcp.excluded), so its tools are not loaded. Remove it from mcp.excluded to use this tool.`;case"pending_approval":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is awaiting approval, so its tools are not loaded. Approve it (run /mcp) to use this tool.`;default:return`Tool "${unknownToolName}" not found on MCP server "${serverHit}". The server may be disconnected, still starting up, or the tool was renamed.`}}getToolSuggestion(unknownToolName,topN=3){const allToolNames=this.toolRegistry.getAllToolNames().filter(name=>this.toolRegistry.isToolDeclared?.(name)??true);const matches=allToolNames.map(toolName=>({name:toolName,distance:import_fast_levenshtein.default.get(unknownToolName,toolName)}));matches.sort((a,b2)=>{const aIsPrefix=unknownToolName.startsWith(a.name);const bIsPrefix=unknownToolName.startsWith(b2.name);if(aIsPrefix!==bIsPrefix){return aIsPrefix?-1:1}return a.distance-b2.distance});const topNResults=matches.slice(0,topN);if(topNResults.length===0){return""}const suggestedNames=topNResults.map(match=>`"${match.name}"`).join(", ");if(topNResults.length>1){return` Did you mean one of: ${suggestedNames}?`}else{return` Did you mean ${suggestedNames}?`}}async resolveToolCallBridgeRequest(request,signal){if(signal.aborted||canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const permissionManager=this.config.getPermissionManager?.();if(permissionManager){let bridgeEnabled;try{bridgeEnabled=await permissionManager.isToolEnabled(ToolNames.TOOL_CALL)}catch(error3){if(signal.aborted){return request}const message=error3 instanceof Error?error3.message:String(error3);return{...request,bridgeResolutionError:{error:new Error(`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${message}`),type:"unhandled_exception"}}}if(signal.aborted||!bridgeEnabled){return request}}else if((this.config.getPermissionsDeny?.()??[]).some(name=>canonicalToolName(name).toLowerCase().trim()===ToolNames.TOOL_CALL)){return request}const resolution=await runInRequestGoalContext(request,()=>resolveDeferredToolCall(this.toolRegistry,request.args,{maxSubagentDepth:this.config.getMaxSubagentDepth()}));if("error"in resolution){return{...request,bridgeResolutionError:{error:resolution.error,type:resolution.errorType}}}if(this.isToolExecutionAllowed&&!this.isToolExecutionAllowed(resolution.tool.name)){return{...request,bridgeResolutionError:{error:new Error(`Tool "${resolution.tool.name}" is not permitted by this agent's tool policy (execution allowlist or disallowedTools blocklist).`),type:"execution_denied"}}}return{...request,name:resolution.tool.name,args:resolution.arguments,modelFacingName:request.name,modelFacingArgs:request.args}}schedule(request,signal,runtimeView){const owner=captureHookExecutionOwner(this.config);if(this.isRunning()||this.isScheduling){if(signal.aborted){return Promise.reject(new Error("Tool call cancelled while in queue."))}return new Promise((resolve34,reject)=>{const abortHandler=__name(()=>{const index=this.requestQueue.findIndex(item=>item.request===request);if(index>-1){this.requestQueue.splice(index,1);reject(new Error("Tool call cancelled while in queue."))}},"abortHandler");signal.addEventListener("abort",abortHandler,{once:true});this.requestQueue.push({request,signal,runtimeView,owner,resolve:__name(()=>{signal.removeEventListener("abort",abortHandler);resolve34()},"resolve"),reject:__name(reason=>{signal.removeEventListener("abort",abortHandler);reject(reason)},"reject")})})}return this.scheduleWithOwner(request,signal,runtimeView,owner)}scheduleWithOwner(request,signal,runtimeView,owner){const items=Array.isArray(request)?request:[request];for(const item of items)this.hookOwners.set(item.callId,owner);return runWithHookExecutionOwner(owner,()=>this._schedule(request,signal,runtimeView)).catch(error3=>{for(const item of items){this.hookOwners.delete(item.callId);this.preToolUseContexts.delete(item.callId);this.nestedHookContexts.delete(item.callId);this.failureContextsForParent.delete(item.callId)}throw error3})}drainRequestQueueIfIdle(){if(this.requestQueue.length===0||this.isScheduling||this.isRunning()){return}const next=this.requestQueue.shift();this.scheduleWithOwner(next.request,next.signal,next.runtimeView,next.owner).then(next.resolve).catch(next.reject)}clearRetryCountsForTool(toolName){const prefix=`${toolName}:`;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(prefix)){this.validationRetryCounts.delete(key)}}}recordRetryableToolError(toolName,errorMessage){const errorKey=`${toolName}:${errorMessage}`;const count=(this.validationRetryCounts.get(errorKey)??0)+1;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(`${toolName}:`)&&key!==errorKey){this.validationRetryCounts.delete(key)}}this.validationRetryCounts.set(errorKey,count);return count}async _schedule(request,signal,runtimeView){if(runtimeView){const items=Array.isArray(request)?request:[request];for(const item of items){this.runtimeContentGeneratorViews.set(item.callId,runtimeView)}try{return await runWithRuntimeContentGenerator(runtimeView,()=>this._schedule(request,signal))}catch(error3){for(const item of items){this.runtimeContentGeneratorViews.delete(item.callId)}throw error3}}this.isScheduling=true;let preparedBatch;try{if(this.isRunning()){throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).")}const requestsToProcess=await Promise.all(dedupeRequestsByCallId(Array.isArray(request)?request:[request]).map(item=>this.resolveToolCallBridgeRequest({...item,args:structuredClone(item.args)},signal)));const planModeEntryBoundaryIndex=findPlanModeEntryBatchBoundaryIndex(requestsToProcess.map(item=>canonicalToolName(item.name)));if(this.validationRetryCounts.size>0){const currentToolNames=new Set(requestsToProcess.map(r=>r.name));for(const key of[...this.validationRetryCounts.keys()]){const sep20=key.indexOf(":");const toolName=sep20===-1?key:key.slice(0,sep20);if(!currentToolNames.has(toolName)){this.validationRetryCounts.delete(key)}}}const newToolCalls=[];const retryErrorsRecordedInBatch=new Map;const recordBatchRetryableToolError=__name((toolName,errorMessage)=>{const key=`${toolName}:${errorMessage}`;const existingCount=retryErrorsRecordedInBatch.get(key);if(existingCount!==void 0){for(const trackedKey of this.validationRetryCounts.keys()){if(trackedKey.startsWith(`${toolName}:`)){this.validationRetryCounts.delete(trackedKey)}}this.validationRetryCounts.set(key,existingCount);return existingCount}const count=this.recordRetryableToolError(toolName,errorMessage);retryErrorsRecordedInBatch.set(key,count);return count},"recordBatchRetryableToolError");const batchState={signal,onAbort:__name(()=>this.drainSpansForBatch(batchState.callIds),"onAbort"),callIds:new Set,preparing:true};preparedBatch=batchState;signal.addEventListener("abort",batchState.onAbort,{once:true});for(const[requestIndex,reqInfo]of requestsToProcess.entries()){let resolvedTool;let resolvedInvocation;const recordPrevalidationCancellation=__name(()=>{if(!signal.aborted)return false;newToolCalls.push({status:"cancelled",request:reqInfo,response:createCancelledResponse(reqInfo,"Tool call cancelled before execution.","not_started"),...resolvedTool?{tool:resolvedTool}:{},...resolvedInvocation?{invocation:resolvedInvocation}:{},durationMs:0});return true},"recordPrevalidationCancellation");try{if(recordPrevalidationCancellation())continue;if(planModeEntryBoundaryIndex!==void 0&&requestIndex!==planModeEntryBoundaryIndex){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE),"execution_denied","not_started"),durationMs:0});continue}if(reqInfo.bridgeResolutionError){let bridgeError=reqInfo.bridgeResolutionError.error;if(reqInfo.bridgeResolutionError.type==="invalid_tool_params"){const count=recordBatchRetryableToolError(reqInfo.name,bridgeError.message);if(count>=VALIDATION_RETRY_LOOP_THRESHOLD){bridgeError=new Error(`${bridgeError.message}${RETRY_LOOP_STOP_DIRECTIVE}`)}}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,bridgeError,reqInfo.bridgeResolutionError.type,"not_started"),durationMs:0});continue}const canonicalName=canonicalToolName(reqInfo.name);if(this.config.getToolMode?.()===ToolMode.CodeModeOnly&&reqInfo.executionOrigin?.kind!=="fixed_policy"&&!isCodeModeToolCallAllowed(canonicalName,reqInfo.source??"model")){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(`Tool "${reqInfo.name}" is unavailable on this CodeModeOnly call surface.`),"execution_denied","not_started"),durationMs:0});continue}const pm=this.config.getPermissionManager?.();const toolAliases2=this.config.getToolRegistry?.()?.getPermissionAliases?.(canonicalName);const mcpIdentity=this.config.getToolRegistry?.()?.getMcpToolIdentity?.(canonicalName);const permissionEnabled=pm?await pm.isToolEnabled(canonicalName,toolAliases2,mcpIdentity):true;if(recordPrevalidationCancellation())continue;if(pm&&!permissionEnabled){const matchingRule=pm.findMatchingDenyRule({toolName:canonicalName,toolAliases:toolAliases2,mcpIdentity});let permissionErrorMessage;if(matchingRule){permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined. Matching deny rule: "${matchingRule}".`}else if(typeof pm.isToolDisabledByCoreToolsAllowList==="function"&&pm.isToolDisabledByCoreToolsAllowList(canonicalName)){permissionErrorMessage=`"${reqInfo.name}" is not listed in the active core tools allowlist (--core-tools or settings tools.core), so the tool is not available. Add it to the core tools list to re-enable it.`}else{permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}if(!pm){const excludeTools=this.config.getPermissionsDeny?.()??void 0;if(excludeTools&&excludeTools.length>0){const normalizedToolName=canonicalName.toLowerCase().trim();const excludedMatch=excludeTools.find(excludedTool=>excludedTool.toLowerCase().trim()===normalizedToolName);if(excludedMatch){const permissionErrorMessage=`Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}}}const toolInstance=await runInRequestGoalContext(reqInfo,()=>this.toolRegistry.ensureTool(canonicalName));resolvedTool=toolInstance;if(recordPrevalidationCancellation())continue;if(!toolInstance){const errorMessage=await runInRequestGoalContext(reqInfo,()=>this.getToolNotFoundMessage(reqInfo.name));if(recordPrevalidationCancellation())continue;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(errorMessage),"tool_not_registered","not_started"),durationMs:0});continue}if((reqInfo.wasOutputTruncated||reqInfo.hadIncompleteArguments)&&toolInstance.kind==="edit"){const truncated=reqInfo.wasOutputTruncated===true;const rejectionMessage=truncated?TRUNCATION_EDIT_REJECTION:INCOMPLETE_ARGS_EDIT_REJECTION;const count=recordBatchRetryableToolError(reqInfo.name,rejectionMessage);const truncationError=new Error(count>=VALIDATION_RETRY_LOOP_THRESHOLD?`${rejectionMessage}${truncated?TRUNCATION_RETRY_LOOP_DIRECTIVE:INCOMPLETE_ARGS_RETRY_LOOP_DIRECTIVE}`:rejectionMessage);newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,truncationError,truncated?"output_truncated":"invalid_tool_params","not_started"),durationMs:0});continue}const preToolUseTerminal=await this.runPreToolUse(reqInfo,toolInstance,batchState,signal);if(preToolUseTerminal){newToolCalls.push(preToolUseTerminal);continue}if(recordPrevalidationCancellation())continue;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool:toolInstance,args:reqInfo.args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"),durationMs:0});continue}const invocationOrError=runInRequestGoalContext(reqInfo,()=>this.buildInvocation(toolInstance,policyGate.args,reqInfo.callId,reqInfo.prompt_id,reqInfo.executionOrigin?.kind==="client"));if(recordPrevalidationCancellation())continue;if(invocationOrError instanceof Error){const targetMessage=reqInfo.modelFacingName!==void 0?describeBridgedArgumentError(reqInfo.name,invocationOrError.message):invocationOrError.message;const paramGuidance=reqInfo.wasOutputTruncated?TRUNCATION_PARAM_GUIDANCE:reqInfo.hadIncompleteArguments?INCOMPLETE_ARGS_PARAM_GUIDANCE:void 0;const displayError=paramGuidance?new Error(`${targetMessage} ${paramGuidance}`):reqInfo.modelFacingName!==void 0?new Error(targetMessage):invocationOrError;const count=recordBatchRetryableToolError(reqInfo.name,invocationOrError.message);const finalError=count>=VALIDATION_RETRY_LOOP_THRESHOLD?new Error(`${targetMessage}${RETRY_LOOP_STOP_DIRECTIVE}`):displayError;newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,finalError,"invalid_tool_params","not_started"),durationMs:0});continue}resolvedInvocation=invocationOrError;this.clearRetryCountsForTool(reqInfo.name);newToolCalls.push({status:"validating",request:reqInfo,tool:toolInstance,invocation:invocationOrError,startTime:Date.now()})}catch(error3){if(recordPrevalidationCancellation())continue;const normalizedError=error3 instanceof Error?error3:new Error(String(error3));newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,normalizedError,error3?.errorType??"unhandled_exception","not_started"),...resolvedTool?{tool:resolvedTool}:{},durationMs:0})}}for(const toolCall of newToolCalls){const span=this.toolSpans.get(toolCall.request.callId);if(!span||toolCall.status==="validating")continue;if(toolCall.status==="cancelled"){setToolSpanCancelled(span)}else if(toolCall.status==="error"){setToolSpanFailure(span,TOOL_FAILURE_KIND_TOOL_EXCEPTION,toolCall.response.error?.message??"Tool call failed validation.")}this.finalizeToolSpan(toolCall.request.callId)}this.toolCalls=this.toolCalls.concat(newToolCalls);for(const toolCall of newToolCalls){this.callIdToPostToolBatchSignal.set(toolCall.request.callId,signal)}const postToolBatchParentCallId=newToolCalls.findLast(toolCall=>toolCall.status==="validating")?.request.callId;this.postToolBatchEnabledForBatch=false;this.postToolBatchSpanCallId=void 0;try{this.postToolBatchEnabledForBatch=!this.config.getDisableAllHooks()&&(this.config.hasHooksForEvent?.("PostToolBatch")??false);if(this.postToolBatchEnabledForBatch){this.postToolBatchSpanCallId=postToolBatchParentCallId}}catch(configError){this.postToolBatchEnabledForBatch=true;this.postToolBatchSpanCallId=postToolBatchParentCallId;if(!this.postToolBatchConfigWarned){this.postToolBatchConfigWarned=true;debugLogger44.warn("PostToolBatch hook detection failed; deferring span as a precaution:",configError)}}this.notifyToolCallsUpdate();const permissionRequestGrants=new Set;for(const toolCall of newToolCalls){if(toolCall.status!=="validating"){continue}const{request:reqInfo,invocation}=toolCall;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=this.openToolSpan(reqInfo,toolCall.tool,batchState);const preToolUseAsk=this.preToolUseAsks.get(reqInfo.callId);try{if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(reqInfo.executionOrigin?.kind==="fixed_policy"){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let toolParams=invocation.params;const flowResult=await runInRequestGoalContext(reqInfo,()=>evaluatePermissionFlow(this.config,invocation,canonicalName,toolParams,signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const modToolCheck=this.schedulerOptions.modToolCheck;if(modToolCheck){const decision=await runInRequestGoalContext(reqInfo,()=>modToolCheck({tool:canonicalName,input:structuredClone(toolParams),tool_use_id:reqInfo.callId},{decision:flowResult.finalPermission==="default"?"ask":flowResult.finalPermission,...flowResult.denyMessage?{reason:flowResult.denyMessage}:{}},signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(!["allow","ask","deny"].includes(decision.decision)){throw new Error("Invalid Mod tool.check decision.")}if(flowResult.finalPermission!=="deny"){if(decision.decision==="deny"){flowResult.finalPermission="deny";flowResult.denyMessage=decision.reason?.trim()||`Tool "${reqInfo.name}" is denied by a Mod.`}else if(decision.decision==="ask"&&flowResult.finalPermission==="allow"){flowResult.finalPermission="ask"}}}const{defaultPermission,finalPermission,pmForcedAsk,pmCtx,denyMessage,requiresUserInteraction}=flowResult;const approvalMode=this.config.getApprovalMode();const isPlanMode=approvalMode==="plan";const isPlanShellCall=isPlanMode&&(canonicalName===ToolNames.SHELL||canonicalName===ToolNames.MONITOR);const isExitPlanModeTool=canonicalName===ToolNames.EXIT_PLAN_MODE;const isEnterPlanModeTool=canonicalName===ToolNames.ENTER_PLAN_MODE;const forceAutoReviewForAllow=approvalMode==="auto"&&(shouldForceAutoModeReviewForAllow(pmCtx,this.config.getCwd())||shouldClassifyAllShellForAutoMode(canonicalName,this.config));const confirmationPermission=getEffectivePermissionForConfirmation(finalPermission,forceAutoReviewForAllow);if(finalPermission==="allow"&&forceAutoReviewForAllow){debugLogger44.info(`Auto mode: L4 allow overridden by protected-write guard for ${canonicalName}`)}if(isPlanRequiredTeammateAwaitingApproval(this.config)&&finalPermission!=="deny"){const isExplicitPreApprovalTool=isPlanRequiredTeammatePreApprovalAllowedTool(canonicalName,toolParams);const canRunBeforeLeaderApproval=!preToolUseAsk&&isExplicitPreApprovalTool&&(canonicalName===ToolNames.EXIT_PLAN_MODE||canonicalName===ToolNames.TASK_UPDATE||defaultPermission==="allow"&&finalPermission==="allow"&&!forceAutoReviewForAllow);if(canRunBeforeLeaderApproval){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const message=getPlanRequiredTeammatePreApprovalMessage(canonicalName);this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(finalPermission==="deny"){this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(denyMessage??`Tool "${reqInfo.name}" is denied.`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_SPAN_STATUS_PERMISSION_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}let planShellAmbientWorkingDirectory;if(isPlanShellCall){const directory=toolParams["directory"];planShellAmbientWorkingDirectory=typeof directory==="string"&&directory.length>0?void 0:this.config.getTargetDir();invocation.params={...structuredClone(invocation.params),directory:typeof directory==="string"&&directory.length>0?directory:planShellAmbientWorkingDirectory};toolParams=invocation.params}const planShellDecision=isPlanShellCall?await runInRequestGoalContext(reqInfo,()=>evaluatePlanModeShellPolicy({config:this.config,toolName:canonicalName,requestArgs:reqInfo.args,invocationParams:toolParams,permissionContext:pmCtx,ambientWorkingDirectory:planShellAmbientWorkingDirectory,signal})):{classification:"not-applicable"};if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const rejectPlanShell=__name(message=>{this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"),resultDisplay:message});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId)},"rejectPlanShell");if(planShellDecision.classification!=="not-applicable"){const initialPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(initialPlanShellError){rejectPlanShell(initialPlanShellError);continue}}if(planShellDecision.classification==="write"){rejectPlanShell(planShellDecision.writeBlockMessage);continue}const planShellRequiresConfirmation=planShellDecision.classification==="unknown";if(finalPermission==="allow"&&!forceAutoReviewForAllow&&!planShellRequiresConfirmation&&!preToolUseAsk){if(approvalMode==="auto"){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());this.config.setAutoModeDenialState(recordAllow(this.config.getAutoModeDenialState(),actionFingerprint))}this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let autoModeFallback;let autoModeFallbackRequiresHuman=false;if(!requiresUserInteraction&&!preToolUseAsk&&shouldRunAutoModeForCall(approvalMode,canonicalName)){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());const{denialState,fallback}=prepareAutoModeFallback(this.config,actionFingerprint);const llmClient=this.config.getLlmClient?.();const messages=llmClient?.getHistoryTail(MAX_TRANSCRIPT_MESSAGES,false)??[];const trustedUserAnswers=llmClient?.getTrustedUserAnswers?.()??[];const decision=await runInRequestGoalContext(reqInfo,()=>evaluateAutoMode({ctx:pmCtx,pmForcedAsk,toolParams,messages,trustedUserAnswers,config:this.config,signal,skipClassifierReason:fallback.fallback?fallback.reason:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const outcome=applyAutoModeDecision(decision,this.config,denialState,actionFingerprint);if(!this.config.getDisableAllHooks()&&shouldFirePermissionDeniedForAutoMode(decision,outcome)){try{await runInRequestGoalContext(reqInfo,()=>this.config.getHookSystem?.()?.firePermissionDeniedEvent(canonicalName,toolParams,reqInfo.callId,getAutoModePermissionDeniedReason(decision),signal,reqInfo.callId))}catch(hookError){debugLogger44.warn(`PermissionDenied hook failed for tool ${reqInfo.callId}: ${hookError instanceof Error?hookError.message:String(hookError)}`)}}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}switch(outcome.kind){case"approved":this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue;case"blocked":debugLogger44.warn(`Auto mode blocked (${outcome.reason}): tool=${canonicalName}, `+formatDenialStateLog(denialState));this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(outcome.errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,outcome.errorMessage);this.finalizeToolSpan(reqInfo.callId);continue;case"fallback":autoModeFallbackRequiresHuman=outcome.requiresHumanDecision===true;if(outcome.message&&(isDenialFallbackReason(outcome.reason)||outcome.reason==="classifier_unavailable")){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger44.warn(`Auto mode fallback to manual approval (${outcome.reason}): `+formatDenialStateLog(denialState))}else if((outcome.reason==="external_write"||outcome.reason==="external_directory")&&outcome.message){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger44.warn(`Auto mode fallback to manual approval (${outcome.reason}): target outside workspace.`)}break;default:{const _exhaustive=outcome;void _exhaustive}}}const isAskUserQuestionTool=canonicalName===ToolNames.ASK_USER_QUESTION;let confirmationDetails;if(!preToolUseAsk&&!needsConfirmation(planShellRequiresConfirmation?"ask":confirmationPermission,approvalMode,canonicalName,requiresUserInteraction)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled")}else{confirmationDetails=await runInRequestGoalContext(reqInfo,()=>invocation.getConfirmationDetails(signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(autoModeFallback){confirmationDetails=decorateAutoModeFallbackConfirmation(confirmationDetails,autoModeFallback.reason,autoModeFallback.message)}if(planShellDecision.classification!=="not-applicable"){const preDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(preDisplayPlanShellError){rejectPlanShell(preDisplayPlanShellError);continue}}try{confirmationDetails=decoratePlanModeShellConfirmation(planShellDecision,confirmationDetails)}catch{if(planShellDecision.classification==="unknown"){rejectPlanShell(planShellDecision.noApprovalMessage);continue}throw new Error("Unable to prepare shell confirmation.")}const planModeDetails=confirmationDetails;if(preToolUseAsk){confirmationDetails=withPreToolUseAskReason(confirmationDetails,preToolUseAsk)}injectPermissionRulesIfMissing(confirmationDetails,pmCtx);if(planShellDecision.classification==="not-applicable"&&isPlanModeBlocked(isPlanMode,isExitPlanModeTool,isAskUserQuestionTool,planModeDetails,isEnterPlanModeTool)){const isPlanRequiredTeammate=!shouldUsePlanOnlyReminderInSubagentContext()&&!this.config.getSdkMode();const planModeError=new Error(`Tool blocked by plan mode: "${reqInfo.name}" is not a read-only tool. Only read-only tools (read_file, grep_search, glob, web_fetch, etc.) are allowed in plan mode. Do NOT retry this tool. `+(isPlanRequiredTeammate?`Pivot to read-only alternatives to gather the information you need, then call exit_plan_mode with a plan that covers this tool's purpose.`:`Pivot to read-only alternatives to gather equivalent information, then present your plan directly to the caller.`));this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,planModeError,"execution_denied","not_started"),resultDisplay:"Plan mode blocked a non-read-only tool call."});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(!requiresUserInteraction&&!preToolUseAsk&&isAutoEditApproved(approvalMode,confirmationDetails)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const isNonInteractiveDeny=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&(this.config.getInputFormat()!=="stream-json"||autoModeFallbackRequiresHuman);if(isNonInteractiveDeny){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"),approvalRequired:true});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_SPAN_STATUS_NON_INTERACTIVE_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}const preparedConfirmationDetails=confirmationDetails;const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();const permissionRequestGrant=permissionRequestGrants.has(reqInfo.callId);if(hooksEnabled&&messageBus||permissionRequestGrant){const permissionMode=String(this.config.getApprovalMode());const hookResult=permissionRequestGrant?{hasDecision:true,shouldAllow:true}:await runInRequestGoalContext(reqInfo,()=>firePermissionRequestHook(messageBus,canonicalName,reqInfo.args||{},permissionMode,void 0,signal,this.hookOwners.get(reqInfo.callId)));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const allowApplies=hookResult.shouldAllow===true&&!requiresUserInteraction&&!autoModeFallbackRequiresHuman&&(!preToolUseAsk||hookResult.updatedInput!==void 0&&planShellDecision.classification==="not-applicable");if(hookResult.hasDecision&&(!hookResult.shouldAllow||allowApplies)){if(hookResult.shouldAllow){if(planShellDecision.classification!=="not-applicable"){const approval=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal,outcome:"proceed_once",payload:hookResult.updatedInput?{updatedInput:hookResult.updatedInput}:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(approval.outcome==="cancel"){await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}rejectPlanShell(approval.payload?.cancelMessage??planShellDecision.noApprovalMessage);continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,approval.outcome);this.setToolCallOutcome(reqInfo.callId,approval.outcome);this.setStatusInternal(reqInfo.callId,"scheduled");continue}if(hookResult.updatedInput){const rebuilt=this.rebuildWithPermissionRequestInput(reqInfo,toolCall.tool,hookResult.updatedInput,toolSpan);if(rebuilt){permissionRequestGrants.add(reqInfo.callId);newToolCalls.push(rebuilt)}continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("proceed_once"));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"proceed_once");this.setToolCallOutcome(reqInfo.callId,"proceed_once");this.setStatusInternal(reqInfo.callId,"scheduled")}else{const cancelPayload=hookResult.denyMessage?{cancelMessage:hookResult.denyMessage}:void 0;await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("cancel",cancelPayload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"cancel");this.setToolCallOutcome(reqInfo.callId,"cancel");this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(hookResult.denyMessage||`Permission denied by hook for "${reqInfo.name}"`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_SPAN_STATUS_PERMISSION_HOOK_DENIED);this.finalizeToolSpan(reqInfo.callId)}continue}}if(this.config.getShouldAvoidPermissionPrompts?.()){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:`Tool "${reqInfo.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_SPAN_STATUS_BACKGROUND_AGENT_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(planShellDecision.classification!=="not-applicable"){const finalPreDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(finalPreDisplayPlanShellError){rejectPlanShell(finalPreDisplayPlanShellError);continue}}if(confirmationDetails.type!=="edit"||!confirmationDetails.skipIdeDiff){this.openIdeDiffIfEnabled(confirmationDetails,reqInfo.callId,signal)}const originalOnConfirm=confirmationDetails.onConfirm;const invocationContext=getInvocationContext();let planShellResponseClaimed=false;const wrappedConfirmationDetails={...confirmationDetails,...pmForcedAsk||requiresUserInteraction||preToolUseAsk?{hideAlwaysAllow:true}:{},onConfirm:__name(async(outcome,payload)=>runWithInvocationContext(invocationContext,async()=>{await runInRequestGoalContext(reqInfo,async()=>{if(planShellDecision.classification!=="not-applicable"){if(planShellResponseClaimed)return;planShellResponseClaimed=true;const currentCall=this.toolCalls.find(call=>call.request.callId===reqInfo.callId&&call.status==="awaiting_approval");if(!currentCall)return;const approval=await validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:currentCall.request.args,invocationParams:currentCall.invocation.params,signal,outcome,payload});await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,approval.outcome,signal,approval.payload);return}await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,outcome,signal,payload)})}),"onConfirm")};this.setStatusInternal(reqInfo.callId,"awaiting_approval",wrappedConfirmationDetails);const blockedSpan=startToolBlockedOnUserSpan(toolSpan,{tool_name:canonicalName,call_id:reqInfo.callId});this.blockedSpans.set(reqInfo.callId,blockedSpan);if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Qwen Code needs your permission to use ${reqInfo.name}`,"permission_prompt","Permission needed",void 0,this.hookOwners.get(reqInfo.callId)).catch(error3=>{debugLogger44.warn(`Permission prompt notification hook failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}}}catch(error3){if(signal.aborted){this.setStatusInternal(reqInfo.callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(reqInfo.callId,"aborted","system");setToolSpanCancelled(toolSpan);this.finalizeToolSpan(reqInfo.callId);continue}const explicitErrorType=error3?.errorType;this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,error3 instanceof Error?error3:new Error(String(error3)),explicitErrorType??"unhandled_exception","not_started"));this.finalizeBlockedSpan(reqInfo.callId,"error","system");setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3));this.finalizeToolSpan(reqInfo.callId)}}batchState.preparing=false;await this.attemptExecutionOfScheduledCalls(signal);void this.checkAndNotifyCompletion().catch(error3=>{debugLogger44.warn(`_schedule completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}finally{if(preparedBatch){preparedBatch.preparing=false;this.releaseIdleBatchListener(preparedBatch)}this.isScheduling=false;this.drainRequestQueueIfIdle()}}async handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload){const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const toolCall=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!toolCall){if(this.nestedToolScheduler?.toolCalls.some(call=>call.request.callId===callId)){return this.nestedToolScheduler.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload)}return}if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const claimsAskUserQuestionResponse=toolCall.tool instanceof AskUserQuestionTool&&toolCall.confirmationDetails.type==="ask_user_question";if(claimsAskUserQuestionResponse&&this.askUserQuestionResponseClaims.has(callId)){return}if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.add(callId)}try{await this._handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload)}catch(error3){const aborted3=signal.aborted;if(aborted3){this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started")}else{this.setStatusInternal(callId,"error",createErrorResponse(toolCall.request,error3 instanceof Error?error3:new Error(String(error3)),"unhandled_exception","not_started"))}this.finalizeBlockedSpan(callId,aborted3?"aborted":"error","system");const toolSpan=this.toolSpans.get(callId);if(toolSpan){if(aborted3){setToolSpanCancelled(toolSpan)}else{setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3))}}this.finalizeToolSpan(callId);debugLogger44.warn(`handleConfirmationResponse failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`);throw error3}finally{if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.delete(callId)}}await this.attemptExecutionOfScheduledCalls(signal)}async _handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload){const shouldSwitchToDefault=outcome==="proceed_once_and_switch_to_default";const normalizedOutcome=shouldSwitchToDefault?"proceed_once":outcome;const isCurrentApproval=__name(()=>!signal.aborted&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentApproval");const isCurrentCancellation=__name(()=>outcome==="cancel"&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentCancellation");if(!isCurrentApproval()&&!isCurrentCancellation())return;if(!signal.aborted)await originalOnConfirm(normalizedOutcome,payload);if(!isCurrentApproval()&&!isCurrentCancellation())return;if(shouldSwitchToDefault){this.config.setApprovalMode("default")}outcome=normalizedOutcome;if(outcome==="proceed_always"||outcome==="proceed_always_project"||outcome==="proceed_always_user"){await persistPermissionOutcome(outcome,toolCall.confirmationDetails,this.config.getOnPersistPermissionRule?.(),this.config.getPermissionManager?.(),payload,isCurrentApproval);if(!isCurrentApproval())return;await this.autoApproveCompatiblePendingTools(signal,callId,isCurrentApproval);if(!isCurrentApproval())return}this.setToolCallOutcome(callId,outcome);this.recordAutoModeFallbackResolution(callId,outcome);if(outcome==="cancel"||signal.aborted){const cancelMessage=payload?.cancelMessage||"User did not allow tool call";this.setStatusInternal(callId,"cancelled",cancelMessage,"not_started");const toolSpan=this.toolSpans.get(callId);if(toolSpan){setToolSpanCancelled(toolSpan)}const explicitCancel=outcome==="cancel";this.finalizeBlockedSpan(callId,explicitCancel?"cancel":"aborted",explicitCancel?this.getBlockedSource():"system");this.finalizeToolSpan(callId)}else if(outcome==="modify_with_editor"){const waitingToolCall=toolCall;if(waitingToolCall.confirmationDetails.type==="edit"&&isModifiableDeclarativeTool(waitingToolCall.tool)){const modifyContext=waitingToolCall.tool.getModifyContext(signal,callId);const editorType=this.getPreferredEditor();if(!editorType){debugLogger44.warn(`ModifyWithEditor requested for ${callId} but no editor available \u2014 tool stays in awaiting_approval; user can recover via Cancel/Proceed`);const toolSpan=this.toolSpans.get(callId);if(toolSpan){try{toolSpan.setAttributes({"qwen-code.tool.modify_with_editor_unavailable":true})}catch{}}return}this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,isModifying:true});const normalizedArgs={...waitingToolCall.request.args};for(const key of PATH_ARG_KEYS){if(typeof normalizedArgs[key]==="string"){normalizedArgs[key]=unescapePath(String(normalizedArgs[key]).trim())}}const{updatedParams,updatedDiff}=await modifyWithEditor(normalizedArgs,modifyContext,editorType,signal,this.onEditorClose);if(!this.setArgsInternal(callId,updatedParams))return;this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,fileDiff:updatedDiff,isModifying:false})}}else{const waitingToolCall=toolCall;if(isApproveOutcome(outcome)&&waitingToolCall.tool instanceof AskUserQuestionTool&&waitingToolCall.confirmationDetails.type==="ask_user_question"){this.config.getLlmClient?.()?.recordTrustedUserAnswers(callId,waitingToolCall.confirmationDetails.questions,payload?.answers)}if(payload?.newContent&&toolCall){if(!await this._applyInlineModify(toolCall,payload,signal)){return}}this.setStatusInternal(callId,"scheduled");const decision=outcome==="proceed_once"?"proceed_once":"proceed_always";this.finalizeBlockedSpan(callId,decision,this.getBlockedSource())}}recordAutoModeFallbackResolution(callId,outcome){const wasAutoModeFallback=this.autoModeFallbackCallIds.delete(callId);if(this.config.getApprovalMode()==="auto"&&wasAutoModeFallback&&isApproveOutcome(outcome)){const before=this.config.getAutoModeDenialState();const after=recordFallbackApprove(before);if(after===before){debugLogger44.warn(`Auto mode denial counters already clear after fallback approval: `+formatDenialStateLog(before));return}debugLogger44.warn(`Auto mode denial counters reset after fallback approval: ${formatDenialStateLog(before)} -> ${formatDenialStateLog(after)}`);this.config.setAutoModeDenialState(after)}}async openIdeDiffIfEnabled(confirmationDetails,callId,signal){if(confirmationDetails.type!=="edit"||!this.config.getIdeMode()||this.config.getExecutionEnvironment?.()){return}let resolution;try{const ideClient=await IdeClient.getInstance();if(!ideClient.isDiffingEnabled())return;resolution=await ideClient.openDiff(confirmationDetails.filePath,confirmationDetails.newContent)}catch(error3){if(!signal.aborted){debugLogger44.warn(`IDE diff open failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`)}return}const still=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!still)return;if(resolution.status==="accepted"){const userEdited=resolution.content!=null&&resolution.content!==confirmationDetails.newContent;await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"proceed_once",signal,userEdited?{newContent:resolution.content}:void 0)}else{await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"cancel",signal)}}async _applyInlineModify(toolCall,payload,signal){const confirmDetails=toolCall.confirmationDetails;if(confirmDetails.type!=="edit"||!isModifiableDeclarativeTool(toolCall.tool)||!payload.newContent){return true}const currentContent=confirmDetails.originalContent??"";const modifyContext=toolCall.tool.getModifyContext(signal,toolCall.request.callId);const updatedParams=modifyContext.createUpdatedParams(currentContent,payload.newContent,toolCall.request.args);const updatedDiff=createPatch(confirmDetails.filePath,currentContent,payload.newContent,"Current","Proposed");if(!this.setArgsInternal(toolCall.request.callId,updatedParams)){return false}this.setStatusInternal(toolCall.request.callId,"awaiting_approval",{...confirmDetails,fileDiff:updatedDiff});return true}async attemptExecutionOfScheduledCalls(signal){while(true){const allCallsFinalOrScheduled=this.toolCalls.every(call=>call.status==="scheduled"||call.status==="cancelled"||call.status==="success"||call.status==="error");if(!allCallsFinalOrScheduled){return}const callsToExecute=this.toolCalls.filter(call=>call.status==="scheduled");if(callsToExecute.length===0){return}const batches=partitionToolCalls(callsToExecute,this.hookReplacedInputCallIds);for(const batch of batches){if(batch.concurrent&&batch.calls.length>1){await this.runConcurrently(batch.calls,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}else{for(const call of batch.calls){await this.executeSingleToolCall(call,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}}}}}hasExecutingOrAwaitingApprovalCall(){return this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}async runConcurrently(calls,signal){const maxConcurrency=parsePositiveIntegerEnv(process.env["QWEN_CODE_MAX_TOOL_CONCURRENCY"],10);const executing=new Set;for(const call of calls){const p2=this.executeSingleToolCall(call,signal).finally(()=>{executing.delete(p2)});executing.add(p2);if(executing.size>=maxConcurrency){await Promise.race(executing)}}await Promise.all(executing)}async executeSingleToolCall(toolCall,signal){if(toolCall.status!=="scheduled")return;if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.executeSingleToolCall(toolCall,signal))}const scheduledCall=toolCall;const{callId,name:toolName}=scheduledCall.request;const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.executeSingleToolCall(toolCall,signal))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.executeSingleToolCall(toolCall,signal))}let toolSpan=this.toolSpans.get(callId);if(!toolSpan){const canonical=canonicalToolName(toolName);toolSpan=startToolSpan(canonical,{"tool.call_id":callId,"gen_ai.tool.call.id":scheduledCall.request.providerCallId??callId,call_id:callId,tool_name:canonical,...scheduledCall.request.parentCallId?{"tool.parent_call_id":scheduledCall.request.parentCallId}:{},...scheduledCall.request.source?{"tool.source":scheduledCall.request.source}:{}},scheduledCall.tool.description,scheduledCall.request.prompt_id);this.toolSpans.set(callId,toolSpan)}try{await runInToolSpanContext(toolSpan,()=>this._executeToolCallBody(scheduledCall,signal,toolSpan))}catch(error3){const errorMessage=error3 instanceof Error?error3.message:String(error3);setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,errorMessage);this.setStatusInternal(callId,"error",createErrorResponse(scheduledCall.request,error3 instanceof Error?error3:new Error(errorMessage),"unhandled_exception",this.toolCalls.find(call=>call.request.callId===callId)?.status==="executing"?"error":"not_started"))}finally{this.finalizeToolSpan(callId);this.memoryMonitor?.scheduleCheck()}}async runPreToolUse(reqInfo,tool,batchState,signal){const messageBus=this.config.getMessageBus();if(this.config.getDisableAllHooks()||!messageBus)return void 0;const{callId}=reqInfo;const canonicalName=canonicalToolName(reqInfo.name);const toolInput=structuredClone(reqInfo.args);for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=generateToolUseId();this.preToolUseIds.set(callId,toolUseId);this.preToolUseSessionHookIds.set(callId,this.sessionPreToolUseHookIds(callId,canonicalName));const toolSpan=this.openToolSpan(reqInfo,tool,batchState);const result=await runInToolSpanContext(toolSpan,()=>runInRequestGoalContext(reqInfo,()=>this.withHookSpan({hookEvent:"PreToolUse",toolName:canonicalName,toolUseId},()=>firePreToolUseHook(messageBus,canonicalName,toolInput,toolUseId,this.config.getApprovalMode(),signal,callId,this.hookOwners.get(callId)),r=>r.hookError?{success:false,error:r.hookError,shouldProceed:true}:{success:true,shouldProceed:r.shouldProceed,blockType:r.shouldProceed?void 0:r.blockType,hasAdditionalContext:!!r.additionalContext})));if(result.additionalContext){this.preToolUseContexts.set(callId,result.additionalContext)}if(signal.aborted)return void 0;const fixedPolicy=reqInfo.executionOrigin?.kind==="fixed_policy";let blockReason;if(!result.shouldProceed&&(result.blockType!=="ask"||fixedPolicy||!this.canPromptForPreToolUseAsk())){blockReason=result.blockReason||"Tool execution blocked by hook"}else if(fixedPolicy&&result.updatedInput){blockReason="PreToolUse updatedInput is not supported for policy-owned tool calls, which skip the permission flow; the tool was not run."}if(blockReason){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);this.finalizeToolSpan(callId);return{status:"error",request:reqInfo,tool,response:createErrorResponse(reqInfo,new Error(blockReason),"execution_denied","not_started"),durationMs:0}}if(!result.shouldProceed){this.preToolUseAsks.set(callId,result.blockReason||`A PreToolUse hook requested confirmation before running ${reqInfo.name}.`)}if(result.updatedInput){reqInfo.args=result.updatedInput;this.hookReplacedInputCallIds.add(callId)}return void 0}rebuildWithPermissionRequestInput(reqInfo,tool,args,toolSpan){const{callId}=reqInfo;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool,args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){this.setStatusInternal(callId,"error",createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,policyGate.message);this.finalizeToolSpan(callId);return void 0}if(!this.setArgsInternal(callId,policyGate.args))return void 0;this.hookReplacedInputCallIds.add(callId);return this.toolCalls.find(call=>call.request.callId===callId&&call.status==="validating")}sessionPreToolUseHookIds(callId,toolName){const sessionId=this.hookOwners.get(callId)?.sessionId??this.config.getSessionId();return new Set(this.config.getHookSystem?.()?.getSessionHooksManager?.().getMatchingHooks(sessionId,"PreToolUse",toolName).map(entry=>entry.hookId)??[])}canPromptForPreToolUseAsk(){const isNonInteractive=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.getInputFormat()!=="stream-json";if(isNonInteractive){return false}if(this.config.getShouldAvoidPermissionPrompts?.()){return false}return true}safelyAddToolArgumentsAttributes(span,argumentsValue){try{addToolArgumentsAttributes(this.config,span,argumentsValue)}catch(error3){debugLogger44.warn("Failed to add tool arguments span attribute:",error3)}}safelyAddToolCallResultAttributes(span,result){try{addToolCallResultAttributes(this.config,span,result)}catch(error3){debugLogger44.warn("Failed to add tool result span attribute:",error3)}}async _executeToolCallBody(scheduledCall,signal,span){const{callId,name:toolName}=scheduledCall.request;const canonicalName=canonicalToolName(toolName);const invocation=scheduledCall.invocation;const toolInput=scheduledCall.request.args;for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=this.preToolUseIds.get(callId)??generateToolUseId();const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();let producerObserved=false;const observeSyntheticProducer=__name(response=>{try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;observeToolResultBoundary({stage:"producer",sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,artifacts:[toolResultBoundaryArtifact(response.persistedOutputFiles??[],response.artifacts??[])],values:__name(()=>[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[]],"values")})}catch{}},"observeSyntheticProducer");const checkedHookIds=this.preToolUseSessionHookIds.get(callId);if(checkedHookIds&&[...this.sessionPreToolUseHookIds(callId,canonicalName)].some(hookId=>!checkedHookIds.has(hookId))){const errorResponse=createErrorResponse(scheduledCall.request,new Error(`A PreToolUse hook was registered after "${toolName}" was checked, so the call was not run. Call the tool again.`),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);return}const toolInvocationGuard=this.config.getToolInvocationGuard?.();if(toolInvocationGuard){const invocationContext=getInvocationContext();const guardDecision=await evaluateToolInvocationGuard(toolInvocationGuard,{callId,toolName:canonicalName,args:invocation.params,signal,permissionChecked:scheduledCall.request.executionOrigin?.kind!=="fixed_policy",sessionId:this.config.getSessionId(),cwd:this.config.getTargetDir(),...invocationContext?{invocationContext}:{}});if(signal.aborted){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}return}if(!guardDecision.allowed){const errorResponse=createErrorResponse(scheduledCall.request,new Error(guardDecision.reason),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_SPAN_STATUS_INVOCATION_GUARD_DENIED);return}}if(signal.aborted){const currentCall=this.toolCalls.find(call=>call.request.callId===callId);if(currentCall&¤tCall.status!=="success"&¤tCall.status!=="error"&¤tCall.status!=="cancelled"){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}}return}const liveOutputCallback=scheduledCall.tool.canUpdateOutput?outputChunk=>{if(isShellProgressData(outputChunk)){if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}return}const compactOutput=this.compactResultDisplayForInteractiveHistory(outputChunk);if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,liveOutput:compactOutput}:tc);this.notifyToolCallsUpdate()}:void 0;const shellExecutionConfig=this.config.getShellExecutionConfig();const sleepInhibitorHandle=acquireSleepInhibitor(this.config,`Qwen Code is executing tool ${canonicalName}`);let removeParentAbortForward;let executionStatus="not_started";let executionSettled=false;let execSpan;let executionStartedAt;const elapsedExecutionMs=__name(()=>executionStartedAt===void 0?void 0:Math.round(performance.now()-executionStartedAt),"elapsedExecutionMs");let producerToolResult;let appliedOutputBudget;const recordBudgetReduction=__name((before,after,value,source)=>{if(before!==after&&measureToolOutput(after,this.config).chars<measureToolOutput(before,this.config).chars)appliedOutputBudget={value,source}},"recordBudgetReduction");const globalBudgetSource=this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global";let observeProducerOutput=observeSyntheticProducer;try{let promise;const toolExecutionTimeoutMs=Math.min(parsePositiveIntegerEnv(process.env["QWEN_CODE_TOOL_EXECUTION_TIMEOUT_MS"],0),2147483647);let execSignal=signal;let timeoutController;if(toolExecutionTimeoutMs>0){timeoutController=new AbortController;execSignal=timeoutController.signal;if(signal.aborted){timeoutController.abort(signal.reason)}else{const controller=timeoutController;const forwardAbort=__name(()=>controller.abort(signal.reason),"forwardAbort");signal.addEventListener("abort",forwardAbort,{once:true});removeParentAbortForward=__name(()=>signal.removeEventListener("abort",forwardAbort),"removeParentAbortForward")}}const inheritedTodoWorkChainId=todoWorkChainContext.getStore();const todoWorkChainId=this.config.getActiveTodoWorkChainOwner?.(scheduledCall.request.prompt_id,inheritedTodoWorkChainId)??inheritedTodoWorkChainId??scheduledCall.request.prompt_id;if(invocation instanceof ShellToolInvocation){const setPidCallback=__name(pid=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,pid}:tc);this.notifyToolCallsUpdate()},"setPidCallback");const setPromoteAbortControllerCallback=__name(ac=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,promoteAbortController:ac}:tc);this.notifyToolCallsUpdate()},"setPromoteAbortControllerCallback");const canPromoteForegroundShell=__name(()=>{const promotableShells=this.toolCalls.filter(tc=>tc.status==="executing"&&tc.request.name===ToolNames.SHELL&&tc.promoteAbortController!==void 0);return promotableShells.length===1&&promotableShells[0]?.request.callId===callId},"canPromoteForegroundShell");this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger44.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig,setPidCallback,setPromoteAbortControllerCallback,canPromoteForegroundShell)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}else{this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger44.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}let toolResult;let schedulerTimeoutResultSelected=false;let schedulerTimeoutWon=false;if(timeoutController){let timeoutTimer;try{toolResult=await new Promise((resolve34,reject)=>{timeoutTimer=setTimeout(()=>{schedulerTimeoutResultSelected=true;schedulerTimeoutWon=!signal.aborted;debugLogger44.warn(`Tool ${canonicalName} (${callId}) timed out after ${toolExecutionTimeoutMs}ms \u2014 aborting`);timeoutController?.abort(new DOMException(`Tool execution timed out after ${toolExecutionTimeoutMs}ms`,"TimeoutError"));resolve34(createToolTimeoutResult(toolExecutionTimeoutMs))},toolExecutionTimeoutMs);timeoutTimer.unref?.();promise.then(resolve34,reject)})}finally{if(timeoutTimer)clearTimeout(timeoutTimer);removeParentAbortForward?.()}}else{toolResult=await promise}producerToolResult=toolResult;observeProducerOutput=__name((response,replacement=false)=>{const rawSize=replacement||producerToolResult?.rawOutputSize===null||producerToolResult?.error!==void 0?void 0:producerToolResult?.rawOutputSize??measureToolOutput(producerToolResult?.llmContent??"",this.config);const processedChars=measureToolOutput(response.responseParts,this.config).chars;const budgetReduced=!replacement&&appliedOutputBudget!==void 0;response.responseParts=attachToolOutputProvenance(response.responseParts,{callId,toolName:getModelFacingToolName(scheduledCall.request),promptId:scheduledCall.request.prompt_id,toolType:scheduledCall.tool instanceof DiscoveredMCPTool?"mcp":"native",rawSize,truncated:!replacement&&producerToolResult?.truncatedByProducer===true?true:budgetReduced?true:rawSize===void 0?void 0:processedChars<rawSize.chars,budget:budgetReduced?appliedOutputBudget?.value:void 0,budgetSource:budgetReduced?appliedOutputBudget?.source:void 0});try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;let producerInputValues;const getProducerInputValues=__name(()=>producerInputValues??=[...toolResultPartDiagnosticValues(producerToolResult?.llmContent),...shellResultText(producerToolResult?.returnDisplay)!==void 0?[{representation:"display",value:shellResultText(producerToolResult?.returnDisplay)}]:[]],"getProducerInputValues");let producerOutputValues;const getProducerOutputValues=__name(()=>producerOutputValues??=[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[],...typeof response.visionBridgeNotice==="string"?[{representation:"display",value:response.visionBridgeNotice}]:[]],"getProducerOutputValues");const inputArtifact=toolResultBoundaryArtifact(producerToolResult?.persistedOutputFiles,producerToolResult?.artifacts);const outputArtifact=toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts);let mutated;const isMutated=__name(()=>mutated??=producerToolResult==null||!producerContentEqual(getModelFacingToolName(scheduledCall.request),callId,producerToolResult.llmContent,response.responseParts)||!isDeepStrictEqual3(producerToolResult.returnDisplay,response.resultDisplay)||!isDeepStrictEqual3(inputArtifact,outputArtifact)||typeof response.visionBridgeNotice==="string","isMutated");const observation={sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,mutated:isMutated};observeToolResultBoundary({...observation,stage:"producer_input",artifacts:[inputArtifact],values:getProducerInputValues});observeToolResultBoundary({...observation,stage:"producer_output",artifacts:[outputArtifact],values:getProducerOutputValues})}catch{}},"observeProducerOutput");const isTimeout=toolResult.error?.type==="execution_timeout"&&(!schedulerTimeoutResultSelected||schedulerTimeoutWon);const parentAbortedAtExecutionSettle=signal.aborted;const aborted3=parentAbortedAtExecutionSettle&&!isTimeout;const executionErrorType=toolResult.error?toolResult.error.type??(scheduledCall.tool instanceof DiscoveredMCPTool?"mcp_tool_error":"unknown"):void 0;executionStatus=aborted3?"cancelled":toolResult.error?"error":"success";executionSettled=true;try{this.schedulerOptions.onToolExecutionSettled?.(callId,executionStatus,elapsedExecutionMs()??0)}catch(error3){debugLogger44.warn("Tool lifecycle end observer failed:",error3)}if(execSpan){const completedExecSpan=execSpan;execSpan=void 0;endToolExecutionSpan(completedExecSpan,{success:executionStatus==="success",error:aborted3?TOOL_SPAN_STATUS_TOOL_CANCELLED:isTimeout?TOOL_SPAN_STATUS_TOOL_TIMEOUT:toolResult.error?TOOL_SPAN_STATUS_TOOL_ERROR:void 0,cancelled:aborted3,executionStatus,errorType:executionErrorType})}if(aborted3){let cancelMessage=TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:true},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,cancelMessage,true,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){cancelMessage+=`
|
|
555
|
+
Tool: ${details.toolName}`,renderPromptAsPlainText:true,hideAlwaysAllow:true,onConfirm:details.onConfirm};default:return details}}__name(withPreToolUseAskReason,"withPreToolUseAskReason");function isConcurrencySafe(call,hookReplacedInput){return isToolCallConcurrencySafe(call.request.name,call.tool.kind,call.request.args,hookReplacedInput?void 0:call.request.source)}__name(isConcurrencySafe,"isConcurrencySafe");function partitionByConcurrencySafety(items,isSafe){return items.reduce((batches,item)=>{const safe=isSafe(item);const lastBatch=batches[batches.length-1];if(safe&&lastBatch?.concurrent){lastBatch.calls.push(item)}else{batches.push({concurrent:safe,calls:[item]})}return batches},[])}__name(partitionByConcurrencySafety,"partitionByConcurrencySafety");function partitionToolCalls(calls,hookReplacedInputCallIds){return partitionByConcurrencySafety(calls,call=>isConcurrencySafe(call,hookReplacedInputCallIds.has(call.request.callId)))}__name(partitionToolCalls,"partitionToolCalls");function producerInputDropsStructuredContent(input){if(input===null||input===void 0||typeof input==="string"){return false}const contentToProcess=Array.isArray(input)&&input.length===1?input[0]:input;if(typeof contentToProcess==="string")return false;const hasOnlyKeys2=__name((part,...keys)=>Object.entries(part).every(([key,value])=>value===void 0||keys.includes(key)),"hasOnlyKeys");if(Array.isArray(contentToProcess)){return contentToProcess.some(part=>{if(typeof part==="string")return false;if(part.text!==void 0)return!hasOnlyKeys2(part,"text");if(part.inlineData!==void 0){return!hasOnlyKeys2(part,"inlineData")}if(part.fileData!==void 0)return!hasOnlyKeys2(part,"fileData");return true})}if(contentToProcess.functionResponse!==void 0){return Boolean(contentToProcess.functionResponse.response?.["content"])}if(contentToProcess.inlineData!==void 0||contentToProcess.fileData!==void 0){return!hasOnlyKeys2(contentToProcess,"inlineData","fileData")}if(contentToProcess.text!==void 0){return!hasOnlyKeys2(contentToProcess,"text")}return true}__name(producerInputDropsStructuredContent,"producerInputDropsStructuredContent");function producerContentEqual(toolName,callId,input,output){if(producerInputDropsStructuredContent(input))return false;return isDeepStrictEqual3(convertToFunctionResponseParts(toolName,callId,input??""),Array.isArray(output)?output.map(part=>typeof part==="string"?part:Object.fromEntries(Object.entries(part))):output)}__name(producerContentEqual,"producerContentEqual");var CoreToolScheduler=class _CoreToolScheduler{static{__name(this,"CoreToolScheduler")}schedulerOptions;get toolRegistry(){return this.config.getToolRegistry()}toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;invocationReleases=new Map;onToolCallsUpdate;getPreferredEditor;config;onEditorClose;chatRecordingService;onToolResultFullTurnModel;shouldObserveProducer;hasSkillToolOverride;isToolExecutionAllowed;isFinalizingToolCalls=false;postToolBatchEnabledForBatch=false;postToolBatchSpanCallId;postToolBatchConfigWarned=false;isScheduling=false;validationRetryCounts=new Map;autoModeFallbackCallIds=new Set;toolSpans=new Map;blockedSpans=new Map;callIdToBatch=new Map;callIdToPostToolBatchSignal=new Map;preToolUseIds=new Map;preToolUseAsks=new Map;preToolUseSessionHookIds=new Map;hookReplacedInputCallIds=new Set;preToolUseContexts=new Map;nestedHookContexts=new Map;failureContextsForParent=new Map;hookContextSink;askUserQuestionResponseClaims=new Set;runtimeContentGeneratorViews=new Map;hookOwners=new Map;requestQueue=[];nestedToolScheduler;nestedToolCalls=[];nestedSequence=0;nestedFlushScheduled=false;nestedQueue=[];nestedResolvers=new Map;constructor(options2){this.schedulerOptions=options2;this.config=options2.config;this.outputUpdateHandler=options2.outputUpdateHandler;this.onAllToolCallsComplete=options2.onAllToolCallsComplete;this.onToolCallsUpdate=options2.onToolCallsUpdate;this.getPreferredEditor=options2.getPreferredEditor;this.onEditorClose=options2.onEditorClose;this.chatRecordingService=options2.chatRecordingService;this.onToolResultFullTurnModel=options2.onToolResultFullTurnModel;this.shouldObserveProducer=options2.shouldObserveProducer??(()=>true);this.hasSkillToolOverride=options2.hasSkillTool;this.isToolExecutionAllowed=options2.isToolExecutionAllowed}getOrCreateNestedToolScheduler(){if(this.nestedToolScheduler)return this.nestedToolScheduler;this.nestedToolScheduler=new _CoreToolScheduler({...this.schedulerOptions,modToolCheck:void 0,onAllToolCallsComplete:__name(async calls=>{for(const call of calls){const resolver=this.nestedResolvers.get(call.request.callId);if(!resolver)continue;this.nestedResolvers.delete(call.request.callId);try{resolver.onResult?.(call.response)}catch(error3){resolver.reject(error3);continue}if(call.status==="success"){const content=extractCodeModeImageContent(call.response.responseParts);resolver.resolve({callId:call.request.callId,name:call.request.name,status:"success",output:extractCodeModeToolOutput(call.response.responseParts),...content?{content}:{}})}else{resolver.reject(call.response.error??new Error(extractCodeModeToolOutput(call.response.responseParts)||`Tool ${call.request.name} failed.`))}}},"onAllToolCallsComplete"),onToolCallsUpdate:__name(calls=>{this.nestedToolCalls=calls;this.notifyToolCallsUpdate()},"onToolCallsUpdate")});this.nestedToolScheduler.hookContextSink=(request,context2)=>{const parentCallId=request.parentCallId;if(!parentCallId||!this.toolCalls.some(call=>call.request.callId===parentCallId&&call.status==="executing")){return}const contexts=this.nestedHookContexts.get(parentCallId)??[];contexts.push(context2);this.nestedHookContexts.set(parentCallId,contexts)};return this.nestedToolScheduler}dispatchCodeModeTool(name,args,parent,signal,onResult){const allowedNames=parent.codeModeAllowedToolNames?new Set(parent.codeModeAllowedToolNames):void 0;if(!isCodeModeToolCallAllowed(name,"code_mode",allowedNames)){return Promise.reject(new Error(`Tool "${name}" is not callable from exec.`))}const callId=`${parent.callId}:code:${++this.nestedSequence}`;const request={callId,name,args,isClientInitiated:true,prompt_id:parent.prompt_id,response_id:parent.response_id,parentCallId:parent.callId,source:"code_mode",goalContext:parent.goalContext};return new Promise((resolve34,reject)=>{this.nestedQueue.push({request,signal,resolve:resolve34,reject,onResult});if(this.nestedFlushScheduled)return;this.nestedFlushScheduled=true;setTimeout(()=>this.flushNestedQueue(),CODE_MODE_BATCH_WINDOW_MS)})}flushNestedQueue(){this.nestedFlushScheduled=false;const entries=this.nestedQueue.splice(0);if(entries.length===0)return;const active=entries.filter(entry=>!entry.signal.aborted);for(const entry of entries){if(entry.signal.aborted)entry.reject(entry.signal.reason)}if(active.length===0)return;const batchController=new AbortController;const abortBatch=__name(event=>{const aborted3=event.currentTarget;batchController.abort(aborted3.reason)},"abortBatch");for(const entry of active){entry.signal.addEventListener("abort",abortBatch,{once:true});this.nestedResolvers.set(entry.request.callId,{resolve:entry.resolve,reject:entry.reject,onResult:entry.onResult})}void runWithoutToolCallRuntime(()=>this.getOrCreateNestedToolScheduler().schedule(active.map(entry=>entry.request),batchController.signal)).catch(error3=>{for(const entry of active){this.nestedResolvers.delete(entry.request.callId);entry.reject(error3)}}).finally(()=>{for(const entry of active){entry.signal.removeEventListener("abort",abortBatch)}})}get memoryMonitor(){return this.config.getMemoryPressureMonitor?.()}compactResultDisplayForInteractiveHistory(resultDisplay){return typeof this.config.isInteractive==="function"&&this.config.isInteractive()?compactToolResultDisplayForHistory(resultDisplay):resultDisplay}async processToolResultImages(responseParts,signal,executionOrigin){if(executionOrigin?.kind==="fixed_policy"){return{responseParts}}let modelOverride;const notices=[];let omniProcessed=responseParts;if(this.config.isOmniEnabled?.()){const{processToolResultOmniMedia}=await import("./tool-result-media-RJ5ONO7R.js");omniProcessed=await processToolResultOmniMedia(responseParts,this.config,signal)}const processedParts=await bridgeToolResultImages({config:this.config,responseParts:omniProcessed,signal,onFullTurnModel:__name(model=>{if(!this.onToolResultFullTurnModel?.(model))return false;modelOverride=model;return true},"onFullTurnModel"),onVisionBridgeNotice:__name(notice=>notices.push(notice),"onVisionBridgeNotice")});return{responseParts:processedParts,...modelOverride!==void 0?{modelOverride}:{},...notices.length>0?{visionBridgeNotice:notices.join("\n")}:{}}}setStatusInternal(targetCallId,newStatus,auxiliaryData,executionStatus){this.toolCalls=this.toolCalls.map(currentCall=>{if(currentCall.request.callId!==targetCallId||currentCall.status==="success"||currentCall.status==="error"||currentCall.status==="cancelled"){return currentCall}const existingStartTime=currentCall.startTime;const toolInstance=currentCall.tool;const invocation=currentCall.invocation;if(invocation?.release&&(newStatus==="success"||newStatus==="error"||newStatus==="cancelled")){this.invocationReleases.set(targetCallId,Promise.resolve().then(()=>invocation.release()).catch(error3=>{debugLogger44.warn("Tool invocation resource cleanup failed:",error3)}))}const outcome=currentCall.outcome;switch(newStatus){case"success":{this.clearRetryCountsForTool(currentCall.request.name);const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,tool:toolInstance,invocation,status:"success",response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"error":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,status:"error",tool:toolInstance,invocation,response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"awaiting_approval":return{request:currentCall.request,tool:toolInstance,status:"awaiting_approval",confirmationDetails:auxiliaryData,startTime:existingStartTime,outcome,invocation};case"scheduled":return{request:currentCall.request,tool:toolInstance,status:"scheduled",startTime:existingStartTime,outcome,invocation};case"cancelled":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;let resultDisplay=void 0;if(currentCall.status==="awaiting_approval"){const waitingCall=currentCall;if(waitingCall.confirmationDetails.type==="edit"){resultDisplay={fileDiff:waitingCall.confirmationDetails.fileDiff,fileName:waitingCall.confirmationDetails.fileName,filePath:waitingCall.confirmationDetails.filePath,originalContent:waitingCall.confirmationDetails.originalContent,newContent:waitingCall.confirmationDetails.newContent}}else if(waitingCall.confirmationDetails.type==="plan"){resultDisplay={type:"plan_summary",message:"Plan was rejected. Remaining in plan mode.",plan:waitingCall.confirmationDetails.plan,rejected:true}}}else if(currentCall.status==="executing"){const executingCall=currentCall;if(executingCall.liveOutput!==void 0){resultDisplay=executingCall.liveOutput}}const preservedResultDisplay=this.compactResultDisplayForInteractiveHistory(resultDisplay);const response=isToolCallResponseInfo(auxiliaryData)?{...auxiliaryData,executionStatus:auxiliaryData.executionStatus??executionStatus??"not_started",resultDisplay:auxiliaryData.resultDisplay??preservedResultDisplay}:{...createCancelledResponse(currentCall.request,String(auxiliaryData),executionStatus??"not_started"),resultDisplay:preservedResultDisplay};return{request:currentCall.request,tool:toolInstance,invocation,status:"cancelled",response,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"validating":return{request:currentCall.request,tool:toolInstance,status:"validating",startTime:existingStartTime,outcome,invocation};case"executing":return{request:currentCall.request,tool:toolInstance,status:"executing",startTime:existingStartTime,executionStartTime:Date.now(),outcome,invocation};default:{const exhaustiveCheck=newStatus;return exhaustiveCheck}}});this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger44.warn(`setStatusInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}setArgsInternal(targetCallId,args){let invocationError;let argsUpdated=false;this.toolCalls=this.toolCalls.map(call=>{if(call.request.callId!==targetCallId||call.status==="success"||call.status==="error"||call.status==="cancelled"){return call}const invocationOrError=runInRequestGoalContext(call.request,()=>this.buildInvocation(call.tool,args,targetCallId,call.request.prompt_id,call.request.executionOrigin?.kind==="client"));if(invocationOrError instanceof Error){invocationError=invocationOrError;const response=createErrorResponse(call.request,invocationOrError,"invalid_tool_params","not_started");return{request:{...call.request,args},status:"error",tool:call.tool,response}}argsUpdated=true;return{...call,request:{...call.request,args},invocation:invocationOrError}});if(invocationError){this.finalizeBlockedSpan(targetCallId,"error","system");const toolSpan=this.toolSpans.get(targetCallId);if(toolSpan){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,invocationError.message)}this.finalizeToolSpan(targetCallId);this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger44.warn(`setArgsInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)});return false}return argsUpdated}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}cancelPreExecutionIfAborted(callId,signal,toolSpan=this.toolSpans.get(callId)){if(!signal.aborted)return false;this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(callId,"aborted","system");if(toolSpan){setToolSpanCancelled(toolSpan)}this.finalizeToolSpan(callId);return true}finalizeToolSpan(callId,force=false){this.preToolUseIds.delete(callId);this.preToolUseAsks.delete(callId);this.preToolUseSessionHookIds.delete(callId);this.hookReplacedInputCallIds.delete(callId);this.autoModeFallbackCallIds.delete(callId);this.runtimeContentGeneratorViews.delete(callId);if(callId===this.postToolBatchSpanCallId&&!force)return;const span=this.toolSpans.get(callId);if(!span)return;this.toolSpans.delete(callId);endToolSpan(span);this.releaseBatchListenerIfDrained(callId)}finalizeBlockedSpan(callId,decision,source){const span=this.blockedSpans.get(callId);if(!span)return;this.blockedSpans.delete(callId);endToolBlockedOnUserSpan(span,{decision,source})}releaseBatchListenerIfDrained(callId){const batch=this.callIdToBatch.get(callId);if(!batch)return;this.callIdToBatch.delete(callId);batch.callIds.delete(callId);this.releaseIdleBatchListener(batch)}releaseIdleBatchListener(batch){if(batch.preparing)return;for(const id of batch.callIds){if(this.toolSpans.has(id)||this.blockedSpans.has(id))return}batch.signal.removeEventListener("abort",batch.onAbort)}getBlockedSource(){return this.config.getIdeMode?.()?"ide":"cli"}drainSpansForBatch(callIds){const ids=Array.from(callIds);setTimeout(()=>{for(const callId of ids){try{const call=this.toolCalls.find(c=>c.request.callId===callId);if(call?.status!=="awaiting_approval"&&call?.status!=="scheduled"){continue}this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");if(this.blockedSpans.has(callId)){this.finalizeBlockedSpan(callId,"aborted","system")}const span=this.toolSpans.get(callId);if(span){setToolSpanCancelled(span);this.finalizeToolSpan(callId,true)}this.callIdToPostToolBatchSignal.delete(callId);this.autoModeFallbackCallIds.delete(callId)}catch(e){debugLogger44.warn(`drainSpansForBatch: failed to drain ${callId}: ${e instanceof Error?e.message:String(e)}`)}}},0)}postToolUseFailureEndMeta=__name(r=>r.hookError?{success:false,error:r.hookError}:{success:true,hasAdditionalContext:!!r.additionalContext},"postToolUseFailureEndMeta");openToolSpan(reqInfo,tool,batchState){const existing=this.toolSpans.get(reqInfo.callId);if(existing)return existing;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=startToolSpan(canonicalName,{"tool.call_id":reqInfo.callId,"gen_ai.tool.call.id":reqInfo.providerCallId??reqInfo.callId,call_id:reqInfo.callId,tool_name:canonicalName,...reqInfo.parentCallId?{"tool.parent_call_id":reqInfo.parentCallId}:{},...reqInfo.source?{"tool.source":reqInfo.source}:{}},tool.description,reqInfo.prompt_id);this.toolSpans.set(reqInfo.callId,toolSpan);batchState.callIds.add(reqInfo.callId);this.callIdToBatch.set(reqInfo.callId,batchState);return toolSpan}async withHookSpan(opts,fn,toEndMeta){const hookSpan=startHookSpan(opts);let endMeta={success:false};try{const result=await fn();endMeta=toEndMeta(result);return result}catch(err){endMeta={success:false,error:err instanceof Error?err.message:String(err)};throw err}finally{endHookSpan(hookSpan,endMeta)}}buildInvocation(tool,args,callId,promptId,notifyOnCompletion=false){try{const invocation=tool.build(structuredClone(args));const notificationAware=invocation;notificationAware.setCompletionNotificationEnabled?.(notifyOnCompletion);if(callId){const maybeAware=invocation;if(typeof maybeAware.setCallId==="function"){maybeAware.setCallId(callId)}}if(promptId){const maybeAware=invocation;if(typeof maybeAware.setPromptId==="function"){maybeAware.setPromptId(promptId)}}return invocation}catch(e){if(e instanceof Error){return e}return new Error(String(e))}}async getToolNotFoundMessage(unknownToolName,topN=3){const skillTool=await this.toolRegistry.ensureTool(ToolNames.SKILL);if(skillTool&&"getAvailableSkillNames"in skillTool){const availableSkillNames=skillTool.getAvailableSkillNames();if(availableSkillNames.includes(unknownToolName)){return`"${unknownToolName}" is a skill name, not a tool name. To use this skill, invoke the "${ToolNames.SKILL}" tool with parameter: skill: "${unknownToolName}"`}}const mcpMessage=this.getMcpToolUnavailableMessage(unknownToolName);if(mcpMessage){return mcpMessage}const optInToolMessage=await getOptInToolNotFoundMessage(this.config,unknownToolName,async canonicalName=>Boolean(await this.toolRegistry.ensureTool(canonicalName)));if(optInToolMessage){return optInToolMessage}const suggestion=this.getToolSuggestion(unknownToolName,topN);return`Tool "${unknownToolName}" not found in registry. Tools must use the exact names that are registered.${suggestion}`}getMcpToolUnavailableMessage(unknownToolName){if(!unknownToolName.startsWith("mcp__")){return null}const prefixOf=__name(server=>sanitizeToolNameForProvider(`mcp__${server}__`),"prefixOf");const byPrefixLengthDesc=__name((a,b2)=>prefixOf(b2).length-prefixOf(a).length,"byPrefixLengthDesc");const candidates=Array.from(new Set([...this.config.getMcpServerNames?.()??[],...this.config.getRecentlyRemovedMcpServers?.()??[]])).sort(byPrefixLengthDesc);const serverHit=candidates.find(s3=>unknownToolName.startsWith(prefixOf(s3)));if(!serverHit){return`Tool "${unknownToolName}" not found: no MCP server providing it is currently configured. If you recently removed or renamed an MCP server, its tools are no longer available.`}switch(this.config.getMcpServerUnavailableReason?.(serverHit)){case"removed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" was removed during this session, so its tools were unloaded. Re-add it to your settings to use this tool again.`;case"not_allowed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is not in the allow-list (mcp.allowed / --allowed-mcp-server-names), so its tools are not loaded. Add it to mcp.allowed to use this tool.`;case"excluded":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is excluded (mcp.excluded), so its tools are not loaded. Remove it from mcp.excluded to use this tool.`;case"pending_approval":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is awaiting approval, so its tools are not loaded. Approve it (run /mcp) to use this tool.`;default:return`Tool "${unknownToolName}" not found on MCP server "${serverHit}". The server may be disconnected, still starting up, or the tool was renamed.`}}getToolSuggestion(unknownToolName,topN=3){const allToolNames=this.toolRegistry.getAllToolNames().filter(name=>this.toolRegistry.isToolDeclared?.(name)??true);const matches=allToolNames.map(toolName=>({name:toolName,distance:import_fast_levenshtein.default.get(unknownToolName,toolName)}));matches.sort((a,b2)=>{const aIsPrefix=unknownToolName.startsWith(a.name);const bIsPrefix=unknownToolName.startsWith(b2.name);if(aIsPrefix!==bIsPrefix){return aIsPrefix?-1:1}return a.distance-b2.distance});const topNResults=matches.slice(0,topN);if(topNResults.length===0){return""}const suggestedNames=topNResults.map(match=>`"${match.name}"`).join(", ");if(topNResults.length>1){return` Did you mean one of: ${suggestedNames}?`}else{return` Did you mean ${suggestedNames}?`}}async resolveToolCallBridgeRequest(request,signal){if(signal.aborted||canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const permissionManager=this.config.getPermissionManager?.();if(permissionManager){let bridgeEnabled;try{bridgeEnabled=await permissionManager.isToolEnabled(ToolNames.TOOL_CALL)}catch(error3){if(signal.aborted){return request}const message=error3 instanceof Error?error3.message:String(error3);return{...request,bridgeResolutionError:{error:new Error(`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${message}`),type:"unhandled_exception"}}}if(signal.aborted||!bridgeEnabled){return request}}else if((this.config.getPermissionsDeny?.()??[]).some(name=>canonicalToolName(name).toLowerCase().trim()===ToolNames.TOOL_CALL)){return request}const resolution=await runInRequestGoalContext(request,()=>resolveDeferredToolCall(this.toolRegistry,request.args,{maxSubagentDepth:this.config.getMaxSubagentDepth()}));if("error"in resolution){return{...request,bridgeResolutionError:{error:resolution.error,type:resolution.errorType}}}if(this.isToolExecutionAllowed&&!this.isToolExecutionAllowed(resolution.tool.name)){return{...request,bridgeResolutionError:{error:new Error(`Tool "${resolution.tool.name}" is not permitted by this agent's tool policy (execution allowlist or disallowedTools blocklist).`),type:"execution_denied"}}}return{...request,name:resolution.tool.name,args:resolution.arguments,modelFacingName:request.name,modelFacingArgs:request.args}}schedule(request,signal,runtimeView){const owner=captureHookExecutionOwner(this.config);if(this.isRunning()||this.isScheduling){if(signal.aborted){return Promise.reject(new Error("Tool call cancelled while in queue."))}return new Promise((resolve34,reject)=>{const abortHandler=__name(()=>{const index=this.requestQueue.findIndex(item=>item.request===request);if(index>-1){this.requestQueue.splice(index,1);reject(new Error("Tool call cancelled while in queue."))}},"abortHandler");signal.addEventListener("abort",abortHandler,{once:true});this.requestQueue.push({request,signal,runtimeView,owner,resolve:__name(()=>{signal.removeEventListener("abort",abortHandler);resolve34()},"resolve"),reject:__name(reason=>{signal.removeEventListener("abort",abortHandler);reject(reason)},"reject")})})}return this.scheduleWithOwner(request,signal,runtimeView,owner)}scheduleWithOwner(request,signal,runtimeView,owner){const items=Array.isArray(request)?request:[request];for(const item of items)this.hookOwners.set(item.callId,owner);return runWithHookExecutionOwner(owner,()=>this._schedule(request,signal,runtimeView)).catch(error3=>{for(const item of items){this.hookOwners.delete(item.callId);this.preToolUseContexts.delete(item.callId);this.nestedHookContexts.delete(item.callId);this.failureContextsForParent.delete(item.callId)}throw error3})}drainRequestQueueIfIdle(){if(this.requestQueue.length===0||this.isScheduling||this.isRunning()){return}const next=this.requestQueue.shift();this.scheduleWithOwner(next.request,next.signal,next.runtimeView,next.owner).then(next.resolve).catch(next.reject)}clearRetryCountsForTool(toolName){const prefix=`${toolName}:`;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(prefix)){this.validationRetryCounts.delete(key)}}}recordRetryableToolError(toolName,errorMessage){const errorKey=`${toolName}:${errorMessage}`;const count=(this.validationRetryCounts.get(errorKey)??0)+1;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(`${toolName}:`)&&key!==errorKey){this.validationRetryCounts.delete(key)}}this.validationRetryCounts.set(errorKey,count);return count}async _schedule(request,signal,runtimeView){if(runtimeView){const items=Array.isArray(request)?request:[request];for(const item of items){this.runtimeContentGeneratorViews.set(item.callId,runtimeView)}try{return await runWithRuntimeContentGenerator(runtimeView,()=>this._schedule(request,signal))}catch(error3){for(const item of items){this.runtimeContentGeneratorViews.delete(item.callId)}throw error3}}this.isScheduling=true;let preparedBatch;try{if(this.isRunning()){throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).")}const requestsToProcess=await Promise.all(dedupeRequestsByCallId(Array.isArray(request)?request:[request]).map(item=>this.resolveToolCallBridgeRequest({...item,args:structuredClone(item.args)},signal)));const planModeEntryBoundaryIndex=findPlanModeEntryBatchBoundaryIndex(requestsToProcess.map(item=>canonicalToolName(item.name)));if(this.validationRetryCounts.size>0){const currentToolNames=new Set(requestsToProcess.map(r=>r.name));for(const key of[...this.validationRetryCounts.keys()]){const sep20=key.indexOf(":");const toolName=sep20===-1?key:key.slice(0,sep20);if(!currentToolNames.has(toolName)){this.validationRetryCounts.delete(key)}}}const newToolCalls=[];const retryErrorsRecordedInBatch=new Map;const recordBatchRetryableToolError=__name((toolName,errorMessage)=>{const key=`${toolName}:${errorMessage}`;const existingCount=retryErrorsRecordedInBatch.get(key);if(existingCount!==void 0){for(const trackedKey of this.validationRetryCounts.keys()){if(trackedKey.startsWith(`${toolName}:`)){this.validationRetryCounts.delete(trackedKey)}}this.validationRetryCounts.set(key,existingCount);return existingCount}const count=this.recordRetryableToolError(toolName,errorMessage);retryErrorsRecordedInBatch.set(key,count);return count},"recordBatchRetryableToolError");const batchState={signal,onAbort:__name(()=>this.drainSpansForBatch(batchState.callIds),"onAbort"),callIds:new Set,preparing:true};preparedBatch=batchState;signal.addEventListener("abort",batchState.onAbort,{once:true});for(const[requestIndex,reqInfo]of requestsToProcess.entries()){let resolvedTool;let resolvedInvocation;const recordPrevalidationCancellation=__name(()=>{if(!signal.aborted)return false;newToolCalls.push({status:"cancelled",request:reqInfo,response:createCancelledResponse(reqInfo,"Tool call cancelled before execution.","not_started"),...resolvedTool?{tool:resolvedTool}:{},...resolvedInvocation?{invocation:resolvedInvocation}:{},durationMs:0});return true},"recordPrevalidationCancellation");try{if(recordPrevalidationCancellation())continue;if(planModeEntryBoundaryIndex!==void 0&&requestIndex!==planModeEntryBoundaryIndex){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE),"execution_denied","not_started"),durationMs:0});continue}if(reqInfo.bridgeResolutionError){let bridgeError=reqInfo.bridgeResolutionError.error;if(reqInfo.bridgeResolutionError.type==="invalid_tool_params"){const count=recordBatchRetryableToolError(reqInfo.name,bridgeError.message);if(count>=VALIDATION_RETRY_LOOP_THRESHOLD){bridgeError=new Error(`${bridgeError.message}${RETRY_LOOP_STOP_DIRECTIVE}`)}}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,bridgeError,reqInfo.bridgeResolutionError.type,"not_started"),durationMs:0});continue}const canonicalName=canonicalToolName(reqInfo.name);if(this.config.getToolMode?.()===ToolMode.CodeModeOnly&&reqInfo.executionOrigin?.kind!=="fixed_policy"&&!isCodeModeToolCallAllowed(canonicalName,reqInfo.source??"model")){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(`Tool "${reqInfo.name}" is unavailable on this CodeModeOnly call surface.`),"execution_denied","not_started"),durationMs:0});continue}const pm=this.config.getPermissionManager?.();const toolAliases2=this.config.getToolRegistry?.()?.getPermissionAliases?.(canonicalName);const mcpIdentity=this.config.getToolRegistry?.()?.getMcpToolIdentity?.(canonicalName);const permissionEnabled=pm?await pm.isToolEnabled(canonicalName,toolAliases2,mcpIdentity):true;if(recordPrevalidationCancellation())continue;if(pm&&!permissionEnabled){const matchingRule=pm.findMatchingDenyRule({toolName:canonicalName,toolAliases:toolAliases2,mcpIdentity});let permissionErrorMessage;if(matchingRule){permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined. Matching deny rule: "${matchingRule}".`}else if(typeof pm.isToolDisabledByCoreToolsAllowList==="function"&&pm.isToolDisabledByCoreToolsAllowList(canonicalName)){permissionErrorMessage=`"${reqInfo.name}" is not listed in the active core tools allowlist (--core-tools or settings tools.core), so the tool is not available. Add it to the core tools list to re-enable it.`}else{permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}if(!pm){const excludeTools=this.config.getPermissionsDeny?.()??void 0;if(excludeTools&&excludeTools.length>0){const normalizedToolName=canonicalName.toLowerCase().trim();const excludedMatch=excludeTools.find(excludedTool=>excludedTool.toLowerCase().trim()===normalizedToolName);if(excludedMatch){const permissionErrorMessage=`Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}}}const toolInstance=await runInRequestGoalContext(reqInfo,()=>this.toolRegistry.ensureTool(canonicalName));resolvedTool=toolInstance;if(recordPrevalidationCancellation())continue;if(!toolInstance){const errorMessage=await runInRequestGoalContext(reqInfo,()=>this.getToolNotFoundMessage(reqInfo.name));if(recordPrevalidationCancellation())continue;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(errorMessage),"tool_not_registered","not_started"),durationMs:0});continue}if((reqInfo.wasOutputTruncated||reqInfo.hadIncompleteArguments)&&toolInstance.kind==="edit"){const truncated=reqInfo.wasOutputTruncated===true;const rejectionMessage=truncated?TRUNCATION_EDIT_REJECTION:INCOMPLETE_ARGS_EDIT_REJECTION;const count=recordBatchRetryableToolError(reqInfo.name,rejectionMessage);const truncationError=new Error(count>=VALIDATION_RETRY_LOOP_THRESHOLD?`${rejectionMessage}${truncated?TRUNCATION_RETRY_LOOP_DIRECTIVE:INCOMPLETE_ARGS_RETRY_LOOP_DIRECTIVE}`:rejectionMessage);newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,truncationError,truncated?"output_truncated":"invalid_tool_params","not_started"),durationMs:0});continue}const preToolUseTerminal=await this.runPreToolUse(reqInfo,toolInstance,batchState,signal);if(preToolUseTerminal){newToolCalls.push(preToolUseTerminal);continue}if(recordPrevalidationCancellation())continue;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool:toolInstance,args:reqInfo.args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"),durationMs:0});continue}const invocationOrError=runInRequestGoalContext(reqInfo,()=>this.buildInvocation(toolInstance,policyGate.args,reqInfo.callId,reqInfo.prompt_id,reqInfo.executionOrigin?.kind==="client"));if(recordPrevalidationCancellation())continue;if(invocationOrError instanceof Error){const targetMessage=reqInfo.modelFacingName!==void 0?describeBridgedArgumentError(reqInfo.name,invocationOrError.message):invocationOrError.message;const paramGuidance=reqInfo.wasOutputTruncated?TRUNCATION_PARAM_GUIDANCE:reqInfo.hadIncompleteArguments?INCOMPLETE_ARGS_PARAM_GUIDANCE:void 0;const displayError=paramGuidance?new Error(`${targetMessage} ${paramGuidance}`):reqInfo.modelFacingName!==void 0?new Error(targetMessage):invocationOrError;const count=recordBatchRetryableToolError(reqInfo.name,invocationOrError.message);const finalError=count>=VALIDATION_RETRY_LOOP_THRESHOLD?new Error(`${targetMessage}${RETRY_LOOP_STOP_DIRECTIVE}`):displayError;newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,finalError,"invalid_tool_params","not_started"),durationMs:0});continue}resolvedInvocation=invocationOrError;this.clearRetryCountsForTool(reqInfo.name);newToolCalls.push({status:"validating",request:reqInfo,tool:toolInstance,invocation:invocationOrError,startTime:Date.now()})}catch(error3){if(recordPrevalidationCancellation())continue;const normalizedError=error3 instanceof Error?error3:new Error(String(error3));newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,normalizedError,error3?.errorType??"unhandled_exception","not_started"),...resolvedTool?{tool:resolvedTool}:{},durationMs:0})}}for(const toolCall of newToolCalls){const span=this.toolSpans.get(toolCall.request.callId);if(!span||toolCall.status==="validating")continue;if(toolCall.status==="cancelled"){setToolSpanCancelled(span)}else if(toolCall.status==="error"){setToolSpanFailure(span,TOOL_FAILURE_KIND_TOOL_EXCEPTION,toolCall.response.error?.message??"Tool call failed validation.")}this.finalizeToolSpan(toolCall.request.callId)}this.toolCalls=this.toolCalls.concat(newToolCalls);for(const toolCall of newToolCalls){this.callIdToPostToolBatchSignal.set(toolCall.request.callId,signal)}const postToolBatchParentCallId=newToolCalls.findLast(toolCall=>toolCall.status==="validating")?.request.callId;this.postToolBatchEnabledForBatch=false;this.postToolBatchSpanCallId=void 0;try{this.postToolBatchEnabledForBatch=!this.config.getDisableAllHooks()&&(this.config.hasHooksForEvent?.("PostToolBatch")??false);if(this.postToolBatchEnabledForBatch){this.postToolBatchSpanCallId=postToolBatchParentCallId}}catch(configError){this.postToolBatchEnabledForBatch=true;this.postToolBatchSpanCallId=postToolBatchParentCallId;if(!this.postToolBatchConfigWarned){this.postToolBatchConfigWarned=true;debugLogger44.warn("PostToolBatch hook detection failed; deferring span as a precaution:",configError)}}this.notifyToolCallsUpdate();const permissionRequestGrants=new Set;for(const toolCall of newToolCalls){if(toolCall.status!=="validating"){continue}const{request:reqInfo,invocation}=toolCall;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=this.openToolSpan(reqInfo,toolCall.tool,batchState);const preToolUseAsk=this.preToolUseAsks.get(reqInfo.callId);try{if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(reqInfo.executionOrigin?.kind==="fixed_policy"){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let toolParams=invocation.params;const flowResult=await runInRequestGoalContext(reqInfo,()=>evaluatePermissionFlow(this.config,invocation,canonicalName,toolParams,signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const modToolCheck=this.schedulerOptions.modToolCheck;if(modToolCheck){const decision=await runInRequestGoalContext(reqInfo,()=>modToolCheck({tool:canonicalName,input:structuredClone(toolParams),tool_use_id:reqInfo.callId},{decision:flowResult.finalPermission==="default"?"ask":flowResult.finalPermission,...flowResult.denyMessage?{reason:flowResult.denyMessage}:{}},signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(!["allow","ask","deny"].includes(decision.decision)){throw new Error("Invalid Mod tool.check decision.")}if(flowResult.finalPermission!=="deny"){if(decision.decision==="deny"){flowResult.finalPermission="deny";flowResult.denyMessage=decision.reason?.trim()||`Tool "${reqInfo.name}" is denied by a Mod.`}else if(decision.decision==="ask"&&flowResult.finalPermission==="allow"){flowResult.finalPermission="ask"}}}const{defaultPermission,finalPermission,pmForcedAsk,pmCtx,denyMessage,requiresUserInteraction}=flowResult;const approvalMode=this.config.getApprovalMode();const isPlanMode=approvalMode==="plan";const isPlanShellCall=isPlanMode&&(canonicalName===ToolNames.SHELL||canonicalName===ToolNames.MONITOR);const isExitPlanModeTool=canonicalName===ToolNames.EXIT_PLAN_MODE;const isEnterPlanModeTool=canonicalName===ToolNames.ENTER_PLAN_MODE;const forceAutoReviewForAllow=approvalMode==="auto"&&(shouldForceAutoModeReviewForAllow(pmCtx,this.config.getCwd())||shouldClassifyAllShellForAutoMode(canonicalName,this.config));const confirmationPermission=getEffectivePermissionForConfirmation(finalPermission,forceAutoReviewForAllow);if(finalPermission==="allow"&&forceAutoReviewForAllow){debugLogger44.info(`Auto mode: L4 allow overridden by protected-write guard for ${canonicalName}`)}if(isPlanRequiredTeammateAwaitingApproval(this.config)&&finalPermission!=="deny"){const isExplicitPreApprovalTool=isPlanRequiredTeammatePreApprovalAllowedTool(canonicalName,toolParams);const canRunBeforeLeaderApproval=!preToolUseAsk&&isExplicitPreApprovalTool&&(canonicalName===ToolNames.EXIT_PLAN_MODE||canonicalName===ToolNames.TASK_UPDATE||defaultPermission==="allow"&&finalPermission==="allow"&&!forceAutoReviewForAllow);if(canRunBeforeLeaderApproval){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const message=getPlanRequiredTeammatePreApprovalMessage(canonicalName);this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(finalPermission==="deny"){this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(denyMessage??`Tool "${reqInfo.name}" is denied.`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_SPAN_STATUS_PERMISSION_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}let planShellAmbientWorkingDirectory;if(isPlanShellCall){const directory=toolParams["directory"];planShellAmbientWorkingDirectory=typeof directory==="string"&&directory.length>0?void 0:this.config.getTargetDir();invocation.params={...structuredClone(invocation.params),directory:typeof directory==="string"&&directory.length>0?directory:planShellAmbientWorkingDirectory};toolParams=invocation.params}const planShellDecision=isPlanShellCall?await runInRequestGoalContext(reqInfo,()=>evaluatePlanModeShellPolicy({config:this.config,toolName:canonicalName,requestArgs:reqInfo.args,invocationParams:toolParams,permissionContext:pmCtx,ambientWorkingDirectory:planShellAmbientWorkingDirectory,signal})):{classification:"not-applicable"};if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const rejectPlanShell=__name(message=>{this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"),resultDisplay:message});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId)},"rejectPlanShell");if(planShellDecision.classification!=="not-applicable"){const initialPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(initialPlanShellError){rejectPlanShell(initialPlanShellError);continue}}if(planShellDecision.classification==="write"){rejectPlanShell(planShellDecision.writeBlockMessage);continue}const planShellRequiresConfirmation=planShellDecision.classification==="unknown";if(finalPermission==="allow"&&!forceAutoReviewForAllow&&!planShellRequiresConfirmation&&!preToolUseAsk){if(approvalMode==="auto"){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());this.config.setAutoModeDenialState(recordAllow(this.config.getAutoModeDenialState(),actionFingerprint))}this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let autoModeFallback;let autoModeFallbackRequiresHuman=false;if(!requiresUserInteraction&&!preToolUseAsk&&shouldRunAutoModeForCall(approvalMode,canonicalName)){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());const{denialState,fallback}=prepareAutoModeFallback(this.config,actionFingerprint);const llmClient=this.config.getLlmClient?.();const messages=llmClient?.getHistoryTail(MAX_TRANSCRIPT_MESSAGES,false)??[];const trustedUserAnswers=llmClient?.getTrustedUserAnswers?.()??[];const decision=await runInRequestGoalContext(reqInfo,()=>evaluateAutoMode({ctx:pmCtx,pmForcedAsk,toolParams,messages,trustedUserAnswers,config:this.config,signal,skipClassifierReason:fallback.fallback?fallback.reason:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const outcome=applyAutoModeDecision(decision,this.config,denialState,actionFingerprint);if(!this.config.getDisableAllHooks()&&shouldFirePermissionDeniedForAutoMode(decision,outcome)){try{await runInRequestGoalContext(reqInfo,()=>this.config.getHookSystem?.()?.firePermissionDeniedEvent(canonicalName,toolParams,reqInfo.callId,getAutoModePermissionDeniedReason(decision),signal,reqInfo.callId))}catch(hookError){debugLogger44.warn(`PermissionDenied hook failed for tool ${reqInfo.callId}: ${hookError instanceof Error?hookError.message:String(hookError)}`)}}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}switch(outcome.kind){case"approved":this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue;case"blocked":debugLogger44.warn(`Auto mode blocked (${outcome.reason}): tool=${canonicalName}, `+formatDenialStateLog(denialState));this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(outcome.errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,outcome.errorMessage);this.finalizeToolSpan(reqInfo.callId);continue;case"fallback":autoModeFallbackRequiresHuman=outcome.requiresHumanDecision===true;if(outcome.message&&(isDenialFallbackReason(outcome.reason)||outcome.reason==="classifier_unavailable")){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger44.warn(`Auto mode fallback to manual approval (${outcome.reason}): `+formatDenialStateLog(denialState))}else if((outcome.reason==="external_write"||outcome.reason==="external_directory")&&outcome.message){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger44.warn(`Auto mode fallback to manual approval (${outcome.reason}): target outside workspace.`)}break;default:{const _exhaustive=outcome;void _exhaustive}}}const isAskUserQuestionTool=canonicalName===ToolNames.ASK_USER_QUESTION;let confirmationDetails;if(!preToolUseAsk&&!needsConfirmation(planShellRequiresConfirmation?"ask":confirmationPermission,approvalMode,canonicalName,requiresUserInteraction)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled")}else{confirmationDetails=await runInRequestGoalContext(reqInfo,()=>invocation.getConfirmationDetails(signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(autoModeFallback){confirmationDetails=decorateAutoModeFallbackConfirmation(confirmationDetails,autoModeFallback.reason,autoModeFallback.message)}if(planShellDecision.classification!=="not-applicable"){const preDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(preDisplayPlanShellError){rejectPlanShell(preDisplayPlanShellError);continue}}try{confirmationDetails=decoratePlanModeShellConfirmation(planShellDecision,confirmationDetails)}catch{if(planShellDecision.classification==="unknown"){rejectPlanShell(planShellDecision.noApprovalMessage);continue}throw new Error("Unable to prepare shell confirmation.")}const planModeDetails=confirmationDetails;if(preToolUseAsk){confirmationDetails=withPreToolUseAskReason(confirmationDetails,preToolUseAsk)}injectPermissionRulesIfMissing(confirmationDetails,pmCtx);if(planShellDecision.classification==="not-applicable"&&isPlanModeBlocked(isPlanMode,isExitPlanModeTool,isAskUserQuestionTool,planModeDetails,isEnterPlanModeTool)){const isPlanRequiredTeammate=!shouldUsePlanOnlyReminderInSubagentContext()&&!this.config.getSdkMode();const planModeError=new Error(`Tool blocked by plan mode: "${reqInfo.name}" is not a read-only tool. Only read-only tools (read_file, grep_search, glob, web_fetch, etc.) are allowed in plan mode. Do NOT retry this tool. `+(isPlanRequiredTeammate?`Pivot to read-only alternatives to gather the information you need, then call exit_plan_mode with a plan that covers this tool's purpose.`:`Pivot to read-only alternatives to gather equivalent information, then present your plan directly to the caller.`));this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,planModeError,"execution_denied","not_started"),resultDisplay:"Plan mode blocked a non-read-only tool call."});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(!requiresUserInteraction&&!preToolUseAsk&&isAutoEditApproved(approvalMode,confirmationDetails)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const isNonInteractiveDeny=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&(this.config.getInputFormat()!=="stream-json"||autoModeFallbackRequiresHuman);if(isNonInteractiveDeny){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"),approvalRequired:true});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_SPAN_STATUS_NON_INTERACTIVE_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}const preparedConfirmationDetails=confirmationDetails;const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();const permissionRequestGrant=permissionRequestGrants.has(reqInfo.callId);if(hooksEnabled&&messageBus||permissionRequestGrant){const permissionMode=String(this.config.getApprovalMode());const hookResult=permissionRequestGrant?{hasDecision:true,shouldAllow:true}:await runInRequestGoalContext(reqInfo,()=>firePermissionRequestHook(messageBus,canonicalName,reqInfo.args||{},permissionMode,void 0,signal,this.hookOwners.get(reqInfo.callId)));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const allowApplies=hookResult.shouldAllow===true&&!requiresUserInteraction&&!autoModeFallbackRequiresHuman&&(!preToolUseAsk||hookResult.updatedInput!==void 0&&planShellDecision.classification==="not-applicable");if(hookResult.hasDecision&&(!hookResult.shouldAllow||allowApplies)){if(hookResult.shouldAllow){if(planShellDecision.classification!=="not-applicable"){const approval=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal,outcome:"proceed_once",payload:hookResult.updatedInput?{updatedInput:hookResult.updatedInput}:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(approval.outcome==="cancel"){await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}rejectPlanShell(approval.payload?.cancelMessage??planShellDecision.noApprovalMessage);continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,approval.outcome);this.setToolCallOutcome(reqInfo.callId,approval.outcome);this.setStatusInternal(reqInfo.callId,"scheduled");continue}if(hookResult.updatedInput){const rebuilt=this.rebuildWithPermissionRequestInput(reqInfo,toolCall.tool,hookResult.updatedInput,toolSpan);if(rebuilt){permissionRequestGrants.add(reqInfo.callId);newToolCalls.push(rebuilt)}continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("proceed_once"));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"proceed_once");this.setToolCallOutcome(reqInfo.callId,"proceed_once");this.setStatusInternal(reqInfo.callId,"scheduled")}else{const cancelPayload=hookResult.denyMessage?{cancelMessage:hookResult.denyMessage}:void 0;await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("cancel",cancelPayload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"cancel");this.setToolCallOutcome(reqInfo.callId,"cancel");this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(hookResult.denyMessage||`Permission denied by hook for "${reqInfo.name}"`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_SPAN_STATUS_PERMISSION_HOOK_DENIED);this.finalizeToolSpan(reqInfo.callId)}continue}}if(this.config.getShouldAvoidPermissionPrompts?.()){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:`Tool "${reqInfo.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_SPAN_STATUS_BACKGROUND_AGENT_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(planShellDecision.classification!=="not-applicable"){const finalPreDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(finalPreDisplayPlanShellError){rejectPlanShell(finalPreDisplayPlanShellError);continue}}if(confirmationDetails.type!=="edit"||!confirmationDetails.skipIdeDiff){this.openIdeDiffIfEnabled(confirmationDetails,reqInfo.callId,signal)}const originalOnConfirm=confirmationDetails.onConfirm;const invocationContext=getInvocationContext();let planShellResponseClaimed=false;const wrappedConfirmationDetails={...confirmationDetails,...pmForcedAsk||requiresUserInteraction||preToolUseAsk?{hideAlwaysAllow:true}:{},onConfirm:__name(async(outcome,payload)=>runWithInvocationContext(invocationContext,async()=>{await runInRequestGoalContext(reqInfo,async()=>{if(planShellDecision.classification!=="not-applicable"){if(planShellResponseClaimed)return;planShellResponseClaimed=true;const currentCall=this.toolCalls.find(call=>call.request.callId===reqInfo.callId&&call.status==="awaiting_approval");if(!currentCall)return;const approval=await validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:currentCall.request.args,invocationParams:currentCall.invocation.params,signal,outcome,payload});await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,approval.outcome,signal,approval.payload);return}await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,outcome,signal,payload)})}),"onConfirm")};this.setStatusInternal(reqInfo.callId,"awaiting_approval",wrappedConfirmationDetails);const blockedSpan=startToolBlockedOnUserSpan(toolSpan,{tool_name:canonicalName,call_id:reqInfo.callId});this.blockedSpans.set(reqInfo.callId,blockedSpan);if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Qwen Code needs your permission to use ${reqInfo.name}`,"permission_prompt","Permission needed",void 0,this.hookOwners.get(reqInfo.callId)).catch(error3=>{debugLogger44.warn(`Permission prompt notification hook failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}}}catch(error3){if(signal.aborted){this.setStatusInternal(reqInfo.callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(reqInfo.callId,"aborted","system");setToolSpanCancelled(toolSpan);this.finalizeToolSpan(reqInfo.callId);continue}const explicitErrorType=error3?.errorType;this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,error3 instanceof Error?error3:new Error(String(error3)),explicitErrorType??"unhandled_exception","not_started"));this.finalizeBlockedSpan(reqInfo.callId,"error","system");setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3));this.finalizeToolSpan(reqInfo.callId)}}batchState.preparing=false;await this.attemptExecutionOfScheduledCalls(signal);void this.checkAndNotifyCompletion().catch(error3=>{debugLogger44.warn(`_schedule completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}finally{if(preparedBatch){preparedBatch.preparing=false;this.releaseIdleBatchListener(preparedBatch)}this.isScheduling=false;this.drainRequestQueueIfIdle()}}async handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload){const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const toolCall=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!toolCall){if(this.nestedToolScheduler?.toolCalls.some(call=>call.request.callId===callId)){return this.nestedToolScheduler.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload)}return}if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const claimsAskUserQuestionResponse=toolCall.tool instanceof AskUserQuestionTool&&toolCall.confirmationDetails.type==="ask_user_question";if(claimsAskUserQuestionResponse&&this.askUserQuestionResponseClaims.has(callId)){return}if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.add(callId)}try{await this._handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload)}catch(error3){const aborted3=signal.aborted;if(aborted3){this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started")}else{this.setStatusInternal(callId,"error",createErrorResponse(toolCall.request,error3 instanceof Error?error3:new Error(String(error3)),"unhandled_exception","not_started"))}this.finalizeBlockedSpan(callId,aborted3?"aborted":"error","system");const toolSpan=this.toolSpans.get(callId);if(toolSpan){if(aborted3){setToolSpanCancelled(toolSpan)}else{setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3))}}this.finalizeToolSpan(callId);debugLogger44.warn(`handleConfirmationResponse failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`);throw error3}finally{if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.delete(callId)}}await this.attemptExecutionOfScheduledCalls(signal)}async _handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload){const shouldSwitchToDefault=outcome==="proceed_once_and_switch_to_default";const normalizedOutcome=shouldSwitchToDefault?"proceed_once":outcome;const isCurrentApproval=__name(()=>!signal.aborted&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentApproval");const isCurrentCancellation=__name(()=>outcome==="cancel"&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentCancellation");if(!isCurrentApproval()&&!isCurrentCancellation())return;if(!signal.aborted)await originalOnConfirm(normalizedOutcome,payload);if(!isCurrentApproval()&&!isCurrentCancellation())return;if(shouldSwitchToDefault){this.config.setApprovalMode("default")}outcome=normalizedOutcome;if(outcome==="proceed_always"||outcome==="proceed_always_project"||outcome==="proceed_always_user"){await persistPermissionOutcome(outcome,toolCall.confirmationDetails,this.config.getOnPersistPermissionRule?.(),this.config.getPermissionManager?.(),payload,isCurrentApproval);if(!isCurrentApproval())return;await this.autoApproveCompatiblePendingTools(signal,callId,isCurrentApproval);if(!isCurrentApproval())return}this.setToolCallOutcome(callId,outcome);this.recordAutoModeFallbackResolution(callId,outcome);if(outcome==="cancel"||signal.aborted){const cancelMessage=payload?.cancelMessage||"User did not allow tool call";this.setStatusInternal(callId,"cancelled",cancelMessage,"not_started");const toolSpan=this.toolSpans.get(callId);if(toolSpan){setToolSpanCancelled(toolSpan)}const explicitCancel=outcome==="cancel";this.finalizeBlockedSpan(callId,explicitCancel?"cancel":"aborted",explicitCancel?this.getBlockedSource():"system");this.finalizeToolSpan(callId)}else if(outcome==="modify_with_editor"){const waitingToolCall=toolCall;if(waitingToolCall.confirmationDetails.type==="edit"&&isModifiableDeclarativeTool(waitingToolCall.tool)){const modifyContext=waitingToolCall.tool.getModifyContext(signal,callId);const editorType=this.getPreferredEditor();if(!editorType){debugLogger44.warn(`ModifyWithEditor requested for ${callId} but no editor available \u2014 tool stays in awaiting_approval; user can recover via Cancel/Proceed`);const toolSpan=this.toolSpans.get(callId);if(toolSpan){try{toolSpan.setAttributes({"qwen-code.tool.modify_with_editor_unavailable":true})}catch{}}return}this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,isModifying:true});const normalizedArgs={...waitingToolCall.request.args};for(const key of PATH_ARG_KEYS){if(typeof normalizedArgs[key]==="string"){normalizedArgs[key]=unescapePath(String(normalizedArgs[key]).trim())}}const{updatedParams,updatedDiff}=await modifyWithEditor(normalizedArgs,modifyContext,editorType,signal,this.onEditorClose);if(!this.setArgsInternal(callId,updatedParams))return;this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,fileDiff:updatedDiff,isModifying:false})}}else{const waitingToolCall=toolCall;if(isApproveOutcome(outcome)&&waitingToolCall.tool instanceof AskUserQuestionTool&&waitingToolCall.confirmationDetails.type==="ask_user_question"){this.config.getLlmClient?.()?.recordTrustedUserAnswers(callId,waitingToolCall.confirmationDetails.questions,payload?.answers)}if(payload?.newContent&&toolCall){if(!await this._applyInlineModify(toolCall,payload,signal)){return}}this.setStatusInternal(callId,"scheduled");const decision=outcome==="proceed_once"?"proceed_once":"proceed_always";this.finalizeBlockedSpan(callId,decision,this.getBlockedSource())}}recordAutoModeFallbackResolution(callId,outcome){const wasAutoModeFallback=this.autoModeFallbackCallIds.delete(callId);if(this.config.getApprovalMode()==="auto"&&wasAutoModeFallback&&isApproveOutcome(outcome)){const before=this.config.getAutoModeDenialState();const after=recordFallbackApprove(before);if(after===before){debugLogger44.warn(`Auto mode denial counters already clear after fallback approval: `+formatDenialStateLog(before));return}debugLogger44.warn(`Auto mode denial counters reset after fallback approval: ${formatDenialStateLog(before)} -> ${formatDenialStateLog(after)}`);this.config.setAutoModeDenialState(after)}}async openIdeDiffIfEnabled(confirmationDetails,callId,signal){if(confirmationDetails.type!=="edit"||!this.config.getIdeMode()||this.config.getExecutionEnvironment?.()){return}let resolution;try{const ideClient=await IdeClient.getInstance();if(!ideClient.isDiffingEnabled())return;resolution=await ideClient.openDiff(confirmationDetails.filePath,confirmationDetails.newContent)}catch(error3){if(!signal.aborted){debugLogger44.warn(`IDE diff open failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`)}return}const still=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!still)return;if(resolution.status==="accepted"){const userEdited=resolution.content!=null&&resolution.content!==confirmationDetails.newContent;await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"proceed_once",signal,userEdited?{newContent:resolution.content}:void 0)}else{await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"cancel",signal)}}async _applyInlineModify(toolCall,payload,signal){const confirmDetails=toolCall.confirmationDetails;if(confirmDetails.type!=="edit"||!isModifiableDeclarativeTool(toolCall.tool)||!payload.newContent){return true}const currentContent=confirmDetails.originalContent??"";const modifyContext=toolCall.tool.getModifyContext(signal,toolCall.request.callId);const updatedParams=modifyContext.createUpdatedParams(currentContent,payload.newContent,toolCall.request.args);const updatedDiff=createPatch(confirmDetails.filePath,currentContent,payload.newContent,"Current","Proposed");if(!this.setArgsInternal(toolCall.request.callId,updatedParams)){return false}this.setStatusInternal(toolCall.request.callId,"awaiting_approval",{...confirmDetails,fileDiff:updatedDiff});return true}async attemptExecutionOfScheduledCalls(signal){while(true){const allCallsFinalOrScheduled=this.toolCalls.every(call=>call.status==="scheduled"||call.status==="cancelled"||call.status==="success"||call.status==="error");if(!allCallsFinalOrScheduled){return}const callsToExecute=this.toolCalls.filter(call=>call.status==="scheduled");if(callsToExecute.length===0){return}const batches=partitionToolCalls(callsToExecute,this.hookReplacedInputCallIds);for(const batch of batches){if(batch.concurrent&&batch.calls.length>1){await this.runConcurrently(batch.calls,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}else{for(const call of batch.calls){await this.executeSingleToolCall(call,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}}}}}hasExecutingOrAwaitingApprovalCall(){return this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}async runConcurrently(calls,signal){const maxConcurrency=parsePositiveIntegerEnv(process.env["QWEN_CODE_MAX_TOOL_CONCURRENCY"],10);const executing=new Set;for(const call of calls){const p2=this.executeSingleToolCall(call,signal).finally(()=>{executing.delete(p2)});executing.add(p2);if(executing.size>=maxConcurrency){await Promise.race(executing)}}await Promise.all(executing)}async executeSingleToolCall(toolCall,signal){if(toolCall.status!=="scheduled")return;if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.executeSingleToolCall(toolCall,signal))}const scheduledCall=toolCall;const{callId,name:toolName}=scheduledCall.request;const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.executeSingleToolCall(toolCall,signal))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.executeSingleToolCall(toolCall,signal))}let toolSpan=this.toolSpans.get(callId);if(!toolSpan){const canonical=canonicalToolName(toolName);toolSpan=startToolSpan(canonical,{"tool.call_id":callId,"gen_ai.tool.call.id":scheduledCall.request.providerCallId??callId,call_id:callId,tool_name:canonical,...scheduledCall.request.parentCallId?{"tool.parent_call_id":scheduledCall.request.parentCallId}:{},...scheduledCall.request.source?{"tool.source":scheduledCall.request.source}:{}},scheduledCall.tool.description,scheduledCall.request.prompt_id);this.toolSpans.set(callId,toolSpan)}try{await runInToolSpanContext(toolSpan,()=>this._executeToolCallBody(scheduledCall,signal,toolSpan))}catch(error3){const errorMessage=error3 instanceof Error?error3.message:String(error3);setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,errorMessage);this.setStatusInternal(callId,"error",createErrorResponse(scheduledCall.request,error3 instanceof Error?error3:new Error(errorMessage),"unhandled_exception",this.toolCalls.find(call=>call.request.callId===callId)?.status==="executing"?"error":"not_started"))}finally{this.finalizeToolSpan(callId);this.memoryMonitor?.scheduleCheck()}}async runPreToolUse(reqInfo,tool,batchState,signal){const messageBus=this.config.getMessageBus();if(this.config.getDisableAllHooks()||!messageBus)return void 0;const{callId}=reqInfo;const canonicalName=canonicalToolName(reqInfo.name);const toolInput=structuredClone(reqInfo.args);for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=generateToolUseId();this.preToolUseIds.set(callId,toolUseId);this.preToolUseSessionHookIds.set(callId,this.sessionPreToolUseHookIds(callId,canonicalName));const toolSpan=this.openToolSpan(reqInfo,tool,batchState);const result=await runInToolSpanContext(toolSpan,()=>runInRequestGoalContext(reqInfo,()=>this.withHookSpan({hookEvent:"PreToolUse",toolName:canonicalName,toolUseId},()=>firePreToolUseHook(messageBus,canonicalName,toolInput,toolUseId,this.config.getApprovalMode(),signal,callId,this.hookOwners.get(callId)),r=>r.hookError?{success:false,error:r.hookError,shouldProceed:true}:{success:true,shouldProceed:r.shouldProceed,blockType:r.shouldProceed?void 0:r.blockType,hasAdditionalContext:!!r.additionalContext})));if(result.additionalContext){this.preToolUseContexts.set(callId,result.additionalContext)}if(signal.aborted)return void 0;const fixedPolicy=reqInfo.executionOrigin?.kind==="fixed_policy";let blockReason;if(!result.shouldProceed&&(result.blockType!=="ask"||fixedPolicy||!this.canPromptForPreToolUseAsk())){blockReason=result.blockReason||"Tool execution blocked by hook"}else if(fixedPolicy&&result.updatedInput){blockReason="PreToolUse updatedInput is not supported for policy-owned tool calls, which skip the permission flow; the tool was not run."}if(blockReason){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);this.finalizeToolSpan(callId);return{status:"error",request:reqInfo,tool,response:createErrorResponse(reqInfo,new Error(blockReason),"execution_denied","not_started"),durationMs:0}}if(!result.shouldProceed){this.preToolUseAsks.set(callId,result.blockReason||`A PreToolUse hook requested confirmation before running ${reqInfo.name}.`)}if(result.updatedInput){reqInfo.args=result.updatedInput;this.hookReplacedInputCallIds.add(callId)}return void 0}rebuildWithPermissionRequestInput(reqInfo,tool,args,toolSpan){const{callId}=reqInfo;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool,args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){this.setStatusInternal(callId,"error",createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,policyGate.message);this.finalizeToolSpan(callId);return void 0}if(!this.setArgsInternal(callId,policyGate.args))return void 0;this.hookReplacedInputCallIds.add(callId);return this.toolCalls.find(call=>call.request.callId===callId&&call.status==="validating")}sessionPreToolUseHookIds(callId,toolName){const sessionId=this.hookOwners.get(callId)?.sessionId??this.config.getSessionId();return new Set(this.config.getHookSystem?.()?.getSessionHooksManager?.().getMatchingHooks(sessionId,"PreToolUse",toolName).map(entry=>entry.hookId)??[])}canPromptForPreToolUseAsk(){const isNonInteractive=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.getInputFormat()!=="stream-json";if(isNonInteractive){return false}if(this.config.getShouldAvoidPermissionPrompts?.()){return false}return true}safelyAddToolArgumentsAttributes(span,argumentsValue){try{addToolArgumentsAttributes(this.config,span,argumentsValue)}catch(error3){debugLogger44.warn("Failed to add tool arguments span attribute:",error3)}}safelyAddToolCallResultAttributes(span,result){try{addToolCallResultAttributes(this.config,span,result)}catch(error3){debugLogger44.warn("Failed to add tool result span attribute:",error3)}}async _executeToolCallBody(scheduledCall,signal,span){const{callId,name:toolName}=scheduledCall.request;const canonicalName=canonicalToolName(toolName);const invocation=scheduledCall.invocation;const toolInput=scheduledCall.request.args;for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=this.preToolUseIds.get(callId)??generateToolUseId();const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();let producerObserved=false;const observeSyntheticProducer=__name(response=>{try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;observeToolResultBoundary({stage:"producer",sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,artifacts:[toolResultBoundaryArtifact(response.persistedOutputFiles??[],response.artifacts??[])],values:__name(()=>[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[]],"values")})}catch{}},"observeSyntheticProducer");const checkedHookIds=this.preToolUseSessionHookIds.get(callId);if(checkedHookIds&&[...this.sessionPreToolUseHookIds(callId,canonicalName)].some(hookId=>!checkedHookIds.has(hookId))){const errorResponse=createErrorResponse(scheduledCall.request,new Error(`A PreToolUse hook was registered after "${toolName}" was checked, so the call was not run. Call the tool again.`),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);return}const toolInvocationGuard=this.config.getToolInvocationGuard?.();if(toolInvocationGuard){const invocationContext=getInvocationContext();const guardDecision=await evaluateToolInvocationGuard(toolInvocationGuard,{callId,toolName:canonicalName,args:invocation.params,signal,permissionChecked:scheduledCall.request.executionOrigin?.kind!=="fixed_policy",sessionId:this.config.getSessionId(),cwd:this.config.getTargetDir(),...invocationContext?{invocationContext}:{}});if(signal.aborted){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}return}if(!guardDecision.allowed){const errorResponse=createErrorResponse(scheduledCall.request,new Error(guardDecision.reason),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_SPAN_STATUS_INVOCATION_GUARD_DENIED);return}}if(signal.aborted){const currentCall=this.toolCalls.find(call=>call.request.callId===callId);if(currentCall&¤tCall.status!=="success"&¤tCall.status!=="error"&¤tCall.status!=="cancelled"){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}}return}const liveOutputCallback=scheduledCall.tool.canUpdateOutput?outputChunk=>{if(isShellProgressData(outputChunk)){if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}return}const compactOutput=this.compactResultDisplayForInteractiveHistory(outputChunk);if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,liveOutput:compactOutput}:tc);this.notifyToolCallsUpdate()}:void 0;const shellExecutionConfig=this.config.getShellExecutionConfig();const sleepInhibitorHandle=acquireSleepInhibitor(this.config,`Qwen Code is executing tool ${canonicalName}`);let removeParentAbortForward;let executionStatus="not_started";let executionSettled=false;let execSpan;let executionStartedAt;const elapsedExecutionMs=__name(()=>executionStartedAt===void 0?void 0:Math.round(performance.now()-executionStartedAt),"elapsedExecutionMs");let producerToolResult;let appliedOutputBudget;const recordBudgetReduction=__name((before,after,value,source)=>{if(before!==after&&measureToolOutput(after,this.config).chars<measureToolOutput(before,this.config).chars)appliedOutputBudget={value,source}},"recordBudgetReduction");const globalBudgetSource=this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global";let observeProducerOutput=observeSyntheticProducer;try{let promise;const toolExecutionTimeoutMs=Math.min(parsePositiveIntegerEnv(process.env["QWEN_CODE_TOOL_EXECUTION_TIMEOUT_MS"],0),2147483647);let execSignal=signal;let timeoutController;if(toolExecutionTimeoutMs>0){timeoutController=new AbortController;execSignal=timeoutController.signal;if(signal.aborted){timeoutController.abort(signal.reason)}else{const controller=timeoutController;const forwardAbort=__name(()=>controller.abort(signal.reason),"forwardAbort");signal.addEventListener("abort",forwardAbort,{once:true});removeParentAbortForward=__name(()=>signal.removeEventListener("abort",forwardAbort),"removeParentAbortForward")}}const inheritedTodoWorkChainId=todoWorkChainContext.getStore();const todoWorkChainId=this.config.getActiveTodoWorkChainOwner?.(scheduledCall.request.prompt_id,inheritedTodoWorkChainId)??inheritedTodoWorkChainId??scheduledCall.request.prompt_id;if(invocation instanceof ShellToolInvocation){const setPidCallback=__name(pid=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,pid}:tc);this.notifyToolCallsUpdate()},"setPidCallback");const setPromoteAbortControllerCallback=__name(ac=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,promoteAbortController:ac}:tc);this.notifyToolCallsUpdate()},"setPromoteAbortControllerCallback");const canPromoteForegroundShell=__name(()=>{const promotableShells=this.toolCalls.filter(tc=>tc.status==="executing"&&tc.request.name===ToolNames.SHELL&&tc.promoteAbortController!==void 0);return promotableShells.length===1&&promotableShells[0]?.request.callId===callId},"canPromoteForegroundShell");this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger44.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig,setPidCallback,setPromoteAbortControllerCallback,canPromoteForegroundShell)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}else{this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger44.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}let toolResult;let schedulerTimeoutResultSelected=false;let schedulerTimeoutWon=false;if(timeoutController){let timeoutTimer;try{toolResult=await new Promise((resolve34,reject)=>{timeoutTimer=setTimeout(()=>{schedulerTimeoutResultSelected=true;schedulerTimeoutWon=!signal.aborted;debugLogger44.warn(`Tool ${canonicalName} (${callId}) timed out after ${toolExecutionTimeoutMs}ms \u2014 aborting`);timeoutController?.abort(new DOMException(`Tool execution timed out after ${toolExecutionTimeoutMs}ms`,"TimeoutError"));resolve34(createToolTimeoutResult(toolExecutionTimeoutMs))},toolExecutionTimeoutMs);timeoutTimer.unref?.();promise.then(resolve34,reject)})}finally{if(timeoutTimer)clearTimeout(timeoutTimer);removeParentAbortForward?.()}}else{toolResult=await promise}producerToolResult=toolResult;observeProducerOutput=__name((response,replacement=false)=>{const rawSize=replacement||producerToolResult?.rawOutputSize===null||producerToolResult?.error!==void 0?void 0:producerToolResult?.rawOutputSize??measureToolOutput(producerToolResult?.llmContent??"",this.config);const processedChars=measureToolOutput(response.responseParts,this.config).chars;const budgetReduced=!replacement&&appliedOutputBudget!==void 0;response.responseParts=attachToolOutputProvenance(response.responseParts,{callId,toolName:getModelFacingToolName(scheduledCall.request),promptId:scheduledCall.request.prompt_id,toolType:scheduledCall.tool instanceof DiscoveredMCPTool?"mcp":"native",rawSize,truncated:!replacement&&producerToolResult?.truncatedByProducer===true?true:budgetReduced?true:rawSize===void 0?void 0:processedChars<rawSize.chars,budget:budgetReduced?appliedOutputBudget?.value:void 0,budgetSource:budgetReduced?appliedOutputBudget?.source:void 0});try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;let producerInputValues;const getProducerInputValues=__name(()=>producerInputValues??=[...toolResultPartDiagnosticValues(producerToolResult?.llmContent),...shellResultText(producerToolResult?.returnDisplay)!==void 0?[{representation:"display",value:shellResultText(producerToolResult?.returnDisplay)}]:[]],"getProducerInputValues");let producerOutputValues;const getProducerOutputValues=__name(()=>producerOutputValues??=[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[],...typeof response.visionBridgeNotice==="string"?[{representation:"display",value:response.visionBridgeNotice}]:[]],"getProducerOutputValues");const inputArtifact=toolResultBoundaryArtifact(producerToolResult?.persistedOutputFiles,producerToolResult?.artifacts);const outputArtifact=toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts);let mutated;const isMutated=__name(()=>mutated??=producerToolResult==null||!producerContentEqual(getModelFacingToolName(scheduledCall.request),callId,producerToolResult.llmContent,response.responseParts)||!isDeepStrictEqual3(producerToolResult.returnDisplay,response.resultDisplay)||!isDeepStrictEqual3(inputArtifact,outputArtifact)||typeof response.visionBridgeNotice==="string","isMutated");const observation={sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,mutated:isMutated};observeToolResultBoundary({...observation,stage:"producer_input",artifacts:[inputArtifact],values:getProducerInputValues});observeToolResultBoundary({...observation,stage:"producer_output",artifacts:[outputArtifact],values:getProducerOutputValues})}catch{}},"observeProducerOutput");const isTimeout=toolResult.error?.type==="execution_timeout"&&(!schedulerTimeoutResultSelected||schedulerTimeoutWon);const parentAbortedAtExecutionSettle=signal.aborted;const aborted3=parentAbortedAtExecutionSettle&&!isTimeout;const executionErrorType=toolResult.error?toolResult.error.type??(scheduledCall.tool instanceof DiscoveredMCPTool?"mcp_tool_error":"unknown"):void 0;executionStatus=aborted3?"cancelled":toolResult.error?"error":"success";executionSettled=true;try{this.schedulerOptions.onToolExecutionSettled?.(callId,executionStatus,elapsedExecutionMs()??0)}catch(error3){debugLogger44.warn("Tool lifecycle end observer failed:",error3)}if(execSpan){const completedExecSpan=execSpan;execSpan=void 0;endToolExecutionSpan(completedExecSpan,{success:executionStatus==="success",error:aborted3?TOOL_SPAN_STATUS_TOOL_CANCELLED:isTimeout?TOOL_SPAN_STATUS_TOOL_TIMEOUT:toolResult.error?TOOL_SPAN_STATUS_TOOL_ERROR:void 0,cancelled:aborted3,executionStatus,errorType:executionErrorType})}if(aborted3){let cancelMessage=TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:true},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,cancelMessage,true,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){cancelMessage+=`
|
|
556
556
|
|
|
557
557
|
${failureHookResult.additionalContext}`}failureHookArtifacts=failureHookResult.artifacts}const cancelledResponse=createCancelledResponse(scheduledCall.request,cancelMessage,executionStatus,failureHookArtifacts,toolResult.persistedOutputFiles);observeProducerOutput(cancelledResponse,true);this.setStatusInternal(callId,"cancelled",cancelledResponse);setToolSpanCancelled(span);return}const cancelAfterPostProcessing=__name((artifacts,preserved)=>{if(!signal.aborted||isTimeout&&parentAbortedAtExecutionSettle){return false}const cancelledResponse=createCancelledResponse(scheduledCall.request,TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE,executionStatus,artifacts,preserved?.persistedOutputFiles,preserved?.visionBridgeNotice);observeProducerOutput(cancelledResponse,true);this.setStatusInternal(callId,"cancelled",cancelledResponse);setToolSpanCancelled(span);return true},"cancelAfterPostProcessing");if(toolResult.error===void 0){let content=toolResult.llmContent??"";let persistedOutputFiles=toolResult.persistedOutputFiles?[...toolResult.persistedOutputFiles]:toolResult.persistedOutputFiles;const mergePersistedOutputFiles=__name(outputFiles=>{if(outputFiles===void 0)return;persistedOutputFiles=Array.from(new Set([...persistedOutputFiles??[],...outputFiles]))},"mergePersistedOutputFiles");let contentLength=typeof content==="string"?content.length:void 0;let postToolUseAdditionalContext;let postToolUseArtifacts;let reminderEnvelope;if(hooksEnabled&&messageBus){const toolResponse={llmContent:content,returnDisplay:toolResult.returnDisplay};const permissionMode=this.config.getApprovalMode();const postHookResult=await this.withHookSpan({hookEvent:"PostToolUse",toolName:canonicalName,toolUseId},()=>firePostToolUseHook(messageBus,canonicalName,toolInput,toolResponse,toolUseId,permissionMode,void 0,callId,elapsedExecutionMs(),this.hookOwners.get(callId)),r=>r.hookError?{success:false,error:r.hookError,shouldStop:false}:{success:true,shouldStop:r.shouldStop,hasAdditionalContext:!!r.additionalContext,blockType:r.shouldStop?"stop":void 0});if(postHookResult.additionalContext){postToolUseAdditionalContext=postHookResult.additionalContext}if(postHookResult.artifacts&&postHookResult.artifacts.length>0){postToolUseArtifacts=postHookResult.artifacts}if(postHookResult.shouldStop){if(cancelAfterPostProcessing(postHookResult.artifacts,{persistedOutputFiles})){return}const stopMessage=postHookResult.stopReason||"Execution stopped by hook";const errorResponse=createErrorResponse(scheduledCall.request,new Error(stopMessage),"execution_denied",executionStatus);if(persistedOutputFiles!==void 0){errorResponse.persistedOutputFiles=persistedOutputFiles}observeProducerOutput(errorResponse,true);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_POST_HOOK_STOPPED,TOOL_SPAN_STATUS_POST_HOOK_STOPPED);return}}const persisted=await this.maybePersistLargeToolResult(callId,toolName,content,toolResult.outputBudgetApplied===true,scheduledCall.request.prompt_id);recordBudgetReduction(content,persisted.content,this.config.getTruncateToolOutputThreshold()+GATE_HEADROOM,globalBudgetSource);content=persisted.content;mergePersistedOutputFiles(persisted.persistedOutputFiles);const inputPaths=extractToolFilePaths(toolName,toolInput);const resultPaths=isFilesystemPathTool(toolName)&&Array.isArray(toolResult.resultFilePaths)?toolResult.resultFilePaths:[];const candidatePaths=Array.from(new Set([...inputPaths.map(p2=>unescapePath(p2)),...resultPaths]));if(candidatePaths.length>0&&!this.config.getExecutionEnvironment?.()){const rulesRegistry=this.config.getConditionalRulesRegistry();const skillManager=sessionSkillManager(this.config);const reminderBlocks=[];for(const candidatePath of candidatePaths){const rulesCtx=await rulesRegistry?.matchAndConsume(candidatePath);if(rulesCtx)reminderBlocks.push(rulesCtx)}const activatedSkills=await skillManager?.matchAndActivateByPaths(candidatePaths);if(activatedSkills&&activatedSkills.length>0&&skillManager){const hasSkillTool=this.hasSkillToolOverride?this.hasSkillToolOverride():!!this.toolRegistry.getTool(ToolNames.SKILL);if(hasSkillTool){let activatedEntries=[];try{const collected=await collectAvailableSkillEntries(skillManager,this.config);const activatedSet=new Set(activatedSkills);activatedEntries=collected.entries.filter(e=>e.level!==void 0&&activatedSet.has(e.name))}catch(error3){debugLogger44.warn("coreToolScheduler: collectAvailableSkillEntries failed in activation path",error3);activatedEntries=activatedSkills.map(name=>({name,description:"",level:"project"}))}if(activatedEntries.length>0){reminderBlocks.push(`${SKILLS_ACTIVATED_OPENER}; invoke a skill by passing its name to the Skill tool:
|
|
558
558
|
<available_skills>
|
|
559
559
|
${renderAvailableSkillsBlock(activatedEntries)}
|
|
560
560
|
</available_skills>`);this.config.addInlineAnnouncedSkillKeys(activatedEntries.map(e=>`skill:${e.name}`))}}}if(reminderBlocks.length>0){const body=escapeSystemReminderTags(reminderBlocks.join("\n\n"));reminderEnvelope=`<system-reminder>
|
|
561
561
|
${body}
|
|
562
|
-
</system-reminder>`}}const limitsTool=scheduledCall.tool;const perToolMax=limitsTool.maxOutputChars;const perToolKeep=limitsTool.truncateKeep;const staticBudgetSource=perToolMax!==void 0?"per_tool":globalBudgetSource;const perToolLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:void 0;const promptIdForTruncation=scheduledCall.request.prompt_id;try{const contentBeforeTruncation=content;const truncated=await truncateLlmContent(this.config,toolName,content,{threshold:perToolMax,lines:perToolLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeTruncation,truncated.content,perToolMax??this.config.getTruncateToolOutputThreshold(),staticBudgetSource);content=truncated.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeTruncation,truncated))}catch(truncErr){debugLogger44.warn(`TRUNCATION failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}if(postToolUseAdditionalContext){content=appendAdditionalContext(content,postToolUseAdditionalContext)}if(reminderEnvelope){content=appendAdditionalContext(content,reminderEnvelope)}if((postToolUseAdditionalContext||reminderEnvelope)&&typeof content==="string"&&!content.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX)){const baseThreshold=perToolMax??this.config.getTruncateToolOutputThreshold();const combinedLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:this.config.getTruncateToolOutputLines()*2;if(content.length>baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR){try{const contentBeforeRecombination=content;const recombined=await truncateToolOutput(this.config,toolName,content,{layer:"combined",source:scheduledCall.tool.maxOutputChars!==void 0?"per_tool":this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global",threshold:baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,lines:combinedLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeRecombination,recombined.content,baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,staticBudgetSource);content=recombined.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeRecombination,recombined))}catch(truncErr){debugLogger44.warn(`TRUNCATION (combined) failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}}}contentLength=typeof content==="string"?content.length:void 0;const convertedResponse=convertToFunctionResponse(getModelFacingToolName(scheduledCall.request),callId,content);const processedImages=await this.processToolResultImages(convertedResponse,signal,scheduledCall.request.executionOrigin);const response=processedImages.responseParts;if(response!==convertedResponse){contentLength=response.reduce((total,part)=>total+extractTextFromPartListUnion(part).length,0)}const artifacts=[...toolResult.artifacts??[],...postToolUseArtifacts??[]];const policyArtifacts=scheduledCall.tool.mediaPolicyDescriptor&&toolResult.artifacts&&toolResult.artifacts.length>0?{toolName:canonicalName,invocationId:callId,executionOrigin:scheduledCall.request.executionOrigin??{kind:"model"},artifacts:toolResult.artifacts}:void 0;if(policyArtifacts&&policyArtifacts.executionOrigin.kind!=="fixed_policy"&&scheduledCall.tool.mediaPolicyDescriptor){const{collectModelPolicyCall}=await import("./model-call-collection-
|
|
562
|
+
</system-reminder>`}}const limitsTool=scheduledCall.tool;const perToolMax=limitsTool.maxOutputChars;const perToolKeep=limitsTool.truncateKeep;const staticBudgetSource=perToolMax!==void 0?"per_tool":globalBudgetSource;const perToolLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:void 0;const promptIdForTruncation=scheduledCall.request.prompt_id;try{const contentBeforeTruncation=content;const truncated=await truncateLlmContent(this.config,toolName,content,{threshold:perToolMax,lines:perToolLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeTruncation,truncated.content,perToolMax??this.config.getTruncateToolOutputThreshold(),staticBudgetSource);content=truncated.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeTruncation,truncated))}catch(truncErr){debugLogger44.warn(`TRUNCATION failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}if(postToolUseAdditionalContext){content=appendAdditionalContext(content,postToolUseAdditionalContext)}if(reminderEnvelope){content=appendAdditionalContext(content,reminderEnvelope)}if((postToolUseAdditionalContext||reminderEnvelope)&&typeof content==="string"&&!content.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX)){const baseThreshold=perToolMax??this.config.getTruncateToolOutputThreshold();const combinedLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:this.config.getTruncateToolOutputLines()*2;if(content.length>baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR){try{const contentBeforeRecombination=content;const recombined=await truncateToolOutput(this.config,toolName,content,{layer:"combined",source:scheduledCall.tool.maxOutputChars!==void 0?"per_tool":this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global",threshold:baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,lines:combinedLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeRecombination,recombined.content,baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,staticBudgetSource);content=recombined.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeRecombination,recombined))}catch(truncErr){debugLogger44.warn(`TRUNCATION (combined) failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}}}contentLength=typeof content==="string"?content.length:void 0;const convertedResponse=convertToFunctionResponse(getModelFacingToolName(scheduledCall.request),callId,content);const processedImages=await this.processToolResultImages(convertedResponse,signal,scheduledCall.request.executionOrigin);const response=processedImages.responseParts;if(response!==convertedResponse){contentLength=response.reduce((total,part)=>total+extractTextFromPartListUnion(part).length,0)}const artifacts=[...toolResult.artifacts??[],...postToolUseArtifacts??[]];const policyArtifacts=scheduledCall.tool.mediaPolicyDescriptor&&toolResult.artifacts&&toolResult.artifacts.length>0?{toolName:canonicalName,invocationId:callId,executionOrigin:scheduledCall.request.executionOrigin??{kind:"model"},artifacts:toolResult.artifacts}:void 0;if(policyArtifacts&&policyArtifacts.executionOrigin.kind!=="fixed_policy"&&scheduledCall.tool.mediaPolicyDescriptor){const{collectModelPolicyCall}=await import("./model-call-collection-6OGPDTPG.js");await collectModelPolicyCall({config:this.config,batch:policyArtifacts,descriptor:scheduledCall.tool.mediaPolicyDescriptor,args:scheduledCall.invocation.params,..."executionStartTime"in scheduledCall&&typeof scheduledCall.executionStartTime==="number"?{startedAt:scheduledCall.executionStartTime}:{},signal})}const successResponse={callId,responseParts:response,resultDisplay:this.compactResultDisplayForInteractiveHistory(toolResult.returnDisplay),error:void 0,errorType:void 0,executionStatus,contentLength,...persistedOutputFiles!==void 0?{persistedOutputFiles}:{},...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:"modelOverride"in toolResult?{modelOverride:toolResult.modelOverride}:{},...toolResult.terminateTurn?{terminateTurn:true}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{},...artifacts.length>0?{artifacts}:{},...policyArtifacts?{policyArtifacts}:{}};if(canonicalName===ToolNames.EXIT_PLAN_MODE&&typeof toolResult.llmContent==="string"&&PLAN_EXIT_APPROVED_LLM_CONTENT_PREFIXES.some(prefix=>toolResult.llmContent.startsWith(prefix))){try{const planPath=this.config.getPlanFilePath();const savedPlan=fsSync.readFileSync(planPath,"utf-8");const redacted=this.config.getLlmClient?.()?.getChat().redactApprovedPlanFromHistory(callId,approvedPlanRedactionText(planPath),savedPlan);if(redacted===false){debugLogger44.debug(`Approved-plan redaction left history unchanged for ${callId}: no matching exit_plan_mode call, or its plan text does not match ${planPath}.`)}}catch(redactErr){debugLogger44.warn(`Skipping approved-plan redaction for ${callId} (plan file unavailable?): ${redactErr instanceof Error?redactErr.message:String(redactErr)}`)}}if(cancelAfterPostProcessing(artifacts,{persistedOutputFiles:successResponse.persistedOutputFiles,visionBridgeNotice:successResponse.visionBridgeNotice})){return}observeProducerOutput(successResponse);this.setStatusInternal(callId,"success",successResponse);try{span.setAttribute("success",true)}catch{}const result=response.find(part=>part.functionResponse!==void 0)?.functionResponse?.response;if(result!==void 0){this.safelyAddToolCallResultAttributes(span,result)}}else{const operationalErrorMessage=toolResult.error.message;let errorMessage=operationalErrorMessage;let errorPersistedOutputFiles=toolResult.persistedOutputFiles?[...toolResult.persistedOutputFiles]:toolResult.persistedOutputFiles;let failureHookAdditionalContext;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:false},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,toolResult.error.message,false,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){if(isTimeout){failureHookAdditionalContext=failureHookResult.additionalContext}else{errorMessage+=`
|
|
563
563
|
|
|
564
564
|
${failureHookResult.additionalContext}`}}failureHookArtifacts=failureHookResult.artifacts}if(isTimeout){const markedProducerBudget=toolResult.outputBudgetApplied===true?scheduledCall.tool.maxOutputChars:void 0;let timeoutContent;if(markedProducerBudget!==void 0){try{const truncated=await truncateLlmContent(this.config,toolName,toolResult.llmContent,{threshold:markedProducerBudget,lines:Number.POSITIVE_INFINITY,keep:scheduledCall.tool.truncateKeep},scheduledCall.request.prompt_id,scheduledCall.request.callId);recordBudgetReduction(toolResult.llmContent,truncated.content,markedProducerBudget,"per_tool");timeoutContent={content:truncated.content,persistedOutputFiles:persistedOutputFilesForTruncation(toolResult.llmContent,truncated)}}catch(truncErr){debugLogger44.warn(`TRUNCATION (timeout detail) failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`);timeoutContent={content:toolResult.llmContent}}}else{timeoutContent=await this.maybePersistLargeToolResult(callId,toolName,toolResult.llmContent,toolResult.outputBudgetApplied===true,scheduledCall.request.prompt_id)}if(markedProducerBudget===void 0)recordBudgetReduction(toolResult.llmContent,timeoutContent.content,this.config.getTruncateToolOutputThreshold()+GATE_HEADROOM,globalBudgetSource);let responseParts=convertToFunctionErrorResponse(getModelFacingToolName(scheduledCall.request),callId,timeoutContent.content,operationalErrorMessage);if(failureHookAdditionalContext&&responseParts.length>0){const lastIndex=responseParts.length-1;responseParts=[...responseParts];responseParts[lastIndex]=appendContextToResponsePart(responseParts[lastIndex],failureHookAdditionalContext)}const processedImages=await this.processToolResultImages(responseParts,signal,scheduledCall.request.executionOrigin);responseParts=processedImages.responseParts;const contentLength=responseParts.reduce((total,part)=>{const error4=part.functionResponse?.response?.["error"];return total+(typeof error4==="string"?error4.length:0)},0);const artifacts=[...toolResult.artifacts??[],...failureHookArtifacts??[]];const timeoutPersistedOutputFiles=errorPersistedOutputFiles===void 0&&timeoutContent.persistedOutputFiles===void 0?void 0:Array.from(new Set([...errorPersistedOutputFiles??[],...timeoutContent.persistedOutputFiles??[]]));if(cancelAfterPostProcessing(artifacts,{persistedOutputFiles:timeoutPersistedOutputFiles,visionBridgeNotice:processedImages.visionBridgeNotice})){return}const timeoutResponse={callId,responseParts,resultDisplay:this.compactResultDisplayForInteractiveHistory(toolResult.returnDisplay),error:new Error(operationalErrorMessage),errorType:"execution_timeout",executionStatus,contentLength,...timeoutPersistedOutputFiles!==void 0?{persistedOutputFiles:timeoutPersistedOutputFiles}:{},...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{},...artifacts.length>0?{artifacts}:{}};observeProducerOutput(timeoutResponse);this.setStatusInternal(callId,"error",timeoutResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_TIMEOUT,TOOL_SPAN_STATUS_TOOL_TIMEOUT);return}const errorGateThreshold=this.config.getTruncateToolOutputThreshold()+GATE_HEADROOM;const errorBodyAlreadyBounded=toolResult.outputBudgetApplied===true&&errorMessage===toolResult.llmContent;if(canonicalName!==ToolNames.EXEC&&errorMessage.length>errorGateThreshold&&!errorBodyAlreadyBounded&&!isAlreadyTruncated(errorMessage)){const persistResult=await persistAndTruncateToolResult(callId,toolName,errorMessage,this.config,scheduledCall.request.prompt_id);recordBudgetReduction(errorMessage,persistResult.content,errorGateThreshold,globalBudgetSource);errorMessage=persistResult.content;errorPersistedOutputFiles=Array.from(new Set([...errorPersistedOutputFiles??[],...persistResult.outputFile?[persistResult.outputFile]:[]]))}const error3=new Error(errorMessage);let errorResponse=createErrorResponse(scheduledCall.request,error3,executionErrorType??"unknown",executionStatus,failureHookArtifacts,typeof toolResult.returnDisplay==="string"?void 0:this.compactResultDisplayForInteractiveHistory(isShellResultDisplay(toolResult.returnDisplay)?{...toolResult.returnDisplay,text:errorMessage}:toolResult.returnDisplay));if(errorPersistedOutputFiles!==void 0){errorResponse.persistedOutputFiles=Array.from(new Set(errorPersistedOutputFiles))}const imageParts=normalizeParts(toolResult.llmContent).flatMap(part=>{const nestedImages=(part.functionResponse?.parts??[]).filter(nested=>isImagePart(nested)).map(nested=>nested);return isImagePart(part)?[part,...nestedImages]:nestedImages});if(imageParts.length>0){const basePart=errorResponse.responseParts[0];const functionResponse=basePart?.functionResponse;const imageErrorParts=functionResponse?[{...basePart,functionResponse:{...functionResponse,parts:imageParts}}]:errorResponse.responseParts;const processedImages=await this.processToolResultImages(imageErrorParts,signal,scheduledCall.request.executionOrigin);const bridgedErrorParts=processedImages.responseParts;if(bridgedErrorParts!==imageErrorParts||this.config.getEffectiveInputModalities?.()?.image===true){errorResponse={...errorResponse,responseParts:bridgedErrorParts,contentLength:bridgedErrorParts.reduce((total,part)=>{const response=part.functionResponse?.response;const text=response?.["error"]??response?.["output"];return total+(typeof text==="string"?text.length:0)},0),...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{}}}}if(canonicalName===ToolNames.EXEC){const audioParts=normalizeParts(toolResult.llmContent).filter(part=>part.inlineData?.mimeType?.startsWith("audio/"));const response=errorResponse.responseParts[0]?.functionResponse;if(response&&audioParts.length>0){response.parts=[...response.parts??[],...audioParts]}}if(cancelAfterPostProcessing([...toolResult.artifacts??[],...failureHookArtifacts??[]],{persistedOutputFiles:errorResponse.persistedOutputFiles,visionBridgeNotice:errorResponse.visionBridgeNotice})){return}observeProducerOutput(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_TOOL_ERROR,TOOL_SPAN_STATUS_TOOL_ERROR)}}catch(executionError){const errorMessage=executionError instanceof Error?executionError.message:String(executionError);const executionThrew=!executionSettled&&executionStatus!=="not_started";const explicitErrorType=executionError?.errorType;const executionTimedOut=executionThrew&&explicitErrorType==="execution_timeout";const aborted3=signal.aborted&&!executionTimedOut;if(executionThrew){executionStatus=aborted3?"cancelled":"error";executionSettled=true;try{this.schedulerOptions.onToolExecutionSettled?.(callId,executionStatus,elapsedExecutionMs()??0)}catch(error3){debugLogger44.warn("Tool lifecycle end observer failed:",error3)}}const exceptionErrorType=explicitErrorType??(executionThrew&&scheduledCall.tool instanceof DiscoveredMCPTool?"mcp_tool_error":"unhandled_exception");if(execSpan){const failedExecSpan=execSpan;execSpan=void 0;endToolExecutionSpan(failedExecSpan,{success:false,error:aborted3?TOOL_SPAN_STATUS_TOOL_CANCELLED:executionTimedOut?TOOL_SPAN_STATUS_TOOL_TIMEOUT:TOOL_SPAN_STATUS_TOOL_EXCEPTION,cancelled:aborted3,executionStatus,errorType:executionStatus==="error"?exceptionErrorType:void 0})}if(aborted3){let cancelMessage=executionThrew?TOOL_CANCELLED_BEFORE_COMPLETION_MESSAGE:TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:true},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,cancelMessage,true,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){cancelMessage+=`
|
|
565
565
|
|
|
@@ -2106,7 +2106,7 @@ ${trimmedContent}
|
|
|
2106
2106
|
--- End of Context from: ${displayPath} ---`}).join("\n\n")}__name(concatenateInstructions,"concatenateInstructions");function createMemoryTypeClassifier(userHomePath,foundRoot,extensionContextFilePaths){const resolvedHome=path78.resolve(userHomePath);const globalQwenDir=path78.resolve(Storage.getGlobalQwenDir());const resolvedRoot=foundRoot?path78.resolve(foundRoot):void 0;const extensionPaths=new Set(extensionContextFilePaths.map(filePath=>path78.resolve(filePath)));const extensionRoots=extensionContextFilePaths.map(filePath=>path78.dirname(path78.resolve(filePath)));return filePath=>{const resolvedPath=path78.resolve(filePath);if(extensionPaths.has(resolvedPath)||extensionRoots.some(root=>isSubpath(root,resolvedPath))){return"extension"}if(resolvedPath.startsWith(`${globalQwenDir}${path78.sep}`)){return"user"}if(resolvedRoot&&resolvedPath===path78.join(resolvedRoot,QWEN_DIR,LOCAL_CONTEXT_FILENAME)){return"local"}if(resolvedRoot&&isSubpath(resolvedRoot,resolvedPath)){return"project"}if(path78.dirname(resolvedPath)===resolvedHome){return"user"}return"project"}}__name(createMemoryTypeClassifier,"createMemoryTypeClassifier");async function loadServerHierarchicalMemory(currentWorkingDirectory,includeDirectoriesToReadMemory,fileService,extensionContextFilePaths=[],folderTrust,importFormat="tree",contextRuleExcludes=[],options2={}){logger5.debug(`Loading server hierarchical memory for CWD: ${currentWorkingDirectory} (importFormat: ${importFormat})`);const implicitDiscoveryEnabled=!options2.explicitOnly;const userHomePath=homedir6();const filePaths=await getMemoryFilePathsInternal(currentWorkingDirectory,includeDirectoriesToReadMemory,userHomePath,fileService,extensionContextFilePaths,folderTrust,implicitDiscoveryEnabled);const resolvedCwd=path78.resolve(currentWorkingDirectory);const foundRoot=await findProjectRoot(resolvedCwd);const effectiveRoot=foundRoot??resolvedCwd;if(implicitDiscoveryEnabled&&folderTrust&&foundRoot){const localContextPath=path78.join(foundRoot,QWEN_DIR,LOCAL_CONTEXT_FILENAME);try{await fs75.access(localContextPath,fsSync5.constants.R_OK);if(!filePaths.includes(localContextPath)){filePaths.push(localContextPath);logger5.debug(`Found readable local ${LOCAL_CONTEXT_FILENAME}: ${localContextPath}`)}}catch{}}const dedupedFilePaths=await dedupeByCanonicalIdentity(filePaths);let combinedInstructions="";let fileCount=0;let contextFilePaths=[];if(dedupedFilePaths.length>0){const loadReason=options2.loadReason??"session_start";const contentsWithPaths=await readMemoryFiles(dedupedFilePaths,importFormat,createMemoryTypeClassifier(userHomePath,foundRoot,extensionContextFilePaths),options2.onInstructionsLoaded,loadReason);combinedInstructions=concatenateInstructions(contentsWithPaths,currentWorkingDirectory);const memoryFilenames=new Set([...getAllMemoryFilenames(),LOCAL_CONTEXT_FILENAME]);const memoryItems=contentsWithPaths.filter(item=>memoryFilenames.has(path78.basename(item.filePath)));fileCount=memoryItems.length;contextFilePaths=contentsWithPaths.filter(hasAttachedContent).map(item=>formatContextFileDisplayPath(item.filePath,currentWorkingDirectory,userHomePath))}const{content:rulesContent,ruleCount,conditionalRules,ignoredExtensionRules}=options2.explicitOnly?{content:"",ruleCount:0,conditionalRules:[],ignoredExtensionRules:[]}:await loadRules(effectiveRoot,folderTrust,contextRuleExcludes,options2.extensionRuleSources??[]);let memoryContent=combinedInstructions;if(rulesContent){memoryContent=memoryContent?`${memoryContent}
|
|
2107
2107
|
|
|
2108
2108
|
${rulesContent}`:rulesContent}if(!memoryContent&&dedupedFilePaths.length===0&&ruleCount===0){logger5.debug("No QWEN.md files or rules found.")}return{memoryContent,fileCount,contextFilePaths,ruleCount,conditionalRules,...ignoredExtensionRules.length>0?{ignoredExtensionRules}:{},projectRoot:effectiveRoot}}__name(loadServerHierarchicalMemory,"loadServerHierarchicalMemory");init_esbuild_shims();import{execFile as execFile8}from"node:child_process";import*as path79 from"node:path";import{promisify as promisify5}from"node:util";var execFileAsync5=promisify5(execFile8);var debugLogger116=createDebugLogger("TEAM_MEMORY_SYNC");var GIT_TIMEOUT_MS=15e3;async function tryGit(cwd,args,killSignal="SIGTERM"){try{const{stdout}=await execFileAsync5("git",[...NO_EXEC_CONFIG,...args],{cwd,encoding:"utf8",timeout:GIT_TIMEOUT_MS,killSignal,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env["GIT_SSH_COMMAND"]?`${process.env["GIT_SSH_COMMAND"]} -oBatchMode=yes -oConnectTimeout=5`:"ssh -oBatchMode=yes -oConnectTimeout=5"}});return stdout}catch(error3){debugLogger116.debug(`git ${args[0]} failed`,error3);return null}}__name(tryGit,"tryGit");async function resolvePushTarget(gitRoot,branch){const remote=(await tryGit(gitRoot,["config","--get",`branch.${branch}.remote`]))?.trim();const mergeRef=(await tryGit(gitRoot,["config","--get",`branch.${branch}.merge`]))?.trim();if(!remote||!mergeRef){return null}return{remote,mergeRef}}__name(resolvePushTarget,"resolvePushTarget");async function syncTeamMemory(projectRoot,opts){const result={committed:false,pulled:false,pushed:false};let ourSha=null;const teamRoot=getTeamAutoMemoryRoot(projectRoot);const gitRoot=findGitRoot(teamRoot);if(!gitRoot||!isGitRepository(gitRoot)){result.skippedReason="not-a-git-repo";return result}const relPath=path79.relative(gitRoot,teamRoot)||".";const branch=(await tryGit(gitRoot,["symbolic-ref","--quiet","--short","HEAD"],"SIGKILL"))?.trim();if(!branch){result.skippedReason="detached-head";return result}const upstream=await tryGit(gitRoot,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],"SIGKILL");let wasAheadBeforeSync=false;if(upstream!==null){const ahead=await tryGit(gitRoot,["rev-list","@{u}..HEAD"]);wasAheadBeforeSync=!!ahead&&ahead.trim().length>0;result.pulled=await tryGit(gitRoot,["pull","--ff-only"],"SIGKILL")!==null;if(!result.pulled){result.skippedReason="pull-failed";return result}}const status=await tryGit(gitRoot,["--no-optional-locks","status","--porcelain","--",relPath]);if(status&&status.trim().length>0){const staged=await tryGit(gitRoot,["add","--",relPath])!==null;const commitArgs=["commit","--no-gpg-sign","-m",opts.message];if(opts.author){const email4=opts.author.email??`${opts.author.name}@users.noreply`;commitArgs.push("--author",`${opts.author.name} <${email4}>`)}commitArgs.push("--",relPath);result.committed=await tryGit(gitRoot,commitArgs)!==null;if(result.committed){ourSha=(await tryGit(gitRoot,["rev-parse","HEAD"],"SIGKILL"))?.trim()??null}if(!result.committed&&staged){await tryGit(gitRoot,["reset","--quiet","--",relPath])}}if(upstream===null){result.skippedReason="no-upstream";return result}if(!result.committed){return result}if(wasAheadBeforeSync){result.skippedReason="local-ahead";return result}const pushTarget=await resolvePushTarget(gitRoot,branch);if(!pushTarget){result.skippedReason="push-failed";return result}result.pushed=await tryGit(gitRoot,["push",pushTarget.remote,`HEAD:${pushTarget.mergeRef}`],"SIGKILL")!==null;if(!result.pushed){const headNow=(await tryGit(gitRoot,["rev-parse","HEAD"],"SIGKILL"))?.trim()??null;const remoteTip=await tryGit(gitRoot,["ls-remote",pushTarget.remote,pushTarget.mergeRef],"SIGKILL");const remoteHasIt=ourSha!==null&&(remoteTip??"").includes(ourSha);if(headNow===ourSha&&!remoteHasIt){const rewound=await tryGit(gitRoot,["reset","--soft",`${ourSha}^`],"SIGTERM")!==null;const unstaged=await tryGit(gitRoot,["reset","--quiet","--",relPath])!==null;if(!rewound||!unstaged){debugLogger116.warn(`team memory push-failed rollback incomplete (reset=${rewound}, unstage=${unstaged})`)}}result.skippedReason="push-failed"}return result}__name(syncTeamMemory,"syncTeamMemory");init_esbuild_shims();import*as path80 from"node:path";init_esbuild_shims();import{execFileSync as execFileSync2}from"node:child_process";var GIT_TIMEOUT_MS2=5e3;function isGitIgnored(worktree,path82,timeoutMs=GIT_TIMEOUT_MS2){const probe=path82.startsWith(":")?`./${path82}`:path82;const env={};for(const[key,value]of Object.entries(process.env)){if(!key.startsWith("GIT_"))env[key]=value}env["GIT_CONFIG_NOSYSTEM"]="1";try{execFileSync2("git",[...NO_EXEC_CONFIG,"-C",worktree,"check-ignore","-q","--",probe],{stdio:"ignore",timeout:timeoutMs,env});return true}catch{return false}}__name(isGitIgnored,"isGitIgnored");var debugLogger117=createDebugLogger("TEAM_MEMORY_GIT_STATUS");function isTeamFileGitIgnored(gitRoot,filePath){const rel=path80.relative(gitRoot,filePath)||".";return isGitIgnored(gitRoot,rel)}__name(isTeamFileGitIgnored,"isTeamFileGitIgnored");function getTeamMemoryShareabilityWarning(projectRoot){const teamRoot=getTeamAutoMemoryRoot(projectRoot);const gitRoot=findGitRoot(teamRoot);if(!gitRoot){debugLogger117.debug(`No git root for team memory at ${teamRoot}.`);return`Team memory is enabled, but ${teamRoot} is not inside a git repository, so saved memories stay local and are not shared with collaborators.`}const indexIgnored=isTeamFileGitIgnored(gitRoot,getTeamAutoMemoryIndexPath(projectRoot));const topicIgnored=isTeamFileGitIgnored(gitRoot,path80.join(teamRoot,"feedback.md"));if(indexIgnored||topicIgnored){debugLogger117.debug(`Team memory at ${teamRoot} is git-ignored (index=${indexIgnored}, topic=${topicIgnored}).`);return`Team memory is enabled, but ${teamRoot} is git-ignored, so saved memories are not shared. If your .gitignore excludes '.qwen/' (directory form), change it to '.qwen/*' and re-include '.qwen/team-memory/' (and its contents, e.g. '!.qwen/team-memory/**').`}return null}__name(getTeamMemoryShareabilityWarning,"getTeamMemoryShareabilityWarning");init_esbuild_shims();var SAFE_MODE_ENV_VAR="QWEN_CODE_SAFE_MODE";function isSafeModeEnv(){return isTruthy(process.env[SAFE_MODE_ENV_VAR])}__name(isSafeModeEnv,"isSafeModeEnv");init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();function resolveField(layers,defaultValue,defaultSource2={kind:"default"}){for(const layer2 of layers){if(isValuePresent(layer2.value)){return{value:layer2.value,source:layer2.source}}}return{value:defaultValue,source:defaultSource2}}__name(resolveField,"resolveField");function resolveOptionalField(layers){for(const layer2 of layers){if(isValuePresent(layer2.value)){return{value:layer2.value,source:layer2.source}}}return void 0}__name(resolveOptionalField,"resolveOptionalField");function isValuePresent(value){if(value===void 0||value===null){return false}if(typeof value==="string"&&value.trim()===""){return false}return true}__name(isValuePresent,"isValuePresent");function cliSource(detail){return{kind:"cli",detail}}__name(cliSource,"cliSource");function envSource(envKey){return{kind:"env",envKey}}__name(envSource,"envSource");function settingsSource(settingsPath){return{kind:"settings",settingsPath}}__name(settingsSource,"settingsSource");function modelProvidersSource(authType,modelId,detail){return{kind:"modelProviders",authType,modelId,detail}}__name(modelProvidersSource,"modelProvidersSource");function defaultSource(detail){return{kind:"default",detail}}__name(defaultSource,"defaultSource");function computedSource(detail){return{kind:"computed",detail}}__name(computedSource,"computedSource");function envLayer(env,key,transform3){const rawValue=env[key];const value=rawValue!==void 0?transform3?transform3(rawValue):rawValue:void 0;return{value,source:envSource(key)}}__name(envLayer,"envLayer");function layer(value,source){return{value,source}}__name(layer,"layer");function applyTimeoutEnvOverride(env,generationConfig,sources,modelProvider){if(modelProvider?.generationConfig?.timeout!==void 0)return;const raw=env["QWEN_CODE_API_TIMEOUT_MS"];if(raw===void 0)return;const trimmed=raw.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);if(!Number.isSafeInteger(parsed))return;generationConfig.timeout=parsed;sources["timeout"]={kind:"env",envKey:"QWEN_CODE_API_TIMEOUT_MS"}}__name(applyTimeoutEnvOverride,"applyTimeoutEnvOverride");function resolveModelConfig(input){const{authType,cli,settings,env,modelProvider,proxy}=input;const warnings=[];const sources={};if(authType==="qwen-oauth"){return resolveQwenOAuthConfig(input,warnings)}const envMapping=authType?AUTH_ENV_MAPPINGS[authType]:{model:[],apiKey:[],baseUrl:[]};const modelLayers=[];if(authType&&modelProvider){modelLayers.push(layer(modelProvider.id,modelProvidersSource(authType,modelProvider.id,"model.id")))}if(cli?.model){modelLayers.push(layer(cli.model,cliSource("--model")))}for(const envKey of envMapping.model){modelLayers.push(envLayer(env,envKey))}if(settings?.model){modelLayers.push(layer(settings.model,settingsSource("model.name")))}const defaultModel=authType?DEFAULT_MODELS[authType]:"";const modelResult=resolveField(modelLayers,defaultModel,defaultSource(defaultModel));sources["model"]=modelResult.source;const apiKeyLayers=[];if(authType&&modelProvider?.envKey){const apiKeyFromEnv=env[modelProvider.envKey];if(apiKeyFromEnv){apiKeyLayers.push(layer(apiKeyFromEnv,{kind:"env",envKey:modelProvider.envKey,via:modelProvidersSource(authType,modelProvider.id,"envKey")}))}}if(cli?.apiKey){apiKeyLayers.push(layer(cli.apiKey,cliSource("--openaiApiKey")))}for(const envKey of envMapping.apiKey){apiKeyLayers.push(envLayer(env,envKey))}if(settings?.apiKey){apiKeyLayers.push(layer(settings.apiKey,settingsSource("security.auth.apiKey")))}const apiKeyResult=resolveOptionalField(apiKeyLayers);if(apiKeyResult){sources["apiKey"]=apiKeyResult.source}const baseUrlLayers=[];if(authType&&modelProvider?.baseUrl){baseUrlLayers.push(layer(modelProvider.baseUrl,modelProvidersSource(authType,modelProvider.id,"baseUrl")))}if(cli?.baseUrl){baseUrlLayers.push(layer(cli.baseUrl,cliSource("--openaiBaseUrl")))}for(const envKey of envMapping.baseUrl){baseUrlLayers.push(envLayer(env,envKey))}if(settings?.baseUrl){baseUrlLayers.push(layer(settings.baseUrl,settingsSource("security.auth.baseUrl")))}const baseUrlResult=resolveOptionalField(baseUrlLayers);if(baseUrlResult){sources["baseUrl"]=baseUrlResult.source}let apiKeyEnvKey;if(authType&&modelProvider?.envKey){apiKeyEnvKey=modelProvider.envKey;sources["apiKeyEnvKey"]={...modelProvidersSource(authType,modelProvider.id,"envKey"),envKey:modelProvider.envKey}}const generationConfig=resolveGenerationConfig(settings?.generationConfig,modelProvider?.generationConfig,authType,modelProvider?.id??modelResult.value,sources);applyTimeoutEnvOverride(env,generationConfig,sources,modelProvider);const config3={authType,model:modelResult.value||"",apiKey:apiKeyResult?.value,apiKeyEnvKey,baseUrl:baseUrlResult?.value,proxy,...generationConfig};if(proxy){sources["proxy"]=computedSource("Config.getProxy()")}sources["authType"]=computedSource("provided by caller");return{config:config3,sources,warnings}}__name(resolveModelConfig,"resolveModelConfig");function resolveQwenOAuthConfig(input,warnings){const{cli,settings,proxy,modelProvider}=input;const sources={};const allowedModels=new Set(QWEN_OAUTH_ALLOWED_MODELS);const requestedModel=cli?.model||settings?.model;let resolvedModel;let modelSource;if(requestedModel&&allowedModels.has(requestedModel)){resolvedModel=requestedModel;modelSource=cli?.model?cliSource("--model"):settingsSource("model.name")}else{if(requestedModel){const isVisionModel=requestedModel.includes("vl")||requestedModel.includes("vision");const extraMessage=isVisionModel?` Note: vision-model has been removed since coder-model now supports vision capabilities.`:"";warnings.push(`Warning: Unsupported Qwen OAuth model '${requestedModel}', falling back to '${DEFAULT_QWEN_MODEL}'.${extraMessage}`)}resolvedModel=DEFAULT_QWEN_MODEL;modelSource=defaultSource(`fallback to '${DEFAULT_QWEN_MODEL}'`)}sources["model"]=modelSource;sources["apiKey"]=computedSource("Qwen OAuth dynamic token");sources["authType"]=computedSource("provided by caller");if(proxy){sources["proxy"]=computedSource("Config.getProxy()")}const generationConfig=resolveGenerationConfig(settings?.generationConfig,modelProvider?.generationConfig,"qwen-oauth",resolvedModel,sources);applyTimeoutEnvOverride(input.env,generationConfig,sources,modelProvider);const config3={authType:"qwen-oauth",model:resolvedModel,apiKey:"QWEN_OAUTH_DYNAMIC_TOKEN",proxy,...generationConfig};return{config:config3,sources,warnings}}__name(resolveQwenOAuthConfig,"resolveQwenOAuthConfig");function resolveGenerationConfig(settingsConfig,modelProviderConfig,authType,modelId,sources){const result={};for(const field of MODEL_GENERATION_CONFIG_FIELDS){if(authType&&modelProviderConfig&&field in modelProviderConfig){result[field]=modelProviderConfig[field];sources[field]=modelProvidersSource(authType,modelId||"",`generationConfig.${field}`)}else if(settingsConfig&&field in settingsConfig){result[field]=settingsConfig[field];sources[field]=settingsSource(`model.generationConfig.${field}`)}}if(result.contextWindowSize===void 0&&modelId){const knownLimit=knownTokenLimit(modelId,"input");if(knownLimit!==void 0){result.contextWindowSize=knownLimit;sources["contextWindowSize"]=computedSource("auto-detected from model")}}if(result.modalities===void 0&&modelId){result.modalities=defaultModalities(modelId);sources["modalities"]=computedSource("auto-detected from model")}return result}__name(resolveGenerationConfig,"resolveGenerationConfig");var gitCoAuthorLogger=createDebugLogger("GIT_CO_AUTHOR");var memoryPressureConfigLogger=createDebugLogger("MEMORY_PRESSURE");var MEMORY_CONTEXT_WARNING_RATIO=.15;var MEMORY_CONTEXT_WARNING_MAX_TOKENS=1e4;var ACTIVE_TODO_REMINDER_REFRESH_TURNS=3;var DEFAULT_TOOL_SEARCH_THRESHOLD=0;var MANAGED_ACTIVATION_LEASE_MS=5*60*1e3;function managedRecordWriter(managed,log){return{canCarry:__name(record3=>managed.sink.canCarry(record3),"canCarry"),write:__name(record3=>managed.sink.write(record3),"write"),project:__name(()=>readManagedSessionRecords({transcriptPath:log.transcriptPath,runtimeBaseDir:log.runtimeBaseDir,sessionKey:managed.authority.sessionHeader.sessionKey}),"project"),stopAdvancing:__name(()=>stopAdvancing(managed),"stopAdvancing"),commitProof:__name(()=>managedCommitProof(managed),"commitProof"),logSize:__name(()=>{try{return fs76.statSync(log.transcriptPath).size}catch{return void 0}},"logSize")}}__name(managedRecordWriter,"managedRecordWriter");async function stopAdvancing(managed){await managed.close();await managed.releaseActivation()}__name(stopAdvancing,"stopAdvancing");function managedCommitProof(managed){const proof=managed.authority.commitProof;return{last_commit_sequence:proof.lastCommitSequence,committed_prefix_hash:proof.committedPrefixHash}}__name(managedCommitProof,"managedCommitProof");function parseVisionModelSetting(setting){if(!setting)return void 0;const nullIdx=setting.indexOf("\0");if(nullIdx<0)return{selector:setting};const selector=setting.slice(0,nullIdx);if(!selector)return void 0;return{selector,baseUrl:setting.slice(nullIdx+1)||void 0}}__name(parseVisionModelSetting,"parseVisionModelSetting");function formatVisionModelSettingForLog(setting){return setting.replace(/\0/g,"\\0")}__name(formatVisionModelSettingForLog,"formatVisionModelSettingForLog");function isValidAdvisorMaxUses(value){return Number.isSafeInteger(value)&&value>=0}__name(isValidAdvisorMaxUses,"isValidAdvisorMaxUses");function normalizeAdvisorModel(model){const trimmed=model?.trim();if(!trimmed||trimmed.toLowerCase()==="off")return void 0;return trimmed}__name(normalizeAdvisorModel,"normalizeAdvisorModel");var TrustGateError=class extends Error{static{__name(this,"TrustGateError")}constructor(message){super(message);this.name="TrustGateError"}};var SESSION_AGENT_APPROVAL_MODE_ERROR='A session agent always asks before writing or running commands; its approval mode stays "default".';var APPROVAL_MODE_INFO={["plan"]:{id:"plan",name:"Plan",description:"Analyze only, do not modify files or execute commands"},["default"]:{id:"default",name:"Default",description:"Require approval for file edits or shell commands"},["auto-edit"]:{id:"auto-edit",name:"Auto Edit",description:"Automatically approve file edits"},["auto"]:{id:"auto",name:"Auto",description:"LLM classifier auto-approves safe actions, blocks risky ones"},["yolo"]:{id:"yolo",name:"YOLO",description:"Automatically approve all tools"}};function normalizeGitCoAuthor(value){if(typeof value==="boolean"){return{commit:value,pr:value}}const pickBool=__name((v2,fieldName)=>{if(v2===void 0)return true;if(typeof v2==="boolean")return v2;if(typeof v2==="string"){const lowered=v2.trim().toLowerCase();if(lowered==="true"||lowered==="yes"||lowered==="on"||lowered==="1"){return true}const knownDisable=["false","no","off","0","disabled",""];if(!knownDisable.includes(lowered)){gitCoAuthorLogger.warn(`Unrecognized string value for general.gitCoAuthor.${fieldName}: ${JSON.stringify(v2)}; treating as false. Accepted forms: true/yes/on/1, false/no/off/0/empty.`)}return false}if(typeof v2==="number")return v2===1;return false},"pickBool");return{commit:pickBool(value?.commit,"commit"),pr:pickBool(value?.pr,"pr")}}__name(normalizeGitCoAuthor,"normalizeGitCoAuthor");var DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD=25e3;var DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES=1e3;var DEFAULT_TOOL_OUTPUT_BATCH_BUDGET=2e5;function normalizeConfigOutputFormat(format){if(!format){return void 0}switch(format){case"stream-json":return"stream-json";case"json":case"json":return"json";case"text":case"text":default:return"text"}}__name(normalizeConfigOutputFormat,"normalizeConfigOutputFormat");function loadMemoryPressureConfig(){const config3={...DEFAULT_PRESSURE_CONFIG};try{config3.softPressureRatio=readMemoryPressureRatioEnv("QWEN_MEMORY_PRESSURE_SOFT",config3.softPressureRatio);config3.hardPressureRatio=readMemoryPressureRatioEnv("QWEN_MEMORY_PRESSURE_HARD",config3.hardPressureRatio);config3.criticalRatio=readMemoryPressureRatioEnv("QWEN_MEMORY_PRESSURE_CRITICAL",config3.criticalRatio);const enableGC=process8.env["QWEN_MEMORY_ENABLE_GC"];if(enableGC&&["0","false","off","no"].includes(enableGC.trim().toLowerCase())){config3.enableExplicitGC=false}validateMemoryPressureConfig(config3)}catch(err){const fallbackMsg=`[QWEN] WARNING: Invalid memory pressure config; using defaults. Error: ${getErrorMessage(err)}`;process8.stderr.write(`${fallbackMsg}
|
|
2109
|
-
`);memoryPressureConfigLogger.warn(fallbackMsg);return{...DEFAULT_PRESSURE_CONFIG}}return config3}__name(loadMemoryPressureConfig,"loadMemoryPressureConfig");var DEFAULT_MAX_SUBAGENT_DEPTH=5;var MAX_SUBAGENT_DEPTH_LIMIT=100;function normalizeMaxSubagentDepth(value){return value==null||!Number.isFinite(value)?DEFAULT_MAX_SUBAGENT_DEPTH:Math.min(MAX_SUBAGENT_DEPTH_LIMIT,Math.max(1,Math.floor(value)))}__name(normalizeMaxSubagentDepth,"normalizeMaxSubagentDepth");function validateMaxSessionTurns(value){const resolved=value??-1;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxSessionTurns: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxSessionTurns,"validateMaxSessionTurns");function normalizeGoalTokenBudget(value){if(value===0||value===-1)return Number.POSITIVE_INFINITY;return isValidGoalTokenBudget(value)?value:GOAL_DEFAULT_TOKEN_BUDGET}__name(normalizeGoalTokenBudget,"normalizeGoalTokenBudget");var GOAL_TOKEN_BUDGET_CAP=10*GOAL_DEFAULT_TOKEN_BUDGET;function isValidGoalTokenBudget(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_TOKEN_BUDGET_CAP)}__name(isValidGoalTokenBudget,"isValidGoalTokenBudget");var GOAL_MAX_TURNS_CAP=1e4;var GOAL_MAX_ACTIVE_MINUTES_CAP=7*24*60;function isValidGoalMaxTurns(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_TURNS_CAP)}__name(isValidGoalMaxTurns,"isValidGoalMaxTurns");function normalizeGoalMaxTurns(value){if(!isValidGoalMaxTurns(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value}__name(normalizeGoalMaxTurns,"normalizeGoalMaxTurns");function isValidGoalMaxActiveMinutes(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_ACTIVE_MINUTES_CAP)}__name(isValidGoalMaxActiveMinutes,"isValidGoalMaxActiveMinutes");function normalizeGoalMaxActiveMinutes(value){if(!isValidGoalMaxActiveMinutes(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value*6e4}__name(normalizeGoalMaxActiveMinutes,"normalizeGoalMaxActiveMinutes");function validateMaxToolCallsPerTurn(value){const resolved=value??DEFAULT_MAX_TOOL_CALLS_PER_TURN;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxToolCallsPerTurn: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxToolCallsPerTurn,"validateMaxToolCallsPerTurn");var MAX_MODEL_FALLBACKS=3;function normalizeModelFallbacks(raw){if(!raw||raw.length===0)return[];const seen=new Set;const result=[];for(const entry of raw){const trimmed=entry.trim();if(!trimmed||seen.has(trimmed))continue;seen.add(trimmed);result.push(trimmed);if(result.length>=MAX_MODEL_FALLBACKS)break}return result}__name(normalizeModelFallbacks,"normalizeModelFallbacks");function bareEnabledGrantWarnings(lists,skills,defaultOffNames=new Set){if(lists.enabled.size===0)return[];const registry3=new Set(skills.map(skill=>skill.name.trim().toLowerCase()));const registryNamesByAuthored=new Map;for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;const group=registryNamesByAuthored.get(authored)??[];group.push(registryName);registryNamesByAuthored.set(authored,group)}const warnings=[];for(const[authored,registryNames]of registryNamesByAuthored){if(registry3.has(authored))continue;if(!lists.enabled.has(authored))continue;const plural=registryNames.length>1;const names=registryNames.map(name=>`'${name}'`).join(", ");const skillWord=plural?"skills":"skill";const hardNote=lists.hardDisabled.has(authored)?` A bare '${authored}' in skills.disabled also blocks ${plural?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove that entry too.`:"";if(lists.defaultDisabled.has(authored)){const offNames=registryNames.filter(name=>defaultOffNames.has(name));const onNames=offNames.filter(name=>lists.enabled.has(name)&&!lists.hardDisabled.has(name)&&!lists.hardDisabled.has(authored));const stillOff=offNames.filter(name=>!onNames.includes(name));if(stillOff.length){const offPlural=stillOff.length>1;const offList=stillOff.map(name=>`'${name}'`).join(", ");const hardQualified=stillOff.filter(name=>lists.hardDisabled.has(name));const qualifiedNote=hardQualified.length?` ${hardQualified.map(name=>`'${name}'`).join(", ")} in skills.disabled also blocks ${hardQualified.length>1?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove ${hardQualified.length>1?"those entries":"that entry"} too.`:"";warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name. The pair cancels the disablement but no longer enables the extension ${offPlural?"skills":"skill"} ${offList}, which ${offPlural?"default":"defaults"} off. Replace the bare '${authored}' with ${offList} in both skills.enabled and skills.defaultDisabled to enable ${offPlural?"them":"it"}.`+hardNote+qualifiedNote)}if(onNames.length){const onPlural=onNames.length>1;const onList=onNames.map(name=>`'${name}'`).join(", ");warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name, but the qualified ${onPlural?"grants":"grant"} ${onList} in skills.enabled already ${onPlural?"enable":"enables"} ${onPlural?"them":"it"}, so the bare pair changes nothing. Replace the bare '${authored}' with ${onList} in both skills.enabled and skills.defaultDisabled to drop the dead entries.`)}continue}warnings.push(`Warning: skills.enabled lists '${authored}' by bare name, which no longer enables the extension ${skillWord} ${names}. Replace it with ${names}.`+hardNote)}return warnings}__name(bareEnabledGrantWarnings,"bareEnabledGrantWarnings");function bareDisablementBlocksQualifiedGrantWarnings(lists,disabledNames,skills){if(lists.enabled.size===0||disabledNames.size===0)return[];const warnings=[];for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;if(!lists.enabled.has(registryName))continue;if(!disabledNames.has(authored))continue;if(lists.hardDisabled.has(authored)){const unlocked=[...new Set(skills.filter(other2=>{const name=other2.name.trim().toLowerCase();return name!==registryName&&(name===authored||authoredSkillName(other2).trim().toLowerCase()===authored)}).map(other2=>other2.name.trim().toLowerCase()))];const names=__name(list2=>list2.map(name=>`'${name}'`).join(", "),"names");const reBlockable=unlocked.filter(name=>name!==authored);const notAlone=unlocked.filter(name=>name===authored);let sideEffect="";if(unlocked.length){sideEffect=` The removal also re-enables ${names(unlocked)}.`;if(reBlockable.length){sideEffect+=` Add ${names(reBlockable)} to skills.disabled to keep ${reBlockable.length>1?"them":"it"} blocked.`}if(notAlone.length){sideEffect+=` ${names(notAlone)} cannot be blocked on ${notAlone.length>1?"their":"its"} own while '${registryName}' stays enabled, because any entry matching ${names(notAlone)} also matches '${registryName}'.`}}warnings.push(`Warning: skills.enabled opts in '${registryName}' but '${authored}' in skills.disabled still blocks it \u2014 hard entries are never cancelled by skills.enabled. Remove '${authored}' from skills.disabled to enable the skill.`+sideEffect);continue}warnings.push(`Warning: skills.enabled opts in '${registryName}' but a bare '${authored}' entry still blocks it \u2014 disable entries match under either spelling; a skills.defaultDisabled entry is cancelled only by the identical spelling. Write '${registryName}' in both lists, or remove '${authored}'.`)}return warnings}__name(bareDisablementBlocksQualifiedGrantWarnings,"bareDisablementBlocksQualifiedGrantWarnings");function readMemoryPressureRatioEnv(envName,fallback){const raw=process8.env[envName];if(!raw){return fallback}const parsed=Number(raw);if(!Number.isFinite(parsed)){throw new Error(`${envName} must be a finite number`)}return parsed}__name(readMemoryPressureRatioEnv,"readMemoryPressureRatioEnv");var DEFAULT_BARE_CORE_TOOLS=[ToolNames.READ_FILE,ToolNames.EDIT,ToolNames.NOTEBOOK_EDIT,ToolNames.SHELL];var EMPTY_DISABLED_SKILL_NAMES=Object.freeze(new Set);var sessionEnvClaimed=false;var projectDirEnvClaimed=false;var modelEnvClaimed=false;function resolveSensitiveSpanAttributeMaxLength(value){if(value===void 0){return DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH}if(!isValidSensitiveSpanAttributeMaxLength(value)){throw new FatalConfigError(`Invalid telemetry.sensitiveSpanAttributeMaxLength: must be a positive integer no greater than ${SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT}, got ${String(value)}`)}return value}__name(resolveSensitiveSpanAttributeMaxLength,"resolveSensitiveSpanAttributeMaxLength");function resolveCronRecurringMaxAgeDays(setting){const env=process8.env["QWEN_CODE_CRON_MAX_AGE_DAYS"];const fromEnv=env!==void 0&&env.trim()!=="";const raw=fromEnv?Number(env):setting;if(raw===void 0||!Number.isFinite(raw)||raw<0){if(raw!==void 0){console.warn((fromEnv?`QWEN_CODE_CRON_MAX_AGE_DAYS="${env}" is invalid`:`cronRecurringMaxAgeDays=${setting} is invalid`)+`; recurring cron jobs will expire after the ${DEFAULT_RECURRING_MAX_AGE_DAYS}-day default.`)}return DEFAULT_RECURRING_MAX_AGE_DAYS}return normalizeRecurringMaxAge(raw,DEFAULT_RECURRING_MAX_AGE_DAYS)}__name(resolveCronRecurringMaxAgeDays,"resolveCronRecurringMaxAgeDays");var SessionWriterShutdownError=class extends SessionWriterUnavailableError{static{__name(this,"SessionWriterShutdownError")}};function containsErrorByIdentity(error3,candidate){return error3===candidate||error3 instanceof Error&&error3.cause instanceof AggregateError&&error3.cause.errors.includes(candidate)}__name(containsErrorByIdentity,"containsErrorByIdentity");var DERIVED_CONFIG=Symbol("derivedConfig");function isDerivedConfig(config3){return config3[DERIVED_CONFIG]===true}__name(isDerivedConfig,"isDerivedConfig");function deriveApprovalModeConfig(base2,mode,options2={}){const baseApprovalMode=base2.getApprovalMode();const initialMode=getTrustedDerivedApprovalMode(base2,mode);let autoOverrideAcquired=false;const acquireAutoOverride=__name(()=>{if(autoOverrideAcquired||base2.getApprovalMode()==="auto"){return}if(options2.hooks){autoOverrideAcquired=options2.hooks.acquireAutoApprovalOverride();return}base2.getPermissionManager?.()?.stripDangerousRulesForAutoMode();autoOverrideAcquired=true},"acquireAutoOverride");const releaseAutoOverride=__name(()=>{if(!autoOverrideAcquired)return;if(options2.hooks){options2.hooks.releaseAutoApprovalOverride()}else if(base2.getApprovalMode()!=="auto"){base2.getPermissionManager?.()?.restoreDangerousRules()}autoOverrideAcquired=false},"releaseAutoOverride");const derived=deriveConfig(base2,{getApprovalMode:Config.prototype.getApprovalMode});const state=derived;state.approvalMode=initialMode;state.prePlanMode=initialMode==="plan"?baseApprovalMode==="plan"?base2.getPrePlanMode():baseApprovalMode:void 0;state.approvalModeRevision=0;state.manualPlanExitNoticeEventState={...base2.manualPlanExitNoticeEventState??{version:0,kind:"clear"}};state.autoModeDenialState=createDenialState();Object.defineProperty(derived,"setApprovalMode",{value:__name((nextMode,setOptions2)=>{const beforeMode=derived.getApprovalMode();const hadOwnPermissionManager=Object.hasOwn(derived,"permissionManager");const ownPermissionManager=state.permissionManager;state.permissionManager=null;try{Config.prototype.setApprovalMode.call(derived,nextMode,setOptions2)}finally{if(hadOwnPermissionManager){state.permissionManager=ownPermissionManager}else{delete state.permissionManager}}const afterMode=derived.getApprovalMode();if(beforeMode!=="auto"&&afterMode==="auto"){acquireAutoOverride()}else if(beforeMode==="auto"&&afterMode!=="auto"){releaseAutoOverride()}},"value"),writable:true,configurable:true,enumerable:true});if(initialMode==="auto"&&base2.getApprovalMode()!=="auto"){acquireAutoOverride()}return{config:derived,cleanup:releaseAutoOverride}}__name(deriveApprovalModeConfig,"deriveApprovalModeConfig");function deriveAgentConfig(base2,workingDirectory,options2={}){const fileService=new FileDiscoveryService(workingDirectory,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(workingDirectory);const derived=deriveConfig(base2,{getTargetDir:__name(()=>workingDirectory,"getTargetDir"),getCwd:__name(()=>workingDirectory,"getCwd"),getWorkingDir:__name(()=>workingDirectory,"getWorkingDir"),getProjectRoot:__name(()=>workingDirectory,"getProjectRoot"),getPlanFilePath:options2.getPlanFilePath,getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=workingDirectory;workspaceState.cwd=workingDirectory;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return{config:derived,fileService,workspaceContext}}__name(deriveAgentConfig,"deriveAgentConfig");function getTrustedDerivedApprovalMode(base2,requestedMode){if((!base2.isTrustedFolder()||base2.isSessionAgentSession?.()===true)&&requestedMode!=="default"&&requestedMode!=="plan"){return"default"}return requestedMode}__name(getTrustedDerivedApprovalMode,"getTrustedDerivedApprovalMode");function deriveWorktreeConfig(base2,worktreePath,options2={}){const fileService=new FileDiscoveryService(worktreePath,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(worktreePath);const derived=deriveConfig(base2,{getTargetDir:__name(()=>worktreePath,"getTargetDir"),getCwd:__name(()=>worktreePath,"getCwd"),getWorkingDir:__name(()=>worktreePath,"getWorkingDir"),getProjectRoot:__name(()=>worktreePath,"getProjectRoot"),getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=worktreePath;workspaceState.cwd=worktreePath;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return derived}__name(deriveWorktreeConfig,"deriveWorktreeConfig");function deriveConfig(base2,overrides={}){const shellSandbox=base2.getShellExecutionSandbox?.();if(shellSandbox){for(const key of["getTargetDir","getCwd","getWorkingDir","getProjectRoot"]){assertShellSandboxCwd(shellSandbox,overrides[key]?.()??base2[key]())}}const derived=Object.create(base2);for(const key in overrides){if(!Object.hasOwn(overrides,key))continue;const override=overrides[key];if(override!==void 0){Object.defineProperty(derived,key,{value:override,writable:true,configurable:true,enumerable:true})}}Object.defineProperty(derived,DERIVED_CONFIG,{value:true});return derived}__name(deriveConfig,"deriveConfig");var Config=class _Config{static{__name(this,"Config")}shellExecutionSandbox;sessionId;sessionSourceType;sessionSourceId;sessionData;pendingSessionRestoreProjection;sessionRestoreRuntime;sessionRestoreProjectionSource;sessionExecutionEngine;managedRuntimeEnvironmentFactory;managedRuntimeEnvironment;onManagedEngineQuarantine;managedRuntimeClosing;managedSessionBlock;restoredFileHistory=false;goalRestoreActivation;rejectGoalRestoreActivation;sessionRuntimeBaseDir;provisionalWorkspace;provisionalWorkspaceActivated=false;provisionalWorkspaceActivation;sessionProjectDirRegistered=false;pendingSessionWriterLease;managedSession;managedRuntimeOutcomes;pendingSessionWriterRelease;sessionWriterReclaimPolicy="local";sessionWriterTakeoverPolicy="never";sessionWriterShutdownRequested=false;sessionWriterHandoffRequested=false;sessionWriterActivationPromise;sessionWriterClosePromise;pendingStartupWorktreeNotice=null;pendingRecoveredAgentsNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;resourceRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry;monitorRegistry=new MonitorRegistry;backgroundAgentResumeService;backgroundShellRegistry=new BackgroundShellRegistry;workflowRunRegistry=new WorkflowRunRegistry;turnBudget=new TurnBudget;fileReadCache=new FileReadCache;extensionManager;skillManager=null;permissionManager=null;toolInvocationGuard;workflowAncestorTrustProvider;modelInvocableCommandsProvider=null;modelInvocableCommandsExecutor=null;pendingInlineAnnouncedSkillKeys=new Set;fileSystemService;contentGeneratorConfig;contentGeneratorConfigSources={};contentGenerator;initialAuthType;initialResolvedAuthType;embeddingModel;modelsConfig;modelProvidersConfig;providerProtocolConfig;sandbox;targetDir;workspaceContext;debugMode;inputFormat;outputFormat;includePartialMessages;question;systemPrompt;workspaceAgentName;workspaceAgentExecutionAllowedTools;workspaceAgentDisallowedTools;sessionAgentSession=false;appendSystemPrompt;liveAppendSystemPrompt;outputStyle;coreTools;allowedTools;excludeTools;disabledSlashCommands;disabledSkillNamesProvider;enabledSkillNamesProvider;skillSettingsListsProvider;terminalImageRenderSupportProvider;disabledSkillLevels;customSkillDirs;disabledTools;visibleTools;eagerTools;toolSearchThreshold;toolMode;freeform;permissionsAllow;permissionsAsk;permissionsDeny;permissionsAutoMode;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;recentlyRemovedMcpServers=new Set;topTierMcpServers;runtimeMcpServers=new Map;lspEnabled;lspClient;lspInitializationError;allowedMcpServers;cliAllowedMcpServerNames;excludedMcpServers;pendingMcpServers;mcpToolIdleTimeoutMs;mcpReconcileInProgress=false;mcpReconcilePending=false;mcpReconcilePromise;sessionSubagents;userMemory;staticSystemPrefix;promptToolSnapshot;promptAgentReachable=false;autoMemoryPrompt="";autoMemoryContext="";memoryRecallMode="legacy";memoryCorpusRevision="";memoryRecallModeInitialized=false;sdkMode;memoryFileCount;loadedContextFilePaths=[];conditionalRulesRegistry;contextRuleExcludes;approvalMode;prePlanMode;planExecutionMode;approvalModeRevision=0;manualPlanExitNoticeEventState={version:0,kind:"clear"};manualPlanExitNoticeCursorState={seenVersion:0};autoModeDenialState=createDenialState();accessibility;showResponseTokensPerSecond;telemetrySettings;telemetryInitializationDeferred;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;activeTodoReminders=new Map;activeTodoWorkChainOwners=new Map;activeTodoReminderTurns=new Map;activeTodoPlanWriterOwner;llmClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;chatRecordingService=void 0;goalRuntime;goalRuntimeReady;pendingGoalProposal;goalProposalApprovalController;pendingGoalRestore;goalTurnHost;goalTurnHostUnbind;goalTurnHostGeneration=0;chatRecordingFailureListeners=new Set;requestLifecycleListeners=new Set;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;goalTokenBudgetGrant;goalTurnBudgetGrant;goalActiveTimeBudgetGrantMs;maxSubagentDepth;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=false;sessionRegistryActive=false;sessionRegistered=false;sessionRegistrySlot=SHARED_RECORD_SLOT;experimentalZedIntegration=false;restoreAskUserQuestion=false;preserveRestorableAskUserQuestion=false;sessionWriterLeaseEnabled=false;cronEnabled=true;cronRecurringMaxAgeDays;lsToolEnabled=false;todoWriteEnabled=false;agentTeamEnabled=false;agentCollaborationEnabled=false;artifactEnabled=true;artifactSnapshotsEnabled=false;artifactAutoOpen=true;artifactPublisher="local";artifactHost;artifactOss;omniEnabled=false;omniMaxUploadFileBytes;omniMaxEstimatedTokens;omniMaxDurationSeconds;omniUrlDownloadMaxFileBytes;omniUploadUrlTtlHours;omniUploadBaseUrl;omniUploadApiKeyEnv;omniUploadModel;omniUploadConfig;omniPolicyTools;omniFixedPolicies;omniTransportGuardPolicies;omniProcessingLimits;omniQuarantineRetentionDays;omniStorageRetentionDays;omniStorageMaxTotalBytes;omniQuarantineMaxBytes;omniMemory;omniProcessingConfig;omniMemoryConfig;omniMediaResourceRegistry;workflowsEnabled;sessionWorkflowEnabled;sessionWorkflowEnabledProvider;sessionWorkflowPlanRevision;externalAgentExecutor;agentExecutionBackend;executionEnvironmentFactory;executionEnvironment;executionEnvironments;executionShutdown=new AbortController;executionCleanupPromise;modelProposedGoals;goalProposalHostSupported=false;goalProposalTurnKey;skipWorkflowUsageWarning=false;workflowSizeGuideline;workflowNameOnly;emitToolUseSummaries=true;chatRecordingEnabled;loadMemoryFromIncludeDirectories=false;importFormat;chatCompression;autoCompactThreshold;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;maxToolCallsPerTurn;maxToolCallsPerTurnExplicit;skipStartupContext;bareMode;safeMode;warnings;ignoredExtensionRules=[];allowedHttpHookUrls;allowPrivateNetworkHooks;onPersistPermissionRuleCallback;initialized=false;initializationPromise;initializationSucceeded=false;initializationSettled=false;shutdownRequested=false;resourceShutdownAfterInitializationScheduled=false;resourceShutdownPromise;proxyDispatcherReady;storage;runtimeStatusWrite=Promise.resolve();sessionRegistryWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputThresholdExplicit;truncateToolOutputLines;toolOutputBatchBudget;shellDefaultTimeoutMs;shellHeartbeatIntervalMs;eventEmitter;channel;jsonFd;jsonFile;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableTeamMemory;enableTeamMemorySync;enableStructuredMemoryRecall;teamMemoryShareabilityChecked=new Set;enableAutoSkill;autoSkillConfirm;memoryAgentTimeoutMinutes;memoryAgentMaxTurns;fastModel;advisorModel;advisorMaxUses;advisorUsage={calls:0};webSearchSettings;webSearchNoticeEmitted=false;webSearchSessionUsage={calls:0};visionModel;compactionModel;reasoningSnapshot;latestReasoningSnapshot;imageModel;visionBridgeTimeoutMs;modelFallbacks;disableAllHooks;stopHookBlockingCap;systemHooks;userHooks;projectHooks;hooks;hookSystem;messageBus;messageBusListeners=new Set;memoryManager;modelChangeListeners=new Set;approvalModeChangeListeners=new Set;ownsModelEnvSlot=false;settingsWatcher;constructor(params){this.executionEnvironment=params.executionEnvironment;if(params.executionEnvironment){this.executionEnvironments=new Set([Promise.resolve(params.executionEnvironment)])}this.agentExecutionBackend=params.agentExecutionBackend;const executionFactory=params.executionEnvironmentFactory;this.executionEnvironmentFactory=executionFactory?(config3,signal)=>executionFactory(config3,AbortSignal.any([signal,this.executionShutdown.signal])):void 0;this.sessionRuntimeBaseDir=Storage.getRuntimeBaseDir();this.shellExecutionSandbox=admitShellSandbox(params,this.sessionRuntimeBaseDir,Storage.getGlobalQwenDir());this.provisionalWorkspace=params.provisionalWorkspace===true;this.sessionId=params.sessionId??randomUUID23();if(!sessionEnvClaimed&&process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId;sessionEnvClaimed=true}this.sessionData=params.sessionData;this.sessionRestoreProjectionSource=params.sessionRestoreProjectionSource;this.sessionExecutionEngine=params.sessionExecutionEngine;this.managedRuntimeEnvironmentFactory=params.sessionExecutionEngine==="managed"?params.managedRuntimeEnvironment:void 0;this.onManagedEngineQuarantine=params.sessionExecutionEngine==="managed"?params.onManagedEngineQuarantine:void 0;this.setSessionRestoreProjection(params.sessionRestoreProjection);if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();this.embeddingModel=params.embeddingModel??DEFAULT_QWEN_EMBEDDING_MODEL;this.fileSystemService=new StandardFileSystemService;this.sandbox=params.sandbox;this.targetDir=path81.resolve(params.targetDir);this.plansDirectoryConfigured=Boolean(params.plansDirectory?.trim());this.plansDir=Storage.getPlansDir(this.targetDir,params.plansDirectory);this.explicitIncludeDirectories=Array.from(new Set(params.includeDirectories??[]));this.workspaceContext=new WorkspaceContext(this.targetDir,this.explicitIncludeDirectories);this.debugMode=params.debugMode;this.inputFormat=params.inputFormat??"text";const normalizedOutputFormat=normalizeConfigOutputFormat(params.outputFormat??params.output?.format);this.outputFormat=normalizedOutputFormat??"text";this.includePartialMessages=params.includePartialMessages??false;this.question=params.question;this.systemPrompt=params.systemPrompt;this.appendSystemPrompt=params.appendSystemPrompt;this.outputStyle=params.outputStyle;this.coreTools=params.coreTools;this.allowedTools=params.allowedTools;this.excludeTools=params.excludeTools;this.disabledSlashCommands=Object.freeze([...params.disabledSlashCommands??[]]);this.disabledSkillNamesProvider=params.disabledSkillNamesProvider??null;this.enabledSkillNamesProvider=params.enabledSkillNamesProvider??null;this.skillSettingsListsProvider=params.skillSettingsListsProvider??null;this.terminalImageRenderSupportProvider=params.terminalImageRenderSupportProvider??null;this.disabledSkillLevels=new Set(params.disabledSkillLevels??[]);this.customSkillDirs=Object.freeze([...params.customSkillDirs??[]]);this.disabledTools=new Set(params.disabledTools??[]);this.visibleTools=new Set((params.visibleTools??[]).filter(name=>typeof name==="string"));this.eagerTools=params.eagerTools===void 0?void 0:Object.freeze(params.eagerTools.filter(name=>typeof name==="string"));this.toolSearchThreshold=params.toolSearchThreshold??DEFAULT_TOOL_SEARCH_THRESHOLD;this.permissionsAllow=params.permissions?.allow||[];this.permissionsAsk=params.permissions?.ask||[];this.permissionsDeny=params.permissions?.deny||[];this.permissionsAutoMode=params.permissions?.autoMode??{};this.toolInvocationGuard=params.toolInvocationGuard;this.workflowAncestorTrustProvider=params.workflowAncestorTrustProvider;this.toolDiscoveryCommand=params.toolDiscoveryCommand;this.toolCallCommand=params.toolCallCommand;this.mcpServerCommand=params.mcpServerCommand;this.mcpServers=params.mcpServers;this.topTierMcpServers=params.topTierMcpServers;this.lspEnabled=params.lsp?.enabled??false;this.lspClient=params.lspClient;this.allowedMcpServers=params.allowedMcpServers;this.cliAllowedMcpServerNames=params.cliAllowedMcpServerNames;this.excludedMcpServers=params.excludedMcpServers;this.pendingMcpServers=params.pendingMcpServers;const envTimeout=process8.env["QWEN_CODE_MCP_TOOL_IDLE_TIMEOUT_MS"];const parsedEnv=envTimeout!==void 0?Number(envTimeout):NaN;this.mcpToolIdleTimeoutMs=params.mcpToolIdleTimeoutMs??(Number.isFinite(parsedEnv)&&parsedEnv>=0?parsedEnv:3e5);this.sessionSubagents=params.sessionSubagents??[];this.sdkMode=params.sdkMode??false;this.userMemory=params.userMemory??"";this.memoryFileCount=params.memoryFileCount??params.geminiMdFileCount??0;this.contextRuleExcludes=params.contextRuleExcludes??[];this.approvalMode=params.approvalMode??"auto";this.accessibility=params.accessibility??{};this.showResponseTokensPerSecond=params.showResponseTokensPerSecond??false;this.telemetrySettings={enabled:params.telemetry?.enabled??false,target:params.telemetry?.target??DEFAULT_TELEMETRY_TARGET,otlpEndpoint:params.telemetry?.otlpEndpoint,otlpProtocol:params.telemetry?.otlpProtocol,otlpTracesEndpoint:params.telemetry?.otlpTracesEndpoint,otlpLogsEndpoint:params.telemetry?.otlpLogsEndpoint,otlpMetricsEndpoint:params.telemetry?.otlpMetricsEndpoint,logPrompts:params.telemetry?.logPrompts??true,userId:params.telemetry?.userId?.trim()||void 0,includeSensitiveSpanAttributes:params.telemetry?.includeSensitiveSpanAttributes??false,sensitiveSpanAttributeMaxLength:resolveSensitiveSpanAttributeMaxLength(params.telemetry?.sensitiveSpanAttributeMaxLength),outfile:params.telemetry?.outfile,resourceAttributes:params.telemetry?.resourceAttributes,metrics:params.telemetry?.metrics,resourceAttributeWarnings:params.telemetry?.resourceAttributeWarnings};this.telemetryInitializationDeferred=params.deferTelemetryInitialization??false;this.outboundCorrelationSettings={propagateTraceContext:params.outboundCorrelation?.propagateTraceContext??false,allowDynamicHeaderValues:params.outboundCorrelation?.allowDynamicHeaderValues===true};this.gitCoAuthor={...normalizeGitCoAuthor(params.gitCoAuthor),name:"Qwen-Coder",email:"qwen-coder@alibabacloud.com"};this.usageStatisticsEnabled=params.usageStatisticsEnabled??true;this.fileReadCacheDisabled=params.sessionExecutionEngine==="managed"||(params.fileReadCacheDisabled??false);this.outputLanguageFilePath=params.outputLanguageFilePath;this.fileFiltering={respectGitIgnore:params.fileFiltering?.respectGitIgnore??true,respectQwenIgnore:params.fileFiltering?.respectQwenIgnore??true,customIgnoreFiles:params.fileFiltering?.customIgnoreFiles??[...DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES],enableRecursiveFileSearch:params.fileFiltering?.enableRecursiveFileSearch??true,enableFuzzySearch:params.fileFiltering?.enableFuzzySearch??true};this.fileCheckpointingEnabled=params.fileCheckpointingEnabled??(!params.sdkMode&&(params.interactive??false));this.proxy=params.proxy;this.cwd=params.cwd??process8.cwd();this.fileDiscoveryService=params.fileDiscoveryService??null;this.bugCommand=params.bugCommand;this.maxSessionTurns=validateMaxSessionTurns(params.maxSessionTurns);this.goalTokenBudgetGrant=normalizeGoalTokenBudget(params.goalTokenBudget);if(params.goalTokenBudget!==void 0&&!isValidGoalTokenBudget(params.goalTokenBudget)){this.debugLogger.warn(`Ignoring invalid goalTokenBudget ${String(params.goalTokenBudget)}: expected a non-negative integer or -1 (no budget); using the default of ${GOAL_DEFAULT_TOKEN_BUDGET}.`)}this.goalTurnBudgetGrant=normalizeGoalMaxTurns(params.goalMaxTurns);if(params.goalMaxTurns!==void 0&&!isValidGoalMaxTurns(params.goalMaxTurns)){this.debugLogger.warn(`Ignoring invalid goalMaxTurns ${String(params.goalMaxTurns)}: expected an integer between 1 and ${GOAL_MAX_TURNS_CAP}, or -1 for no turn ceiling; Goals will run with no turn ceiling.`)}this.goalActiveTimeBudgetGrantMs=normalizeGoalMaxActiveMinutes(params.goalMaxActiveMinutes);if(params.goalMaxActiveMinutes!==void 0&&!isValidGoalMaxActiveMinutes(params.goalMaxActiveMinutes)){this.debugLogger.warn(`Ignoring invalid goalMaxActiveMinutes ${String(params.goalMaxActiveMinutes)}: expected an integer between 1 and ${GOAL_MAX_ACTIVE_MINUTES_CAP}, or -1 for no time ceiling; Goals will run with no time ceiling.`)}this.maxSubagentDepth=normalizeMaxSubagentDepth(params.maxSubagentDepth);this.maxWallTimeSeconds=params.maxWallTimeSeconds??-1;this.maxToolCalls=params.maxToolCalls??-1;const clearContextOnIdle=params.clearContextOnIdle;const toolResultsThresholdMinutes=clearContextOnIdle?.toolResultsThresholdMinutes??60;this.clearContextOnIdle={toolResultsThresholdMinutes,toolResultsNumToKeep:clearContextOnIdle?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:clearContextOnIdle?.toolResultsTotalCharsThreshold??((clearContextOnIdle?.toolResultsThresholdMinutes??0)<0?-1:DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD)};this.sessionTokenLimit=params.sessionTokenLimit??-1;this.experimentalZedIntegration=params.experimentalZedIntegration??false;this.restoreAskUserQuestion=params.restoreAskUserQuestion===true;this.preserveRestorableAskUserQuestion=this.restoreAskUserQuestion;this.sessionWriterLeaseEnabled=this.experimentalZedIntegration===true&¶ms.sessionWriterLeaseEnabled===true;this.cronEnabled=params.cronEnabled??true;this.cronRecurringMaxAgeDays=resolveCronRecurringMaxAgeDays(params.cronRecurringMaxAgeDays);this.lsToolEnabled=params.lsToolEnabled??false;this.todoWriteEnabled=params.todoWriteEnabled??false;this.agentTeamEnabled=params.agentTeamEnabled??false;this.agentCollaborationEnabled=params.agentCollaborationEnabled??false;this.artifactEnabled=params.artifactEnabled??true;this.artifactAutoOpen=params.artifactAutoOpen??true;this.artifactPublisher=params.artifactPublisher??"local";this.artifactHost=params.artifactHost;this.artifactOss=params.artifactOss;this.omniEnabled=params.omniEnabled??false;this.omniMaxUploadFileBytes=params.omniMaxUploadFileBytes;this.omniMaxEstimatedTokens=params.omniMaxEstimatedTokens;this.omniMaxDurationSeconds=params.omniMaxDurationSeconds;this.omniUrlDownloadMaxFileBytes=params.omniUrlDownloadMaxFileBytes;this.omniUploadUrlTtlHours=params.omniUploadUrlTtlHours;this.omniUploadBaseUrl=params.omniUploadBaseUrl;this.omniUploadApiKeyEnv=params.omniUploadApiKeyEnv;this.omniUploadModel=params.omniUploadModel;this.omniPolicyTools=params.omniPolicyTools;this.omniFixedPolicies=params.omniFixedPolicies;this.omniTransportGuardPolicies=params.omniTransportGuardPolicies;this.omniProcessingLimits=params.omniProcessingLimits;this.omniQuarantineRetentionDays=params.omniQuarantineRetentionDays;this.omniQuarantineMaxBytes=params.omniQuarantineMaxBytes;this.omniStorageRetentionDays=params.omniStorageRetentionDays;this.omniStorageMaxTotalBytes=params.omniStorageMaxTotalBytes;this.omniMemory=params.omniMemory;this.workflowsEnabled=params.workflowsEnabled;this.sessionWorkflowEnabled=params.sessionWorkflowEnabled??false;this.modelProposedGoals=params.modelProposedGoals??"alwaysAsk";this.skipWorkflowUsageWarning=params.skipWorkflowUsageWarning??false;this.workflowSizeGuideline=isWorkflowSizeGuideline(params.workflowSizeGuideline)?params.workflowSizeGuideline:void 0;this.workflowNameOnly=params.workflowNameOnly===true||process8.env["QWEN_CODE_WORKFLOW_NAME_ONLY"]==="1";this.workflowRunRegistry.setNameOnly(this.workflowNameOnly);this.emitToolUseSummaries=params.emitToolUseSummaries??true;this.listExtensions=params.listExtensions??false;this.overrideExtensions=params.overrideExtensions;this.noBrowser=params.noBrowser??false;this.folderTrustFeature=params.folderTrustFeature??false;this.folderTrust=params.folderTrust??false;this.ideMode=params.ideMode??false;this.modelProvidersConfig=params.modelProvidersConfig;this.providerProtocolConfig=params.providerProtocolConfig;this.cliVersion=params.cliVersion;this.chatRecordingEnabled=params.chatRecording??true;this.loadMemoryFromIncludeDirectories=params.loadMemoryFromIncludeDirectories??false;this.importFormat=params.importFormat??"tree";this.chatCompression=params.chatCompression;this.autoCompactThreshold=params.autoCompactThreshold;this.interactive=params.interactive??false;this.trustedFolder=params.trustedFolder;this.skipLoopDetection=params.skipLoopDetection??false;this.maxToolCallsPerTurn=validateMaxToolCallsPerTurn(params.maxToolCallsPerTurn);this.maxToolCallsPerTurnExplicit=params.maxToolCallsPerTurn!==void 0;this.skipStartupContext=params.skipStartupContext??false;this.bareMode=params.bareMode??false;this.safeMode=params.safeMode??isSafeModeEnv();this.toolMode=params.codeModeOnly&&!this.bareMode&&!this.safeMode?ToolMode.CodeModeOnly:ToolMode.Direct;this.freeform=this.toolMode===ToolMode.CodeModeOnly&¶ms.freeform===true;if(this.safeMode){this.debugLogger.info("Safe mode active: hooks, extensions, skills, MCP servers, context files, rules disabled")}this.warnings=params.warnings??[];this.addLegacyPlanLocationWarning();this.allowedHttpHookUrls=params.allowedHttpHookUrls??[];this.allowPrivateNetworkHooks=params.allowPrivateNetworkHooks??false;this.onPersistPermissionRuleCallback=params.onPersistPermissionRule;this.useRipgrep=params.useRipgrep??true;this.useBuiltinRipgrep=params.useBuiltinRipgrep??true;this.shouldUseNodePtyShell=params.shouldUseNodePtyShell??shouldDefaultToNodePty();this.preventSystemSleep=params.preventSystemSleep??true;this.skipNextSpeakerCheck=params.skipNextSpeakerCheck??true;this.shellExecutionConfig={terminalWidth:params.shellExecutionConfig?.terminalWidth??80,terminalHeight:params.shellExecutionConfig?.terminalHeight??24,showColor:params.shellExecutionConfig?.showColor??false,pager:params.shellExecutionConfig?.pager,maxBufferedOutputBytes:params.shellExecutionConfig?.maxBufferedOutputBytes};this.truncateToolOutputThreshold=params.truncateToolOutputThreshold??DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;this.truncateToolOutputThresholdExplicit=params.truncateToolOutputThreshold!=null;this.truncateToolOutputLines=params.truncateToolOutputLines??DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES;this.toolOutputBatchBudget=params.toolOutputBatchBudget??DEFAULT_TOOL_OUTPUT_BATCH_BUDGET;this.shellDefaultTimeoutMs=params.shellDefaultTimeoutMs!==void 0&&Number.isInteger(params.shellDefaultTimeoutMs)&¶ms.shellDefaultTimeoutMs>=0&¶ms.shellDefaultTimeoutMs<=2147483647?params.shellDefaultTimeoutMs:void 0;this.shellHeartbeatIntervalMs=params.shellHeartbeatIntervalMs!==void 0&&Number.isInteger(params.shellHeartbeatIntervalMs)&¶ms.shellHeartbeatIntervalMs>=0&¶ms.shellHeartbeatIntervalMs<=2147483647?params.shellHeartbeatIntervalMs:void 0;this.channel=params.channel;this.jsonFd=params.jsonFd;this.jsonFile=params.jsonFile;this.jsonSchema=params.jsonSchema;this.inputFile=params.inputFile;this.defaultFileEncoding=params.defaultFileEncoding;this.storage=new Storage(this.targetDir,this.sessionRuntimeBaseDir);if(!projectDirEnvClaimed&&process8.env){process8.env["QWEN_CODE_PROJECT_DIR"]=this.storage.getProjectDir();projectDirEnvClaimed=true}this.inputFormat=params.inputFormat??"text";this.fileExclusions=new FileExclusions(this);this.eventEmitter=params.eventEmitter;this.arenaAgentClient=ArenaAgentClient.create();this.agentsSettings=params.agents??{};this.backgroundTaskRegistry=new BackgroundTaskRegistry({...this.agentsSettings.maxParallelAgents!==void 0?{maxConcurrentBackgroundAgents:this.agentsSettings.maxParallelAgents}:{},...this.agentsSettings.maxParallelAgentsByModel!==void 0?{maxConcurrentBackgroundAgentsByModel:this.agentsSettings.maxParallelAgentsByModel}:{}});this.worktreeSettings=params.worktree??{};if(params.contextFileName){setMemoryFilename(params.contextFileName)}this.initialAuthType=params.authType??params.generationConfig?.authType;this.modelsConfig=new ModelsConfig({initialAuthType:this.initialAuthType,modelProvidersConfig:this.modelProvidersConfig,providerProtocolConfig:this.providerProtocolConfig,generationConfig:{model:params.model,...params.generationConfig||{},baseUrl:params.generationConfig?.baseUrl},generationConfigSources:params.generationConfigSources,initialRegistryBaseUrl:params.initialModelRegistryBaseUrl,onModelChange:this.handleModelChange.bind(this)});this.initialResolvedAuthType=this.modelsConfig.getCurrentAuthType();if(!modelEnvClaimed&&process8.env){modelEnvClaimed=true;this.ownsModelEnvSlot=true}this.publishModelEnv();if(this.telemetrySettings.enabled&&!this.telemetryInitializationDeferred){void Promise.resolve(initializeTelemetry(this)).catch(error3=>{this.debugLogger.error("Failed to initialize telemetry:",error3)})}const proxyUrl=this.getProxy();if(proxyUrl&&(params.installProxyDispatcher??true)){this.proxyDispatcherReady=loadUndici().then(({EnvHttpProxyAgent,setGlobalDispatcher})=>{setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}));setResolvedProxyUrlForRuntimeFetch(proxyUrl)}).catch(error3=>{this.debugLogger.error("Failed to install proxy dispatcher:",redactProxyError(error3));throw error3});this.proxyDispatcherReady.catch(()=>{})}this.llmClient=new LlmClient(this);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;if(!this.sessionRestoreProjectionSource||this.sessionRestoreRuntime||!this.sessionWriterLeaseEnabled){this.initializeGoalRuntime(this.sessionRestoreRuntime?.goalRecords??this.sessionData?.conversation.messages,this.sessionRestoreRuntime)}this.extensionManager=new ExtensionManager({workspaceDir:this.targetDir,enabledExtensionOverrides:this.overrideExtensions,isWorkspaceTrusted:this.isTrustedFolder(),locale:params.locale,usageStatisticsEnabled:this.usageStatisticsEnabled,proxy:this.proxy});this.enableManagedAutoMemory=params.enableManagedAutoMemory??true;this.enableManagedAutoDream=params.enableManagedAutoDream??true;this.enableTeamMemory=params.enableTeamMemory??false;this.enableTeamMemorySync=params.enableTeamMemorySync??false;this.enableStructuredMemoryRecall=params.enableStructuredMemoryRecall??false;this.enableAutoSkill=params.enableAutoSkill??false;this.autoSkillConfirm=params.autoSkillConfirm??true;this.memoryAgentTimeoutMinutes=params.memoryAgentTimeoutMinutes!==void 0&¶ms.memoryAgentTimeoutMinutes>=0?params.memoryAgentTimeoutMinutes:void 0;this.memoryAgentMaxTurns=params.memoryAgentMaxTurns!==void 0&&Number.isInteger(params.memoryAgentMaxTurns)&¶ms.memoryAgentMaxTurns>=0?params.memoryAgentMaxTurns:void 0;this.fastModel=params.fastModel||void 0;this.advisorModel=normalizeAdvisorModel(params.advisorModel);this.advisorMaxUses=isValidAdvisorMaxUses(params.advisorMaxUses)?params.advisorMaxUses:0;this.webSearchSettings=params.webSearch;this.visionModel=params.visionModel||void 0;this.compactionModel=params.compactionModel||void 0;this.imageModel=params.imageModel||void 0;this.visionBridgeTimeoutMs=params.visionBridgeTimeoutMs!==void 0&&Number.isInteger(params.visionBridgeTimeoutMs)&¶ms.visionBridgeTimeoutMs>0&¶ms.visionBridgeTimeoutMs<=2147483647?params.visionBridgeTimeoutMs:void 0;this.modelFallbacks=normalizeModelFallbacks(params.modelFallbacks);this.disableAllHooks=params.disableAllHooks??false;this.stopHookBlockingCap=resolveStopHookBlockingCap(params.stopHookBlockingCap);this.systemHooks=params.systemHooks;this.userHooks=params.userHooks;this.projectHooks=params.projectHooks;this.hooks=params.hooks;this.settingsWatcher=params.settingsWatcher;this.memoryManager=new MemoryManager}async initialize(options2){if(this.executionEnvironment){options2={...options2,skipHooks:true,skipMcpDiscovery:true,skipSkillManager:true,skipFileCheckpointing:true}}if(this.sessionExecutionEngine==="managed"){options2={...options2,skipMcpDiscovery:true}}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot be initialized")}if(this.initialized){if(!this.initializationSettled){options2?.signal?.throwIfAborted();this.debugLogger.debug("Config.initialize() called while initialization is in flight; joining the existing run");await this.initializationPromise;return}throw Error("Config was already initialized")}if(this.shutdownRequested){throw Error("Config is shutting down")}options2?.signal?.throwIfAborted();this.initialized=true;const initialization=this.initializeOnce(options2);this.initializationPromise=initialization;try{await initialization;this.initializationSucceeded=true}finally{this.initializationSettled=true}}async activateProvisionalWorkspace(){if(!this.provisionalWorkspace||this.provisionalWorkspaceActivated){return}if(this.provisionalWorkspaceActivation){return this.provisionalWorkspaceActivation}const activation=(async()=>{this.getFileService();await this.llmClient.initialize();await this.toolRegistry.warmAll({strict:true});await this.initializeOmniPolicies();logStartSession(this,new StartSessionEvent(this));this.provisionalWorkspaceActivated=true})();this.provisionalWorkspaceActivation=activation;return activation}async initializeOmniPolicies(){if(this.isOmniEnabled()){const{normalizeOmniProcessingConfig}=await import("./config-3AMQTA2S.js");this.omniProcessingConfig=normalizeOmniProcessingConfig({fixedPolicies:this.omniFixedPolicies,transportGuardPolicies:this.omniTransportGuardPolicies,limits:this.omniProcessingLimits,policyTools:this.omniPolicyTools,maxUploadFileBytes:this.omniMaxUploadFileBytes,maxEstimatedTokens:this.omniMaxEstimatedTokens,urlTtlHours:this.omniUploadUrlTtlHours},this.toolRegistry);await this.ensureOmniMemoryConfig()}}isProvisionalWorkspace(){return this.provisionalWorkspace}async initializeOnce(options2){try{if(this.shellExecutionSandbox)this.shellExecutionSandbox=await probeShellSandbox(this.shellExecutionSandbox,options2?.signal);const activation=this.activateChatRecording();this.sessionWriterActivationPromise=activation;try{await activation}finally{if(this.sessionWriterActivationPromise===activation){this.sessionWriterActivationPromise=void 0}}options2?.signal?.throwIfAborted();await this.bindSessionExecutionEngine();registerSessionProjectDir(this.sessionId,this.storage.getProjectDir());this.sessionProjectDirRegistered=true;await this.initializeInternal(options2)}catch(error3){this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}try{await this.closeSessionWriter()}catch(closeError){if(options2?.signal?.aborted&&containsErrorByIdentity(error3,options2.signal.reason)){this.debugLogger.warn("Chat recording close failed after initialization was aborted:",closeError);options2.signal.throwIfAborted()}if(containsErrorByIdentity(error3,closeError)){throw error3}throw new SessionWriterUnavailableError({cause:new AggregateError([error3,closeError],"Chat recording close failed during failed initialization")})}throw error3}}async bindSessionExecutionEngine(){const engine=this.sessionExecutionEngine;if(engine===void 0)return;if(this.sessionRestoreProjectionSource||this.sessionData){assertSessionExecutionEngine(this.pendingSessionRestoreProjection?.executionEngine,this.sessionId,engine);return}if(this.managedSession)return;await this.chatRecordingService?.recordExecutionEngine(engine)}async initializeInternal(options2){this.debugLogger.info("Config initialization started");await this.proxyDispatcherReady;void refreshModelCatalog();options2?.signal?.throwIfAborted();if(this.isOmniEnabled()){const{normalizeDedicatedOmniUploadConfig}=await import("./upload-config-CBT7ARZY.js");this.omniUploadConfig=normalizeDedicatedOmniUploadConfig({baseUrl:this.omniUploadBaseUrl,apiKeyEnv:this.omniUploadApiKeyEnv,model:this.omniUploadModel});const{assertOmniRuntimeDependencies}=await import("./ffmpeg-3AJSGZKK.js");await assertOmniRuntimeDependencies()}if(options2?.skipFileCheckpointing===true||this.shellExecutionSandbox){this.fileCheckpointingEnabled=false;this.fileHistoryService=void 0}if(!this.provisionalWorkspace){this.getFileService()}this.promptRegistry=new PromptRegistry;this.resourceRegistry=new ResourceRegistry;this.extensionManager.setConfig(this);const explicitExtensionNames=this.isSafeMode()?[]:(this.overrideExtensions??[]).filter(n=>n.trim()!==""&&n.toLowerCase()!=="none");recordStartupEvent("config_initialize_extensions_initial_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&!this.getBareMode()){await this.extensionManager.refreshCache()}else if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&explicitExtensionNames.length>0){await this.extensionManager.refreshCache({names:explicitExtensionNames})}recordStartupEvent("config_initialize_extensions_initial_end");options2?.signal?.throwIfAborted();this.debugLogger.debug("Extension manager initialized");recordStartupEvent("config_initialize_hooks_start");if(!this.shellExecutionSandbox&&(options2?.managedHookDispatcher||!options2?.skipHooks&&!this.getDisableAllHooks())){this.hookSystem=new HookSystem(this,options2?.managedHookDispatcher);await this.hookSystem.initialize();this.debugLogger.debug("Hook system initialized");this.messageBus=new MessageBus;this.messageBus.subscribe("hook-execution-request",async request=>{try{const hookSystem=this.hookSystem;if(!hookSystem){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook system not initialized")});return}if(request.signal?.aborted){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook execution cancelled (aborted)")});return}assertHookExecutionOwner(request.owner,hookSystem.runtimeId,this.getSessionId());await runWithHookExecutionOwner(request.owner,async()=>{let result;let stopHookCount;const input=request.input||{};const signal=request.signal;switch(request.eventName){case"UserPromptSubmit":result=await hookSystem.fireUserPromptSubmitEvent(input["prompt"]||"",signal,typeof input["submitted_prompt"]==="string"&&input["submitted_prompt"].trim().length>0?input["submitted_prompt"]:void 0);break;case"UserPromptExpansion":result=await hookSystem.fireUserPromptExpansionEvent(input["command_name"]||"",input["command_args"]||"",input["prompt"]||"",signal);break;case"Stop":{const contextUsageData=buildContextUsage(input["context_limit"],input["input_tokens"]??0);const stopResult=await hookSystem.fireStopEvent(input["stop_hook_active"]||false,input["last_assistant_message"]||"",contextUsageData,signal);result=stopResult.finalOutput?createHookOutput("Stop",stopResult.finalOutput):void 0;stopHookCount=stopResult.allOutputs.length;break}case"MessageDisplay":{const messageDisplayResult=await hookSystem.fireMessageDisplayEvent(input["message_id"]||"",input["displayed_text"]||"",input["is_final"]||false,signal);result=messageDisplayResult.finalOutput?createHookOutput("MessageDisplay",messageDisplayResult.finalOutput):void 0;break}case"PreToolUse":{result=await hookSystem.firePreToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["permission_mode"]??"default",signal,input["tool_call_id"]||void 0);break}case"PostToolUse":result=await hookSystem.firePostToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_response"]||{},input["tool_use_id"]||"",input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolUseFailure":result=await hookSystem.firePostToolUseFailureEvent(input["tool_use_id"]||"",input["tool_name"]||"",input["tool_input"]||{},input["error"]||"",input["is_interrupt"],input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolBatch":result=await hookSystem.firePostToolBatchEvent(input["tool_calls"]||[],input["permission_mode"]||"default",signal);break;case"Notification":result=await hookSystem.fireNotificationEvent(input["message"]||"",input["notification_type"]||"permission_prompt",input["title"]||void 0,signal);break;case"PermissionRequest":result=await hookSystem.firePermissionRequestEvent(input["tool_name"]||"",input["tool_input"]||{},input["permission_mode"]||"default",input["permission_suggestions"]||void 0,signal);break;case"PermissionDenied":result=await hookSystem.firePermissionDeniedEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["reason"]||"classifier_blocked",signal,input["tool_call_id"]||void 0);break;case"SubagentStart":result=await hookSystem.fireSubagentStartEvent(input["agent_id"]||"",input["agent_type"]||"",input["permission_mode"]||"default",signal);break;case"SubagentStop":result=await hookSystem.fireSubagentStopEvent(input["agent_id"]||"",input["agent_type"]||"",input["agent_transcript_path"]||"",input["last_assistant_message"]||"",input["stop_hook_active"]||false,input["permission_mode"]||"default",signal);break;case"SessionStart":result=await hookSystem.fireSessionStartEvent(input["source"],input["model"]||"",input["permission_mode"]||void 0,input["agent_type"],signal);break;case"SessionEnd":result=await hookSystem.fireSessionEndEvent(input["reason"],signal);break;case"SessionDelete":result=await hookSystem.fireSessionDeleteEvent(input["deleted_session_id"]||"",signal);break;case"PreCompact":result=await hookSystem.firePreCompactEvent(input["trigger"],input["custom_instructions"]||"",signal);break;case"PostCompact":result=await hookSystem.firePostCompactEvent(input["trigger"],input["compact_summary"]||"",signal);break;case"InstructionsLoaded":result=await hookSystem.fireInstructionsLoadedEvent(input["file_path"]||"",input["memory_type"],input["load_reason"],{triggerFilePath:input["trigger_file_path"],parentFilePath:input["parent_file_path"]},signal);break;case"StopFailure":result=(await hookSystem.fireStopFailureEvent(input["error"],input["error_details"],input["last_assistant_message"],signal)).finalOutput;break;case"TodoCreated":result=(await hookSystem.fireTodoCreatedEvent(input["todo_id"]||"",input["todo_content"]||"",input["todo_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;case"TodoCompleted":result=(await hookSystem.fireTodoCompletedEvent(input["todo_id"]||"",input["todo_content"]||"",input["previous_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;default:this.debugLogger.warn(`Unknown hook event: ${request.eventName}`);result=void 0}this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:true,output:result,stopHookCount})})}catch(error3){this.debugLogger.warn(`Hook execution failed: ${error3}`);this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:error3 instanceof Error?error3:new Error(String(error3))})}});this.announceMessageBus(this.messageBus);this.debugLogger.debug("MessageBus initialized with hook subscription")}else{this.debugLogger.debug("Hook system disabled, skipping initialization")}recordStartupEvent("config_initialize_hooks_end");options2?.signal?.throwIfAborted();this.subagentManager=new SubagentManager(this);recordStartupEvent("config_initialize_skills_start");if(!options2?.skipSkillManager){if(!this.provisionalWorkspace&&this.getAutoSkillEnabled()&&this.isTrustedFolder()){try{const curatorResult=await maybeRunAutoSkillCurator(this.getProjectRoot());if(curatorResult.status==="ran"){this.debugLogger.debug(`Auto-skill curator checked ${curatorResult.result.checked} skill(s) and archived ${curatorResult.result.archived.length}.`)}}catch(error3){this.debugLogger.warn(`Auto-skill curator skipped: ${error3 instanceof Error?error3.message:String(error3)}`)}}this.skillManager=new SkillManager(this);if(this.shellExecutionSandbox||this.getBareMode()||this.isSafeMode()){await this.skillManager.refreshCache()}else{await this.skillManager.startWatching()}this.debugLogger.debug("Skill manager initialized");if(this.skillSettingsListsProvider){try{const lists=this.skillSettingsListsProvider();const skills=await this.skillManager.listSkills();const extensionIdByName=new Map(this.getExtensions().map(extension=>[extension.name,extension.id]));const defaultOffNames=new Set;for(const skill of skills){const extensionId=skill.extensionName?extensionIdByName.get(skill.extensionName):void 0;if(skill.level!=="extension"||!extensionId)continue;const state=this.extensionManager.getExtensionSkillState(extensionId,authoredSkillName(skill));if(state.defaultEnabled===false&&!state.workspaceEnabled){defaultOffNames.add(skill.name.trim().toLowerCase())}}this.warnings.push(...bareEnabledGrantWarnings(lists,skills,defaultOffNames),...bareDisablementBlocksQualifiedGrantWarnings(lists,this.getDisabledSkillNames(),skills))}catch(error3){this.debugLogger.warn(`Skill settings migration warning skipped: ${getErrorMessage(error3)}`)}}}else{this.skillManager=null;this.debugLogger.debug("Skill manager skipped")}recordStartupEvent("config_initialize_skills_end");options2?.signal?.throwIfAborted();this.memoryPressureConfig=loadMemoryPressureConfig();this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig);this.permissionManager=new PermissionManager(this);this.permissionManager.initialize();this.debugLogger.debug("Permission manager initialized");if(this.sessionSubagents.length>0){this.subagentManager.loadSessionSubagents(this.sessionSubagents)}recordStartupEvent("config_initialize_extensions_final_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.isSafeMode()){await this.extensionManager.refreshCache()}recordStartupEvent("config_initialize_extensions_final_end");options2?.signal?.throwIfAborted();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_hierarchical_memory_start");await this.refreshHierarchicalMemory("session_start",options2?.signal);recordStartupEvent("config_initialize_hierarchical_memory_end");this.debugLogger.debug("Hierarchical memory loaded")}options2?.signal?.throwIfAborted();const legacyBlockingMcp=process8.env["QWEN_CODE_LEGACY_MCP_BLOCKING"]==="1";const skipInlineMcpDiscovery=this.getBareMode()||this.isSafeMode()||this.provisionalWorkspace||!legacyBlockingMcp||options2?.skipMcpDiscovery===true;recordStartupEvent("config_initialize_tool_registry_start");this.toolRegistry=await this.createToolRegistry(options2?.sendSdkMcpMessage,skipInlineMcpDiscovery?{skipDiscovery:true}:void 0);options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_registry_end");recordStartupEvent("tool_registry_created",{toolCount:this.toolRegistry.getAllToolNames().length,mcpInline:!skipInlineMcpDiscovery});this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`);if(!(options2?.skipLlmInitialization??options2?.skipGeminiInitialization)&&!this.provisionalWorkspace){await this.llmClient.initialize(void 0,options2?.signal);this.debugLogger.info("LLM client initialized")}else{this.debugLogger.info("LLM client initialization skipped")}this.modelsConfig.detectAndCaptureRuntimeModel();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_tool_warmup_start");await this.toolRegistry.warmAll({strict:options2?.lenientToolWarmup!==true});options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_warmup_end")}if(!this.provisionalWorkspace){await this.initializeOmniPolicies();options2?.signal?.throwIfAborted()}const hasMcpServers=Object.keys(this.getMcpServers()??{}).length>0;if(!this.shellExecutionSandbox&&skipInlineMcpDiscovery&&(!(this.getBareMode()||this.isSafeMode())||hasMcpServers)&&!this.provisionalWorkspace&&!options2?.skipMcpDiscovery){this.startMcpDiscoveryInBackground()}if(!this.provisionalWorkspace){options2?.signal?.throwIfAborted();logStartSession(this,new StartSessionEvent(this))}this.debugLogger.info("Config initialization completed");if(!this.shellExecutionSandbox&&!this.getBareMode()&&this.sessionSourceType!=="agent-host"&&!this.provisionalWorkspace){void(async()=>{try{const root=findGitRoot(this.targetDir)??this.targetDir;const worktreesDir=path81.join(root,".qwen","worktrees");try{await fsPromises4.access(worktreesDir)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${worktreesDir} does not exist`);return}const removed=await cleanupStaleAgentWorktrees(root);if(removed>0){this.debugLogger.info(`Stale worktree sweep removed ${removed} ephemeral worktree(s) under ${root}`)}else{this.debugLogger.debug(`Stale worktree sweep ran under ${root}: nothing to remove`)}}catch(error3){this.debugLogger.warn(`Stale worktree sweep failed (non-fatal): ${error3}`)}})()}}async openManagedSessionLog(lease){const transcriptPath=this.getTranscriptPath();const sessionKey=localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId);const resources=LocalManagedSessionResourceStore.create({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionKey});const create=isManagedSessionTranscriptSync(transcriptPath)?void 0:await this.publishManagedSessionRoot(resources);const open6=__name(()=>openManagedSession({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath,sessionKey,cwd:this.getProjectRoot(),version:this.getCliVersion()||"unknown",workerId:this.sessionId,activationLeaseDurationMs:MANAGED_ACTIVATION_LEASE_MS,lease,resourceStore:resources,...create===void 0?{}:{create}}),"open");try{return await open6()}catch(error3){if(!(error3 instanceof ManagedSessionUncommittedTailError))throw error3;await LocalManagedSessionAuthority.recoverUncommittedTail({lease,sessionKey});return await open6()}}isLegacyTranscript(){const transcriptPath=this.getTranscriptPath();try{if(fs76.statSync(transcriptPath).size===0)return false}catch{return false}return readManagedExecutionEvidenceSync(transcriptPath)===false}async finishManagedWriter(lease,opened){if(opened){try{await stopAdvancing(opened)}catch{}await lease.sealForHandoff(managedCommitProof(opened));return}const takenOver=lease.takeoverCommitProof;if(takenOver!==void 0){await lease.sealForHandoff(takenOver);return}const transcriptPath=this.getTranscriptPath();const evidence=readManagedExecutionEvidenceSync(transcriptPath);if(evidence===false){await lease.release();return}if(evidence===void 0)return;let scan;try{scan=await LocalJsonlManagedSessionJournalStore.read(transcriptPath,localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId))}catch{return}await lease.sealForHandoff({last_commit_sequence:scan.committed,committed_prefix_hash:scan.lastMarkerDigest??EMPTY_COMMIT_PREFIX_HASH})}async publishManagedSessionRoot(resources){const[definitionRef,rootSnapshotRef]=await Promise.all([resources.publish("managed-session-definition",Buffer.from(JSON.stringify({version:1,engine:"managed",model:this.getModel(),approvalMode:this.getApprovalMode()}),"utf8")),resources.publish("managed-session-root-snapshot",Buffer.from(JSON.stringify({version:1,messages:[]}),"utf8"))]);return{definitionRef,rootSnapshotRef,createdBy:`qwen-code/${this.getCliVersion()||"unknown"}`}}async activateChatRecording(){const managed=this.sessionExecutionEngine==="managed";if(managed&&(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled)){throw new SessionExecutionEngineError(this.sessionId,"managed execution requires chat recording and a writer lease")}if(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled){return}if(managed&&this.isLegacyTranscript()){throw new SessionExecutionEngineError(this.sessionId,"belongs to legacy, cannot execute with managed")}if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const recorder=this.chatRecordingService;if(!recorder)throw new SessionWriterUnavailableError;let lease;try{lease=await SessionWriterLease.acquire({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath:this.getTranscriptPath(),processKind:"acp",qwenVersion:this.cliVersion??null,reclaimPolicy:this.sessionWriterReclaimPolicy,takeoverPolicy:managed?"certified":this.sessionWriterTakeoverPolicy,...managed?{lockSchema:{schemaVersion:3,formatVersion:MANAGED_SESSION_FORMAT_VERSION}}:{},onOwnershipAcquired:__name(acquiredLease=>{lease=acquiredLease;this.pendingSessionWriterLease=acquiredLease;if(this.sessionWriterShutdownRequested){this.startPendingSessionWriterRelease(acquiredLease)}},"onOwnershipAcquired")});if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const location=await this.getSessionService().getSessionLocation(this.sessionId);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}if(location==="archived"){throw new SessionTranscriptChangedError}let authoritative;let projection;if(this.sessionRestoreProjectionSource){addDaemonRequestAttribute("qwen-code.daemon.session_restore.projection_acquisition","after_writer_lease");projection=await this.sessionRestoreProjectionSource();if(managed){assertSessionExecutionEngine(projection?.executionEngine,this.sessionId,"managed")}this.setSessionRestoreProjection(projection)}else if(managed&&(this.sessionData||lease.transcriptExistedAtAcquire)){throw new SessionExecutionEngineError(this.sessionId,"managed restore requires a restore projection")}else if(this.sessionData||lease.transcriptExistedAtAcquire){authoritative=await this.getSessionService().loadSession(this.sessionId);if(!authoritative)throw new SessionWriterUnavailableError}else if(location!==void 0){throw new SessionTranscriptChangedError}const persistedTitleInfo=authoritative?this.getSessionService().getSessionTitleInfo(this.sessionId):void 0;await lease.assertOwnedAndUnchanged();if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}this.sessionData=authoritative;if(managed){this.managedSession=await this.openManagedSessionLog(lease);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const sequenceBeforeRepair=this.managedSession.authority.committedSequence;await this.getManagedRuntimeOutcomes()?.recoverCommittedReceipts();if(this.sessionRestoreProjectionSource&&this.managedSession.authority.committedSequence!==sequenceBeforeRepair){projection=await this.sessionRestoreProjectionSource();this.setSessionRestoreProjection(projection)}const unresolved=await unresolvedRuntimeWorkReason(this.managedSession.authority);if(unresolved!==void 0){this.blockManagedSession(new ManagedRuntimeOutcomeUnknownError(`The Managed session's log shows Runtime work with an unknown outcome: ${unresolved}.`))}recorder.bindManagedSink(managedRecordWriter(this.managedSession,{transcriptPath:this.getTranscriptPath(),runtimeBaseDir:this.sessionRuntimeBaseDir}))}recorder.activate(lease,authoritative,persistedTitleInfo,projection?.runtime.recording);if(this.sessionRestoreProjectionSource){this.initializeGoalRuntime(projection?.runtime.goalRecords,projection?.runtime)}this.pendingSessionWriterLease=void 0;lease=void 0;this.startPendingGoalRestore()}catch(error3){let failure=error3;const ownedLease=lease??this.pendingSessionWriterLease;let releaseFailureAlreadyReported=false;const abandonedManagedSession=this.managedSession;this.managedSession=void 0;if(managed&&ownedLease){const finishing=this.finishManagedWriter(ownedLease,abandonedManagedSession);void finishing.catch(()=>void 0);this.pendingSessionWriterRelease={lease:ownedLease,promise:finishing}}if(!(failure instanceof SessionWriterError)&&!(failure instanceof ManagedSessionRecordError)&&failure&&typeof failure==="object"&&typeof failure.code==="string"){failure=new SessionWriterUnavailableError({cause:failure})}try{await this.startPendingSessionWriterRelease(ownedLease);if(this.pendingSessionWriterLease===ownedLease&&(ownedLease?.isReleased??true)&&!ownedLease?.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}if(this.sessionWriterShutdownRequested&&failure instanceof SessionWriterLostError&&ownedLease?.isReleased){failure=new SessionWriterShutdownError}}catch(releaseError){if(releaseError instanceof SessionWriterLostError||ownedLease?.isReleased&&!ownedLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}else{releaseFailureAlreadyReported=containsErrorByIdentity(failure,releaseError);if(!releaseFailureAlreadyReported){failure=new SessionWriterUnavailableError({cause:new AggregateError([failure,releaseError],"Session writer lease release failed during activation cleanup")})}}}finally{if(!releaseFailureAlreadyReported&&this.pendingSessionWriterRelease?.lease===ownedLease){this.pendingSessionWriterRelease=void 0}}this.settlePendingGoalRestore(failure);throw failure}}mcpDiscoveryPromise;startMcpDiscoveryInBackground(){const manager=this.toolRegistry.getMcpClientManager?.();if(!manager){this.debugLogger.debug("Skipping background MCP discovery: ToolRegistry has no MCP client manager");return}this.mcpDiscoveryPromise=manager.discoverAllMcpToolsIncremental(this).then(async()=>{try{await this.llmClient?.setTools()}catch(err){this.debugLogger.error(`setTools() after background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)}}).catch(err=>{this.debugLogger.error(`Background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)})}async waitForMcpReady(){if(this.mcpDiscoveryPromise){await this.mcpDiscoveryPromise}}getFailedMcpServerNames(){const servers=this.getMcpServers();if(!servers){return[]}const failed=[];for(const name of Object.keys(servers)){if(this.isMcpServerDisabled(name)){continue}if(this.isMcpServerPendingApproval(name)){continue}if(getMCPServerStatus(name)!=="connected"){failed.push(name)}}return failed}async refreshHierarchicalMemory(loadReason="refresh",signal){if(this.executionEnvironment)return;if(this.isSafeMode()){this.setUserMemory("");this.autoMemoryPrompt="";this.autoMemoryContext="";this.setMemoryFileCount(0);this.setContextFilePaths([]);this.conditionalRulesRegistry=new ConditionalRulesRegistry([],this.getWorkingDir());return}const{memoryContent,fileCount,contextFilePaths,conditionalRules,ignoredExtensionRules,projectRoot}=await loadServerHierarchicalMemory(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason,onInstructionsLoaded:createInstructionsLoadedCallback(()=>this.hookSystem,signal),extensionRuleSources:this.getExtensionRuleSources()});this.ignoredExtensionRules=ignoredExtensionRules??[];if(this.isManagedMemoryAvailable()){const teamMemoryEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();if(this.getTeamMemoryEnabled()&&!this.isTrustedFolder()){this.debugLogger.debug("Team memory enabled but inactive: workspace is not trusted.")}const teamProjectRoot=this.getProjectRoot();if(teamMemoryEnabled&&!this.teamMemoryShareabilityChecked.has(teamProjectRoot)){this.teamMemoryShareabilityChecked.add(teamProjectRoot);const shareabilityWarning=getTeamMemoryShareabilityWarning(teamProjectRoot);if(shareabilityWarning){this.warnings.push(shareabilityWarning);this.debugLogger.warn(shareabilityWarning)}}let teamAutoMemoryIndex=null;if(teamMemoryEnabled){let teamRootSecurityBlocked=false;try{teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot)}catch(err){if(err instanceof TeamMemoryRootSecurityError){teamRootSecurityBlocked=true;this.debugLogger.warn("team memory root failed the symlink/escape safety check; skipping sync",err)}else{this.debugLogger.warn("team memory index rebuild failed (operational); not security-gating sync",err)}}if(!teamRootSecurityBlocked&&this.getTeamMemorySyncEnabled()){const syncResult=await syncTeamMemory(teamProjectRoot,{message:"chore(memory): sync team memory"}).catch(err=>{this.debugLogger.warn("team memory sync failed",err);return void 0});if(syncResult?.skippedReason){this.debugLogger.warn(`team memory sync skipped: ${syncResult.skippedReason}`)}if(syncResult?.pulled){teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot).catch(()=>teamAutoMemoryIndex)}}}if(!this.memoryRecallModeInitialized){const corpusStatus=this.getStructuredMemoryRecallEnabled()?await this.scanMemoryRecallCorpusStatus().catch(error3=>{this.debugLogger.warn("memory metadata readiness scan failed; preserving the active recall protocol",error3);return void 0}):void 0;this.memoryRecallMode=corpusStatus?.ready?"structured":"legacy";this.memoryCorpusRevision=corpusStatus?.revision??"";this.memoryRecallModeInitialized=true}const[managedAutoMemoryIndexRead,userAutoMemoryIndexRead]=await Promise.all([readAutoMemoryIndexWithStats(this.getProjectRoot()),readUserAutoMemoryIndexWithStats().catch(()=>null)]);this.recordAutoMemoryIndexRead(getAutoMemoryIndexPath(this.getProjectRoot()),managedAutoMemoryIndexRead);this.recordAutoMemoryIndexRead(getUserAutoMemoryIndexPath(),userAutoMemoryIndexRead);const managedAutoMemoryIndex=managedAutoMemoryIndexRead?.content??null;const userAutoMemoryIndex=userAutoMemoryIndexRead?.content??null;this.setUserMemory(memoryContent);const memoryDir=getAutoMemoryRoot(this.getProjectRoot());const userSection={memoryDir:getUserAutoMemoryRoot(),indexContent:userAutoMemoryIndex};const teamSection=teamMemoryEnabled?{memoryDir:getTeamAutoMemoryRoot(this.getProjectRoot()),indexContent:teamAutoMemoryIndex}:void 0;if(this.memoryRecallMode==="structured"){this.autoMemoryPrompt=buildStructuredAutoMemoryPrompt(memoryDir,userSection.memoryDir,teamSection?.memoryDir)}else{const policy=this.memoryManager.buildAutoMemoryPrompt(memoryDir,managedAutoMemoryIndex,userSection,teamSection,{includeIndexes:false});const catalog=buildAutoMemoryIndexContext(memoryDir,managedAutoMemoryIndex,userSection,teamSection);this.autoMemoryPrompt=policy;this.autoMemoryContext=catalog}}else{this.setUserMemory(memoryContent);this.autoMemoryPrompt="";this.autoMemoryContext=""}this.setMemoryFileCount(fileCount);this.setContextFilePaths(contextFilePaths);this.conditionalRulesRegistry=new ConditionalRulesRegistry(conditionalRules,projectRoot)}recordAutoMemoryIndexRead(indexPath,indexRead){if(indexRead===null||this.getFileReadCacheDisabled()){return}this.getFileReadCache().recordRead(indexPath,indexRead.stats,{full:true,cacheable:true})}buildMemoryContextWarning(memoryContent){const contextWindowSize=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??tokenLimit(this.getModel(),"input");if(!contextWindowSize||contextWindowSize<=0||!memoryContent){return void 0}const estimatedTokens=Math.ceil(memoryContent.length/CHARS_PER_TOKEN);const ratioTokens=Math.floor(contextWindowSize*MEMORY_CONTEXT_WARNING_RATIO);const thresholdTokens=Math.min(ratioTokens,MEMORY_CONTEXT_WARNING_MAX_TOKENS);if(estimatedTokens<=thresholdTokens){return void 0}const windowClause=`${Math.round(MEMORY_CONTEXT_WARNING_RATIO*100)}% of this model's ${contextWindowSize.toLocaleString()} token context window`;const bound=thresholdTokens===ratioTokens?windowClause:`${MEMORY_CONTEXT_WARNING_MAX_TOKENS.toLocaleString()} tokens \u2014 the smaller of that and ${windowClause}`;return`Warning: Loaded always-on context (QWEN.md context files + auto-memory) uses about ${estimatedTokens.toLocaleString()} tokens, more than ${bound}. Consider trimming long always-loaded context or moving details into on-demand files.`}getMemoryDiscoveryDirectories(){if(!this.shouldLoadMemoryFromIncludeDirectories()){return[]}if(this.getBareMode()){return this.explicitIncludeDirectories}return[...this.getWorkspaceContext().getDirectories()]}getConditionalRulesRegistry(){return this.conditionalRulesRegistry}setConditionalRulesRegistry(registry3){this.conditionalRulesRegistry=registry3}getContextRuleExcludes(){return this.contextRuleExcludes}getContentGenerator(){return getRuntimeContentGenerator()?.contentGenerator??this.contentGenerator}getModelsConfig(){return this.modelsConfig}updateCredentials(credentials,settingsGenerationConfig){this.modelsConfig.updateCredentials(credentials,settingsGenerationConfig)}reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig){this.modelsConfig.reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig);this.captureLatestReasoning();this.baseLlmClient?.clearPerModelGeneratorCache()}getReasoningSnapshot(){return this.reasoningSnapshot??=captureReasoningSnapshot(this.getAllConfiguredModels())}stageReasoningOverrides(providers,protocols={}){const previous=this.latestReasoningSnapshot??this.getReasoningSnapshot();const models=this.getAllConfiguredModels().map(model=>{const prior=previous.find(row=>row.id===model.id&&row.authType===model.authType&&row.registryBaseUrl===model.registryBaseUrl);const configured=Object.entries(providers??{}).flatMap(([provider,entries])=>model.authType!=="qwen-oauth"&&resolveProviderProtocol(provider,protocols)===model.authType&&Array.isArray(entries)?entries:[]).find(entry=>entry?.id===model.id&&entry.baseUrl===model.registryBaseUrl);return{...model,capabilities:{...model.capabilities,reasoning:configured?configured.capabilities?.reasoning:prior?prior.reasoning:model.capabilities?.reasoning}}});return this.captureLatestReasoning(models)}captureLatestReasoning(models=this.getAllConfiguredModels()){try{const next=captureReasoningSnapshot(models);for(const row of next){if(row.authType!=="qwen-oauth"||row.reasoning?.profile){validateReasoningCapabilities({model:row.id,authType:row.authType,baseUrl:row.baseUrl},row.reasoning)}}const generation=this.getContentGeneratorConfig();if(generation)resolveReasoningForModel(this,{...generation,reasoningSnapshot:next},generation.model,true);this.latestReasoningSnapshot=next;return void 0}catch(error3){const message=`Reasoning settings not applied; keeping the previous configuration. ${getErrorMessage(error3)}`;console.warn(message);return message}}applyReasoningOverrides(){if(!this.latestReasoningSnapshot)this.captureLatestReasoning();const next=this.latestReasoningSnapshot;if(!next||JSON.stringify(next)===JSON.stringify(this.reasoningSnapshot))return false;this.reasoningSnapshot=next;const generation=this.getContentGeneratorConfig();if(generation)generation.reasoningSnapshot=next;this.baseLlmClient?.clearPerModelGeneratorCache();this.notifyModelChangeListeners();return true}getModelProvidersConfig(){return this.modelsConfig.getModelProvidersConfig()}getProviderProtocolConfig(){return this.modelsConfig.getProviderProtocolConfig()}syncModelSelection(authType,modelId,baseUrl){this.modelsConfig.syncAfterAuthRefresh(authType,modelId,baseUrl);this.initialResolvedAuthType=void 0}async refreshAuth(authMethod,isInitialAuth){const hookOwner=captureHookExecutionOwner(this,null);if(!this.contentGenerator&&authMethod===this.initialAuthType){authMethod=this.initialResolvedAuthType??authMethod}const priorGeneration={...this.modelsConfig.getGenerationConfig(),authType:this.modelsConfig.getCurrentAuthType()};const priorReasoning=priorGeneration.reasoning;const priorReasoningSource=this.modelsConfig.getGenerationConfigSources()["reasoning"];const priorReasoningEffort=priorReasoning?priorReasoning.effort:void 0;const modelId=this.modelsConfig.getModel();this.modelsConfig.syncAfterAuthRefresh(authMethod,modelId);const requireCached=this.modelsConfig.consumeRequireCachedCredentialsFlag();const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authMethod,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});const newContentGeneratorConfig=config3;const requestModel=getRequestModel(newContentGeneratorConfig);const deepSeekRoute=getBuiltinDeepSeekReasoning({...priorGeneration,model:getRequestModel(priorGeneration)})||getBuiltinDeepSeekReasoning({...newContentGeneratorConfig,model:requestModel});const explicitOff=priorReasoningSource?.kind==="settings"&&priorReasoningSource.settingsPath==="model.reasoningEffort"||priorReasoningSource?.kind==="programmatic"&&priorReasoningSource.detail==="reasoning selection";const preserveReasoningOff=priorReasoning===false&&(requestModel!==newContentGeneratorConfig.model||newContentGeneratorConfig.thinkingMandatory!==true)&&(!deepSeekRoute||explicitOff&&priorGeneration.authType===newContentGeneratorConfig.authType&&priorGeneration.model===newContentGeneratorConfig.model&&priorGeneration.baseUrl===newContentGeneratorConfig.baseUrl&&resolveReasoningForModel(this,newContentGeneratorConfig)?.canDisable!==false);if(preserveReasoningOff){newContentGeneratorConfig.reasoning=false;if(deepSeekRoute&&priorReasoningSource)sources["reasoning"]=priorReasoningSource}this.contentGenerator=await createContentGenerator(newContentGeneratorConfig,this,requireCached?true:isInitialAuth);this.contentGeneratorConfig=newContentGeneratorConfig;this.contentGeneratorConfigSources=sources;this.publishModelEnv();if(priorReasoning===false&&newContentGeneratorConfig.reasoning===false){this.modelsConfig.getGenerationConfig().reasoning=false;if(preserveReasoningOff&&deepSeekRoute&&priorReasoningSource){this.modelsConfig.getGenerationConfigSources()["reasoning"]=priorReasoningSource}}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}this.baseLlmClient=new BaseLlmClient(this.contentGenerator,this);const messageBus=this.getMessageBus();const hooksEnabled=!this.getDisableAllHooks();if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Successfully authenticated with ${authMethod}`,"auth_success","Authentication successful",void 0,hookOwner).catch(()=>{})}}getBaseLlmClient(){if(!this.baseLlmClient){if(this.contentGenerator){this.baseLlmClient=new BaseLlmClient(this.getContentGenerator(),this)}else{throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.")}}return this.baseLlmClient}getSessionId(){return this.sessionId}getSessionExecutionEngine(){return this.sessionExecutionEngine}getManagedRuntimeEnvironment(){if(isDerivedConfig(this))return void 0;if(!this.managedRuntimeEnvironment&&!this.shutdownRequested&&!this.managedRuntimeClosing){this.managedRuntimeEnvironment=this.managedRuntimeEnvironmentFactory?.(this)}return this.managedRuntimeEnvironment}closeManagedRuntime(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).closeManagedRuntime()}if(!this.managedRuntimeClosing){const environment=this.managedRuntimeEnvironment;this.managedRuntimeEnvironment=void 0;this.managedRuntimeClosing=Promise.resolve(environment?.dispose())}return this.managedRuntimeClosing}blockManagedSession(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).blockManagedSession(reason);return}this.managedSessionBlock??=reason}getManagedSessionBlock(){return this.managedSessionBlock}reportManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).reportManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(true,reason)}clearManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).clearManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(false,reason)}getManagedRuntimeOutcomes(){if(isDerivedConfig(this)||!this.managedSession)return void 0;return this.managedRuntimeOutcomes??=new LocalManagedRuntimeOutcomes(this.managedSession)}getSessionRestoreRuntime(){return this.sessionRestoreRuntime}consumeSessionRestoreProjection(){const projection=this.pendingSessionRestoreProjection;this.pendingSessionRestoreProjection=void 0;return projection}hydrateSessionRestoreFileHistory(){if(this.restoredFileHistory)return;const snapshots=this.sessionRestoreRuntime?.fileHistorySnapshots;if(!snapshots?.length)return;const service=this.getFileHistoryService();if(!service.isEnabled())return;service.restoreFromSnapshots(snapshots);this.restoredFileHistory=true}finalizeSessionRestore(){const runtime=this.sessionRestoreRuntime;if(!runtime)return;this.sessionRestoreRuntime=void 0;if(runtime.attributionSnapshot){try{CommitAttributionService.getInstance().restoreFromSnapshot(runtime.attributionSnapshot)}catch(error3){this.debugLogger.error(`Session restore attribution activation failed: ${error3}`)}}const activateGoal=this.goalRestoreActivation;this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;if(activateGoal){try{void activateGoal().catch(error3=>{this.debugLogger.error(`Session restore goal activation failed: ${error3}`)})}catch(error3){this.debugLogger.error(`Session restore goal activation failed: ${error3}`)}}if(this.restoredFileHistory&&this.fileHistoryService){try{void this.fileHistoryService.validateRestoredSnapshots().catch(error3=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)})}catch(error3){this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)}}}applyWorkspaceAgentPersona(systemPrompt,agentName,executionAllowedTools,disallowedTools){if(this.sessionSourceType!=="agent"){throw new Error("A workspace-agent persona may only be applied to an agent session.")}if(this.systemPrompt!==void 0){throw new Error("This session already has a persona; it cannot be changed in place.")}this.systemPrompt=systemPrompt;this.workspaceAgentName=agentName;this.workspaceAgentExecutionAllowedTools=executionAllowedTools?new Set(executionAllowedTools):void 0;this.workspaceAgentDisallowedTools=disallowedTools?[...disallowedTools]:void 0}getWorkspaceAgentName(){return this.workspaceAgentName}markSessionAgentSession(){if(this.sessionSourceType!=="agent"){throw new Error("Only an agent session can be marked as a session-agents session.")}this.sessionAgentSession=true;this.approvalMode="default";this.prePlanMode=void 0;this.planExecutionMode=void 0}isSessionAgentSession(){return this.sessionAgentSession&&this.sessionSourceType==="agent"}setSessionSource(sourceType,sourceId){this.sessionSourceType=sourceType;this.sessionSourceId=sourceId}getSessionSourceType(){return this.sessionSourceType}getSessionSourceId(){return this.sessionSourceId}getWarnings(){const memoryContextWarning=this.buildMemoryContextWarning([this.getUserMemory(),this.getAutoMemoryPrompt(),this.getAutoMemoryContext()].filter(Boolean).join("\n\n"));const ruleWarnings=this.ignoredExtensionRules.map(displayPath=>`Extension rule ${displayPath} has no \`paths:\` and was skipped. An extension's rules must be conditional: a baseline one would be sent with every request, which is the cost a rule exists to avoid. Add \`paths:\` to it, or move the content into the extension's context file.`);const extra=memoryContextWarning?[...ruleWarnings,memoryContextWarning]:ruleWarnings;return extra.length>0?[...this.warnings,...extra]:this.warnings}getDebugLogger(){return this.debugLogger}startNewSession(sessionId,sessionData){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot start new sessions")}if(this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}if(Object.hasOwn(this,"goalRuntime")){this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalRuntime?.dispose()}const outgoingChatRecordingService=this.chatRecordingService;try{outgoingChatRecordingService?.finalize()}catch{}void outgoingChatRecordingService?.flush().catch(()=>{});const previousSessionId=this.sessionId;const nextSessionId=sessionId??randomUUID23();const isSessionTransition=nextSessionId!==previousSessionId;if(isSessionTransition){logSessionEnd(this)}this.sessionId=nextSessionId;if(process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId}unregisterSessionModel(previousSessionId);this.publishModelEnv();this.sessionData=sessionData;if(isSessionTransition){const skillTool=this.toolRegistry?.getTool?.(ToolNames.SKILL);if(skillTool&&"clearLoadedSkills"in skillTool){skillTool.clearLoadedSkills()}this.toolRegistry?.clearReviewedDeclarations?.();this.permissionManager?.clearSessionAllowRules();this.webSearchSessionUsage.calls=0;this.advisorUsage.calls=0}this.clearSessionRestoreProjection();this.pendingRecoveredAgentsNotice=null;this.clearActiveTodoReminders();if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();outgoingChatRecordingService?.pinSessionIdentity(previousSessionId);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;this.sessionSourceService=this.sessionSourceServiceFactory?.();this.initializeGoalRuntime(this.sessionData?.conversation.messages);this.getFileReadCache().clear();this.toolResultBudget.bytesWritten=0;this.getMemoryPressureMonitor()?.resetForNewSession();this.fileHistoryService=void 0;refreshSessionContext(this.sessionId);CommitAttributionService.resetInstance();if(this.initialized){logStartSession(this,new StartSessionEvent(this),sessionData&&isSessionTransition?previousSessionId:void 0)}if(isSessionTransition){if(this.runtimeStatusEnabled){const oldPath=this.storage.getRuntimeStatusPath(previousSessionId);const newPath=this.storage.getRuntimeStatusPath(this.sessionId);const cliVersion=this.cliVersion??null;const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await clearRuntimeStatus(oldPath);await writeRuntimeStatus(newPath,{sessionId:newSessionId,workDir,qwenVersion:cliVersion})})}if(this.sessionRegistryActive){const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRetriedSessionRegistryPatch({sessionId:newSessionId,cwd:workDir},"session registry record still names the previous session id; peers addressing this session by its new id will be refused until it is re-asserted")}}return this.sessionId}async reassertSessionRegistryRecord(){if(!this.sessionRegistryActive)return;this.queueRetriedSessionRegistryPatch({sessionId:this.sessionId,cwd:this.targetDir},"session registry record could not be re-asserted; peers may keep addressing a stale session id");await this.sessionRegistryWrite}queueRetriedSessionRegistryPatch(patch,failureWarning){this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;let applied=await patchSessionRecord(patch,slot);for(let attempt=0;attempt<2&&!applied;attempt+=1){await delay(250);applied=await patchSessionRecord(patch,slot)}if(!applied){this.debugLogger.warn(failureWarning)}})}markRuntimeStatusEnabled(){this.runtimeStatusEnabled=true}trackSessionRegistration(registration){this.sessionRegistryActive=true;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{const outcome=await registration;this.sessionRegistrySlot=outcome.slot;this.sessionRegistered=outcome.registered;if(!this.sessionRegistered)this.sessionRegistryActive=false}).catch(()=>{this.sessionRegistered=false;this.sessionRegistryActive=false})}getSessionRegistrySlot(){return this.sessionRegistrySlot}async whenSessionRegistered(){await this.sessionRegistryWrite.catch(()=>{});return this.sessionRegistered}async updateSessionRegistryIpcPath(ipcPath,ipcToken){if(!this.sessionRegistryActive)return;let applied=false;this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;applied=await patchSessionRecord({ipcPath,ipcToken},slot);if(ipcPath===void 0||applied)return;for(let attempt=0;attempt<2&&!applied;attempt+=1){await delay(250);applied=await patchSessionRecord({ipcPath,ipcToken},slot)}if(!applied){this.debugLogger.warn("peer inbox address was not published to the session registry; peers cannot discover this session until it restarts")}});await this.sessionRegistryWrite}async unregisterSessionRegistry(){this.sessionRegistryActive=false;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{if(!this.sessionRegistered)return;this.sessionRegistered=false;await unregisterSession(this.sessionRegistrySlot)}).catch(()=>{});await this.sessionRegistryWrite}queueRuntimeStatusWrite(write){this.runtimeStatusWrite=this.runtimeStatusWrite.catch(()=>{}).then(write).catch(()=>{})}queueSessionRegistryWrite(write){this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(write).catch(()=>{})}async flushRuntimeStatusWrites(){await this.runtimeStatusWrite.catch(()=>{})}async refreshCurrentRuntimeStatus(workDir){const sessionId=this.sessionId;if(this.runtimeStatusEnabled){const sidecarPath=this.storage.getRuntimeStatusPath(sessionId);this.queueRuntimeStatusWrite(async()=>{await writeRuntimeStatus(sidecarPath,{sessionId,workDir,qwenVersion:this.cliVersion??null})})}if(this.sessionRegistryActive){this.queueSessionRegistryWrite(async()=>{await patchSessionRecord({cwd:workDir,name:deriveSessionName(workDir,sessionId)},this.sessionRegistrySlot)})}await this.flushRuntimeStatusWrites()}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return getRuntimeContentGenerator()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){if(Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig){return this.modelsConfig.getGenerationConfigSources()}return this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getCurrentModelRegistryBaseUrl(){return this.modelsConfig.getCurrentRegistryBaseUrl()}getCurrentAuthType(){return this.modelsConfig.getCurrentAuthType()}getEffectiveInputModalities(){return this.getContentGeneratorConfig()?.modalities??{}}getModelDisplayName(){return this.modelsConfig.getModelDisplayName(this.getModel())}onModelChange(listener){this.modelChangeListeners.add(listener);return()=>{this.modelChangeListeners.delete(listener)}}notifyModelChangeListeners(){this.publishModelEnv();const model=this.getModel();for(const listener of this.modelChangeListeners){listener(model)}}onApprovalModeChange(listener){this.approvalModeChangeListeners.add(listener);return()=>{this.approvalModeChangeListeners.delete(listener)}}notifyApprovalModeChangeListeners(){if(isDerivedConfig(this))return;for(const listener of this.approvalModeChangeListeners){listener(this.approvalMode,this.prePlanMode)}}publishModelEnv(){if(!process8.env){return}const model=this.getModel();registerSessionModel(this.sessionId,model,this.resolvedModelIdentity());if(this.ownsModelEnvSlot){process8.env["QWEN_CODE_MODEL"]=model;process8.env["QWEN_CODE_MODEL_IDENTITY"]=this.resolvedModelIdentity()}}resolvedModelIdentity(model=this.getModel(),generatorConfig=this.getContentGeneratorConfig()){const authType=generatorConfig?.authType??"";const baseUrl=generatorConfig?.baseUrl??(model===this.getModel()?this.getCurrentModelRegistryBaseUrl():void 0)??"";if(authType===""&&baseUrl==="")return model;const digest=createHash19("sha256").update(`${authType}\0${baseUrl}`).digest("hex").slice(0,8);return`${model}@${digest}`}getModelRouteIdentity(model,generatorConfig){return this.resolvedModelIdentity(model,generatorConfig)}getFastModel(){const selector=this.resolveFastModelSelector();if(!selector)return void 0;const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(model=>model.id===selector.modelId&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly)){return void 0}const rawSelector=resolveModelId(this.fastModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.fastModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}pinnedAuxEndpoint(persisted,modelId,available){const endpoint=persisted?.trim().split("\0")[1];if(!endpoint)return void 0;const hits=available.filter(model=>model.id===modelId&&model.baseUrl===endpoint);const matched=hits.find(model=>model.registryBaseUrl!==void 0)??hits[0];if(!matched){this.debugLogger.warn(`Aux endpoint pin dropped for "${modelId}": no configured entry at ${formatVisionModelSettingForLog(endpoint)}; falling back to the first same-id match.`);return void 0}return matched.registryBaseUrl}getWebSearchSettings(){return this.webSearchSettings}getWebSearchSessionUsage(){return this.webSearchSessionUsage}resolveFastModelSelector(){if(!this.fastModel)return void 0;try{const rawSelector=resolveModelId(this.fastModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare fast model resolution");return void 0}return resolveModelId(this.fastModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setFastModel(model){this.fastModel=model||void 0}getAdvisorMaxUses(){return this.advisorMaxUses}getAdvisorUseCount(){return this.advisorUsage.calls}tryConsumeAdvisorUse(){if(this.advisorMaxUses>0&&this.advisorUsage.calls>=this.advisorMaxUses)return false;this.advisorUsage.calls+=1;return true}getAdvisorModel(){return this.advisorModel}async setAdvisorModel(model){const normalizedModel=normalizeAdvisorModel(model);if(normalizedModel&&this.getDisabledTools().has(ToolNames.ADVISOR)){return false}this.advisorModel=normalizedModel;if(!this.initialized||!this.toolRegistry){return true}await this.syncAdvisorToolRegistration(this.toolRegistry);await this.llmClient?.setTools();return true}setVisionModel(model){this.visionModel=model||void 0}getCompactionModel(){const selector=this.resolveCompactionModelSelector();if(selector){const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(m2=>m2.id===selector.modelId&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!m2.visionOnly)){return void 0}const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.compactionModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}return this.getModel()}resolveCompactionModelSelector(){if(!this.compactionModel)return void 0;try{const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare compaction model resolution");return void 0}return resolveModelId(this.compactionModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setCompactionModel(model){this.compactionModel=model||void 0}async setImageModel(model){this.imageModel=model||void 0;if(!this.initialized||!this.toolRegistry){return}if(this.isImageGenerationEnabled()){await this.registerImageGenerationTool(this.toolRegistry);await this.toolRegistry.ensureTool(ToolNames.IMAGE_GEN)}await this.llmClient.setTools()}getModelFallbacks(){return this.modelFallbacks}getReasoningEffort(){const reasoning=this.getContentGeneratorConfig()?.reasoning;if(!reasoning){return void 0}return reasoning.effort}getReasoningEffortOverride(){const cfg=this.getContentGeneratorConfig();if(!cfg||!DashScopeOpenAICompatibleProvider.isDashScopeProvider(cfg)){return void 0}const configuredReasoning=resolveReasoningForModel(this,cfg);const model=getRequestModel(cfg);const tieredModel=isTieredEffortWireModel(model,configuredReasoning);if(!tieredModel)return void 0;const currentEffort=this.getReasoningEffort();const selected=selectDashScopeThinkingKnob(model,cfg.extra_body,cfg.samplingParams,currentEffort,tieredModel);if(!selected||selected.source==="reasoning"||selected.field==="reasoning_effort"&&selected.value===currentEffort){return void 0}if(selected.field==="enable_thinking"&&selected.value===true){if(selected.source!=="extra_body"){return void 0}const below=selectDashScopeThinkingKnob(model,void 0,cfg.samplingParams,currentEffort,tieredModel);if(below?.source==="samplingParams"&&below.field==="reasoning_effort"&&below.value!==currentEffort){return{source:below.source,field:below.field}}return void 0}return{source:selected.source,field:selected.field}}setReasoningEffort(effort){const applyEffort=__name(cfg=>{setGeneratorReasoningEffort(cfg,effort)},"applyEffort");applyEffort(this.contentGeneratorConfig);const runtimeCfg=getRuntimeContentGenerator()?.contentGeneratorConfig;if(runtimeCfg&&runtimeCfg!==this.contentGeneratorConfig){applyEffort(runtimeCfg)}applyEffort(this.modelsConfig?.getGenerationConfig())}isCurrentPrimaryModel(model){if(model.id!==this.getModel())return false;const cfg=this.getContentGeneratorConfig();const primaryAuthType=cfg?.authType;if(primaryAuthType===void 0)return true;if(model.authType!==primaryAuthType)return false;const primaryBaseUrl=cfg?.baseUrl;if(primaryBaseUrl!==void 0&&model.baseUrl!==void 0){return model.baseUrl===primaryBaseUrl}return true}resolveVisionModelSelection(){if(!this.visionModel)return void 0;const visionModelForLog=formatVisionModelSettingForLog(this.visionModel);const parsedSetting=parseVisionModelSetting(this.visionModel);if(!parsedSetting){this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}if(!selector){this.debugLogger.warn(`vision model pin '${visionModelForLog}' resolved to no selector; falling back to auto-select`);return void 0}const routeMatches=this.getAllConfiguredModels().filter(m2=>m2.id===selector.modelId&&(!selector.authType||m2.authType===selector.authType)&&(!parsedSetting.baseUrl||m2.baseUrl===parsedSetting.baseUrl)&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!this.isCurrentPrimaryModel(m2));if(routeMatches.length>1){this.debugLogger.warn(`vision model pin '${visionModelForLog}' matched multiple configured routes; falling back to auto-select`);return void 0}const match=routeMatches[0];if(!match){this.debugLogger.warn(`vision model pin '${visionModelForLog}' did not match a usable configured model (removed, mistyped, selector-only, or the primary itself); falling back to auto-select`);return void 0}const agentCapable=isFullTurnVisionCapable(match);return{id:getQualifiedVisionModelId(match),...(parsedSetting.baseUrl??match.baseUrl)&&{baseUrl:parsedSetting.baseUrl??match.baseUrl},...agentCapable&&{agentCapable:true}}}getDefaultVisionBridgeModel(){const explicit=this.resolveVisionModelSelection();if(explicit)return explicit;const contentGeneratorConfig=this.getContentGeneratorConfig();return selectVisionBridgeModel(this.getModel(),this.getAllConfiguredModels(),{authType:contentGeneratorConfig?.authType,baseUrl:contentGeneratorConfig?.baseUrl})}getVisionBridgeTimeoutMs(){return this.visionBridgeTimeoutMs}async setModel(newModel,metadata){await this.modelsConfig.setModel(newModel,metadata);if(this.contentGeneratorConfig){this.contentGeneratorConfig.model=newModel}this.notifyModelChangeListeners()}async handleModelChange(authType,requiresRefresh){this.initialResolvedAuthType=void 0;if(!this.contentGeneratorConfig){return}const priorReasoningEffort=this.getReasoningEffort();if(authType==="qwen-oauth"&&!requiresRefresh){const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authType,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});this.contentGeneratorConfig.reasoningRouteBaseUrl=config3.reasoningRouteBaseUrl;this.contentGeneratorConfig.model=config3.model;this.contentGeneratorConfig.samplingParams=config3.samplingParams;this.contentGeneratorConfig.contextWindowSize=config3.contextWindowSize;this.contentGeneratorConfig.enableCacheControl=config3.enableCacheControl;this.contentGeneratorConfig.enableRequestMetadata=config3.enableRequestMetadata;this.contentGeneratorConfig.forceGlobalCacheScope=config3.forceGlobalCacheScope;this.contentGeneratorConfig.cacheRetention=config3.cacheRetention;this.contentGeneratorConfig.cacheRetentionByBlock=config3.cacheRetentionByBlock;this.contentGeneratorConfig.splitToolMedia=config3.splitToolMedia;this.contentGeneratorConfig.toolResultContentFormat=config3.toolResultContentFormat;this.contentGeneratorConfig.modalities=config3.modalities;if("model"in sources){this.contentGeneratorConfigSources["model"]=sources["model"]}if("modalities"in sources){this.contentGeneratorConfigSources["modalities"]=sources["modalities"]}if("samplingParams"in sources){this.contentGeneratorConfigSources["samplingParams"]=sources["samplingParams"]}if("enableCacheControl"in sources){this.contentGeneratorConfigSources["enableCacheControl"]=sources["enableCacheControl"]}if("enableRequestMetadata"in sources){this.contentGeneratorConfigSources["enableRequestMetadata"]=sources["enableRequestMetadata"]}if("forceGlobalCacheScope"in sources){this.contentGeneratorConfigSources["forceGlobalCacheScope"]=sources["forceGlobalCacheScope"]}if("cacheRetention"in sources){this.contentGeneratorConfigSources["cacheRetention"]=sources["cacheRetention"]}if("cacheRetentionByBlock"in sources){this.contentGeneratorConfigSources["cacheRetentionByBlock"]=sources["cacheRetentionByBlock"]}if("contextWindowSize"in sources){this.contentGeneratorConfigSources["contextWindowSize"]=sources["contextWindowSize"]}if("splitToolMedia"in sources){this.contentGeneratorConfigSources["splitToolMedia"]=sources["splitToolMedia"]}if("toolResultContentFormat"in sources){this.contentGeneratorConfigSources["toolResultContentFormat"]=sources["toolResultContentFormat"]}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}resetPreloadedContentGenerator(this.contentGenerator);return}await this.refreshAuth(authType);if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}}getAvailableModels(){return this.modelsConfig.getAvailableModels()}getAvailableModelsForAuthType(authType){return this.modelsConfig.getAvailableModelsForAuthType(authType)}getAllConfiguredModels(authTypes){return this.modelsConfig.getAllConfiguredModels(authTypes)}getResolvedModelConfig(authType,modelId,baseUrl){return this.modelsConfig.getResolvedModel(authType,modelId,baseUrl)}getActiveRuntimeModelSnapshot(){return this.modelsConfig.getActiveRuntimeModelSnapshot()}async switchModel(authType,modelId,options2){await this.modelsConfig.switchModel(authType,modelId,options2);this.notifyModelChangeListeners()}getMaxSessionTurns(){return this.maxSessionTurns}getGoalTokenBudgetGrant(){return this.goalTokenBudgetGrant}getGoalTurnBudgetGrant(){return this.goalTurnBudgetGrant}getGoalActiveTimeBudgetGrantMs(){return this.goalActiveTimeBudgetGrantMs}getMaxSubagentDepth(){return this.maxSubagentDepth}getMaxWallTimeSeconds(){return this.maxWallTimeSeconds}getMaxToolCalls(){return this.maxToolCalls}getClearContextOnIdle(){return this.clearContextOnIdle}getSessionTokenLimit(){return this.sessionTokenLimit}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){const sandboxConfig=this.getSandbox();const seatbeltProfile=process8.env["SEATBELT_PROFILE"];return!!sandboxConfig&&sandboxConfig.command==="sandbox-exec"&&!!seatbeltProfile&&seatbeltProfile.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(oldStorage,newStorage){const oldChatsDir=path81.join(oldStorage.getProjectDir(),"chats");const newChatsDir=path81.join(newStorage.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`,`${this.sessionId}.pr.json`].map(fileName=>({from:path81.join(oldChatsDir,fileName),to:path81.join(newChatsDir,fileName)}))}moveFile(from,to2){try{fs76.renameSync(from,to2)}catch(error3){if(error3.code!=="EXDEV"){throw error3}let copied=false;try{fs76.copyFileSync(from,to2);copied=true;fs76.unlinkSync(from)}catch(fallbackError){if(copied){try{fs76.unlinkSync(to2)}catch{}}throw fallbackError}}}moveCurrentSessionArtifacts(oldStorage,newStorage){const moved=[];for(const{from,to:to2}of this.getCurrentSessionArtifactMoves(oldStorage,newStorage)){if(!fs76.existsSync(from)){continue}fs76.mkdirSync(path81.dirname(to2),{recursive:true});try{this.moveFile(from,to2);moved.push({from,to:to2})}catch(error3){for(const movedArtifact of moved.reverse()){try{fs76.mkdirSync(path81.dirname(movedArtifact.from),{recursive:true});this.moveFile(movedArtifact.to,movedArtifact.from)}catch(rollbackError){this.debugLogger.warn("Failed to roll back moved session artifact",rollbackError)}}throw error3}}}async prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch(error3){this.debugLogger.debug("Continuing session artifact migration after chat recording settle failed:",error3)}await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(oldStorage,newStorage)}catch(error3){if(!opts?.skipProcessChdir){try{process8.chdir(oldDir)}catch(rollbackError){this.debugLogger.warn("Failed to roll back working directory after session artifact migration failed",rollbackError)}}throw error3}}async relocateWorkingDirectory(newDir,expectedCanonicalDir,opts){if(this.shellExecutionSandbox){assertShellSandboxCwd(this.shellExecutionSandbox,path81.resolve(newDir))}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot relocate working directories")}if(this.sessionExecutionEngine==="managed"){throw new Error("A Managed session cannot change its directory.")}if(!opts?.skipArtifactMigration&&this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}const oldDir=opts?.skipProcessChdir?this.cwd:fs76.realpathSync(process8.cwd());const targetPath=path81.resolve(newDir);const expected=expectedCanonicalDir??fs76.realpathSync(targetPath);if(!fs76.statSync(targetPath).isDirectory()){throw new Error(`Path is not a directory: ${targetPath}`)}const workspaceDirectories=WorkspaceContext.resolveRootDirectories(expected,this.explicitIncludeDirectories);if(!opts?.skipProcessChdir){process8.chdir(targetPath);const actualCwd=fs76.realpathSync(process8.cwd());if(actualCwd!==expected){process8.chdir(oldDir);throw new Error(`Changed directory to ${actualCwd}, expected ${expected}.`)}}else{const actualCanonical=fs76.realpathSync(targetPath);if(actualCanonical!==expected){throw new Error(`Realpath mismatch: resolved ${actualCanonical}, expected ${expected}.`)}}const oldStorage=this.storage;if(!opts?.skipArtifactMigration){const newStorage=new Storage(expected,this.sessionRuntimeBaseDir);await this.prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts);this.storage=newStorage;this.chatRecordingService?.resetStoragePaths()}this.backgroundTaskRegistry.disposeResidentAgents();this.targetDir=expected;this.cwd=expected;resetPreloadedContentGenerator(this.contentGenerator);await this.refreshCurrentRuntimeStatus(expected);this.workspaceContext.applyRootDirectories(workspaceDirectories);this.fileDiscoveryService=null;const sessionPrBoundCallback=this.sessionService?.getSessionPrBoundCallback();this.sessionService=void 0;if(sessionPrBoundCallback){this.getSessionService().setSessionPrBoundCallback(sessionPrBoundCallback)}this.fileHistoryService=void 0;this.getFileReadCache().clear();this.memoryRecallMode="legacy";this.memoryCorpusRevision="";this.memoryRecallModeInitialized=false;this.autoMemoryPrompt="";this.autoMemoryContext="";let memoryRefreshError;try{await this.refreshHierarchicalMemory()}catch(error3){memoryRefreshError=error3}let mcpRefreshError;try{await this.waitForMcpReady();await this.refreshMcpServers()}catch(error3){mcpRefreshError=error3}return{...memoryRefreshError!==void 0&&{memoryRefreshError},...mcpRefreshError!==void 0&&{mcpRefreshError}}}setPendingStartupWorktreeNotice(notice){this.pendingStartupWorktreeNotice=notice}consumePendingStartupWorktreeNotice(){const v2=this.pendingStartupWorktreeNotice;this.pendingStartupWorktreeNotice=null;return v2}getProjectRoot(){return this.targetDir}getCwd(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return this.toolRegistry}async shutdown(options2){if(isDerivedConfig(this))return;this.shutdownRequested=true;void this.shutdownExecutionEnvironments().catch(()=>void 0);this.settingsWatcher?.stopWatching();if(this.managedRuntimeEnvironment||this.managedRuntimeClosing){try{await this.closeManagedRuntime()}catch(error3){this.debugLogger.error("Failed to stop the Managed Runtime worker:",error3)}}const closeWriter=__name(()=>this.closeSessionWriter().catch(error3=>{this.debugLogger.error("Failed to release session writer lease:",error3)}),"closeWriter");const earlyWriterClose=!options2?.skipSessionWriter&&this.initializationPromise!==void 0&&!this.initializationSucceeded?closeWriter():void 0;try{if(!options2?.skipSessionWriter&&!earlyWriterClose){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch{}}try{await this.shutdownResources(options2?.strictResourceCleanup===true)}catch(error3){if(options2?.strictResourceCleanup)throw error3}}finally{if(!options2?.skipSessionWriter){await(earlyWriterClose??closeWriter())}this.chatRecordingFailureListeners.clear();this.requestLifecycleListeners.clear();if(options2?.shutdownTelemetry!==false&&isTelemetrySdkInitialized()){await shutdownTelemetry()}}}async shutdownResources(waitForInitialization){if(waitForInitialization){try{await this.initializationPromise}catch{}}else if(this.initializationPromise&&!this.initializationSettled){this.scheduleResourceShutdownAfterInitialization();return}return this.runResourceShutdown()}scheduleResourceShutdownAfterInitialization(){if(this.resourceShutdownAfterInitializationScheduled||!this.initializationPromise){return}this.resourceShutdownAfterInitializationScheduled=true;void this.initializationPromise.then(()=>this.runResourceShutdown(),()=>this.runResourceShutdown()).catch(error3=>{this.debugLogger.error("Deferred Config resource cleanup failed:",error3)})}runResourceShutdown(){if(this.resourceShutdownPromise){return this.resourceShutdownPromise}const shutdown=this.shutdownResourcesOnce();this.resourceShutdownPromise=shutdown;const clear=__name(()=>{if(this.resourceShutdownPromise===shutdown){this.resourceShutdownPromise=void 0}},"clear");void shutdown.then(clear,clear);return shutdown}async shutdownResourcesOnce(){let resourceError;try{this.memoryManager.cancelMigrations();this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}unregisterSessionModel(this.sessionId);if(Object.hasOwn(this,"goalRuntime")){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime disposed"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Config shut down before the session writer became available"));this.goalRuntime?.dispose()}if(this.initialized){this.skillManager?.stopWatching();if(this.toolRegistry){await this.toolRegistry.stop()}this.backgroundTaskRegistry.abortAll();this.monitorRegistry.abortAll({notify:false});this.backgroundShellRegistry.abortAll();this.workflowRunRegistry.abortAll()}}catch(error3){resourceError=error3;this.debugLogger.error("Error during Config shutdown:",error3)}try{await this.shutdownExecutionEnvironments()}catch(cleanupError){const errors=cleanupError instanceof AggregateError?[...cleanupError.errors]:[cleanupError];if(resourceError!==void 0)errors.unshift(resourceError);throw new AggregateError(errors,"Container execution cleanup failed during session shutdown.")}if(resourceError!==void 0)throw resourceError;if(!this.initialized)return;try{await this.cleanupArenaRuntime();await this.cleanupTeamRuntime()}catch(error3){this.debugLogger.error("Error during session runtime cleanup:",error3);throw error3}}getPromptRegistry(){return this.promptRegistry}getResourceRegistry(){return this.resourceRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){const parts=[this.appendSystemPrompt,this.liveAppendSystemPrompt].filter(part=>Boolean(part?.trim()));return parts.length>0?parts.join("\n\n"):void 0}setLiveAppendSystemPrompt(prompt){this.liveAppendSystemPrompt=prompt}getOutputStyle(){return this.outputStyle}setOutputStyle(style){this.outputStyle=style}getCoreTools(){if(this.shellExecutionSandbox)return[ToolNames.SHELL,ToolNames.TASK_STOP,ToolNames.READ_FILE,ToolNames.WRITE_FILE,ToolNames.EDIT,ToolNames.MONITOR,ToolNames.AGENT,ToolNames.EXEC,ToolNames.GLOB,ToolNames.LS,ToolNames.ASK_USER_QUESTION,ToolNames.STRUCTURED_OUTPUT];if(this.getBareMode()){return DEFAULT_BARE_CORE_TOOLS}return this.coreTools}getPermissionsAllow(){const base2=this.permissionsAllow??[];const sdkAllow=[...this.allowedTools??[]];if(sdkAllow.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkAllow){if(t&&!merged.includes(t))merged.push(t)}return merged}getPermissionsAsk(){return this.permissionsAsk}getEagerTools(){return this.eagerTools}getPermissionsDeny(){const base2=this.permissionsDeny??[];const sdkDeny=this.excludeTools??[];if(sdkDeny.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkDeny){if(t&&!merged.includes(t))merged.push(t)}return merged}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getDisabledSlashCommands(){return this.disabledSlashCommands}getDisabledSkillNames(){return this.disabledSkillNamesProvider?.()??EMPTY_DISABLED_SKILL_NAMES}hasSkillSettingsListsProvider(){return this.skillSettingsListsProvider!==null}isSkillEnabled(skill){const registryName=skill.name.trim().toLowerCase();const authoredName=authoredSkillName(skill).trim().toLowerCase();const extension=skill.level==="extension"?this.getExtensions().find(candidate=>candidate.name===skill.extensionName&&candidate.skills?.some(owned=>owned.name.trim().toLowerCase()===authoredName&&owned.filePath===skill.filePath)):void 0;if(skill.level==="extension"&&!extension?.isActive)return false;const disabledNames=this.getDisabledSkillNames();if(skillRestrictionNames(skill).some(entry=>disabledNames.has(entry))){return false}if(!extension||this.enabledSkillNamesProvider?.().has(registryName)){return true}const state=this.extensionManager.getExtensionSkillState(extension.id,authoredSkillName(skill));return state.workspaceEnabled??state.defaultEnabled}getDisabledSkillLevels(){return this.disabledSkillLevels}getCustomSkillDirs(){return this.customSkillDirs}getDisabledTools(){return this.disabledTools}getVisibleTools(){return this.visibleTools}getToolSearchThreshold(){return this.toolSearchThreshold}getCodeModeOnly(){return this.toolMode===ToolMode.CodeModeOnly}getFreeform(){return this.freeform}getToolMode(){return this.toolMode}setDisabledTools(disabled){this.disabledTools=new Set(disabled)}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}mcpTransportPool;setMcpTransportPool(pool){this.mcpTransportPool=pool}getMcpTransportPool(){return this.mcpTransportPool}getSettingsMcpServers(){return this.mcpServers}getTopTierMcpServers(){return this.topTierMcpServers}getMergedMcpServers(){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}for(const[name,cfg]of this.runtimeMcpServers){mcpServers[name]=cfg}return mcpServers}getMcpServers(){if(this.executionEnvironment||this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return{}}let mcpServers=this.isSafeMode()?{...this.topTierMcpServers}:this.getMergedMcpServers();if(this.allowedMcpServers){mcpServers=Object.fromEntries(Object.entries(mcpServers).filter(([key])=>matchesAnyServerPattern(key,this.allowedMcpServers)))}return mcpServers}getExcludedMcpServers(){return this.excludedMcpServers}setExcludedMcpServers(excluded){this.excludedMcpServers=excluded}getMcpToolIdleTimeoutMs(){return this.mcpToolIdleTimeoutMs}isMcpServerDisabled(serverName){if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return true;if(this.mcpServers?.[serverName])return false;for(const extension of this.getActiveExtensions()){if(extension.config.mcpServers?.[serverName]){return this.extensionManager?.getDisabledMcpServers(extension.config.name).includes(serverName)??false}}return false}isMcpServerPendingApproval(serverName){return this.pendingMcpServers?.includes(serverName)??false}approveMcpServerForSession(serverName){if(!this.pendingMcpServers){return}this.pendingMcpServers=this.pendingMcpServers.filter(name=>name!==serverName)}addMcpServers(servers){if(this.shellExecutionSandbox&&Object.keys(servers).length)throw new Error("Tool execution sandbox does not support MCP servers.");if(this.initialized){throw new Error("Cannot modify mcpServers after initialization")}this.mcpServers={...this.mcpServers,...servers}}setMcpServers(servers){if(this.shellExecutionSandbox&&Object.keys(servers??{}).length)throw new Error("Tool execution sandbox does not support MCP servers.");this.mcpServers=servers}setAllowedMcpServers(allowed){this.allowedMcpServers=allowed}getAllowedMcpServers(){return this.allowedMcpServers}getCliAllowedMcpServerNames(){return this.cliAllowedMcpServerNames}setPendingMcpServers(pending){this.pendingMcpServers=pending}getMcpGating(){return{excluded:this.excludedMcpServers,allowed:this.allowedMcpServers,pending:this.pendingMcpServers}}getRecentlyRemovedMcpServers(){return[...this.recentlyRemovedMcpServers]}getMcpServerNames(){return Object.keys(this.getMergedMcpServers())}getMcpServerUnavailableReason(serverName){if(this.recentlyRemovedMcpServers.has(serverName))return"removed";if(!(serverName in this.getMergedMcpServers()))return void 0;if(this.allowedMcpServers&&!matchesAnyServerPattern(serverName,this.allowedMcpServers)){return"not_allowed"}if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return"excluded";if(this.isMcpServerPendingApproval(serverName))return"pending_approval";return void 0}async reinitializeMcpServers(servers){this.debugLogger.debug(`[mcp-hot-reload] reinitializeMcpServers: servers=[${Object.keys(servers??{}).join(", ")}] initialized=${this.initialized} inProgress=${this.mcpReconcileInProgress}`);const prevConfigured=new Set(Object.keys(this.getMergedMcpServers()));this.setMcpServers(servers);const nextConfigured=new Set(Object.keys(this.getMergedMcpServers()));for(const name of nextConfigured){this.recentlyRemovedMcpServers.delete(name)}for(const name of prevConfigured){if(!nextConfigured.has(name)){this.recentlyRemovedMcpServers.add(name)}}await this.refreshMcpServers()}async refreshMcpServers(){if(this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return}if(!this.initialized){this.debugLogger.debug("[mcp-hot-reload] not initialized yet \u2014 deferring to boot-time discovery (no-op)");return}if(this.mcpReconcileInProgress){this.mcpReconcilePending=true;this.debugLogger.debug("[mcp-hot-reload] reconcile already in flight \u2014 coalescing into a follow-up pass");return this.mcpReconcilePromise??Promise.resolve()}this.mcpReconcileInProgress=true;const registry3=this.getToolRegistry();const runReconcile=(async()=>{try{this.debugLogger.debug("[mcp-hot-reload] running incremental reconcile (pass 1)");await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this);let pass=1;while(this.mcpReconcilePending){this.mcpReconcilePending=false;pass+=1;this.debugLogger.debug(`[mcp-hot-reload] running coalesced incremental reconcile (pass ${pass})`);await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this)}this.debugLogger.debug(`[mcp-hot-reload] reconcile complete after ${pass} pass(es); live servers=[${Object.keys(this.getMcpServers()??{}).join(", ")}]`)}catch(err){this.debugLogger.error(`[mcp-hot-reload] reconcile failed: ${err instanceof Error?err.stack??err.message:String(err)}`);throw err}finally{this.mcpReconcileInProgress=false;this.mcpReconcilePending=false;this.mcpReconcilePromise=void 0}})();this.mcpReconcilePromise=runReconcile;await runReconcile}addRuntimeMcpServer(name,config3){if(this.shellExecutionSandbox)throw new Error("Tool execution sandbox does not support MCP servers.");this.runtimeMcpServers.set(name,config3)}getRuntimeMcpServers(){return Object.fromEntries(this.runtimeMcpServers)}removeRuntimeMcpServer(name){return this.runtimeMcpServers.delete(name)}isLspEnabled(){return this.lspEnabled&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.provisionalWorkspace}getLspClient(){return this.lspClient}getLspStatusSnapshot(){if(!this.isLspEnabled()){return this.createLspStatusSnapshot(false)}const clientSnapshot=this.lspClient?.getStatusSnapshot?.();if(clientSnapshot){return{...clientSnapshot,enabled:true,initializationError:this.lspInitializationError??clientSnapshot.initializationError}}if(this.lspClient){return{...this.createLspStatusSnapshot(true,this.lspInitializationError),statusUnavailable:true}}return this.createLspStatusSnapshot(true,this.lspInitializationError??"LSP client is not initialized")}createLspStatusSnapshot(enabled,initializationError){return{enabled,configuredServers:0,readyServers:0,failedServers:0,inProgressServers:0,notStartedServers:0,servers:[],...initializationError?{initializationError}:{}}}setLspClient(client){if(this.shellExecutionSandbox&&client)throw new Error("Tool execution sandbox does not support LSP.");if(this.initialized){throw new Error("Cannot set LSP client after initialization")}this.lspClient=client}setLspInitializationError(error3){if(this.initialized){throw new Error("Cannot set LSP status after initialization")}this.setRuntimeLspInitializationError(error3)}setRuntimeLspInitializationError(error3){this.lspInitializationError=error3 instanceof Error?error3.message:error3}async reinitializeLsp(){if(!this.isLspEnabled()||!this.lspClient?.reinitialize){return void 0}try{const result=await this.lspClient.reinitialize();if(result.reconcile.failed.length>0){this.setRuntimeLspInitializationError(`LSP reload partially failed: ${result.reconcile.failed.join(", ")}`)}else{this.setRuntimeLspInitializationError(void 0)}return result}catch(error3){this.setRuntimeLspInitializationError(error3 instanceof Error?error3:String(error3));throw error3}}getSessionSubagents(){return this.sessionSubagents}setSessionSubagents(subagents){if(this.initialized){throw new Error("Cannot modify sessionSubagents after initialization")}this.sessionSubagents=subagents}getSdkMode(){return this.sdkMode}setSdkMode(value){this.sdkMode=value}getUserMemory(){return this.userMemory}getStaticSystemPrefix(){return this.staticSystemPrefix}setStaticSystemPrefix(prefix){this.staticSystemPrefix=prefix}getPromptToolSnapshot(){return this.promptToolSnapshot}setPromptToolSnapshot(names){this.promptToolSnapshot=names}getPromptAgentReachable(){return this.promptAgentReachable}setPromptAgentReachable(reachable){this.promptAgentReachable=reachable}getAutoMemoryPrompt(){return this.autoMemoryPrompt}getAutoMemoryContext(){return this.memoryRecallMode==="legacy"&&this.getAutoMemoryPrompt()?this.autoMemoryContext:""}getMemoryRecallMode(){return this.memoryRecallMode}async prepareMemoryRecallTransition(){if(!this.getManagedAutoMemoryEnabled())return void 0;if(!this.getStructuredMemoryRecallEnabled())return void 0;if(this.memoryRecallMode==="structured")return void 0;const status=await this.scanMemoryRecallCorpusStatus();if(!status.ready){this.memoryCorpusRevision=status.revision;return void 0}const projectRoot=this.getProjectRoot();const teamEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();const configuredProjectRoot=getAutoMemoryRoot(projectRoot);await Promise.all([...getProjectMetadataMigrationRoots(projectRoot,this.isTrustedFolder()).map(root=>root===configuredProjectRoot?rebuildManagedAutoMemoryIndex(projectRoot):rebuildAutoMemoryIndexAtRoot(root,"project")),rebuildUserAutoMemoryIndex(),...teamEnabled?[rebuildTeamAutoMemoryIndex(projectRoot)]:[]].map(pending=>pending.catch(error3=>{this.debugLogger.debug(`Memory index rebuild failed during recall transition: ${error3 instanceof Error?error3.message:String(error3)}`)})));const autoMemoryPrompt=await buildStructuredAutoMemoryPrompt(getAutoMemoryRoot(projectRoot),getUserAutoMemoryRoot(),teamEnabled?getTeamAutoMemoryRoot(projectRoot):void 0);const confirmed=await this.scanMemoryRecallCorpusStatus();if(confirmed.revision!==status.revision)return void 0;return{from:"legacy",to:"structured",revision:confirmed.revision,autoMemoryPrompt,previousRevision:this.memoryCorpusRevision,previousAutoMemoryPrompt:this.autoMemoryPrompt}}async confirmMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return false;const status=await this.scanMemoryRecallCorpusStatus();return status.revision===transition.revision&&(status.ready?"structured":"legacy")===transition.to}commitMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return;this.memoryRecallMode=transition.to;this.memoryCorpusRevision=transition.revision;this.autoMemoryPrompt=transition.autoMemoryPrompt;this.memoryRecallModeInitialized=true}rollbackMemoryRecallTransition(transition){if(this.memoryRecallMode!==transition.to)return;this.memoryRecallMode=transition.from;this.memoryCorpusRevision=transition.previousRevision;this.autoMemoryPrompt=transition.previousAutoMemoryPrompt}scanMemoryRecallCorpusStatus(){return scanMemoryMetadataCorpusStatus({projectRoot:this.getProjectRoot(),teamMemoryEnabled:this.getTeamMemoryEnabled(),trustedProject:this.isTrustedFolder()})}getOutputLanguageFilePath(){return this.outputLanguageFilePath}setOutputLanguageFilePath(filePath){this.outputLanguageFilePath=filePath}setUserMemory(newUserMemory){this.userMemory=newUserMemory}getMemoryFileCount(){return this.memoryFileCount}setMemoryFileCount(count){this.memoryFileCount=count}getGeminiMdFileCount(){return this.getMemoryFileCount()}setGeminiMdFileCount(count){this.setMemoryFileCount(count)}getContextFilePaths(){return this.loadedContextFilePaths}setContextFilePaths(paths){this.loadedContextFilePaths=paths}getArenaManager(){return this.arenaManager}setArenaManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent arenas.");this.arenaManager=manager;this.arenaManagerChangeCallback?.(manager)}onArenaManagerChange(cb){this.arenaManagerChangeCallback=cb}getArenaAgentClient(){return this.arenaAgentClient}getAgentsSettings(){return this.agentsSettings}getTeamManager(){return this.teamManager}setTeamManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent teams.");this.teamManager=manager;for(const cb of this.teamManagerChangeCallbacks){cb(manager)}}onTeamManagerChange(cb,previous){if(previous){this.teamManagerChangeCallbacks.delete(previous)}if(cb){this.teamManagerChangeCallbacks.add(cb)}}getTeamContext(){return this.teamContext}setTeamContext(ctx){this.teamContext=ctx}async cleanupTeamRuntime(){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Team runtime")}const manager=this.teamManager;if(!manager){return}await manager.cleanup();this.setTeamManager(null);this.setTeamContext(null)}getWorktreeSymlinkDirectories(){return this.worktreeSettings.symlinkDirectories??[]}async cleanupArenaRuntime(force){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Arena runtime")}const manager=this.arenaManager;if(!manager){return}if(!force&&this.agentsSettings.arena?.preserveArtifacts){await manager.cleanupRuntime()}else{await manager.cleanup()}this.setArenaManager(null)}getApprovalMode(){return this.approvalMode}getSessionApprovalMode(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).getSessionApprovalMode()}return this.getApprovalMode()}getAutoModeSettings(){return this.permissionsAutoMode}getAutoModeDenialState(){return this.autoModeDenialState}setAutoModeDenialState(state){this.autoModeDenialState=state}getPrePlanMode(){return this.prePlanMode??"default"}getPlanExecutionMode(){return Object.hasOwn(this,"planExecutionMode")?this.planExecutionMode:void 0}setPlanMode(enabled,executionMode){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot change plan workflow mode")}if(executionMode==="plan"){throw new Error("Plan is not an execution approval mode")}if(this.isSessionAgentSession?.()===true&&executionMode!=="default"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&executionMode!=="default"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const previousMode=this.approvalMode;const previousExecutionMode=this.planExecutionMode;if(enabled)this.planExecutionMode=executionMode;try{this.setApprovalMode(enabled?"plan":executionMode)}catch(error3){this.planExecutionMode=previousExecutionMode;throw error3}if(enabled&&previousMode==="plan"&&previousExecutionMode!==executionMode){this.notifyApprovalModeChangeListeners()}}getApprovalModeRevision(){return this.approvalModeRevision}getManualPlanExitNoticeEventState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeEventState")&&Object.prototype.hasOwnProperty.call(this,"approvalMode")){const inheritedEvent=this.manualPlanExitNoticeEventState;this.manualPlanExitNoticeEventState=inheritedEvent?{...inheritedEvent}:{version:0,kind:"clear"}}return this.manualPlanExitNoticeEventState}getOwnManualPlanExitNoticeCursorState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeCursorState")){this.manualPlanExitNoticeCursorState={seenVersion:0}}return this.manualPlanExitNoticeCursorState}setApprovalMode(mode,options2){if(isDerivedConfig(this)&&!Object.prototype.hasOwnProperty.call(this,"setApprovalMode")){throw new Error("Derived Configs cannot change approval mode")}if(this.isSessionAgentSession?.()===true&&mode!=="default"&&mode!=="plan"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&mode!=="default"&&mode!=="plan"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const fromMode=this.approvalMode;if(this.permissionManager){if(mode==="auto"&&fromMode!=="auto"){this.permissionManager.stripDangerousRulesForAutoMode()}else if(fromMode==="auto"&&mode!=="auto"){this.permissionManager.restoreDangerousRules()}}let noticeEvent=_Config.prototype.getManualPlanExitNoticeEventState.call(this);if(!Object.prototype.hasOwnProperty.call(this,"approvalMode")){noticeEvent={...noticeEvent};this.manualPlanExitNoticeEventState=noticeEvent}if(mode==="plan"&&fromMode!=="plan"){if(!isDerivedConfig(this)){this.goalProposalApprovalController?.abort()}this.prePlanMode=fromMode;noticeEvent.version++;noticeEvent.kind="clear"}else if(mode!=="plan"&&fromMode==="plan"){this.prePlanMode=void 0;noticeEvent.version++;noticeEvent.kind=options2?.fromApprovedPlanExit||options2?.fromSessionRestore?"clear":"manual-exit";if(options2?.fromApprovedPlanExit&&Object.getPrototypeOf(this)===_Config.prototype){this.approveSessionWorkflowPlanRevision()}}if(fromMode!==mode){this.autoModeDenialState=resetDenialState();if(!isDerivedConfig(this)&&mode!=="plan"&&fromMode!=="plan"){clearSessionCommits()}}this.approvalMode=mode;if(mode!=="plan")this.planExecutionMode=void 0;if(fromMode!==mode){this.approvalModeRevision++;if(!isDerivedConfig(this)){this.notifyApprovalModeChangeListeners()}}}takePendingManualPlanExitNotice(){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version<=cursor.seenVersion){return void 0}cursor.seenVersion=event.version;if(event.kind!=="manual-exit"||this.approvalMode==="plan"){return void 0}return{version:event.version,currentMode:this.approvalMode}}restorePendingManualPlanExitNotice(version4){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version===version4&&event.kind==="manual-exit"&&this.approvalMode!=="plan"&&cursor.seenVersion===version4){cursor.seenVersion=Math.max(0,version4-1)}}consumePendingManualPlanExitNotice(){return _Config.prototype.takePendingManualPlanExitNotice.call(this)!==void 0}getPlansDir(){return this.plansDir}getPlansAnchorTargetDir(){if(Object.prototype.hasOwnProperty.call(this,"plansDirectoryConfigured")){return this.targetDir}let current2=Object.getPrototypeOf(this);while(current2!==null&¤t2!==_Config.prototype){if(Object.prototype.hasOwnProperty.call(current2,"plansDirectoryConfigured")){return current2.targetDir}current2=Object.getPrototypeOf(current2)}return this.targetDir}assertPlansDirWithinTargetDir(){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(this.plansDir,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}assertPlanFilePathWithinTargetDir(filePath){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(filePath,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured){return}const legacyPlansDir=Storage.getPlansDir();const legacyPlanFiles=this.getPlanFileNames(legacyPlansDir);if(legacyPlanFiles.length===0){return}const configuredPlanFiles=new Set(this.getPlanFileNames(this.plansDir));const hiddenLegacyPlanFiles=legacyPlanFiles.filter(fileName=>!configuredPlanFiles.has(fileName));if(hiddenLegacyPlanFiles.length===0){return}this.warnings.push(`Warning: Saved plan files exist at ${legacyPlansDir}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(err){const message=`Failed to check legacy plan directory migration warning: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err)}}getPlanFileNames(plansDir){try{return fs76.readdirSync(plansDir).filter(entry=>entry.endsWith(".md"))}catch(err){const code=err.code;if(code==="ENOENT"){return[]}if(code==="EACCES"||code==="EPERM"){const message=`Failed to read plan directory ${plansDir}: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err);return[]}throw err}}getPlanFilePath(){return path81.join(this.plansDir,`${Storage.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(plan){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();const dir=path81.dirname(filePath);fs76.mkdirSync(dir,{recursive:true});const tmpPath=filePath+".tmp";fs76.writeFileSync(tmpPath,plan,"utf-8");try{fs76.renameSync(tmpPath,filePath)}catch(err){if(err.code!=="EXDEV"){throw err}fs76.copyFileSync(tmpPath,filePath);fs76.unlinkSync(tmpPath)}try{this.assertPlanFilePathWithinTargetDir(filePath)}catch(err){try{fs76.unlinkSync(filePath)}catch{}throw err}}loadPlan(){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(filePath);try{return fs76.readFileSync(filePath,"utf-8")}catch(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3&&error3.code==="ENOENT"){return void 0}throw error3}}getInputFormat(){return this.inputFormat}getIncludePartialMessages(){return this.includePartialMessages}getAccessibility(){return this.accessibility}getShowResponseTokensPerSecond(){return this.showResponseTokensPerSecond}getTelemetryEnabled(){return this.telemetrySettings.enabled??false}isTelemetryInitializationDeferred(){return this.telemetryInitializationDeferred}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??true}getTelemetryUserId(){return this.telemetrySettings.userId}getTelemetryIncludeSensitiveSpanAttributes(){return this.telemetrySettings.includeSensitiveSpanAttributes??false}getTelemetrySensitiveSpanAttributeMaxLength(){return this.telemetrySettings.sensitiveSpanAttributeMaxLength}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??DEFAULT_OTLP_ENDPOINT}getTelemetryOtlpProtocol(){return this.telemetrySettings.otlpProtocol??"grpc"}getTelemetryOtlpTracesEndpoint(){return this.telemetrySettings.otlpTracesEndpoint}getTelemetryOtlpLogsEndpoint(){return this.telemetrySettings.otlpLogsEndpoint}getTelemetryOtlpMetricsEndpoint(){return this.telemetrySettings.otlpMetricsEndpoint}getTelemetryTarget(){return this.telemetrySettings.target??DEFAULT_TELEMETRY_TARGET}getTelemetryResourceAttributes(){return this.telemetrySettings.resourceAttributes??{}}getTelemetryMetricsIncludeSessionId(){return this.telemetrySettings.metrics?.includeSessionId??false}getTelemetryResourceAttributeWarnings(){return this.telemetrySettings.resourceAttributeWarnings??[]}getOutboundCorrelationPropagateTraceContext(){return this.outboundCorrelationSettings.propagateTraceContext??false}getOutboundAllowDynamicHeaderValues(){return this.outboundCorrelationSettings.allowDynamicHeaderValues??false}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGitCoAuthor(){return this.gitCoAuthor}getLlmClient(){return this.llmClient}getGeminiClient(){return this.getLlmClient()}getOwnActiveTodoReminders(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminders")){this.activeTodoReminders=new Map}return this.activeTodoReminders}getOwnActiveTodoWorkChainOwners(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoWorkChainOwners")){this.activeTodoWorkChainOwners=new Map}return this.activeTodoWorkChainOwners}getOwnActiveTodoReminderTurns(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminderTurns")){this.activeTodoReminderTurns=new Map}return this.activeTodoReminderTurns}getActiveTodoWorkChainOwner(promptId,fallbackOwner=promptId){return this.getOwnActiveTodoWorkChainOwners().get(promptId)??fallbackOwner}getActiveTodoReminder(promptId){return this.getOwnActiveTodoReminders().get(this.getActiveTodoWorkChainOwner(promptId))}getActiveTodoPlanWriterOwner(){return this.activeTodoPlanWriterOwner}recordActiveTodoPlanWriter(promptId){this.activeTodoPlanWriterOwner=this.getActiveTodoWorkChainOwner(promptId)}takeActiveTodoReminder(promptId,force=false){const owner=this.getActiveTodoWorkChainOwner(promptId);const reminder=this.getOwnActiveTodoReminders().get(owner);if(!reminder)return void 0;const turns=this.getOwnActiveTodoReminderTurns();const elapsed=(turns.get(owner)??0)+1;if(!force&&elapsed<ACTIVE_TODO_REMINDER_REFRESH_TURNS){turns.set(owner,elapsed);return void 0}turns.set(owner,0);return reminder}setActiveTodoReminder(promptId,reminder){const reminders=this.getOwnActiveTodoReminders();const owner=this.getActiveTodoWorkChainOwner(promptId);if(reminder){reminders.set(owner,reminder);this.getOwnActiveTodoReminderTurns().set(owner,0)}else{reminders.clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}}startActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();if(!continuedFrom){reminders.clear();owners.clear();this.getOwnActiveTodoReminderTurns().clear();owners.set(promptId,promptId);return}const owner=this.getActiveTodoWorkChainOwner(continuedFrom);for(const reminderOwner of reminders.keys()){if(reminderOwner!==owner)reminders.delete(reminderOwner)}for(const[mappedPromptId,mappedOwner]of owners){if(mappedOwner!==owner)owners.delete(mappedPromptId)}owners.delete(continuedFrom);owners.set(promptId,owner)}startAutomaticActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();const owner=continuedFrom?this.getActiveTodoWorkChainOwner(continuedFrom):promptId;owners.set(promptId,owner);if(owner===promptId)reminders.delete(owner)}endAutomaticActiveTodoWorkChain(promptId){const owners=this.getOwnActiveTodoWorkChainOwners();const owner=this.getActiveTodoWorkChainOwner(promptId);owners.delete(promptId);if(![...owners.values()].includes(owner)){this.getOwnActiveTodoReminders().delete(owner)}}clearActiveTodoReminders(){this.getOwnActiveTodoReminders().clear();this.getOwnActiveTodoWorkChainOwners().clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}getMemoryPressureMonitor(){if(!Object.prototype.hasOwnProperty.call(this,"memoryPressureMonitor")){const inheritedMonitor=this.memoryPressureMonitor;if(inheritedMonitor){const inheritedConfig=this.memoryPressureConfig;if(!inheritedConfig){throw new Error("Inherited memory pressure monitor is missing config")}this.memoryPressureConfig={...inheritedConfig};this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig)}}return this.memoryPressureMonitor}getCronScheduler(){if(!this.cronScheduler){this.cronScheduler=new CronScheduler(this.getProjectRoot(),this.getCronRecurringMaxAgeDays()*24*60*60*1e3)}return this.cronScheduler}getCronRecurringMaxAgeDays(){return this.cronRecurringMaxAgeDays}isCronEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_CRON"]==="1")return false;return this.cronEnabled}isLsToolEnabled(){if(this.lsToolEnabled)return true;return this.getCoreTools()?.some(name=>parseRule(name).toolName===ToolNames.LS)??false}isTodoWriteEnabled(){return this.todoWriteEnabled}isAgentTeamEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_ENABLE_AGENT_TEAM"]==="1")return true;return this.agentTeamEnabled}isAgentCollaborationEnabled(){if(process8.env["QWEN_CODE_ENABLE_AGENT_COLLABORATION"]==="1"){return true}return this.agentCollaborationEnabled}isArtifactEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(!this.interactive&&!this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}sessionSourceService;sessionSourceServiceFactory;setSessionSourceServiceFactory(factory){this.sessionSourceServiceFactory=factory;this.sessionSourceService=factory()}getSessionSourceService(){return Object.hasOwn(this,"sessionSourceService")?this.sessionSourceService:void 0}isRecordArtifactEnabled(){if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}getArtifactPublisherKind(){return this.artifactPublisher}isArtifactSnapshotsEnabled(){return this.artifactSnapshotsEnabled&&this.chatRecordingEnabled}setArtifactSnapshotsEnabled(enabled){this.artifactSnapshotsEnabled=enabled}getArtifactHostConfig(){return this.artifactHost}getArtifactOssConfig(){return this.artifactOss}isOmniEnabled(){if(this.bareMode)return false;if(process8.env["QWEN_CODE_ENABLE_OMNI"]==="1")return true;return this.omniEnabled}getOmniMaxUploadFileBytes(){return this.omniMaxUploadFileBytes}getOmniMaxEstimatedTokens(){return this.omniMaxEstimatedTokens}getOmniMaxDurationSeconds(){return this.omniMaxDurationSeconds}getOmniUrlDownloadMaxFileBytes(){return this.omniUrlDownloadMaxFileBytes}getOmniUploadUrlTtlHours(){return this.omniUploadUrlTtlHours}getOmniUploadConfig(){return this.omniUploadConfig}getOmniPolicyToolsSettings(){return this.omniPolicyTools}async loadOmniMediaReader(){return import("./omni-POUUDVU3.js")}getOmniProcessingConfig(){return this.omniProcessingConfig}getOmniMemoryConfig(){return this.omniMemoryConfig}async ensureOmniMemoryConfig(){if(!this.omniMemoryConfig){const{normalizeOmniMemoryConfig}=await import("./config-NOIFIDXC.js");this.omniMemoryConfig=normalizeOmniMemoryConfig(this.omniMemory)}return this.omniMemoryConfig}getOmniMediaResourceRegistry(){this.omniMediaResourceRegistry??=new MediaResourceRegistry;return this.omniMediaResourceRegistry}getOmniQuarantineRetentionDays(){const days=this.omniQuarantineRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>0?days:7}getOmniQuarantineMaxBytes(){const bytes=this.omniQuarantineMaxBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:5*1024*1024*1024}getOmniStorageRetentionDays(){const days=this.omniStorageRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>=1?days:14}getOmniStorageMaxTotalBytes(){const bytes=this.omniStorageMaxTotalBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:20*1024*1024*1024}resolveImageGenerationModel(setting){const parsedSetting=parseVisionModelSetting(setting);if(!parsedSetting)return void 0;let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{return void 0}if(!selector)return void 0;const routeMatches=this.getAllConfiguredModels().filter(model=>isImageGenerationCapable(model)&&!model.fastOnly&&!model.voiceOnly&&model.id===selector.modelId&&(!selector.authType||model.authType===selector.authType)&&(!parsedSetting.baseUrl||model.baseUrl===parsedSetting.baseUrl));if(routeMatches.length!==1)return void 0;const match=routeMatches[0];const apiKeyEnv=match.envKey?.trim();const configuredBaseUrl=match.registryBaseUrl?.trim();if(!apiKeyEnv||!configuredBaseUrl)return void 0;const baseUrl=normalizeImageGenerationBaseUrl(parsedSetting.baseUrl??configuredBaseUrl);if(!baseUrl)return void 0;return{model:match.id,baseUrl,apiKeyEnv}}getImageGenerationConfig(){if(this.bareMode||this.safeMode)return void 0;return this.resolveImageGenerationModel(this.imageModel)}isImageGenerationEnabled(){if(this.shellExecutionSandbox)return false;return this.getImageGenerationConfig()!==void 0}shouldAutoOpenArtifact(){if(this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_ARTIFACT_NO_AUTO_OPEN"]==="1")return false;return this.artifactAutoOpen&&!this.isBrowserLaunchSuppressed()}isWorkflowsEnabled(){if(this.shellExecutionSandbox)return false;if(this.provisionalWorkspace)return false;if(process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1")return false;if(process8.env["QWEN_CODE_ENABLE_WORKFLOWS"]==="1")return true;return this.workflowsEnabled??false}setWorkflowsEnabled(enabled){this.workflowsEnabled=enabled}async enableReviewWorkflow(){if(this.shellExecutionSandbox||this.workflowsEnabled===false||!isTopLevelSession()||this.getBareMode()||this.provisionalWorkspace||process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1"){return}if(await this.registerWorkflowTool(this.getToolRegistry())){this.setWorkflowsEnabled(true);await this.getLlmClient().setTools()}}isSessionWorkflowEnabled(){if(this.shellExecutionSandbox)return false;return this.sessionWorkflowEnabledProvider?.()??this.sessionWorkflowEnabled}setSessionWorkflowEnabledProvider(provider){this.sessionWorkflowEnabledProvider=provider;if(!this.isSessionWorkflowEnabled()){this.sessionWorkflowPlanRevision=void 0}}setExternalAgentExecutor(executor){this.externalAgentExecutor=executor}getExternalAgentExecutor(){return this.externalAgentExecutor}getAgentExecutionBackend(){return this.agentExecutionBackend}getExecutionEnvironmentFactory(){return this.shutdownRequested||this.executionShutdown.signal.aborted?void 0:this.executionEnvironmentFactory}getExecutionEnvironment(){return this.executionEnvironment}shutdownExecutionEnvironments(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).shutdownExecutionEnvironments()}this.executionShutdown.abort();if(this.executionCleanupPromise)return this.executionCleanupPromise;const cleanup=Promise.allSettled([...this.executionEnvironments??[]].map(async pending=>{let environment;try{environment=await pending}catch(error3){if(error3 instanceof ExecutionCleanupError){if(!error3.retryCleanup)throw error3;await error3.retryCleanup()}this.executionEnvironments?.delete(pending);return}await environment.dispose();this.executionEnvironments?.delete(pending)})).then(results=>{const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,errors.map(String).join("; "))});let timer;this.executionCleanupPromise=new Promise((resolve34,reject)=>{timer=setTimeout(()=>reject(new ExecutionCleanupError(`Container cleanup is still pending for workspace ${this.getWorkingDir()}. Keep its workspace and inspect qwen-agent-* containers and qwen-agent-executor-* temporary directories before manual removal.`)),1e3);cleanup.then(resolve34,reject)}).catch(error3=>{console.warn(`Container execution cleanup incomplete: ${String(error3)}`);throw error3}).finally(()=>clearTimeout(timer));const clear=__name(()=>{this.executionCleanupPromise=void 0},"clear");void cleanup.then(clear,clear);return this.executionCleanupPromise}registerExecutionEnvironment(pending){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).registerExecutionEnvironment(pending)}this.executionEnvironments??=new Set;this.executionEnvironments.add(pending);return()=>this.executionEnvironments?.delete(pending)}getSessionWorkflowPlanRevision(){if(!this.isSessionWorkflowEnabled())return void 0;return this.sessionWorkflowPlanRevision}setSessionWorkflowPlanRevision(revision){if(!this.isSessionWorkflowEnabled()||revision===void 0||revision.planId.trim()===""||revision.sourceCallId.trim()===""){this.sessionWorkflowPlanRevision=void 0;return}const todoIds=Array.from(new Set(revision.todoIds.filter(todoId=>typeof todoId==="string"&&todoId.trim()!=="")));this.sessionWorkflowPlanRevision=todoIds.length>0?{planId:revision.planId,sourceCallId:revision.sourceCallId,todoIds,...revision.approved?{approved:true}:{}}:void 0}clearSessionWorkflowPlanRevision(){this.sessionWorkflowPlanRevision=void 0}approveSessionWorkflowPlanRevision(){const revision=this.getSessionWorkflowPlanRevision();if(!revision||revision.approved)return;this.setSessionWorkflowPlanRevision({...revision,approved:true})}isSessionWorkflowTodoContextActive(){return this.isSessionWorkflowEnabled()&&(this.approvalMode==="plan"||this.sessionWorkflowPlanRevision!==void 0)}getModelProposedGoals(){return this.modelProposedGoals}setGoalProposalHostSupported(supported){this.goalProposalHostSupported=supported}getGoalProposalHostSupported(){return this.goalProposalHostSupported}setGoalProposalTurnKey(turnKey){if(this.goalProposalTurnKey===turnKey)return false;this.goalProposalTurnKey=turnKey;return true}isGoalProposalAvailable(){return resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported&&this.goalProposalTurnKey!==void 0}hasPendingGoalProposal(){return this.pendingGoalProposal!==void 0}setPendingGoalProposal(proposal){if(this.pendingGoalProposal)return false;this.goalProposalApprovalController=new AbortController;if(this.approvalMode==="plan"){this.goalProposalApprovalController.abort()}this.pendingGoalProposal={...proposal,approvalSignal:this.goalProposalApprovalController.signal};return true}takePendingGoalProposal(expectedTurnKey){const proposal=this.pendingGoalProposal;if(expectedTurnKey!==void 0&&proposal?.turnKey!==expectedTurnKey){return void 0}this.pendingGoalProposal=void 0;return proposal}getSkipWorkflowUsageWarning(){return this.skipWorkflowUsageWarning}getWorkflowSizeGuideline(){return resolveWorkflowSizeGuidelineSetting(this.workflowSizeGuideline)}isWorkflowNameOnly(){return this.workflowNameOnly}setWorkflowSizeGuideline(size){this.workflowSizeGuideline=isWorkflowSizeGuideline(size)?size:void 0}getEmitToolUseSummaries(){const env=process8.env["QWEN_CODE_EMIT_TOOL_USE_SUMMARIES"];if(env==="0"||env==="false")return false;if(env==="1"||env==="true")return true;return this.emitToolUseSummaries}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringEnableFuzzySearch(){return this.fileFiltering.enableFuzzySearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectQwenIgnore(){return this.fileFiltering.respectQwenIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectQwenIgnore:this.fileFiltering.respectQwenIgnore,customIgnoreFiles:[...this.fileFiltering.customIgnoreFiles]}}getCustomExcludes(){return[]}getFileCheckpointingEnabled(){return!this.shellExecutionSandbox&&this.fileCheckpointingEnabled}enableFileCheckpointing(){if(this.shellExecutionSandbox)throw new Error("File checkpointing is unavailable with tools.executionSandbox.");this.fileCheckpointingEnabled=true;this.fileHistoryService=void 0}getFileHistoryService(){if(!this.fileHistoryService){const service=new FileHistoryService(this.sessionId,this.getFileCheckpointingEnabled(),this.cwd,snapshot=>{if(this.fileHistoryService!==service)return;this.getChatRecordingService()?.recordFileHistorySnapshot(snapshot)});this.fileHistoryService=service;const snapshots=this.sessionData?.fileHistorySnapshots;if(snapshots?.length&&service.isEnabled()){service.restoreFromSnapshots(snapshots);void service.validateRestoredSnapshots().catch(e=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${e}`)})}}return this.fileHistoryService}getProxy(){return normalizeProxyUrl(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){if(!this.fileDiscoveryService){this.fileDiscoveryService=new FileDiscoveryService(this.targetDir,this.fileFiltering.customIgnoreFiles)}return this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionRuleSources(){return this.getActiveExtensions().filter(extension=>Boolean(extension.path)).map(extension=>({name:extension.name,dir:path81.join(extension.path,"rules")}))}getExtensionContextFilePaths(){const extensionContextFilePaths=this.getActiveExtensions().flatMap(e=>e.contextFiles);return[...extensionContextFilePaths,...this.outputLanguageFilePath?[this.outputLanguageFilePath]:[]]}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getRestoreAskUserQuestion(){return this.restoreAskUserQuestion}getPreserveRestorableAskUserQuestion(){return this.preserveRestorableAskUserQuestion}suppressRestorableAskUserQuestionPreservation(){this.preserveRestorableAskUserQuestion=false}isSessionWriterLeaseEnabled(){return this.sessionWriterLeaseEnabled}getListExtensions(){return this.listExtensions}getExtensionManager(){return this.extensionManager}getHookSystem(){if(this.shellExecutionSandbox)return void 0;return this.hookSystem}hasHooksForEvent(eventName,sessionId){return this.hookSystem?.hasHooksForEvent(eventName,sessionId??this.getSessionId())??false}getDisableAllHooks(){if(this.shellExecutionSandbox)return true;if(this.hookSystem?.isManaged())return false;return this.disableAllHooks||this.getBareMode()||this.isSafeMode()}getStopHookBlockingCap(){return this.stopHookBlockingCap}getManagedAutoMemoryEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()&&!this.isSafeMode()}getTeamMemoryEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemory}getTeamMemorySyncEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM_SYNC"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemorySync}getStructuredMemoryRecallEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.isSafeMode())return false;const override=process8.env["QWEN_CODE_MEMORY_STRUCTURED_RECALL"];if(override==="0"){return false}if(override==="1"){return true}return this.enableStructuredMemoryRecall}isManagedMemoryAvailable(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()}getManagedAutoDreamEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoDream&&!this.getBareMode()&&!this.isSafeMode()}getAutoSkillEnabled(){if(this.shellExecutionSandbox)return false;return this.enableAutoSkill&&!this.getBareMode()&&!this.isSafeMode()&&!this.provisionalWorkspace}setAutoSkillEnabled(enabled){this.enableAutoSkill=enabled}getAutoSkillConfirmEnabled(){return this.autoSkillConfirm&&!this.getBareMode()}getMemoryAgentTimeoutMinutes(){return this.memoryAgentTimeoutMinutes}getMemoryAgentMaxTurns(){return this.memoryAgentMaxTurns}getPreventSystemSleepEnabled(){return this.preventSystemSleep&&!this.isSafeMode()}getMemoryManager(){return this.memoryManager}getMessageBus(){return this.messageBus}setMessageBus(messageBus){if(this.messageBus===messageBus){return}this.messageBus=messageBus;this.announceMessageBus(messageBus)}onMessageBusChange(listener){this.messageBusListeners.add(listener);if(this.messageBus){this.notifyMessageBusListener(listener,this.messageBus)}return()=>{this.messageBusListeners.delete(listener)}}notifyMessageBusListener(listener,bus){try{const result=listener(bus);if(result instanceof Promise){result.catch(error3=>{this.debugLogger.debug(`MessageBus observer failed: ${error3}`)})}}catch(error3){this.debugLogger.debug(`MessageBus observer failed: ${error3}`)}}announceMessageBus(bus){for(const listener of[...this.messageBusListeners]){this.notifyMessageBusListener(listener,bus)}}getProjectHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}if(!this.isTrustedFolder()){return void 0}const hooks=this.projectHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getUserHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}const hooks=this.userHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getSystemHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}return this.systemHooks}hasScopedHooks(){return this.systemHooks!==void 0||this.userHooks!==void 0||this.projectHooks!==void 0}setHooksFromSettings(hooks){this.systemHooks=hooks.systemHooks;this.userHooks=hooks.userHooks;this.projectHooks=hooks.projectHooks;this.hooks=hooks.hooks}getExtensions(){if(this.shellExecutionSandbox)return[];const extensions=this.extensionManager.getLoadedExtensions();if(this.overrideExtensions){const overrideExtensionNames=new Set(this.overrideExtensions.map(name=>name.toLowerCase()));return extensions.filter(e=>overrideExtensionNames.has(e.name.toLowerCase()))}else{return extensions}}getActiveExtensions(){return this.getExtensions().filter(e=>e.isActive)}getBlockedMcpServers(){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}const blockedMcpServers=[];if(this.allowedMcpServers){Object.entries(mcpServers).forEach(([key,server])=>{const isAllowed=matchesAnyServerPattern(key,this.allowedMcpServers);if(!isAllowed){blockedMcpServers.push({name:key,extensionName:server.extensionName||""})}})}return blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!shouldAttemptBrowserLaunch()}getIdeMode(){return!this.shellExecutionSandbox&&this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()||this.isSafeMode()?[]:this.allowedHttpHookUrls}getAllowPrivateNetworkHooks(){return this.getBareMode()||this.isSafeMode()?false:this.allowPrivateNetworkHooks}isTrustedFolder(){const context2=ideContextStore.get();if(context2?.workspaceState?.isTrusted!==void 0){return context2.workspaceState.isTrusted}return this.trustedFolder??!this.folderTrust}setIdeMode(value){if(this.shellExecutionSandbox&&value)throw new Error("Tool execution sandbox does not support IDE integration.");this.ideMode=value}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(fileSystemService){if(this.shellExecutionSandbox){throw new Error("Internal sandbox does not support delegated filesystem services.")}this.fileSystemService=fileSystemService}getChatCompression(){return this.chatCompression}getAutoCompactThreshold(){const threshold=this.autoCompactThreshold;if(typeof threshold==="number"&&threshold>0&&threshold<=1){return threshold}return void 0}isInteractive(){return this.interactive}async getTerminalImageRenderSupport(){return this.terminalImageRenderSupportProvider?this.terminalImageRenderSupportProvider():{available:false,reason:"No terminal image renderer is configured."}}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(config3){this.shellExecutionConfig={terminalWidth:config3.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:config3.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:config3.showColor??this.shellExecutionConfig.showColor,pager:Object.prototype.hasOwnProperty.call(config3,"pager")?config3.pager:this.shellExecutionConfig.pager,maxBufferedOutputBytes:config3.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??false}getSkipLoopDetection(){return this.skipLoopDetection}getMaxToolCallsPerTurn(){if(this.maxToolCallsPerTurn<=0){return Number.POSITIVE_INFINITY}return this.maxToolCallsPerTurn}isMaxToolCallsPerTurnExplicit(){return this.maxToolCallsPerTurnExplicit}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}isSafeMode(){return this.safeMode}getTruncateToolOutputThreshold(){if(this.truncateToolOutputThreshold<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputThreshold}isTruncateToolOutputThresholdExplicit(){return this.truncateToolOutputThresholdExplicit}getTruncateToolOutputLines(){if(this.truncateToolOutputLines<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputLines}getShellDefaultTimeoutMs(){return this.shellDefaultTimeoutMs}getShellHeartbeatIntervalMs(){return this.shellHeartbeatIntervalMs}getToolOutputBatchBudget(){if(this.toolOutputBatchBudget<=0){return Number.POSITIVE_INFINITY}return this.toolOutputBatchBudget}trackToolResultBytes(n){this.toolResultBudget.bytesWritten+=n}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(!this.chatRecordingEnabled){return void 0}if(!this.chatRecordingService){this.chatRecordingService=this.createChatRecordingService()}return this.chatRecordingService}getGoalRuntime(){if(!Object.hasOwn(this,"goalRuntime")||!this.chatRecordingEnabled||!this.chatRecordingService||!this.goalRuntime){throw new GoalPersistenceUnavailableError}return this.goalRuntime}async getGoalRuntimeReady(){const runtime=this.getGoalRuntime();if(!Object.hasOwn(this,"goalRuntimeReady")||!this.goalRuntimeReady){throw new GoalPersistenceUnavailableError}return this.goalRuntimeReady.then(()=>runtime)}async getGoalRuntimePrepared(){const runtime=this.getGoalRuntime();if(!this.sessionRestoreRuntime)return this.getGoalRuntimeReady();return runtime.getPreparedRestore().then(()=>runtime)}async rebaseGoalRuntimeFromActiveTranscript(){const runtime=this.getGoalRuntime();const recordingService=this.chatRecordingService;if(!recordingService){throw new GoalPersistenceUnavailableError}const records=await recordingService.readActiveTranscriptChain();this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;runtime.dispose();this.initializeGoalRuntime(records);await this.goalRuntimeReady}bindGoalTurnHost(host){if(!Object.hasOwn(this,"goalRuntime")){throw new GoalPersistenceUnavailableError}const generation=this.goalTurnHostGeneration+1;this.goalTurnHostGeneration=generation;this.goalTurnHostUnbind?.();this.goalTurnHost=host;this.goalTurnHostUnbind=this.goalRuntime?.bindHost(host);return()=>{if(this.goalTurnHostGeneration!==generation||this.goalTurnHost!==host){return}this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalTurnHost=void 0}}onChatRecordingFailure(listener){this.chatRecordingFailureListeners.add(listener);return()=>{this.chatRecordingFailureListeners.delete(listener)}}onRequestLifecycle(listener){this.requestLifecycleListeners.add(listener);return()=>this.requestLifecycleListeners.delete(listener)}notifyRequestLifecycle(event){for(const listener of this.requestLifecycleListeners){try{listener(event)}catch(error3){this.debugLogger.warn("Request lifecycle listener failed:",error3)}}}createChatRecordingService(){return new ChatRecordingService(this,event=>{this.notifyChatRecordingFailure(event)},this.sessionWriterLeaseEnabled,this.sessionRestoreRuntime?.recording)}initializeGoalRuntime(records,restoreRuntime){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime replaced"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));this.goalProposalApprovalController?.abort();this.goalProposalApprovalController=void 0;this.pendingGoalProposal=void 0;if(!this.chatRecordingService){this.goalRuntime=void 0;this.goalRuntimeReady=void 0;return}const recorder=this.chatRecordingService;const runtime=createGoalRuntime({journal:recorder,evidenceSource:recorder,ledger:recorder,verifier:createGoalVerifier(this),tokenBudgetGrant:this.goalTokenBudgetGrant,turnBudgetGrant:this.goalTurnBudgetGrant,activeTimeBudgetGrantMs:this.goalActiveTimeBudgetGrantMs});runtime.subscribe((snapshot,cause,meta4)=>{if(meta4?.replayed)return;const event=goalStateEventFromSnapshot(snapshot,cause);if(event)logGoalState(this,event)});this.goalRuntime=runtime;if(this.goalTurnHost){this.goalTurnHostUnbind=runtime.bindHost(this.goalTurnHost)}if(restoreRuntime){const preparation=runtime.prepareRestore(records??[]);let resolveActivation;let rejectActivation;const activation=new Promise((resolve34,reject)=>{resolveActivation=resolve34;rejectActivation=reject});this.rejectGoalRestoreActivation=rejectActivation;this.goalRestoreActivation=()=>{const started=runtime.activateRestoredWork();void started.then(resolveActivation,rejectActivation);return started};this.goalRuntimeReady=Promise.all([preparation,activation]).then(()=>runtime)}else if(this.sessionWriterLeaseEnabled&&!recorder.hasWriteOwnership()){const ready=new Promise((resolve34,reject)=>{this.pendingGoalRestore={runtime,resolve:resolve34,reject}});this.goalRuntimeReady=ready}else{this.goalRuntimeReady=runtime.restore(records??[]).then(()=>runtime)}void this.goalRuntimeReady.catch(()=>void 0)}startPendingGoalRestore(){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;if(pending.runtime!==this.goalRuntime){pending.reject(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));return}void pending.runtime.restore(this.sessionData?.conversation.messages??[]).then(()=>pending.resolve(pending.runtime),error3=>pending.reject(error3))}settlePendingGoalRestore(error3){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;pending.reject(error3)}setSessionRestoreProjection(projection){this.pendingSessionRestoreProjection=projection;this.sessionRestoreRuntime=projection?.runtime;this.restoredFileHistory=false}clearSessionRestoreProjection(){this.pendingSessionRestoreProjection=void 0;this.sessionRestoreRuntime=void 0;this.restoredFileHistory=false;this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Session restore was abandoned"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0}notifyChatRecordingFailure(event){for(const listener of[...this.chatRecordingFailureListeners]){try{const notification=listener(event);if(notification){void notification.catch(error3=>{this.debugLogger.debug("Chat recording failure listener rejected:",error3)})}}catch(error3){this.debugLogger.debug("Chat recording failure listener threw:",error3)}}}getTranscriptPath(){if(!this.chatRecordingEnabled){return""}const projectDir=this.storage.getProjectDir();const sessionId=this.getSessionId();const safeFilename=`${sessionId}.jsonl`;return path81.join(projectDir,"chats",safeFilename)}async assertCanStartTurn(){if(isDerivedConfig(this))return;if(this.chatRecordingService?.hasWriteOwnership()){await this.chatRecordingService.assertCanStartTurn()}}hasSessionWriteOwnership(){if(isDerivedConfig(this))return false;return this.pendingSessionWriterLease!==void 0&&!this.pendingSessionWriterLease.isReleased||this.chatRecordingService?.hasWriteOwnership()===true}setSessionWriterReclaimPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterReclaimPolicy=policy}setSessionWriterTakeoverPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterTakeoverPolicy=policy}closeSessionWriter(options2){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(options2?.handoff&&this.sessionWriterTakeoverPolicy==="certified"){this.sessionWriterHandoffRequested=true}this.sessionWriterShutdownRequested=true;this.chatRecordingService?.beginClose({handoff:this.sessionWriterHandoffRequested});this.startPendingSessionWriterRelease();if(this.sessionWriterClosePromise)return this.sessionWriterClosePromise;const pending=this.closeSessionWriterOnce();this.sessionWriterClosePromise=pending;void pending.catch(()=>{if(this.sessionWriterClosePromise===pending){this.sessionWriterClosePromise=void 0}});return pending}async closeSessionWriterOnce(){const failures=[];const activation=this.sessionWriterActivationPromise;try{await activation}catch(error3){if(!(error3 instanceof SessionWriterShutdownError)){failures.push(error3)}}try{await this.chatRecordingService?.close({handoff:this.sessionWriterHandoffRequested})}catch(error3){failures.push(error3)}const pendingLease=activation?void 0:this.pendingSessionWriterLease;if(pendingLease){try{await this.startPendingSessionWriterRelease(pendingLease);if(this.pendingSessionWriterLease===pendingLease&&pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}}catch(error3){if(error3 instanceof SessionWriterLostError||pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}failures.push(error3)}finally{if(this.pendingSessionWriterRelease?.lease===pendingLease){this.pendingSessionWriterRelease=void 0}}}if(failures.length===1){throw failures[0]}if(failures.length>1){throw new AggregateError(failures,"Session writer shutdown failed")}}startPendingSessionWriterRelease(lease=this.pendingSessionWriterLease){if(!lease)return void 0;const existing=this.pendingSessionWriterRelease;if(existing?.lease===lease)return existing.promise;if(this.sessionExecutionEngine==="managed")return void 0;const promise=lease.release();this.pendingSessionWriterRelease={lease,promise};void promise.catch(()=>void 0);return promise}getSessionRuntimeBaseDir(){return this.sessionRuntimeBaseDir}getSessionService(){if(!this.sessionService){this.sessionService=new SessionService(this.storage.getProjectRoot(),{runtimeBaseDir:this.sessionRuntimeBaseDir})}return this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){if(!this.backgroundAgentResumeService){this.backgroundAgentResumeService=new BackgroundAgentResumeService(this)}return this.backgroundAgentResumeService}async loadPausedBackgroundAgents(sessionId=this.getSessionId()){if(sessionId!==this.getSessionId()){this.debugLogger.warn(`Refusing to restore background agents for non-current session ${sessionId}.`);return[]}const service=this.getBackgroundAgentResumeService();let recovered;try{recovered=await service.loadPausedBackgroundAgents(sessionId)}catch(error3){this.debugLogger.warn(`Background agent restore failed for session ${sessionId}; continuing without restored agents.`,error3);return[]}if(recovered.length>0&&!this.getBareMode()){this.pendingRecoveredAgentsNotice=service.buildRecoveredBackgroundAgentsModelNotice(recovered.length)}return recovered}consumePendingRecoveredAgentsNotice(){const notice=this.pendingRecoveredAgentsNotice;this.pendingRecoveredAgentsNotice=null;return notice}async resumeBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().resumeBackgroundAgent(agentId,initialInput)}async reviveCompletedBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().reviveCompletedBackgroundAgent(agentId,initialInput)}abandonBackgroundAgent(agentId){return this.getBackgroundAgentResumeService().abandonBackgroundAgent(agentId)}getBackgroundShellRegistry(){return this.backgroundShellRegistry}getWorkflowRunRegistry(){return this.workflowRunRegistry}getTurnBudget(){return this.turnBudget}getFileReadCache(){if(!Object.prototype.hasOwnProperty.call(this,"fileReadCache")){this.fileReadCache=new FileReadCache}return this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return false}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(provider){this.modelInvocableCommandsProvider=provider}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(executor){this.modelInvocableCommandsExecutor=executor}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(keys){for(const k2 of keys){this.pendingInlineAnnouncedSkillKeys.add(k2)}}consumeInlineAnnouncedSkillKeys(){const result=this.pendingInlineAnnouncedSkillKeys;this.pendingInlineAnnouncedSkillKeys=new Set;return result}getPermissionManager(){return this.permissionManager}isWorkspaceAgentSession(){return this.isAgentCollaborationEnabled()&&this.sessionSourceType==="agent"}getWorkflowAncestorTrustProvider(){return this.workflowAncestorTrustProvider}getToolInvocationGuard(){if(this.sessionSourceType==="agent-host"){return createAgentHostToolInvocationGuard(this.toolInvocationGuard,this.getTargetDir(),candidate=>this.getWorkspaceContext().isPathWithinWorkspace(candidate))}if(this.isWorkspaceAgentSession()&&this.isSessionAgentSession()){return createSessionAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools,this.workspaceAgentDisallowedTools)}return this.isWorkspaceAgentSession()?createAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools):this.toolInvocationGuard}getShellExecutionSandbox(){return this.shellExecutionSandbox}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}async registerLazyTool(registry3,toolName,factory){let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(toolName):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${toolName}", skipping registration:`,error3);return}if(status==="deferred"){registry3.registerPermissionDeferredFactory(toolName,factory)}else if(status==="registered"){registry3.registerFactory(toolName,factory)}}async registerManagedRuntimeTools(registry3){const environment=this.getManagedRuntimeEnvironment();if(!environment)return;const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-IE5BOI7Y.js"),import("./execution-tool-KT3EBWHG.js")]);const tools=createExecutionTools(this);for(const name of MANAGED_RUNTIME_TOOL_NAMES){const tool=tools.get(name);if(!tool)continue;let status;try{status=await this.getPermissionManager()?.getToolRegistrationStatus(name)??"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${name}", skipping registration:`,error3);continue}if(status==="disabled")continue;registry3.registerRuntimeBackedFactory(name,async()=>wrapExecutionTool(tool,environment,this),environment,status==="deferred")}}async registerWorkflowTool(registry3){if(registry3.getAllToolNames().includes(ToolNames.WORKFLOW))return true;await this.registerLazyTool(registry3,ToolNames.WORKFLOW,async()=>{const{WorkflowTool}=await import("./workflow-FGAUAYIP.js");return new WorkflowTool(this)});return registry3.getAllToolNames().includes(ToolNames.WORKFLOW)}async registerImageGenerationTool(registry3){if(!this.isImageGenerationEnabled()||registry3.getAllToolNames().includes(ToolNames.IMAGE_GEN)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.IMAGE_GEN):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.IMAGE_GEN}", skipping registration:`,error3);return}if(status==="disabled")return;const factory=__name(async()=>{const{ImageGenTool}=await import("./image-gen-F5BMNMYK.js");return new ImageGenTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.IMAGE_GEN,factory)}else{registry3.registerFactory(ToolNames.IMAGE_GEN,factory)}}async syncAdvisorToolRegistration(registry3){if(!this.getAdvisorModel()||this.getBareMode()||this.isSafeMode()){registry3.unregisterTool(ToolNames.ADVISOR);return}if(this.getDisabledTools().has(ToolNames.ADVISOR))return;registry3.unregisterTool(ToolNames.ADVISOR);await this.registerLazyTool(registry3,ToolNames.ADVISOR,async()=>{const{AdvisorTool}=await import("./advisor-MSOUBMJ6.js");return new AdvisorTool(this)});await registry3.ensureTool(ToolNames.ADVISOR)}async registerSessionSourceTool(registry3=this.toolRegistry){if(!this.getSessionSourceService()||this.sdkMode||this.getBareMode()||this.isSafeMode()||registry3.getAllToolNames().includes(ToolNames.RECORD_SOURCE)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.RECORD_SOURCE):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.RECORD_SOURCE}", skipping registration:`,error3);return}const factory=__name(async()=>{const{RecordSourceTool}=await import("./record-source-S2552VVB.js");return new RecordSourceTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.RECORD_SOURCE,factory)}else if(status==="registered"){registry3.registerFactory(ToolNames.RECORD_SOURCE,factory)}}async createToolRegistry(sendSdkMcpMessage,options2){const registry3=new ToolRegistry(this,this.eventEmitter,sendSdkMcpMessage);if(this.sessionExecutionEngine==="managed"){this.applyPendingMcpBudgetCallback(registry3);await this.registerManagedRuntimeTools(registry3);return registry3}const registerLazy=__name((toolName,factory)=>this.registerLazyTool(registry3,toolName,factory),"registerLazy");const registerStructuredOutputIfRequested=__name(async()=>{if(!this.jsonSchema)return;if(options2?.forSubAgent)return;const schema=this.jsonSchema;await registerLazy(ToolNames.STRUCTURED_OUTPUT,async()=>{const{SyntheticOutputTool}=await import("./syntheticOutput-IETGBFDA.js");return new SyntheticOutputTool(schema)})},"registerStructuredOutputIfRequested");const registerGoalWorkerTools=__name(async()=>{if(options2?.forSubAgent)return;await registerLazy(ToolNames.GET_GOAL,async()=>{const{GetGoalTool:GetGoalTool2}=await import("./goal-tools-SHSIDLZX.js");return new GetGoalTool2(this)});await registerLazy(ToolNames.UPDATE_GOAL,async()=>{const{UpdateGoalTool:UpdateGoalTool2}=await import("./goal-tools-SHSIDLZX.js");return new UpdateGoalTool2(this)});if(this.getModelProposedGoals()!=="disabled"&&(resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported)){await registerLazy(ToolNames.PROPOSE_GOAL,async()=>{const{ProposeGoalTool:ProposeGoalTool2}=await import("./goal-tools-SHSIDLZX.js");return new ProposeGoalTool2(this)})}},"registerGoalWorkerTools");const registerExecIfEnabled=__name(async()=>{if(this.getToolMode()!==ToolMode.CodeModeOnly)return;await registerLazy(ToolNames.EXEC,async()=>{const{ExecTool}=await import("./exec-KO2K3GTK.js");return new ExecTool(this)})},"registerExecIfEnabled");const registerHostSessionTools=__name(async()=>{if(this.isTodoWriteEnabled()){await registerLazy(ToolNames.TODO_WRITE,async()=>{const{TodoWriteTool}=await import("./todoWrite-U2EPDDWF.js");return new TodoWriteTool(this)})}await registerLazy(ToolNames.WEB_FETCH,async()=>{const{WebFetchTool}=await import("./web-fetch-L5XCBCBA.js");return new WebFetchTool(this)});const hasExplicitWebSearchBackend=!!this.webSearchSettings?.model?.trim()||!!this.webSearchSettings?.baseUrl;if(!this.getBareMode()&&!this.isSafeMode()&&this.webSearchSettings?.enabled!==false&&(this.webSearchSettings?.enabled===true||!hasExplicitWebSearchBackend)){const{evaluateWebSearchGate}=await import("./web-search-4EHUA3LJ.js");const gate=evaluateWebSearchGate(this);if(gate.ok){await registerLazy(ToolNames.WEB_SEARCH,async()=>{const{WebSearchTool}=await import("./web-search-4EHUA3LJ.js");return new WebSearchTool(this)})}else if(!gate.silent&&!this.webSearchNoticeEmitted&&!options2?.forSubAgent){this.webSearchNoticeEmitted=true;this.warnings.push(gate.notice)}}},"registerHostSessionTools");const environment=this.getExecutionEnvironment();if(environment){if(this.getCodeModeOnly()){throw new Error("Container execution cannot be combined with tools.codeModeOnly.")}const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-IE5BOI7Y.js"),import("./execution-tool-KT3EBWHG.js")]);for(const[name,tool]of createExecutionTools(this)){if(environment.toolNames&&!environment.toolNames.has(name))continue;if(name===ToolNames.LS&&!this.isLsToolEnabled())continue;await registerLazy(name,async()=>wrapExecutionTool(tool,environment,this))}await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-W2CJR74U.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-7GY5YTOU.js");return new ToolSearchTool(this)});if(this.executionEnvironment&&!options2?.forSubAgent){await registerStructuredOutputIfRequested();await registerGoalWorkerTools();if(!this.getBareMode())await registerHostSessionTools()}return registry3}if(this.shellExecutionSandbox){await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-TYOPVB7H.js");return new ShellTool2(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-WMSWQFRF.js");return new TaskStopTool(this)});await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-VEELW4OQ.js");return new ReadFileTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-BJCKSXX7.js");return new WriteFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-W44XQCIS.js");return new EditTool(this)});await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool}=await import("./monitor-7I7Q73UR.js");return new MonitorTool(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-H7XIWYWQ.js");return new AgentTool2(this)});await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-LYA2H6X3.js");return new GlobTool(this)});await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-V7A2PC3T.js");return new LSTool(this)});if(resolveInteractionMode(this)!=="headless"){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-B5E4RG6M.js");return new AskUserQuestionTool2(this)})}await registerExecIfEnabled();await registerStructuredOutputIfRequested();return registry3}if(this.getBareMode()){await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-VEELW4OQ.js");return new ReadFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-W44XQCIS.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-WAD7IQCF.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-TYOPVB7H.js");return new ShellTool2(this)});await registerGoalWorkerTools();await registerStructuredOutputIfRequested();await registerExecIfEnabled();this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}await registerHostSessionTools();await registerExecIfEnabled();await registerGoalWorkerTools();await this.syncAdvisorToolRegistration(registry3);await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-W2CJR74U.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-7GY5YTOU.js");return new ToolSearchTool(this)});await registerLazy(ToolNames.READ_MCP_RESOURCE,async()=>{const{ReadMcpResourceTool}=await import("./read-mcp-resource-ANPZBEC4.js");return new ReadMcpResourceTool(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-H7XIWYWQ.js");return new AgentTool2(this)});await registerLazy(ToolNames.LIST_AGENTS,async()=>{const{ListAgentsTool}=await import("./list-agents-5Z7ZEBYP.js");return new ListAgentsTool(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-WMSWQFRF.js");return new TaskStopTool(this)});await registerLazy(ToolNames.SEND_MESSAGE,async()=>{const{SendMessageTool}=await import("./send-message-FAQ7XEZ5.js");return new SendMessageTool(this)});if(!options2?.forSubAgent||this.getSkillManager()){await registerLazy(ToolNames.SKILL,async()=>{const{SkillTool}=await import("./skill-GJQIE5AX.js");return new SkillTool(this)})}if(this.isLsToolEnabled()){await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-V7A2PC3T.js");return new LSTool(this)})}await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-VEELW4OQ.js");return new ReadFileTool(this)});await registerLazy(ToolNames.MANAGE_MEMORY,async()=>{const{ManageMemoryTool}=await import("./manage-memory-CRV5SXZZ.js");return new ManageMemoryTool(this)});await registerLazy(ToolNames.SEARCH_MEMORY,async()=>{const{SearchMemoryTool}=await import("./search-memory-HEAQCHIK.js");return new SearchMemoryTool(this)});await registerLazy(ToolNames.ZOOM_IMAGE,async()=>{const{ZoomImageTool}=await import("./zoom-image-TLJPD4DB.js");return new ZoomImageTool(this)});if(this.getUseRipgrep()){let useRipgrep=false;let errorString=void 0;recordStartupEvent("config_initialize_ripgrep_probe_start");try{useRipgrep=await canUseRipgrep(this.getUseBuiltinRipgrep())}catch(error3){errorString=getErrorMessage(error3)}recordStartupEvent("config_initialize_ripgrep_probe_end");if(useRipgrep){await registerLazy(ToolNames.GREP,async()=>{const{RipGrepTool}=await import("./ripGrep-4J6ASSE3.js");return new RipGrepTool(this)})}else{logRipgrepFallback(this,new RipgrepFallbackEvent(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),errorString||"ripgrep is not available"));await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-6ACG2X2D.js");return new GrepTool(this)})}}else{recordStartupEvent("config_initialize_ripgrep_probe_start");recordStartupEvent("config_initialize_ripgrep_probe_end");await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-6ACG2X2D.js");return new GrepTool(this)})}await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-LYA2H6X3.js");return new GlobTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-W44XQCIS.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-WAD7IQCF.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-BJCKSXX7.js");return new WriteFileTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-TYOPVB7H.js");return new ShellTool2(this)});await registerLazy(ToolNames.REPORT_FINDINGS,async()=>{const{ReportFindingsTool}=await import("./report-findings-67OAIS2F.js");return new ReportFindingsTool});const supportsUserInteraction=resolveInteractionMode(this)!=="headless";if(supportsUserInteraction){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-B5E4RG6M.js");return new AskUserQuestionTool2(this)})}if(!this.sdkMode&&(supportsUserInteraction||options2?.forSubAgent)){await registerLazy(ToolNames.EXIT_PLAN_MODE,async()=>{const{ExitPlanModeTool:ExitPlanModeTool2}=await import("./exitPlanMode-JLKS76IA.js");return new ExitPlanModeTool2(this)})}if(!this.sdkMode&&supportsUserInteraction){await registerLazy(ToolNames.ENTER_PLAN_MODE,async()=>{const{EnterPlanModeTool}=await import("./enterPlanMode-B456A2XO.js");return new EnterPlanModeTool(this)})}await registerLazy(ToolNames.ENTER_WORKTREE,async()=>{const{EnterWorktreeTool}=await import("./enter-worktree-OYEYIBHG.js");return new EnterWorktreeTool(this)});await registerLazy(ToolNames.EXIT_WORKTREE,async()=>{const{ExitWorktreeTool}=await import("./exit-worktree-XGLOXMHT.js");return new ExitWorktreeTool(this)});if(resolveInteractionMode(this)==="interactive"&&!this.sdkMode&&!this.getScreenReader()&&!options2?.forSubAgent){await registerLazy(ToolNames.DISPLAY_IMAGE,async()=>{const{DisplayImageTool}=await import("./display-image-D7L3HAX2.js");return new DisplayImageTool(this)})}await this.registerImageGenerationTool(registry3);if(this.isArtifactEnabled()){await registerLazy(ToolNames.ARTIFACT,async()=>{const{ArtifactTool}=await import("./artifact-tool-C7SXUVAD.js");return new ArtifactTool(this)})}if(!options2?.forSubAgent){await this.registerSessionSourceTool(registry3)}if(this.isRecordArtifactEnabled()){await registerLazy(ToolNames.RECORD_ARTIFACT,async()=>{const{RecordArtifactTool}=await import("./record-artifact-B5ZMCBZR.js");return new RecordArtifactTool(this)})}if(this.isLspEnabled()&&this.getLspClient()){await registerLazy(ToolNames.LSP,async()=>{const{LspTool}=await import("./lsp-KC7CEAXE.js");return new LspTool(this)})}await registerStructuredOutputIfRequested();if(this.isCronEnabled()){await registerLazy(ToolNames.CRON_CREATE,async()=>{const{CronCreateTool}=await import("./cron-create-CFCMKKF6.js");return new CronCreateTool(this)});await registerLazy(ToolNames.CRON_LIST,async()=>{const{CronListTool}=await import("./cron-list-3NXRSQKN.js");return new CronListTool(this)});await registerLazy(ToolNames.CRON_DELETE,async()=>{const{CronDeleteTool}=await import("./cron-delete-5QRFSNES.js");return new CronDeleteTool(this)});await registerLazy(ToolNames.LOOP_WAKEUP,async()=>{const{LoopWakeupTool}=await import("./loop-wakeup-R3MS4W4A.js");return new LoopWakeupTool(this)})}if(this.getSubSessionSpawner()){await registerLazy(ToolNames.CREATE_SUB_SESSION,async()=>{const{CreateSubSessionTool}=await import("./create-sub-session-6IRYZOGY.js");return new CreateSubSessionTool(this)})}if(this.isAgentTeamEnabled()){await registerLazy(ToolNames.TEAM_CREATE,async()=>{const{TeamCreateTool}=await import("./team-create-RFZNEF76.js");return new TeamCreateTool(this)});await registerLazy(ToolNames.TEAM_DELETE,async()=>{const{TeamDeleteTool}=await import("./team-delete-LVJPX4CM.js");return new TeamDeleteTool(this)});await registerLazy(ToolNames.TEAM_PLAN_APPROVAL,async()=>{const{TeamPlanApprovalTool}=await import("./team-plan-approval-MGW3JGSC.js");return new TeamPlanApprovalTool(this)});if(!options2?.forSubAgent){await registerLazy(ToolNames.REQUEST_SHUTDOWN,async()=>{const{RequestShutdownTool}=await import("./request-shutdown-VJPXPFRB.js");return new RequestShutdownTool(this)})}await registerLazy(ToolNames.TASK_CREATE,async()=>{const{TaskCreateTool}=await import("./task-create-2BNUK636.js");return new TaskCreateTool(this)});await registerLazy(ToolNames.TASK_UPDATE,async()=>{const{TaskUpdateTool}=await import("./task-update-YNIRBBU7.js");return new TaskUpdateTool(this)});await registerLazy(ToolNames.TASK_LIST,async()=>{const{TaskListTool}=await import("./task-list-UQKC23DG.js");return new TaskListTool(this)})}if(this.isWorkflowsEnabled()){await this.registerWorkflowTool(registry3)}if(this.isOmniEnabled()){const omniPolicyToolFactories=[[ToolNames.OMNI_DOWNSAMPLE_IMAGE,async()=>new(await import("./downsample-image-Y6BWJFSA.js")).OmniDownsampleImageTool(this)],[ToolNames.OMNI_DOWNSCALE_VIDEO,async()=>new(await import("./downscale-video-WEUPQZUG.js")).OmniDownscaleVideoTool(this)],[ToolNames.OMNI_DOWNSAMPLE_AUDIO,async()=>new(await import("./downsample-audio-KA3MINGD.js")).OmniDownsampleAudioTool(this)],[ToolNames.OMNI_EXTRACT_KEYFRAMES,async()=>new(await import("./extract-keyframes-VLHSMGTR.js")).OmniExtractKeyframesTool(this)],[ToolNames.OMNI_EXTRACT_AUDIO,async()=>new(await import("./extract-audio-YQDXPJLW.js")).OmniExtractAudioTool(this)],[ToolNames.OMNI_CLIP_VIDEO,async()=>new(await import("./clip-video-4FXV4BGI.js")).OmniClipVideoTool(this)],[ToolNames.OMNI_CONVERT_IMAGE,async()=>new(await import("./convert-image-JI2ICEFQ.js")).OmniConvertImageTool(this)],[ToolNames.OMNI_TRANSCRIBE_AUDIO,async()=>new(await import("./transcribe-audio-PAEN23DB.js")).OmniTranscribeAudioTool(this)],[ToolNames.OMNI_CLIP_IMAGE,async()=>new(await import("./clip-image-X5W3KSTA.js")).OmniClipImageTool(this)],[ToolNames.OMNI_CLIP_AUDIO,async()=>new(await import("./clip-audio-6YBATJFU.js")).OmniClipAudioTool(this)],[ToolNames.OMNI_CAPTION_IMAGE,async()=>new(await import("./caption-image-5NODVPQP.js")).OmniCaptionImageTool(this)],[ToolNames.OMNI_CAPTION_AUDIO,async()=>new(await import("./caption-audio-FSHF5JWX.js")).OmniCaptionAudioTool(this)],[ToolNames.OMNI_OCR_IMAGE,async()=>new(await import("./ocr-image-76FNJ7ZC.js")).OmniOcrImageTool(this)],[ToolNames.OMNI_UNDERSTAND_VIDEO_SEGMENTS,async()=>new(await import("./understand-video-segments-CEHQZNK3.js")).OmniUnderstandVideoSegmentsTool(this)]];for(const[name,factory]of omniPolicyToolFactories){await registerLazy(name,factory)}const memoryConfig=await this.ensureOmniMemoryConfig();if(memoryConfig.recall.mode==="active"){await registerLazy(ToolNames.OMNI_RECALL_MEDIA_MEMORY,async()=>{const{OmniRecallMediaMemoryTool}=await import("./recall-media-memory-tool-DSUGPS7U.js");return new OmniRecallMediaMemoryTool(this)})}}await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool}=await import("./monitor-7I7Q73UR.js");return new MonitorTool(this)});this.applyPendingMcpBudgetCallback(registry3);if(!options2?.skipDiscovery){await registry3.discoverAllTools()}this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}applyPendingMcpBudgetCallback(registry3){if(!this.pendingMcpBudgetCallback)return;const mgr=registry3.getMcpClientManager();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(this.pendingMcpBudgetCallback)}this.pendingMcpBudgetCallback=void 0}setMcpBudgetEventCallback(cb){if(this.toolRegistry){const mgr=this.toolRegistry.getMcpClientManager?.();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(cb)}this.pendingMcpBudgetCallback=void 0;return}this.pendingMcpBudgetCallback=cb}subSessionSpawner;currentSessionScheduledTaskCreator;setSubSessionSpawner(spawner){this.subSessionSpawner=spawner}getSubSessionSpawner(){return this.subSessionSpawner}setCurrentSessionScheduledTaskCreator(creator){this.currentSessionScheduledTaskCreator=creator}getCurrentSessionScheduledTaskCreator(){return this.currentSessionScheduledTaskCreator}};function installSessionWorkflowRevisionWriteThrough(wrapper,base2){const ov=wrapper;ov.setSessionWorkflowPlanRevision=revision=>{base2.setSessionWorkflowPlanRevision(revision)};ov.clearSessionWorkflowPlanRevision=()=>{base2.clearSessionWorkflowPlanRevision()}}__name(installSessionWorkflowRevisionWriteThrough,"installSessionWorkflowRevisionWriteThrough");var debugLogger118=createDebugLogger("EXIT_PLAN_MODE");var exitPlanModeToolDescription=`Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.
|
|
2109
|
+
`);memoryPressureConfigLogger.warn(fallbackMsg);return{...DEFAULT_PRESSURE_CONFIG}}return config3}__name(loadMemoryPressureConfig,"loadMemoryPressureConfig");var DEFAULT_MAX_SUBAGENT_DEPTH=5;var MAX_SUBAGENT_DEPTH_LIMIT=100;function normalizeMaxSubagentDepth(value){return value==null||!Number.isFinite(value)?DEFAULT_MAX_SUBAGENT_DEPTH:Math.min(MAX_SUBAGENT_DEPTH_LIMIT,Math.max(1,Math.floor(value)))}__name(normalizeMaxSubagentDepth,"normalizeMaxSubagentDepth");function validateMaxSessionTurns(value){const resolved=value??-1;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxSessionTurns: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxSessionTurns,"validateMaxSessionTurns");function normalizeGoalTokenBudget(value){if(value===0||value===-1)return Number.POSITIVE_INFINITY;return isValidGoalTokenBudget(value)?value:GOAL_DEFAULT_TOKEN_BUDGET}__name(normalizeGoalTokenBudget,"normalizeGoalTokenBudget");var GOAL_TOKEN_BUDGET_CAP=10*GOAL_DEFAULT_TOKEN_BUDGET;function isValidGoalTokenBudget(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_TOKEN_BUDGET_CAP)}__name(isValidGoalTokenBudget,"isValidGoalTokenBudget");var GOAL_MAX_TURNS_CAP=1e4;var GOAL_MAX_ACTIVE_MINUTES_CAP=7*24*60;function isValidGoalMaxTurns(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_TURNS_CAP)}__name(isValidGoalMaxTurns,"isValidGoalMaxTurns");function normalizeGoalMaxTurns(value){if(!isValidGoalMaxTurns(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value}__name(normalizeGoalMaxTurns,"normalizeGoalMaxTurns");function isValidGoalMaxActiveMinutes(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_ACTIVE_MINUTES_CAP)}__name(isValidGoalMaxActiveMinutes,"isValidGoalMaxActiveMinutes");function normalizeGoalMaxActiveMinutes(value){if(!isValidGoalMaxActiveMinutes(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value*6e4}__name(normalizeGoalMaxActiveMinutes,"normalizeGoalMaxActiveMinutes");function validateMaxToolCallsPerTurn(value){const resolved=value??DEFAULT_MAX_TOOL_CALLS_PER_TURN;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxToolCallsPerTurn: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxToolCallsPerTurn,"validateMaxToolCallsPerTurn");var MAX_MODEL_FALLBACKS=3;function normalizeModelFallbacks(raw){if(!raw||raw.length===0)return[];const seen=new Set;const result=[];for(const entry of raw){const trimmed=entry.trim();if(!trimmed||seen.has(trimmed))continue;seen.add(trimmed);result.push(trimmed);if(result.length>=MAX_MODEL_FALLBACKS)break}return result}__name(normalizeModelFallbacks,"normalizeModelFallbacks");function bareEnabledGrantWarnings(lists,skills,defaultOffNames=new Set){if(lists.enabled.size===0)return[];const registry3=new Set(skills.map(skill=>skill.name.trim().toLowerCase()));const registryNamesByAuthored=new Map;for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;const group=registryNamesByAuthored.get(authored)??[];group.push(registryName);registryNamesByAuthored.set(authored,group)}const warnings=[];for(const[authored,registryNames]of registryNamesByAuthored){if(registry3.has(authored))continue;if(!lists.enabled.has(authored))continue;const plural=registryNames.length>1;const names=registryNames.map(name=>`'${name}'`).join(", ");const skillWord=plural?"skills":"skill";const hardNote=lists.hardDisabled.has(authored)?` A bare '${authored}' in skills.disabled also blocks ${plural?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove that entry too.`:"";if(lists.defaultDisabled.has(authored)){const offNames=registryNames.filter(name=>defaultOffNames.has(name));const onNames=offNames.filter(name=>lists.enabled.has(name)&&!lists.hardDisabled.has(name)&&!lists.hardDisabled.has(authored));const stillOff=offNames.filter(name=>!onNames.includes(name));if(stillOff.length){const offPlural=stillOff.length>1;const offList=stillOff.map(name=>`'${name}'`).join(", ");const hardQualified=stillOff.filter(name=>lists.hardDisabled.has(name));const qualifiedNote=hardQualified.length?` ${hardQualified.map(name=>`'${name}'`).join(", ")} in skills.disabled also blocks ${hardQualified.length>1?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove ${hardQualified.length>1?"those entries":"that entry"} too.`:"";warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name. The pair cancels the disablement but no longer enables the extension ${offPlural?"skills":"skill"} ${offList}, which ${offPlural?"default":"defaults"} off. Replace the bare '${authored}' with ${offList} in both skills.enabled and skills.defaultDisabled to enable ${offPlural?"them":"it"}.`+hardNote+qualifiedNote)}if(onNames.length){const onPlural=onNames.length>1;const onList=onNames.map(name=>`'${name}'`).join(", ");warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name, but the qualified ${onPlural?"grants":"grant"} ${onList} in skills.enabled already ${onPlural?"enable":"enables"} ${onPlural?"them":"it"}, so the bare pair changes nothing. Replace the bare '${authored}' with ${onList} in both skills.enabled and skills.defaultDisabled to drop the dead entries.`)}continue}warnings.push(`Warning: skills.enabled lists '${authored}' by bare name, which no longer enables the extension ${skillWord} ${names}. Replace it with ${names}.`+hardNote)}return warnings}__name(bareEnabledGrantWarnings,"bareEnabledGrantWarnings");function bareDisablementBlocksQualifiedGrantWarnings(lists,disabledNames,skills){if(lists.enabled.size===0||disabledNames.size===0)return[];const warnings=[];for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;if(!lists.enabled.has(registryName))continue;if(!disabledNames.has(authored))continue;if(lists.hardDisabled.has(authored)){const unlocked=[...new Set(skills.filter(other2=>{const name=other2.name.trim().toLowerCase();return name!==registryName&&(name===authored||authoredSkillName(other2).trim().toLowerCase()===authored)}).map(other2=>other2.name.trim().toLowerCase()))];const names=__name(list2=>list2.map(name=>`'${name}'`).join(", "),"names");const reBlockable=unlocked.filter(name=>name!==authored);const notAlone=unlocked.filter(name=>name===authored);let sideEffect="";if(unlocked.length){sideEffect=` The removal also re-enables ${names(unlocked)}.`;if(reBlockable.length){sideEffect+=` Add ${names(reBlockable)} to skills.disabled to keep ${reBlockable.length>1?"them":"it"} blocked.`}if(notAlone.length){sideEffect+=` ${names(notAlone)} cannot be blocked on ${notAlone.length>1?"their":"its"} own while '${registryName}' stays enabled, because any entry matching ${names(notAlone)} also matches '${registryName}'.`}}warnings.push(`Warning: skills.enabled opts in '${registryName}' but '${authored}' in skills.disabled still blocks it \u2014 hard entries are never cancelled by skills.enabled. Remove '${authored}' from skills.disabled to enable the skill.`+sideEffect);continue}warnings.push(`Warning: skills.enabled opts in '${registryName}' but a bare '${authored}' entry still blocks it \u2014 disable entries match under either spelling; a skills.defaultDisabled entry is cancelled only by the identical spelling. Write '${registryName}' in both lists, or remove '${authored}'.`)}return warnings}__name(bareDisablementBlocksQualifiedGrantWarnings,"bareDisablementBlocksQualifiedGrantWarnings");function readMemoryPressureRatioEnv(envName,fallback){const raw=process8.env[envName];if(!raw){return fallback}const parsed=Number(raw);if(!Number.isFinite(parsed)){throw new Error(`${envName} must be a finite number`)}return parsed}__name(readMemoryPressureRatioEnv,"readMemoryPressureRatioEnv");var DEFAULT_BARE_CORE_TOOLS=[ToolNames.READ_FILE,ToolNames.EDIT,ToolNames.NOTEBOOK_EDIT,ToolNames.SHELL];var EMPTY_DISABLED_SKILL_NAMES=Object.freeze(new Set);var sessionEnvClaimed=false;var projectDirEnvClaimed=false;var modelEnvClaimed=false;function resolveSensitiveSpanAttributeMaxLength(value){if(value===void 0){return DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH}if(!isValidSensitiveSpanAttributeMaxLength(value)){throw new FatalConfigError(`Invalid telemetry.sensitiveSpanAttributeMaxLength: must be a positive integer no greater than ${SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT}, got ${String(value)}`)}return value}__name(resolveSensitiveSpanAttributeMaxLength,"resolveSensitiveSpanAttributeMaxLength");function resolveCronRecurringMaxAgeDays(setting){const env=process8.env["QWEN_CODE_CRON_MAX_AGE_DAYS"];const fromEnv=env!==void 0&&env.trim()!=="";const raw=fromEnv?Number(env):setting;if(raw===void 0||!Number.isFinite(raw)||raw<0){if(raw!==void 0){console.warn((fromEnv?`QWEN_CODE_CRON_MAX_AGE_DAYS="${env}" is invalid`:`cronRecurringMaxAgeDays=${setting} is invalid`)+`; recurring cron jobs will expire after the ${DEFAULT_RECURRING_MAX_AGE_DAYS}-day default.`)}return DEFAULT_RECURRING_MAX_AGE_DAYS}return normalizeRecurringMaxAge(raw,DEFAULT_RECURRING_MAX_AGE_DAYS)}__name(resolveCronRecurringMaxAgeDays,"resolveCronRecurringMaxAgeDays");var SessionWriterShutdownError=class extends SessionWriterUnavailableError{static{__name(this,"SessionWriterShutdownError")}};function containsErrorByIdentity(error3,candidate){return error3===candidate||error3 instanceof Error&&error3.cause instanceof AggregateError&&error3.cause.errors.includes(candidate)}__name(containsErrorByIdentity,"containsErrorByIdentity");var DERIVED_CONFIG=Symbol("derivedConfig");function isDerivedConfig(config3){return config3[DERIVED_CONFIG]===true}__name(isDerivedConfig,"isDerivedConfig");function deriveApprovalModeConfig(base2,mode,options2={}){const baseApprovalMode=base2.getApprovalMode();const initialMode=getTrustedDerivedApprovalMode(base2,mode);let autoOverrideAcquired=false;const acquireAutoOverride=__name(()=>{if(autoOverrideAcquired||base2.getApprovalMode()==="auto"){return}if(options2.hooks){autoOverrideAcquired=options2.hooks.acquireAutoApprovalOverride();return}base2.getPermissionManager?.()?.stripDangerousRulesForAutoMode();autoOverrideAcquired=true},"acquireAutoOverride");const releaseAutoOverride=__name(()=>{if(!autoOverrideAcquired)return;if(options2.hooks){options2.hooks.releaseAutoApprovalOverride()}else if(base2.getApprovalMode()!=="auto"){base2.getPermissionManager?.()?.restoreDangerousRules()}autoOverrideAcquired=false},"releaseAutoOverride");const derived=deriveConfig(base2,{getApprovalMode:Config.prototype.getApprovalMode});const state=derived;state.approvalMode=initialMode;state.prePlanMode=initialMode==="plan"?baseApprovalMode==="plan"?base2.getPrePlanMode():baseApprovalMode:void 0;state.approvalModeRevision=0;state.manualPlanExitNoticeEventState={...base2.manualPlanExitNoticeEventState??{version:0,kind:"clear"}};state.autoModeDenialState=createDenialState();Object.defineProperty(derived,"setApprovalMode",{value:__name((nextMode,setOptions2)=>{const beforeMode=derived.getApprovalMode();const hadOwnPermissionManager=Object.hasOwn(derived,"permissionManager");const ownPermissionManager=state.permissionManager;state.permissionManager=null;try{Config.prototype.setApprovalMode.call(derived,nextMode,setOptions2)}finally{if(hadOwnPermissionManager){state.permissionManager=ownPermissionManager}else{delete state.permissionManager}}const afterMode=derived.getApprovalMode();if(beforeMode!=="auto"&&afterMode==="auto"){acquireAutoOverride()}else if(beforeMode==="auto"&&afterMode!=="auto"){releaseAutoOverride()}},"value"),writable:true,configurable:true,enumerable:true});if(initialMode==="auto"&&base2.getApprovalMode()!=="auto"){acquireAutoOverride()}return{config:derived,cleanup:releaseAutoOverride}}__name(deriveApprovalModeConfig,"deriveApprovalModeConfig");function deriveAgentConfig(base2,workingDirectory,options2={}){const fileService=new FileDiscoveryService(workingDirectory,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(workingDirectory);const derived=deriveConfig(base2,{getTargetDir:__name(()=>workingDirectory,"getTargetDir"),getCwd:__name(()=>workingDirectory,"getCwd"),getWorkingDir:__name(()=>workingDirectory,"getWorkingDir"),getProjectRoot:__name(()=>workingDirectory,"getProjectRoot"),getPlanFilePath:options2.getPlanFilePath,getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=workingDirectory;workspaceState.cwd=workingDirectory;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return{config:derived,fileService,workspaceContext}}__name(deriveAgentConfig,"deriveAgentConfig");function getTrustedDerivedApprovalMode(base2,requestedMode){if((!base2.isTrustedFolder()||base2.isSessionAgentSession?.()===true)&&requestedMode!=="default"&&requestedMode!=="plan"){return"default"}return requestedMode}__name(getTrustedDerivedApprovalMode,"getTrustedDerivedApprovalMode");function deriveWorktreeConfig(base2,worktreePath,options2={}){const fileService=new FileDiscoveryService(worktreePath,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(worktreePath);const derived=deriveConfig(base2,{getTargetDir:__name(()=>worktreePath,"getTargetDir"),getCwd:__name(()=>worktreePath,"getCwd"),getWorkingDir:__name(()=>worktreePath,"getWorkingDir"),getProjectRoot:__name(()=>worktreePath,"getProjectRoot"),getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=worktreePath;workspaceState.cwd=worktreePath;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return derived}__name(deriveWorktreeConfig,"deriveWorktreeConfig");function deriveConfig(base2,overrides={}){const shellSandbox=base2.getShellExecutionSandbox?.();if(shellSandbox){for(const key of["getTargetDir","getCwd","getWorkingDir","getProjectRoot"]){assertShellSandboxCwd(shellSandbox,overrides[key]?.()??base2[key]())}}const derived=Object.create(base2);for(const key in overrides){if(!Object.hasOwn(overrides,key))continue;const override=overrides[key];if(override!==void 0){Object.defineProperty(derived,key,{value:override,writable:true,configurable:true,enumerable:true})}}Object.defineProperty(derived,DERIVED_CONFIG,{value:true});return derived}__name(deriveConfig,"deriveConfig");var Config=class _Config{static{__name(this,"Config")}shellExecutionSandbox;sessionId;sessionSourceType;sessionSourceId;sessionData;pendingSessionRestoreProjection;sessionRestoreRuntime;sessionRestoreProjectionSource;sessionExecutionEngine;managedRuntimeEnvironmentFactory;managedRuntimeEnvironment;onManagedEngineQuarantine;managedRuntimeClosing;managedSessionBlock;restoredFileHistory=false;goalRestoreActivation;rejectGoalRestoreActivation;sessionRuntimeBaseDir;provisionalWorkspace;provisionalWorkspaceActivated=false;provisionalWorkspaceActivation;sessionProjectDirRegistered=false;pendingSessionWriterLease;managedSession;managedRuntimeOutcomes;pendingSessionWriterRelease;sessionWriterReclaimPolicy="local";sessionWriterTakeoverPolicy="never";sessionWriterShutdownRequested=false;sessionWriterHandoffRequested=false;sessionWriterActivationPromise;sessionWriterClosePromise;pendingStartupWorktreeNotice=null;pendingRecoveredAgentsNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;resourceRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry;monitorRegistry=new MonitorRegistry;backgroundAgentResumeService;backgroundShellRegistry=new BackgroundShellRegistry;workflowRunRegistry=new WorkflowRunRegistry;turnBudget=new TurnBudget;fileReadCache=new FileReadCache;extensionManager;skillManager=null;permissionManager=null;toolInvocationGuard;workflowAncestorTrustProvider;modelInvocableCommandsProvider=null;modelInvocableCommandsExecutor=null;pendingInlineAnnouncedSkillKeys=new Set;fileSystemService;contentGeneratorConfig;contentGeneratorConfigSources={};contentGenerator;initialAuthType;initialResolvedAuthType;embeddingModel;modelsConfig;modelProvidersConfig;providerProtocolConfig;sandbox;targetDir;workspaceContext;debugMode;inputFormat;outputFormat;includePartialMessages;question;systemPrompt;workspaceAgentName;workspaceAgentExecutionAllowedTools;workspaceAgentDisallowedTools;sessionAgentSession=false;appendSystemPrompt;liveAppendSystemPrompt;outputStyle;coreTools;allowedTools;excludeTools;disabledSlashCommands;disabledSkillNamesProvider;enabledSkillNamesProvider;skillSettingsListsProvider;terminalImageRenderSupportProvider;disabledSkillLevels;customSkillDirs;disabledTools;visibleTools;eagerTools;toolSearchThreshold;toolMode;freeform;permissionsAllow;permissionsAsk;permissionsDeny;permissionsAutoMode;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;recentlyRemovedMcpServers=new Set;topTierMcpServers;runtimeMcpServers=new Map;lspEnabled;lspClient;lspInitializationError;allowedMcpServers;cliAllowedMcpServerNames;excludedMcpServers;pendingMcpServers;mcpToolIdleTimeoutMs;mcpReconcileInProgress=false;mcpReconcilePending=false;mcpReconcilePromise;sessionSubagents;userMemory;staticSystemPrefix;promptToolSnapshot;promptAgentReachable=false;autoMemoryPrompt="";autoMemoryContext="";memoryRecallMode="legacy";memoryCorpusRevision="";memoryRecallModeInitialized=false;sdkMode;memoryFileCount;loadedContextFilePaths=[];conditionalRulesRegistry;contextRuleExcludes;approvalMode;prePlanMode;planExecutionMode;approvalModeRevision=0;manualPlanExitNoticeEventState={version:0,kind:"clear"};manualPlanExitNoticeCursorState={seenVersion:0};autoModeDenialState=createDenialState();accessibility;showResponseTokensPerSecond;telemetrySettings;telemetryInitializationDeferred;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;activeTodoReminders=new Map;activeTodoWorkChainOwners=new Map;activeTodoReminderTurns=new Map;activeTodoPlanWriterOwner;llmClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;chatRecordingService=void 0;goalRuntime;goalRuntimeReady;pendingGoalProposal;goalProposalApprovalController;pendingGoalRestore;goalTurnHost;goalTurnHostUnbind;goalTurnHostGeneration=0;chatRecordingFailureListeners=new Set;requestLifecycleListeners=new Set;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;goalTokenBudgetGrant;goalTurnBudgetGrant;goalActiveTimeBudgetGrantMs;maxSubagentDepth;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=false;sessionRegistryActive=false;sessionRegistered=false;sessionRegistrySlot=SHARED_RECORD_SLOT;experimentalZedIntegration=false;restoreAskUserQuestion=false;preserveRestorableAskUserQuestion=false;sessionWriterLeaseEnabled=false;cronEnabled=true;cronRecurringMaxAgeDays;lsToolEnabled=false;todoWriteEnabled=false;agentTeamEnabled=false;agentCollaborationEnabled=false;artifactEnabled=true;artifactSnapshotsEnabled=false;artifactAutoOpen=true;artifactPublisher="local";artifactHost;artifactOss;omniEnabled=false;omniMaxUploadFileBytes;omniMaxEstimatedTokens;omniMaxDurationSeconds;omniUrlDownloadMaxFileBytes;omniUploadUrlTtlHours;omniUploadBaseUrl;omniUploadApiKeyEnv;omniUploadModel;omniUploadConfig;omniPolicyTools;omniFixedPolicies;omniTransportGuardPolicies;omniProcessingLimits;omniQuarantineRetentionDays;omniStorageRetentionDays;omniStorageMaxTotalBytes;omniQuarantineMaxBytes;omniMemory;omniProcessingConfig;omniMemoryConfig;omniMediaResourceRegistry;workflowsEnabled;sessionWorkflowEnabled;sessionWorkflowEnabledProvider;sessionWorkflowPlanRevision;externalAgentExecutor;agentExecutionBackend;executionEnvironmentFactory;executionEnvironment;executionEnvironments;executionShutdown=new AbortController;executionCleanupPromise;modelProposedGoals;goalProposalHostSupported=false;goalProposalTurnKey;skipWorkflowUsageWarning=false;workflowSizeGuideline;workflowNameOnly;emitToolUseSummaries=true;chatRecordingEnabled;loadMemoryFromIncludeDirectories=false;importFormat;chatCompression;autoCompactThreshold;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;maxToolCallsPerTurn;maxToolCallsPerTurnExplicit;skipStartupContext;bareMode;safeMode;warnings;ignoredExtensionRules=[];allowedHttpHookUrls;allowPrivateNetworkHooks;onPersistPermissionRuleCallback;initialized=false;initializationPromise;initializationSucceeded=false;initializationSettled=false;shutdownRequested=false;resourceShutdownAfterInitializationScheduled=false;resourceShutdownPromise;proxyDispatcherReady;storage;runtimeStatusWrite=Promise.resolve();sessionRegistryWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputThresholdExplicit;truncateToolOutputLines;toolOutputBatchBudget;shellDefaultTimeoutMs;shellHeartbeatIntervalMs;eventEmitter;channel;jsonFd;jsonFile;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableTeamMemory;enableTeamMemorySync;enableStructuredMemoryRecall;teamMemoryShareabilityChecked=new Set;enableAutoSkill;autoSkillConfirm;memoryAgentTimeoutMinutes;memoryAgentMaxTurns;fastModel;advisorModel;advisorMaxUses;advisorUsage={calls:0};webSearchSettings;webSearchNoticeEmitted=false;webSearchSessionUsage={calls:0};visionModel;compactionModel;reasoningSnapshot;latestReasoningSnapshot;imageModel;visionBridgeTimeoutMs;modelFallbacks;disableAllHooks;stopHookBlockingCap;systemHooks;userHooks;projectHooks;hooks;hookSystem;messageBus;messageBusListeners=new Set;memoryManager;modelChangeListeners=new Set;approvalModeChangeListeners=new Set;ownsModelEnvSlot=false;settingsWatcher;constructor(params){this.executionEnvironment=params.executionEnvironment;if(params.executionEnvironment){this.executionEnvironments=new Set([Promise.resolve(params.executionEnvironment)])}this.agentExecutionBackend=params.agentExecutionBackend;const executionFactory=params.executionEnvironmentFactory;this.executionEnvironmentFactory=executionFactory?(config3,signal)=>executionFactory(config3,AbortSignal.any([signal,this.executionShutdown.signal])):void 0;this.sessionRuntimeBaseDir=Storage.getRuntimeBaseDir();this.shellExecutionSandbox=admitShellSandbox(params,this.sessionRuntimeBaseDir,Storage.getGlobalQwenDir());this.provisionalWorkspace=params.provisionalWorkspace===true;this.sessionId=params.sessionId??randomUUID23();if(!sessionEnvClaimed&&process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId;sessionEnvClaimed=true}this.sessionData=params.sessionData;this.sessionRestoreProjectionSource=params.sessionRestoreProjectionSource;this.sessionExecutionEngine=params.sessionExecutionEngine;this.managedRuntimeEnvironmentFactory=params.sessionExecutionEngine==="managed"?params.managedRuntimeEnvironment:void 0;this.onManagedEngineQuarantine=params.sessionExecutionEngine==="managed"?params.onManagedEngineQuarantine:void 0;this.setSessionRestoreProjection(params.sessionRestoreProjection);if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();this.embeddingModel=params.embeddingModel??DEFAULT_QWEN_EMBEDDING_MODEL;this.fileSystemService=new StandardFileSystemService;this.sandbox=params.sandbox;this.targetDir=path81.resolve(params.targetDir);this.plansDirectoryConfigured=Boolean(params.plansDirectory?.trim());this.plansDir=Storage.getPlansDir(this.targetDir,params.plansDirectory);this.explicitIncludeDirectories=Array.from(new Set(params.includeDirectories??[]));this.workspaceContext=new WorkspaceContext(this.targetDir,this.explicitIncludeDirectories);this.debugMode=params.debugMode;this.inputFormat=params.inputFormat??"text";const normalizedOutputFormat=normalizeConfigOutputFormat(params.outputFormat??params.output?.format);this.outputFormat=normalizedOutputFormat??"text";this.includePartialMessages=params.includePartialMessages??false;this.question=params.question;this.systemPrompt=params.systemPrompt;this.appendSystemPrompt=params.appendSystemPrompt;this.outputStyle=params.outputStyle;this.coreTools=params.coreTools;this.allowedTools=params.allowedTools;this.excludeTools=params.excludeTools;this.disabledSlashCommands=Object.freeze([...params.disabledSlashCommands??[]]);this.disabledSkillNamesProvider=params.disabledSkillNamesProvider??null;this.enabledSkillNamesProvider=params.enabledSkillNamesProvider??null;this.skillSettingsListsProvider=params.skillSettingsListsProvider??null;this.terminalImageRenderSupportProvider=params.terminalImageRenderSupportProvider??null;this.disabledSkillLevels=new Set(params.disabledSkillLevels??[]);this.customSkillDirs=Object.freeze([...params.customSkillDirs??[]]);this.disabledTools=new Set(params.disabledTools??[]);this.visibleTools=new Set((params.visibleTools??[]).filter(name=>typeof name==="string"));this.eagerTools=params.eagerTools===void 0?void 0:Object.freeze(params.eagerTools.filter(name=>typeof name==="string"));this.toolSearchThreshold=params.toolSearchThreshold??DEFAULT_TOOL_SEARCH_THRESHOLD;this.permissionsAllow=params.permissions?.allow||[];this.permissionsAsk=params.permissions?.ask||[];this.permissionsDeny=params.permissions?.deny||[];this.permissionsAutoMode=params.permissions?.autoMode??{};this.toolInvocationGuard=params.toolInvocationGuard;this.workflowAncestorTrustProvider=params.workflowAncestorTrustProvider;this.toolDiscoveryCommand=params.toolDiscoveryCommand;this.toolCallCommand=params.toolCallCommand;this.mcpServerCommand=params.mcpServerCommand;this.mcpServers=params.mcpServers;this.topTierMcpServers=params.topTierMcpServers;this.lspEnabled=params.lsp?.enabled??false;this.lspClient=params.lspClient;this.allowedMcpServers=params.allowedMcpServers;this.cliAllowedMcpServerNames=params.cliAllowedMcpServerNames;this.excludedMcpServers=params.excludedMcpServers;this.pendingMcpServers=params.pendingMcpServers;const envTimeout=process8.env["QWEN_CODE_MCP_TOOL_IDLE_TIMEOUT_MS"];const parsedEnv=envTimeout!==void 0?Number(envTimeout):NaN;this.mcpToolIdleTimeoutMs=params.mcpToolIdleTimeoutMs??(Number.isFinite(parsedEnv)&&parsedEnv>=0?parsedEnv:3e5);this.sessionSubagents=params.sessionSubagents??[];this.sdkMode=params.sdkMode??false;this.userMemory=params.userMemory??"";this.memoryFileCount=params.memoryFileCount??params.geminiMdFileCount??0;this.contextRuleExcludes=params.contextRuleExcludes??[];this.approvalMode=params.approvalMode??"auto";this.accessibility=params.accessibility??{};this.showResponseTokensPerSecond=params.showResponseTokensPerSecond??false;this.telemetrySettings={enabled:params.telemetry?.enabled??false,target:params.telemetry?.target??DEFAULT_TELEMETRY_TARGET,otlpEndpoint:params.telemetry?.otlpEndpoint,otlpProtocol:params.telemetry?.otlpProtocol,otlpTracesEndpoint:params.telemetry?.otlpTracesEndpoint,otlpLogsEndpoint:params.telemetry?.otlpLogsEndpoint,otlpMetricsEndpoint:params.telemetry?.otlpMetricsEndpoint,logPrompts:params.telemetry?.logPrompts??true,userId:params.telemetry?.userId?.trim()||void 0,includeSensitiveSpanAttributes:params.telemetry?.includeSensitiveSpanAttributes??false,sensitiveSpanAttributeMaxLength:resolveSensitiveSpanAttributeMaxLength(params.telemetry?.sensitiveSpanAttributeMaxLength),outfile:params.telemetry?.outfile,resourceAttributes:params.telemetry?.resourceAttributes,metrics:params.telemetry?.metrics,resourceAttributeWarnings:params.telemetry?.resourceAttributeWarnings};this.telemetryInitializationDeferred=params.deferTelemetryInitialization??false;this.outboundCorrelationSettings={propagateTraceContext:params.outboundCorrelation?.propagateTraceContext??false,allowDynamicHeaderValues:params.outboundCorrelation?.allowDynamicHeaderValues===true};this.gitCoAuthor={...normalizeGitCoAuthor(params.gitCoAuthor),name:"Qwen-Coder",email:"qwen-coder@alibabacloud.com"};this.usageStatisticsEnabled=params.usageStatisticsEnabled??true;this.fileReadCacheDisabled=params.sessionExecutionEngine==="managed"||(params.fileReadCacheDisabled??false);this.outputLanguageFilePath=params.outputLanguageFilePath;this.fileFiltering={respectGitIgnore:params.fileFiltering?.respectGitIgnore??true,respectQwenIgnore:params.fileFiltering?.respectQwenIgnore??true,customIgnoreFiles:params.fileFiltering?.customIgnoreFiles??[...DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES],enableRecursiveFileSearch:params.fileFiltering?.enableRecursiveFileSearch??true,enableFuzzySearch:params.fileFiltering?.enableFuzzySearch??true};this.fileCheckpointingEnabled=params.fileCheckpointingEnabled??(!params.sdkMode&&(params.interactive??false));this.proxy=params.proxy;this.cwd=params.cwd??process8.cwd();this.fileDiscoveryService=params.fileDiscoveryService??null;this.bugCommand=params.bugCommand;this.maxSessionTurns=validateMaxSessionTurns(params.maxSessionTurns);this.goalTokenBudgetGrant=normalizeGoalTokenBudget(params.goalTokenBudget);if(params.goalTokenBudget!==void 0&&!isValidGoalTokenBudget(params.goalTokenBudget)){this.debugLogger.warn(`Ignoring invalid goalTokenBudget ${String(params.goalTokenBudget)}: expected a non-negative integer or -1 (no budget); using the default of ${GOAL_DEFAULT_TOKEN_BUDGET}.`)}this.goalTurnBudgetGrant=normalizeGoalMaxTurns(params.goalMaxTurns);if(params.goalMaxTurns!==void 0&&!isValidGoalMaxTurns(params.goalMaxTurns)){this.debugLogger.warn(`Ignoring invalid goalMaxTurns ${String(params.goalMaxTurns)}: expected an integer between 1 and ${GOAL_MAX_TURNS_CAP}, or -1 for no turn ceiling; Goals will run with no turn ceiling.`)}this.goalActiveTimeBudgetGrantMs=normalizeGoalMaxActiveMinutes(params.goalMaxActiveMinutes);if(params.goalMaxActiveMinutes!==void 0&&!isValidGoalMaxActiveMinutes(params.goalMaxActiveMinutes)){this.debugLogger.warn(`Ignoring invalid goalMaxActiveMinutes ${String(params.goalMaxActiveMinutes)}: expected an integer between 1 and ${GOAL_MAX_ACTIVE_MINUTES_CAP}, or -1 for no time ceiling; Goals will run with no time ceiling.`)}this.maxSubagentDepth=normalizeMaxSubagentDepth(params.maxSubagentDepth);this.maxWallTimeSeconds=params.maxWallTimeSeconds??-1;this.maxToolCalls=params.maxToolCalls??-1;const clearContextOnIdle=params.clearContextOnIdle;const toolResultsThresholdMinutes=clearContextOnIdle?.toolResultsThresholdMinutes??60;this.clearContextOnIdle={toolResultsThresholdMinutes,toolResultsNumToKeep:clearContextOnIdle?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:clearContextOnIdle?.toolResultsTotalCharsThreshold??((clearContextOnIdle?.toolResultsThresholdMinutes??0)<0?-1:DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD)};this.sessionTokenLimit=params.sessionTokenLimit??-1;this.experimentalZedIntegration=params.experimentalZedIntegration??false;this.restoreAskUserQuestion=params.restoreAskUserQuestion===true;this.preserveRestorableAskUserQuestion=this.restoreAskUserQuestion;this.sessionWriterLeaseEnabled=this.experimentalZedIntegration===true&¶ms.sessionWriterLeaseEnabled===true;this.cronEnabled=params.cronEnabled??true;this.cronRecurringMaxAgeDays=resolveCronRecurringMaxAgeDays(params.cronRecurringMaxAgeDays);this.lsToolEnabled=params.lsToolEnabled??false;this.todoWriteEnabled=params.todoWriteEnabled??false;this.agentTeamEnabled=params.agentTeamEnabled??false;this.agentCollaborationEnabled=params.agentCollaborationEnabled??false;this.artifactEnabled=params.artifactEnabled??true;this.artifactAutoOpen=params.artifactAutoOpen??true;this.artifactPublisher=params.artifactPublisher??"local";this.artifactHost=params.artifactHost;this.artifactOss=params.artifactOss;this.omniEnabled=params.omniEnabled??false;this.omniMaxUploadFileBytes=params.omniMaxUploadFileBytes;this.omniMaxEstimatedTokens=params.omniMaxEstimatedTokens;this.omniMaxDurationSeconds=params.omniMaxDurationSeconds;this.omniUrlDownloadMaxFileBytes=params.omniUrlDownloadMaxFileBytes;this.omniUploadUrlTtlHours=params.omniUploadUrlTtlHours;this.omniUploadBaseUrl=params.omniUploadBaseUrl;this.omniUploadApiKeyEnv=params.omniUploadApiKeyEnv;this.omniUploadModel=params.omniUploadModel;this.omniPolicyTools=params.omniPolicyTools;this.omniFixedPolicies=params.omniFixedPolicies;this.omniTransportGuardPolicies=params.omniTransportGuardPolicies;this.omniProcessingLimits=params.omniProcessingLimits;this.omniQuarantineRetentionDays=params.omniQuarantineRetentionDays;this.omniQuarantineMaxBytes=params.omniQuarantineMaxBytes;this.omniStorageRetentionDays=params.omniStorageRetentionDays;this.omniStorageMaxTotalBytes=params.omniStorageMaxTotalBytes;this.omniMemory=params.omniMemory;this.workflowsEnabled=params.workflowsEnabled;this.sessionWorkflowEnabled=params.sessionWorkflowEnabled??false;this.modelProposedGoals=params.modelProposedGoals??"alwaysAsk";this.skipWorkflowUsageWarning=params.skipWorkflowUsageWarning??false;this.workflowSizeGuideline=isWorkflowSizeGuideline(params.workflowSizeGuideline)?params.workflowSizeGuideline:void 0;this.workflowNameOnly=params.workflowNameOnly===true||process8.env["QWEN_CODE_WORKFLOW_NAME_ONLY"]==="1";this.workflowRunRegistry.setNameOnly(this.workflowNameOnly);this.emitToolUseSummaries=params.emitToolUseSummaries??true;this.listExtensions=params.listExtensions??false;this.overrideExtensions=params.overrideExtensions;this.noBrowser=params.noBrowser??false;this.folderTrustFeature=params.folderTrustFeature??false;this.folderTrust=params.folderTrust??false;this.ideMode=params.ideMode??false;this.modelProvidersConfig=params.modelProvidersConfig;this.providerProtocolConfig=params.providerProtocolConfig;this.cliVersion=params.cliVersion;this.chatRecordingEnabled=params.chatRecording??true;this.loadMemoryFromIncludeDirectories=params.loadMemoryFromIncludeDirectories??false;this.importFormat=params.importFormat??"tree";this.chatCompression=params.chatCompression;this.autoCompactThreshold=params.autoCompactThreshold;this.interactive=params.interactive??false;this.trustedFolder=params.trustedFolder;this.skipLoopDetection=params.skipLoopDetection??false;this.maxToolCallsPerTurn=validateMaxToolCallsPerTurn(params.maxToolCallsPerTurn);this.maxToolCallsPerTurnExplicit=params.maxToolCallsPerTurn!==void 0;this.skipStartupContext=params.skipStartupContext??false;this.bareMode=params.bareMode??false;this.safeMode=params.safeMode??isSafeModeEnv();this.toolMode=params.codeModeOnly&&!this.bareMode&&!this.safeMode?ToolMode.CodeModeOnly:ToolMode.Direct;this.freeform=this.toolMode===ToolMode.CodeModeOnly&¶ms.freeform===true;if(this.safeMode){this.debugLogger.info("Safe mode active: hooks, extensions, skills, MCP servers, context files, rules disabled")}this.warnings=params.warnings??[];this.addLegacyPlanLocationWarning();this.allowedHttpHookUrls=params.allowedHttpHookUrls??[];this.allowPrivateNetworkHooks=params.allowPrivateNetworkHooks??false;this.onPersistPermissionRuleCallback=params.onPersistPermissionRule;this.useRipgrep=params.useRipgrep??true;this.useBuiltinRipgrep=params.useBuiltinRipgrep??true;this.shouldUseNodePtyShell=params.shouldUseNodePtyShell??shouldDefaultToNodePty();this.preventSystemSleep=params.preventSystemSleep??true;this.skipNextSpeakerCheck=params.skipNextSpeakerCheck??true;this.shellExecutionConfig={terminalWidth:params.shellExecutionConfig?.terminalWidth??80,terminalHeight:params.shellExecutionConfig?.terminalHeight??24,showColor:params.shellExecutionConfig?.showColor??false,pager:params.shellExecutionConfig?.pager,maxBufferedOutputBytes:params.shellExecutionConfig?.maxBufferedOutputBytes};this.truncateToolOutputThreshold=params.truncateToolOutputThreshold??DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;this.truncateToolOutputThresholdExplicit=params.truncateToolOutputThreshold!=null;this.truncateToolOutputLines=params.truncateToolOutputLines??DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES;this.toolOutputBatchBudget=params.toolOutputBatchBudget??DEFAULT_TOOL_OUTPUT_BATCH_BUDGET;this.shellDefaultTimeoutMs=params.shellDefaultTimeoutMs!==void 0&&Number.isInteger(params.shellDefaultTimeoutMs)&¶ms.shellDefaultTimeoutMs>=0&¶ms.shellDefaultTimeoutMs<=2147483647?params.shellDefaultTimeoutMs:void 0;this.shellHeartbeatIntervalMs=params.shellHeartbeatIntervalMs!==void 0&&Number.isInteger(params.shellHeartbeatIntervalMs)&¶ms.shellHeartbeatIntervalMs>=0&¶ms.shellHeartbeatIntervalMs<=2147483647?params.shellHeartbeatIntervalMs:void 0;this.channel=params.channel;this.jsonFd=params.jsonFd;this.jsonFile=params.jsonFile;this.jsonSchema=params.jsonSchema;this.inputFile=params.inputFile;this.defaultFileEncoding=params.defaultFileEncoding;this.storage=new Storage(this.targetDir,this.sessionRuntimeBaseDir);if(!projectDirEnvClaimed&&process8.env){process8.env["QWEN_CODE_PROJECT_DIR"]=this.storage.getProjectDir();projectDirEnvClaimed=true}this.inputFormat=params.inputFormat??"text";this.fileExclusions=new FileExclusions(this);this.eventEmitter=params.eventEmitter;this.arenaAgentClient=ArenaAgentClient.create();this.agentsSettings=params.agents??{};this.backgroundTaskRegistry=new BackgroundTaskRegistry({...this.agentsSettings.maxParallelAgents!==void 0?{maxConcurrentBackgroundAgents:this.agentsSettings.maxParallelAgents}:{},...this.agentsSettings.maxParallelAgentsByModel!==void 0?{maxConcurrentBackgroundAgentsByModel:this.agentsSettings.maxParallelAgentsByModel}:{}});this.worktreeSettings=params.worktree??{};if(params.contextFileName){setMemoryFilename(params.contextFileName)}this.initialAuthType=params.authType??params.generationConfig?.authType;this.modelsConfig=new ModelsConfig({initialAuthType:this.initialAuthType,modelProvidersConfig:this.modelProvidersConfig,providerProtocolConfig:this.providerProtocolConfig,generationConfig:{model:params.model,...params.generationConfig||{},baseUrl:params.generationConfig?.baseUrl},generationConfigSources:params.generationConfigSources,initialRegistryBaseUrl:params.initialModelRegistryBaseUrl,onModelChange:this.handleModelChange.bind(this)});this.initialResolvedAuthType=this.modelsConfig.getCurrentAuthType();if(!modelEnvClaimed&&process8.env){modelEnvClaimed=true;this.ownsModelEnvSlot=true}this.publishModelEnv();if(this.telemetrySettings.enabled&&!this.telemetryInitializationDeferred){void Promise.resolve(initializeTelemetry(this)).catch(error3=>{this.debugLogger.error("Failed to initialize telemetry:",error3)})}const proxyUrl=this.getProxy();if(proxyUrl&&(params.installProxyDispatcher??true)){this.proxyDispatcherReady=loadUndici().then(({EnvHttpProxyAgent,setGlobalDispatcher})=>{setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}));setResolvedProxyUrlForRuntimeFetch(proxyUrl)}).catch(error3=>{this.debugLogger.error("Failed to install proxy dispatcher:",redactProxyError(error3));throw error3});this.proxyDispatcherReady.catch(()=>{})}this.llmClient=new LlmClient(this);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;if(!this.sessionRestoreProjectionSource||this.sessionRestoreRuntime||!this.sessionWriterLeaseEnabled){this.initializeGoalRuntime(this.sessionRestoreRuntime?.goalRecords??this.sessionData?.conversation.messages,this.sessionRestoreRuntime)}this.extensionManager=new ExtensionManager({workspaceDir:this.targetDir,enabledExtensionOverrides:this.overrideExtensions,isWorkspaceTrusted:this.isTrustedFolder(),locale:params.locale,usageStatisticsEnabled:this.usageStatisticsEnabled,proxy:this.proxy});this.enableManagedAutoMemory=params.enableManagedAutoMemory??true;this.enableManagedAutoDream=params.enableManagedAutoDream??true;this.enableTeamMemory=params.enableTeamMemory??false;this.enableTeamMemorySync=params.enableTeamMemorySync??false;this.enableStructuredMemoryRecall=params.enableStructuredMemoryRecall??false;this.enableAutoSkill=params.enableAutoSkill??false;this.autoSkillConfirm=params.autoSkillConfirm??true;this.memoryAgentTimeoutMinutes=params.memoryAgentTimeoutMinutes!==void 0&¶ms.memoryAgentTimeoutMinutes>=0?params.memoryAgentTimeoutMinutes:void 0;this.memoryAgentMaxTurns=params.memoryAgentMaxTurns!==void 0&&Number.isInteger(params.memoryAgentMaxTurns)&¶ms.memoryAgentMaxTurns>=0?params.memoryAgentMaxTurns:void 0;this.fastModel=params.fastModel||void 0;this.advisorModel=normalizeAdvisorModel(params.advisorModel);this.advisorMaxUses=isValidAdvisorMaxUses(params.advisorMaxUses)?params.advisorMaxUses:0;this.webSearchSettings=params.webSearch;this.visionModel=params.visionModel||void 0;this.compactionModel=params.compactionModel||void 0;this.imageModel=params.imageModel||void 0;this.visionBridgeTimeoutMs=params.visionBridgeTimeoutMs!==void 0&&Number.isInteger(params.visionBridgeTimeoutMs)&¶ms.visionBridgeTimeoutMs>0&¶ms.visionBridgeTimeoutMs<=2147483647?params.visionBridgeTimeoutMs:void 0;this.modelFallbacks=normalizeModelFallbacks(params.modelFallbacks);this.disableAllHooks=params.disableAllHooks??false;this.stopHookBlockingCap=resolveStopHookBlockingCap(params.stopHookBlockingCap);this.systemHooks=params.systemHooks;this.userHooks=params.userHooks;this.projectHooks=params.projectHooks;this.hooks=params.hooks;this.settingsWatcher=params.settingsWatcher;this.memoryManager=new MemoryManager}async initialize(options2){if(this.executionEnvironment){options2={...options2,skipHooks:true,skipMcpDiscovery:true,skipSkillManager:true,skipFileCheckpointing:true}}if(this.sessionExecutionEngine==="managed"){options2={...options2,skipMcpDiscovery:true}}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot be initialized")}if(this.initialized){if(!this.initializationSettled){options2?.signal?.throwIfAborted();this.debugLogger.debug("Config.initialize() called while initialization is in flight; joining the existing run");await this.initializationPromise;return}throw Error("Config was already initialized")}if(this.shutdownRequested){throw Error("Config is shutting down")}options2?.signal?.throwIfAborted();this.initialized=true;const initialization=this.initializeOnce(options2);this.initializationPromise=initialization;try{await initialization;this.initializationSucceeded=true}finally{this.initializationSettled=true}}async activateProvisionalWorkspace(){if(!this.provisionalWorkspace||this.provisionalWorkspaceActivated){return}if(this.provisionalWorkspaceActivation){return this.provisionalWorkspaceActivation}const activation=(async()=>{this.getFileService();await this.llmClient.initialize();await this.toolRegistry.warmAll({strict:true});await this.initializeOmniPolicies();logStartSession(this,new StartSessionEvent(this));this.provisionalWorkspaceActivated=true})();this.provisionalWorkspaceActivation=activation;return activation}async initializeOmniPolicies(){if(this.isOmniEnabled()){const{normalizeOmniProcessingConfig}=await import("./config-3AMQTA2S.js");this.omniProcessingConfig=normalizeOmniProcessingConfig({fixedPolicies:this.omniFixedPolicies,transportGuardPolicies:this.omniTransportGuardPolicies,limits:this.omniProcessingLimits,policyTools:this.omniPolicyTools,maxUploadFileBytes:this.omniMaxUploadFileBytes,maxEstimatedTokens:this.omniMaxEstimatedTokens,urlTtlHours:this.omniUploadUrlTtlHours},this.toolRegistry);await this.ensureOmniMemoryConfig()}}isProvisionalWorkspace(){return this.provisionalWorkspace}async initializeOnce(options2){try{if(this.shellExecutionSandbox)this.shellExecutionSandbox=await probeShellSandbox(this.shellExecutionSandbox,options2?.signal);const activation=this.activateChatRecording();this.sessionWriterActivationPromise=activation;try{await activation}finally{if(this.sessionWriterActivationPromise===activation){this.sessionWriterActivationPromise=void 0}}options2?.signal?.throwIfAborted();await this.bindSessionExecutionEngine();registerSessionProjectDir(this.sessionId,this.storage.getProjectDir());this.sessionProjectDirRegistered=true;await this.initializeInternal(options2)}catch(error3){this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}try{await this.closeSessionWriter()}catch(closeError){if(options2?.signal?.aborted&&containsErrorByIdentity(error3,options2.signal.reason)){this.debugLogger.warn("Chat recording close failed after initialization was aborted:",closeError);options2.signal.throwIfAborted()}if(containsErrorByIdentity(error3,closeError)){throw error3}throw new SessionWriterUnavailableError({cause:new AggregateError([error3,closeError],"Chat recording close failed during failed initialization")})}throw error3}}async bindSessionExecutionEngine(){const engine=this.sessionExecutionEngine;if(engine===void 0)return;if(this.sessionRestoreProjectionSource||this.sessionData){assertSessionExecutionEngine(this.pendingSessionRestoreProjection?.executionEngine,this.sessionId,engine);return}if(this.managedSession)return;await this.chatRecordingService?.recordExecutionEngine(engine)}async initializeInternal(options2){this.debugLogger.info("Config initialization started");await this.proxyDispatcherReady;void refreshModelCatalog();options2?.signal?.throwIfAborted();if(this.isOmniEnabled()){const{normalizeDedicatedOmniUploadConfig}=await import("./upload-config-ET7NRHU7.js");this.omniUploadConfig=normalizeDedicatedOmniUploadConfig({baseUrl:this.omniUploadBaseUrl,apiKeyEnv:this.omniUploadApiKeyEnv,model:this.omniUploadModel});const{assertOmniRuntimeDependencies}=await import("./ffmpeg-3AJSGZKK.js");await assertOmniRuntimeDependencies()}if(options2?.skipFileCheckpointing===true||this.shellExecutionSandbox){this.fileCheckpointingEnabled=false;this.fileHistoryService=void 0}if(!this.provisionalWorkspace){this.getFileService()}this.promptRegistry=new PromptRegistry;this.resourceRegistry=new ResourceRegistry;this.extensionManager.setConfig(this);const explicitExtensionNames=this.isSafeMode()?[]:(this.overrideExtensions??[]).filter(n=>n.trim()!==""&&n.toLowerCase()!=="none");recordStartupEvent("config_initialize_extensions_initial_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&!this.getBareMode()){await this.extensionManager.refreshCache()}else if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&explicitExtensionNames.length>0){await this.extensionManager.refreshCache({names:explicitExtensionNames})}recordStartupEvent("config_initialize_extensions_initial_end");options2?.signal?.throwIfAborted();this.debugLogger.debug("Extension manager initialized");recordStartupEvent("config_initialize_hooks_start");if(!this.shellExecutionSandbox&&(options2?.managedHookDispatcher||!options2?.skipHooks&&!this.getDisableAllHooks())){this.hookSystem=new HookSystem(this,options2?.managedHookDispatcher);await this.hookSystem.initialize();this.debugLogger.debug("Hook system initialized");this.messageBus=new MessageBus;this.messageBus.subscribe("hook-execution-request",async request=>{try{const hookSystem=this.hookSystem;if(!hookSystem){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook system not initialized")});return}if(request.signal?.aborted){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook execution cancelled (aborted)")});return}assertHookExecutionOwner(request.owner,hookSystem.runtimeId,this.getSessionId());await runWithHookExecutionOwner(request.owner,async()=>{let result;let stopHookCount;const input=request.input||{};const signal=request.signal;switch(request.eventName){case"UserPromptSubmit":result=await hookSystem.fireUserPromptSubmitEvent(input["prompt"]||"",signal,typeof input["submitted_prompt"]==="string"&&input["submitted_prompt"].trim().length>0?input["submitted_prompt"]:void 0);break;case"UserPromptExpansion":result=await hookSystem.fireUserPromptExpansionEvent(input["command_name"]||"",input["command_args"]||"",input["prompt"]||"",signal);break;case"Stop":{const contextUsageData=buildContextUsage(input["context_limit"],input["input_tokens"]??0);const stopResult=await hookSystem.fireStopEvent(input["stop_hook_active"]||false,input["last_assistant_message"]||"",contextUsageData,signal);result=stopResult.finalOutput?createHookOutput("Stop",stopResult.finalOutput):void 0;stopHookCount=stopResult.allOutputs.length;break}case"MessageDisplay":{const messageDisplayResult=await hookSystem.fireMessageDisplayEvent(input["message_id"]||"",input["displayed_text"]||"",input["is_final"]||false,signal);result=messageDisplayResult.finalOutput?createHookOutput("MessageDisplay",messageDisplayResult.finalOutput):void 0;break}case"PreToolUse":{result=await hookSystem.firePreToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["permission_mode"]??"default",signal,input["tool_call_id"]||void 0);break}case"PostToolUse":result=await hookSystem.firePostToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_response"]||{},input["tool_use_id"]||"",input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolUseFailure":result=await hookSystem.firePostToolUseFailureEvent(input["tool_use_id"]||"",input["tool_name"]||"",input["tool_input"]||{},input["error"]||"",input["is_interrupt"],input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolBatch":result=await hookSystem.firePostToolBatchEvent(input["tool_calls"]||[],input["permission_mode"]||"default",signal);break;case"Notification":result=await hookSystem.fireNotificationEvent(input["message"]||"",input["notification_type"]||"permission_prompt",input["title"]||void 0,signal);break;case"PermissionRequest":result=await hookSystem.firePermissionRequestEvent(input["tool_name"]||"",input["tool_input"]||{},input["permission_mode"]||"default",input["permission_suggestions"]||void 0,signal);break;case"PermissionDenied":result=await hookSystem.firePermissionDeniedEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["reason"]||"classifier_blocked",signal,input["tool_call_id"]||void 0);break;case"SubagentStart":result=await hookSystem.fireSubagentStartEvent(input["agent_id"]||"",input["agent_type"]||"",input["permission_mode"]||"default",signal);break;case"SubagentStop":result=await hookSystem.fireSubagentStopEvent(input["agent_id"]||"",input["agent_type"]||"",input["agent_transcript_path"]||"",input["last_assistant_message"]||"",input["stop_hook_active"]||false,input["permission_mode"]||"default",signal);break;case"SessionStart":result=await hookSystem.fireSessionStartEvent(input["source"],input["model"]||"",input["permission_mode"]||void 0,input["agent_type"],signal);break;case"SessionEnd":result=await hookSystem.fireSessionEndEvent(input["reason"],signal);break;case"SessionDelete":result=await hookSystem.fireSessionDeleteEvent(input["deleted_session_id"]||"",signal);break;case"PreCompact":result=await hookSystem.firePreCompactEvent(input["trigger"],input["custom_instructions"]||"",signal);break;case"PostCompact":result=await hookSystem.firePostCompactEvent(input["trigger"],input["compact_summary"]||"",signal);break;case"InstructionsLoaded":result=await hookSystem.fireInstructionsLoadedEvent(input["file_path"]||"",input["memory_type"],input["load_reason"],{triggerFilePath:input["trigger_file_path"],parentFilePath:input["parent_file_path"]},signal);break;case"StopFailure":result=(await hookSystem.fireStopFailureEvent(input["error"],input["error_details"],input["last_assistant_message"],signal)).finalOutput;break;case"TodoCreated":result=(await hookSystem.fireTodoCreatedEvent(input["todo_id"]||"",input["todo_content"]||"",input["todo_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;case"TodoCompleted":result=(await hookSystem.fireTodoCompletedEvent(input["todo_id"]||"",input["todo_content"]||"",input["previous_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;default:this.debugLogger.warn(`Unknown hook event: ${request.eventName}`);result=void 0}this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:true,output:result,stopHookCount})})}catch(error3){this.debugLogger.warn(`Hook execution failed: ${error3}`);this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:error3 instanceof Error?error3:new Error(String(error3))})}});this.announceMessageBus(this.messageBus);this.debugLogger.debug("MessageBus initialized with hook subscription")}else{this.debugLogger.debug("Hook system disabled, skipping initialization")}recordStartupEvent("config_initialize_hooks_end");options2?.signal?.throwIfAborted();this.subagentManager=new SubagentManager(this);recordStartupEvent("config_initialize_skills_start");if(!options2?.skipSkillManager){if(!this.provisionalWorkspace&&this.getAutoSkillEnabled()&&this.isTrustedFolder()){try{const curatorResult=await maybeRunAutoSkillCurator(this.getProjectRoot());if(curatorResult.status==="ran"){this.debugLogger.debug(`Auto-skill curator checked ${curatorResult.result.checked} skill(s) and archived ${curatorResult.result.archived.length}.`)}}catch(error3){this.debugLogger.warn(`Auto-skill curator skipped: ${error3 instanceof Error?error3.message:String(error3)}`)}}this.skillManager=new SkillManager(this);if(this.shellExecutionSandbox||this.getBareMode()||this.isSafeMode()){await this.skillManager.refreshCache()}else{await this.skillManager.startWatching()}this.debugLogger.debug("Skill manager initialized");if(this.skillSettingsListsProvider){try{const lists=this.skillSettingsListsProvider();const skills=await this.skillManager.listSkills();const extensionIdByName=new Map(this.getExtensions().map(extension=>[extension.name,extension.id]));const defaultOffNames=new Set;for(const skill of skills){const extensionId=skill.extensionName?extensionIdByName.get(skill.extensionName):void 0;if(skill.level!=="extension"||!extensionId)continue;const state=this.extensionManager.getExtensionSkillState(extensionId,authoredSkillName(skill));if(state.defaultEnabled===false&&!state.workspaceEnabled){defaultOffNames.add(skill.name.trim().toLowerCase())}}this.warnings.push(...bareEnabledGrantWarnings(lists,skills,defaultOffNames),...bareDisablementBlocksQualifiedGrantWarnings(lists,this.getDisabledSkillNames(),skills))}catch(error3){this.debugLogger.warn(`Skill settings migration warning skipped: ${getErrorMessage(error3)}`)}}}else{this.skillManager=null;this.debugLogger.debug("Skill manager skipped")}recordStartupEvent("config_initialize_skills_end");options2?.signal?.throwIfAborted();this.memoryPressureConfig=loadMemoryPressureConfig();this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig);this.permissionManager=new PermissionManager(this);this.permissionManager.initialize();this.debugLogger.debug("Permission manager initialized");if(this.sessionSubagents.length>0){this.subagentManager.loadSessionSubagents(this.sessionSubagents)}recordStartupEvent("config_initialize_extensions_final_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.isSafeMode()){await this.extensionManager.refreshCache()}recordStartupEvent("config_initialize_extensions_final_end");options2?.signal?.throwIfAborted();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_hierarchical_memory_start");await this.refreshHierarchicalMemory("session_start",options2?.signal);recordStartupEvent("config_initialize_hierarchical_memory_end");this.debugLogger.debug("Hierarchical memory loaded")}options2?.signal?.throwIfAborted();const legacyBlockingMcp=process8.env["QWEN_CODE_LEGACY_MCP_BLOCKING"]==="1";const skipInlineMcpDiscovery=this.getBareMode()||this.isSafeMode()||this.provisionalWorkspace||!legacyBlockingMcp||options2?.skipMcpDiscovery===true;recordStartupEvent("config_initialize_tool_registry_start");this.toolRegistry=await this.createToolRegistry(options2?.sendSdkMcpMessage,skipInlineMcpDiscovery?{skipDiscovery:true}:void 0);options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_registry_end");recordStartupEvent("tool_registry_created",{toolCount:this.toolRegistry.getAllToolNames().length,mcpInline:!skipInlineMcpDiscovery});this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`);if(!(options2?.skipLlmInitialization??options2?.skipGeminiInitialization)&&!this.provisionalWorkspace){await this.llmClient.initialize(void 0,options2?.signal);this.debugLogger.info("LLM client initialized")}else{this.debugLogger.info("LLM client initialization skipped")}this.modelsConfig.detectAndCaptureRuntimeModel();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_tool_warmup_start");await this.toolRegistry.warmAll({strict:options2?.lenientToolWarmup!==true});options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_warmup_end")}if(!this.provisionalWorkspace){await this.initializeOmniPolicies();options2?.signal?.throwIfAborted()}const hasMcpServers=Object.keys(this.getMcpServers()??{}).length>0;if(!this.shellExecutionSandbox&&skipInlineMcpDiscovery&&(!(this.getBareMode()||this.isSafeMode())||hasMcpServers)&&!this.provisionalWorkspace&&!options2?.skipMcpDiscovery){this.startMcpDiscoveryInBackground()}if(!this.provisionalWorkspace){options2?.signal?.throwIfAborted();logStartSession(this,new StartSessionEvent(this))}this.debugLogger.info("Config initialization completed");if(!this.shellExecutionSandbox&&!this.getBareMode()&&this.sessionSourceType!=="agent-host"&&!this.provisionalWorkspace){void(async()=>{try{const root=findGitRoot(this.targetDir)??this.targetDir;const worktreesDir=path81.join(root,".qwen","worktrees");try{await fsPromises4.access(worktreesDir)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${worktreesDir} does not exist`);return}const removed=await cleanupStaleAgentWorktrees(root);if(removed>0){this.debugLogger.info(`Stale worktree sweep removed ${removed} ephemeral worktree(s) under ${root}`)}else{this.debugLogger.debug(`Stale worktree sweep ran under ${root}: nothing to remove`)}}catch(error3){this.debugLogger.warn(`Stale worktree sweep failed (non-fatal): ${error3}`)}})()}}async openManagedSessionLog(lease){const transcriptPath=this.getTranscriptPath();const sessionKey=localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId);const resources=LocalManagedSessionResourceStore.create({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionKey});const create=isManagedSessionTranscriptSync(transcriptPath)?void 0:await this.publishManagedSessionRoot(resources);const open6=__name(()=>openManagedSession({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath,sessionKey,cwd:this.getProjectRoot(),version:this.getCliVersion()||"unknown",workerId:this.sessionId,activationLeaseDurationMs:MANAGED_ACTIVATION_LEASE_MS,lease,resourceStore:resources,...create===void 0?{}:{create}}),"open");try{return await open6()}catch(error3){if(!(error3 instanceof ManagedSessionUncommittedTailError))throw error3;await LocalManagedSessionAuthority.recoverUncommittedTail({lease,sessionKey});return await open6()}}isLegacyTranscript(){const transcriptPath=this.getTranscriptPath();try{if(fs76.statSync(transcriptPath).size===0)return false}catch{return false}return readManagedExecutionEvidenceSync(transcriptPath)===false}async finishManagedWriter(lease,opened){if(opened){try{await stopAdvancing(opened)}catch{}await lease.sealForHandoff(managedCommitProof(opened));return}const takenOver=lease.takeoverCommitProof;if(takenOver!==void 0){await lease.sealForHandoff(takenOver);return}const transcriptPath=this.getTranscriptPath();const evidence=readManagedExecutionEvidenceSync(transcriptPath);if(evidence===false){await lease.release();return}if(evidence===void 0)return;let scan;try{scan=await LocalJsonlManagedSessionJournalStore.read(transcriptPath,localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId))}catch{return}await lease.sealForHandoff({last_commit_sequence:scan.committed,committed_prefix_hash:scan.lastMarkerDigest??EMPTY_COMMIT_PREFIX_HASH})}async publishManagedSessionRoot(resources){const[definitionRef,rootSnapshotRef]=await Promise.all([resources.publish("managed-session-definition",Buffer.from(JSON.stringify({version:1,engine:"managed",model:this.getModel(),approvalMode:this.getApprovalMode()}),"utf8")),resources.publish("managed-session-root-snapshot",Buffer.from(JSON.stringify({version:1,messages:[]}),"utf8"))]);return{definitionRef,rootSnapshotRef,createdBy:`qwen-code/${this.getCliVersion()||"unknown"}`}}async activateChatRecording(){const managed=this.sessionExecutionEngine==="managed";if(managed&&(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled)){throw new SessionExecutionEngineError(this.sessionId,"managed execution requires chat recording and a writer lease")}if(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled){return}if(managed&&this.isLegacyTranscript()){throw new SessionExecutionEngineError(this.sessionId,"belongs to legacy, cannot execute with managed")}if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const recorder=this.chatRecordingService;if(!recorder)throw new SessionWriterUnavailableError;let lease;try{lease=await SessionWriterLease.acquire({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath:this.getTranscriptPath(),processKind:"acp",qwenVersion:this.cliVersion??null,reclaimPolicy:this.sessionWriterReclaimPolicy,takeoverPolicy:managed?"certified":this.sessionWriterTakeoverPolicy,...managed?{lockSchema:{schemaVersion:3,formatVersion:MANAGED_SESSION_FORMAT_VERSION}}:{},onOwnershipAcquired:__name(acquiredLease=>{lease=acquiredLease;this.pendingSessionWriterLease=acquiredLease;if(this.sessionWriterShutdownRequested){this.startPendingSessionWriterRelease(acquiredLease)}},"onOwnershipAcquired")});if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const location=await this.getSessionService().getSessionLocation(this.sessionId);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}if(location==="archived"){throw new SessionTranscriptChangedError}let authoritative;let projection;if(this.sessionRestoreProjectionSource){addDaemonRequestAttribute("qwen-code.daemon.session_restore.projection_acquisition","after_writer_lease");projection=await this.sessionRestoreProjectionSource();if(managed){assertSessionExecutionEngine(projection?.executionEngine,this.sessionId,"managed")}this.setSessionRestoreProjection(projection)}else if(managed&&(this.sessionData||lease.transcriptExistedAtAcquire)){throw new SessionExecutionEngineError(this.sessionId,"managed restore requires a restore projection")}else if(this.sessionData||lease.transcriptExistedAtAcquire){authoritative=await this.getSessionService().loadSession(this.sessionId);if(!authoritative)throw new SessionWriterUnavailableError}else if(location!==void 0){throw new SessionTranscriptChangedError}const persistedTitleInfo=authoritative?this.getSessionService().getSessionTitleInfo(this.sessionId):void 0;await lease.assertOwnedAndUnchanged();if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}this.sessionData=authoritative;if(managed){this.managedSession=await this.openManagedSessionLog(lease);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const sequenceBeforeRepair=this.managedSession.authority.committedSequence;await this.getManagedRuntimeOutcomes()?.recoverCommittedReceipts();if(this.sessionRestoreProjectionSource&&this.managedSession.authority.committedSequence!==sequenceBeforeRepair){projection=await this.sessionRestoreProjectionSource();this.setSessionRestoreProjection(projection)}const unresolved=await unresolvedRuntimeWorkReason(this.managedSession.authority);if(unresolved!==void 0){this.blockManagedSession(new ManagedRuntimeOutcomeUnknownError(`The Managed session's log shows Runtime work with an unknown outcome: ${unresolved}.`))}recorder.bindManagedSink(managedRecordWriter(this.managedSession,{transcriptPath:this.getTranscriptPath(),runtimeBaseDir:this.sessionRuntimeBaseDir}))}recorder.activate(lease,authoritative,persistedTitleInfo,projection?.runtime.recording);if(this.sessionRestoreProjectionSource){this.initializeGoalRuntime(projection?.runtime.goalRecords,projection?.runtime)}this.pendingSessionWriterLease=void 0;lease=void 0;this.startPendingGoalRestore()}catch(error3){let failure=error3;const ownedLease=lease??this.pendingSessionWriterLease;let releaseFailureAlreadyReported=false;const abandonedManagedSession=this.managedSession;this.managedSession=void 0;if(managed&&ownedLease){const finishing=this.finishManagedWriter(ownedLease,abandonedManagedSession);void finishing.catch(()=>void 0);this.pendingSessionWriterRelease={lease:ownedLease,promise:finishing}}if(!(failure instanceof SessionWriterError)&&!(failure instanceof ManagedSessionRecordError)&&failure&&typeof failure==="object"&&typeof failure.code==="string"){failure=new SessionWriterUnavailableError({cause:failure})}try{await this.startPendingSessionWriterRelease(ownedLease);if(this.pendingSessionWriterLease===ownedLease&&(ownedLease?.isReleased??true)&&!ownedLease?.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}if(this.sessionWriterShutdownRequested&&failure instanceof SessionWriterLostError&&ownedLease?.isReleased){failure=new SessionWriterShutdownError}}catch(releaseError){if(releaseError instanceof SessionWriterLostError||ownedLease?.isReleased&&!ownedLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}else{releaseFailureAlreadyReported=containsErrorByIdentity(failure,releaseError);if(!releaseFailureAlreadyReported){failure=new SessionWriterUnavailableError({cause:new AggregateError([failure,releaseError],"Session writer lease release failed during activation cleanup")})}}}finally{if(!releaseFailureAlreadyReported&&this.pendingSessionWriterRelease?.lease===ownedLease){this.pendingSessionWriterRelease=void 0}}this.settlePendingGoalRestore(failure);throw failure}}mcpDiscoveryPromise;startMcpDiscoveryInBackground(){const manager=this.toolRegistry.getMcpClientManager?.();if(!manager){this.debugLogger.debug("Skipping background MCP discovery: ToolRegistry has no MCP client manager");return}this.mcpDiscoveryPromise=manager.discoverAllMcpToolsIncremental(this).then(async()=>{try{await this.llmClient?.setTools()}catch(err){this.debugLogger.error(`setTools() after background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)}}).catch(err=>{this.debugLogger.error(`Background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)})}async waitForMcpReady(){if(this.mcpDiscoveryPromise){await this.mcpDiscoveryPromise}}getFailedMcpServerNames(){const servers=this.getMcpServers();if(!servers){return[]}const failed=[];for(const name of Object.keys(servers)){if(this.isMcpServerDisabled(name)){continue}if(this.isMcpServerPendingApproval(name)){continue}if(getMCPServerStatus(name)!=="connected"){failed.push(name)}}return failed}async refreshHierarchicalMemory(loadReason="refresh",signal){if(this.executionEnvironment)return;if(this.isSafeMode()){this.setUserMemory("");this.autoMemoryPrompt="";this.autoMemoryContext="";this.setMemoryFileCount(0);this.setContextFilePaths([]);this.conditionalRulesRegistry=new ConditionalRulesRegistry([],this.getWorkingDir());return}const{memoryContent,fileCount,contextFilePaths,conditionalRules,ignoredExtensionRules,projectRoot}=await loadServerHierarchicalMemory(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason,onInstructionsLoaded:createInstructionsLoadedCallback(()=>this.hookSystem,signal),extensionRuleSources:this.getExtensionRuleSources()});this.ignoredExtensionRules=ignoredExtensionRules??[];if(this.isManagedMemoryAvailable()){const teamMemoryEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();if(this.getTeamMemoryEnabled()&&!this.isTrustedFolder()){this.debugLogger.debug("Team memory enabled but inactive: workspace is not trusted.")}const teamProjectRoot=this.getProjectRoot();if(teamMemoryEnabled&&!this.teamMemoryShareabilityChecked.has(teamProjectRoot)){this.teamMemoryShareabilityChecked.add(teamProjectRoot);const shareabilityWarning=getTeamMemoryShareabilityWarning(teamProjectRoot);if(shareabilityWarning){this.warnings.push(shareabilityWarning);this.debugLogger.warn(shareabilityWarning)}}let teamAutoMemoryIndex=null;if(teamMemoryEnabled){let teamRootSecurityBlocked=false;try{teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot)}catch(err){if(err instanceof TeamMemoryRootSecurityError){teamRootSecurityBlocked=true;this.debugLogger.warn("team memory root failed the symlink/escape safety check; skipping sync",err)}else{this.debugLogger.warn("team memory index rebuild failed (operational); not security-gating sync",err)}}if(!teamRootSecurityBlocked&&this.getTeamMemorySyncEnabled()){const syncResult=await syncTeamMemory(teamProjectRoot,{message:"chore(memory): sync team memory"}).catch(err=>{this.debugLogger.warn("team memory sync failed",err);return void 0});if(syncResult?.skippedReason){this.debugLogger.warn(`team memory sync skipped: ${syncResult.skippedReason}`)}if(syncResult?.pulled){teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot).catch(()=>teamAutoMemoryIndex)}}}if(!this.memoryRecallModeInitialized){const corpusStatus=this.getStructuredMemoryRecallEnabled()?await this.scanMemoryRecallCorpusStatus().catch(error3=>{this.debugLogger.warn("memory metadata readiness scan failed; preserving the active recall protocol",error3);return void 0}):void 0;this.memoryRecallMode=corpusStatus?.ready?"structured":"legacy";this.memoryCorpusRevision=corpusStatus?.revision??"";this.memoryRecallModeInitialized=true}const[managedAutoMemoryIndexRead,userAutoMemoryIndexRead]=await Promise.all([readAutoMemoryIndexWithStats(this.getProjectRoot()),readUserAutoMemoryIndexWithStats().catch(()=>null)]);this.recordAutoMemoryIndexRead(getAutoMemoryIndexPath(this.getProjectRoot()),managedAutoMemoryIndexRead);this.recordAutoMemoryIndexRead(getUserAutoMemoryIndexPath(),userAutoMemoryIndexRead);const managedAutoMemoryIndex=managedAutoMemoryIndexRead?.content??null;const userAutoMemoryIndex=userAutoMemoryIndexRead?.content??null;this.setUserMemory(memoryContent);const memoryDir=getAutoMemoryRoot(this.getProjectRoot());const userSection={memoryDir:getUserAutoMemoryRoot(),indexContent:userAutoMemoryIndex};const teamSection=teamMemoryEnabled?{memoryDir:getTeamAutoMemoryRoot(this.getProjectRoot()),indexContent:teamAutoMemoryIndex}:void 0;if(this.memoryRecallMode==="structured"){this.autoMemoryPrompt=buildStructuredAutoMemoryPrompt(memoryDir,userSection.memoryDir,teamSection?.memoryDir)}else{const policy=this.memoryManager.buildAutoMemoryPrompt(memoryDir,managedAutoMemoryIndex,userSection,teamSection,{includeIndexes:false});const catalog=buildAutoMemoryIndexContext(memoryDir,managedAutoMemoryIndex,userSection,teamSection);this.autoMemoryPrompt=policy;this.autoMemoryContext=catalog}}else{this.setUserMemory(memoryContent);this.autoMemoryPrompt="";this.autoMemoryContext=""}this.setMemoryFileCount(fileCount);this.setContextFilePaths(contextFilePaths);this.conditionalRulesRegistry=new ConditionalRulesRegistry(conditionalRules,projectRoot)}recordAutoMemoryIndexRead(indexPath,indexRead){if(indexRead===null||this.getFileReadCacheDisabled()){return}this.getFileReadCache().recordRead(indexPath,indexRead.stats,{full:true,cacheable:true})}buildMemoryContextWarning(memoryContent){const contextWindowSize=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??tokenLimit(this.getModel(),"input");if(!contextWindowSize||contextWindowSize<=0||!memoryContent){return void 0}const estimatedTokens=Math.ceil(memoryContent.length/CHARS_PER_TOKEN);const ratioTokens=Math.floor(contextWindowSize*MEMORY_CONTEXT_WARNING_RATIO);const thresholdTokens=Math.min(ratioTokens,MEMORY_CONTEXT_WARNING_MAX_TOKENS);if(estimatedTokens<=thresholdTokens){return void 0}const windowClause=`${Math.round(MEMORY_CONTEXT_WARNING_RATIO*100)}% of this model's ${contextWindowSize.toLocaleString()} token context window`;const bound=thresholdTokens===ratioTokens?windowClause:`${MEMORY_CONTEXT_WARNING_MAX_TOKENS.toLocaleString()} tokens \u2014 the smaller of that and ${windowClause}`;return`Warning: Loaded always-on context (QWEN.md context files + auto-memory) uses about ${estimatedTokens.toLocaleString()} tokens, more than ${bound}. Consider trimming long always-loaded context or moving details into on-demand files.`}getMemoryDiscoveryDirectories(){if(!this.shouldLoadMemoryFromIncludeDirectories()){return[]}if(this.getBareMode()){return this.explicitIncludeDirectories}return[...this.getWorkspaceContext().getDirectories()]}getConditionalRulesRegistry(){return this.conditionalRulesRegistry}setConditionalRulesRegistry(registry3){this.conditionalRulesRegistry=registry3}getContextRuleExcludes(){return this.contextRuleExcludes}getContentGenerator(){return getRuntimeContentGenerator()?.contentGenerator??this.contentGenerator}getModelsConfig(){return this.modelsConfig}updateCredentials(credentials,settingsGenerationConfig){this.modelsConfig.updateCredentials(credentials,settingsGenerationConfig)}reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig){this.modelsConfig.reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig);this.captureLatestReasoning();this.baseLlmClient?.clearPerModelGeneratorCache()}getReasoningSnapshot(){return this.reasoningSnapshot??=captureReasoningSnapshot(this.getAllConfiguredModels())}stageReasoningOverrides(providers,protocols={}){const previous=this.latestReasoningSnapshot??this.getReasoningSnapshot();const models=this.getAllConfiguredModels().map(model=>{const prior=previous.find(row=>row.id===model.id&&row.authType===model.authType&&row.registryBaseUrl===model.registryBaseUrl);const configured=Object.entries(providers??{}).flatMap(([provider,entries])=>model.authType!=="qwen-oauth"&&resolveProviderProtocol(provider,protocols)===model.authType&&Array.isArray(entries)?entries:[]).find(entry=>entry?.id===model.id&&entry.baseUrl===model.registryBaseUrl);return{...model,capabilities:{...model.capabilities,reasoning:configured?configured.capabilities?.reasoning:prior?prior.reasoning:model.capabilities?.reasoning}}});return this.captureLatestReasoning(models)}captureLatestReasoning(models=this.getAllConfiguredModels()){try{const next=captureReasoningSnapshot(models);for(const row of next){if(row.authType!=="qwen-oauth"||row.reasoning?.profile){validateReasoningCapabilities({model:row.id,authType:row.authType,baseUrl:row.baseUrl},row.reasoning)}}const generation=this.getContentGeneratorConfig();if(generation)resolveReasoningForModel(this,{...generation,reasoningSnapshot:next},generation.model,true);this.latestReasoningSnapshot=next;return void 0}catch(error3){const message=`Reasoning settings not applied; keeping the previous configuration. ${getErrorMessage(error3)}`;console.warn(message);return message}}applyReasoningOverrides(){if(!this.latestReasoningSnapshot)this.captureLatestReasoning();const next=this.latestReasoningSnapshot;if(!next||JSON.stringify(next)===JSON.stringify(this.reasoningSnapshot))return false;this.reasoningSnapshot=next;const generation=this.getContentGeneratorConfig();if(generation)generation.reasoningSnapshot=next;this.baseLlmClient?.clearPerModelGeneratorCache();this.notifyModelChangeListeners();return true}getModelProvidersConfig(){return this.modelsConfig.getModelProvidersConfig()}getProviderProtocolConfig(){return this.modelsConfig.getProviderProtocolConfig()}syncModelSelection(authType,modelId,baseUrl){this.modelsConfig.syncAfterAuthRefresh(authType,modelId,baseUrl);this.initialResolvedAuthType=void 0}async refreshAuth(authMethod,isInitialAuth){const hookOwner=captureHookExecutionOwner(this,null);if(!this.contentGenerator&&authMethod===this.initialAuthType){authMethod=this.initialResolvedAuthType??authMethod}const priorGeneration={...this.modelsConfig.getGenerationConfig(),authType:this.modelsConfig.getCurrentAuthType()};const priorReasoning=priorGeneration.reasoning;const priorReasoningSource=this.modelsConfig.getGenerationConfigSources()["reasoning"];const priorReasoningEffort=priorReasoning?priorReasoning.effort:void 0;const modelId=this.modelsConfig.getModel();this.modelsConfig.syncAfterAuthRefresh(authMethod,modelId);const requireCached=this.modelsConfig.consumeRequireCachedCredentialsFlag();const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authMethod,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});const newContentGeneratorConfig=config3;const requestModel=getRequestModel(newContentGeneratorConfig);const deepSeekRoute=getBuiltinDeepSeekReasoning({...priorGeneration,model:getRequestModel(priorGeneration)})||getBuiltinDeepSeekReasoning({...newContentGeneratorConfig,model:requestModel});const explicitOff=priorReasoningSource?.kind==="settings"&&priorReasoningSource.settingsPath==="model.reasoningEffort"||priorReasoningSource?.kind==="programmatic"&&priorReasoningSource.detail==="reasoning selection";const preserveReasoningOff=priorReasoning===false&&(requestModel!==newContentGeneratorConfig.model||newContentGeneratorConfig.thinkingMandatory!==true)&&(!deepSeekRoute||explicitOff&&priorGeneration.authType===newContentGeneratorConfig.authType&&priorGeneration.model===newContentGeneratorConfig.model&&priorGeneration.baseUrl===newContentGeneratorConfig.baseUrl&&resolveReasoningForModel(this,newContentGeneratorConfig)?.canDisable!==false);if(preserveReasoningOff){newContentGeneratorConfig.reasoning=false;if(deepSeekRoute&&priorReasoningSource)sources["reasoning"]=priorReasoningSource}this.contentGenerator=await createContentGenerator(newContentGeneratorConfig,this,requireCached?true:isInitialAuth);this.contentGeneratorConfig=newContentGeneratorConfig;this.contentGeneratorConfigSources=sources;this.publishModelEnv();if(priorReasoning===false&&newContentGeneratorConfig.reasoning===false){this.modelsConfig.getGenerationConfig().reasoning=false;if(preserveReasoningOff&&deepSeekRoute&&priorReasoningSource){this.modelsConfig.getGenerationConfigSources()["reasoning"]=priorReasoningSource}}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}this.baseLlmClient=new BaseLlmClient(this.contentGenerator,this);const messageBus=this.getMessageBus();const hooksEnabled=!this.getDisableAllHooks();if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Successfully authenticated with ${authMethod}`,"auth_success","Authentication successful",void 0,hookOwner).catch(()=>{})}}getBaseLlmClient(){if(!this.baseLlmClient){if(this.contentGenerator){this.baseLlmClient=new BaseLlmClient(this.getContentGenerator(),this)}else{throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.")}}return this.baseLlmClient}getSessionId(){return this.sessionId}getSessionExecutionEngine(){return this.sessionExecutionEngine}getManagedRuntimeEnvironment(){if(isDerivedConfig(this))return void 0;if(!this.managedRuntimeEnvironment&&!this.shutdownRequested&&!this.managedRuntimeClosing){this.managedRuntimeEnvironment=this.managedRuntimeEnvironmentFactory?.(this)}return this.managedRuntimeEnvironment}closeManagedRuntime(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).closeManagedRuntime()}if(!this.managedRuntimeClosing){const environment=this.managedRuntimeEnvironment;this.managedRuntimeEnvironment=void 0;this.managedRuntimeClosing=Promise.resolve(environment?.dispose())}return this.managedRuntimeClosing}blockManagedSession(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).blockManagedSession(reason);return}this.managedSessionBlock??=reason}getManagedSessionBlock(){return this.managedSessionBlock}reportManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).reportManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(true,reason)}clearManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).clearManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(false,reason)}getManagedRuntimeOutcomes(){if(isDerivedConfig(this)||!this.managedSession)return void 0;return this.managedRuntimeOutcomes??=new LocalManagedRuntimeOutcomes(this.managedSession)}getSessionRestoreRuntime(){return this.sessionRestoreRuntime}consumeSessionRestoreProjection(){const projection=this.pendingSessionRestoreProjection;this.pendingSessionRestoreProjection=void 0;return projection}hydrateSessionRestoreFileHistory(){if(this.restoredFileHistory)return;const snapshots=this.sessionRestoreRuntime?.fileHistorySnapshots;if(!snapshots?.length)return;const service=this.getFileHistoryService();if(!service.isEnabled())return;service.restoreFromSnapshots(snapshots);this.restoredFileHistory=true}finalizeSessionRestore(){const runtime=this.sessionRestoreRuntime;if(!runtime)return;this.sessionRestoreRuntime=void 0;if(runtime.attributionSnapshot){try{CommitAttributionService.getInstance().restoreFromSnapshot(runtime.attributionSnapshot)}catch(error3){this.debugLogger.error(`Session restore attribution activation failed: ${error3}`)}}const activateGoal=this.goalRestoreActivation;this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;if(activateGoal){try{void activateGoal().catch(error3=>{this.debugLogger.error(`Session restore goal activation failed: ${error3}`)})}catch(error3){this.debugLogger.error(`Session restore goal activation failed: ${error3}`)}}if(this.restoredFileHistory&&this.fileHistoryService){try{void this.fileHistoryService.validateRestoredSnapshots().catch(error3=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)})}catch(error3){this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)}}}applyWorkspaceAgentPersona(systemPrompt,agentName,executionAllowedTools,disallowedTools){if(this.sessionSourceType!=="agent"){throw new Error("A workspace-agent persona may only be applied to an agent session.")}if(this.systemPrompt!==void 0){throw new Error("This session already has a persona; it cannot be changed in place.")}this.systemPrompt=systemPrompt;this.workspaceAgentName=agentName;this.workspaceAgentExecutionAllowedTools=executionAllowedTools?new Set(executionAllowedTools):void 0;this.workspaceAgentDisallowedTools=disallowedTools?[...disallowedTools]:void 0}getWorkspaceAgentName(){return this.workspaceAgentName}markSessionAgentSession(){if(this.sessionSourceType!=="agent"){throw new Error("Only an agent session can be marked as a session-agents session.")}this.sessionAgentSession=true;this.approvalMode="default";this.prePlanMode=void 0;this.planExecutionMode=void 0}isSessionAgentSession(){return this.sessionAgentSession&&this.sessionSourceType==="agent"}setSessionSource(sourceType,sourceId){this.sessionSourceType=sourceType;this.sessionSourceId=sourceId}getSessionSourceType(){return this.sessionSourceType}getSessionSourceId(){return this.sessionSourceId}getWarnings(){const memoryContextWarning=this.buildMemoryContextWarning([this.getUserMemory(),this.getAutoMemoryPrompt(),this.getAutoMemoryContext()].filter(Boolean).join("\n\n"));const ruleWarnings=this.ignoredExtensionRules.map(displayPath=>`Extension rule ${displayPath} has no \`paths:\` and was skipped. An extension's rules must be conditional: a baseline one would be sent with every request, which is the cost a rule exists to avoid. Add \`paths:\` to it, or move the content into the extension's context file.`);const extra=memoryContextWarning?[...ruleWarnings,memoryContextWarning]:ruleWarnings;return extra.length>0?[...this.warnings,...extra]:this.warnings}getDebugLogger(){return this.debugLogger}startNewSession(sessionId,sessionData){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot start new sessions")}if(this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}if(Object.hasOwn(this,"goalRuntime")){this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalRuntime?.dispose()}const outgoingChatRecordingService=this.chatRecordingService;try{outgoingChatRecordingService?.finalize()}catch{}void outgoingChatRecordingService?.flush().catch(()=>{});const previousSessionId=this.sessionId;const nextSessionId=sessionId??randomUUID23();const isSessionTransition=nextSessionId!==previousSessionId;if(isSessionTransition){logSessionEnd(this)}this.sessionId=nextSessionId;if(process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId}unregisterSessionModel(previousSessionId);this.publishModelEnv();this.sessionData=sessionData;if(isSessionTransition){const skillTool=this.toolRegistry?.getTool?.(ToolNames.SKILL);if(skillTool&&"clearLoadedSkills"in skillTool){skillTool.clearLoadedSkills()}this.toolRegistry?.clearReviewedDeclarations?.();this.permissionManager?.clearSessionAllowRules();this.webSearchSessionUsage.calls=0;this.advisorUsage.calls=0}this.clearSessionRestoreProjection();this.pendingRecoveredAgentsNotice=null;this.clearActiveTodoReminders();if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();outgoingChatRecordingService?.pinSessionIdentity(previousSessionId);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;this.sessionSourceService=this.sessionSourceServiceFactory?.();this.initializeGoalRuntime(this.sessionData?.conversation.messages);this.getFileReadCache().clear();this.toolResultBudget.bytesWritten=0;this.getMemoryPressureMonitor()?.resetForNewSession();this.fileHistoryService=void 0;refreshSessionContext(this.sessionId);CommitAttributionService.resetInstance();if(this.initialized){logStartSession(this,new StartSessionEvent(this),sessionData&&isSessionTransition?previousSessionId:void 0)}if(isSessionTransition){if(this.runtimeStatusEnabled){const oldPath=this.storage.getRuntimeStatusPath(previousSessionId);const newPath=this.storage.getRuntimeStatusPath(this.sessionId);const cliVersion=this.cliVersion??null;const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await clearRuntimeStatus(oldPath);await writeRuntimeStatus(newPath,{sessionId:newSessionId,workDir,qwenVersion:cliVersion})})}if(this.sessionRegistryActive){const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRetriedSessionRegistryPatch({sessionId:newSessionId,cwd:workDir},"session registry record still names the previous session id; peers addressing this session by its new id will be refused until it is re-asserted")}}return this.sessionId}async reassertSessionRegistryRecord(){if(!this.sessionRegistryActive)return;this.queueRetriedSessionRegistryPatch({sessionId:this.sessionId,cwd:this.targetDir},"session registry record could not be re-asserted; peers may keep addressing a stale session id");await this.sessionRegistryWrite}queueRetriedSessionRegistryPatch(patch,failureWarning){this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;let applied=await patchSessionRecord(patch,slot);for(let attempt=0;attempt<2&&!applied;attempt+=1){await delay(250);applied=await patchSessionRecord(patch,slot)}if(!applied){this.debugLogger.warn(failureWarning)}})}markRuntimeStatusEnabled(){this.runtimeStatusEnabled=true}trackSessionRegistration(registration){this.sessionRegistryActive=true;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{const outcome=await registration;this.sessionRegistrySlot=outcome.slot;this.sessionRegistered=outcome.registered;if(!this.sessionRegistered)this.sessionRegistryActive=false}).catch(()=>{this.sessionRegistered=false;this.sessionRegistryActive=false})}getSessionRegistrySlot(){return this.sessionRegistrySlot}async whenSessionRegistered(){await this.sessionRegistryWrite.catch(()=>{});return this.sessionRegistered}async updateSessionRegistryIpcPath(ipcPath,ipcToken){if(!this.sessionRegistryActive)return;let applied=false;this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;applied=await patchSessionRecord({ipcPath,ipcToken},slot);if(ipcPath===void 0||applied)return;for(let attempt=0;attempt<2&&!applied;attempt+=1){await delay(250);applied=await patchSessionRecord({ipcPath,ipcToken},slot)}if(!applied){this.debugLogger.warn("peer inbox address was not published to the session registry; peers cannot discover this session until it restarts")}});await this.sessionRegistryWrite}async unregisterSessionRegistry(){this.sessionRegistryActive=false;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{if(!this.sessionRegistered)return;this.sessionRegistered=false;await unregisterSession(this.sessionRegistrySlot)}).catch(()=>{});await this.sessionRegistryWrite}queueRuntimeStatusWrite(write){this.runtimeStatusWrite=this.runtimeStatusWrite.catch(()=>{}).then(write).catch(()=>{})}queueSessionRegistryWrite(write){this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(write).catch(()=>{})}async flushRuntimeStatusWrites(){await this.runtimeStatusWrite.catch(()=>{})}async refreshCurrentRuntimeStatus(workDir){const sessionId=this.sessionId;if(this.runtimeStatusEnabled){const sidecarPath=this.storage.getRuntimeStatusPath(sessionId);this.queueRuntimeStatusWrite(async()=>{await writeRuntimeStatus(sidecarPath,{sessionId,workDir,qwenVersion:this.cliVersion??null})})}if(this.sessionRegistryActive){this.queueSessionRegistryWrite(async()=>{await patchSessionRecord({cwd:workDir,name:deriveSessionName(workDir,sessionId)},this.sessionRegistrySlot)})}await this.flushRuntimeStatusWrites()}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return getRuntimeContentGenerator()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){if(Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig){return this.modelsConfig.getGenerationConfigSources()}return this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getCurrentModelRegistryBaseUrl(){return this.modelsConfig.getCurrentRegistryBaseUrl()}getCurrentAuthType(){return this.modelsConfig.getCurrentAuthType()}getEffectiveInputModalities(){return this.getContentGeneratorConfig()?.modalities??{}}getModelDisplayName(){return this.modelsConfig.getModelDisplayName(this.getModel())}onModelChange(listener){this.modelChangeListeners.add(listener);return()=>{this.modelChangeListeners.delete(listener)}}notifyModelChangeListeners(){this.publishModelEnv();const model=this.getModel();for(const listener of this.modelChangeListeners){listener(model)}}onApprovalModeChange(listener){this.approvalModeChangeListeners.add(listener);return()=>{this.approvalModeChangeListeners.delete(listener)}}notifyApprovalModeChangeListeners(){if(isDerivedConfig(this))return;for(const listener of this.approvalModeChangeListeners){listener(this.approvalMode,this.prePlanMode)}}publishModelEnv(){if(!process8.env){return}const model=this.getModel();registerSessionModel(this.sessionId,model,this.resolvedModelIdentity());if(this.ownsModelEnvSlot){process8.env["QWEN_CODE_MODEL"]=model;process8.env["QWEN_CODE_MODEL_IDENTITY"]=this.resolvedModelIdentity()}}resolvedModelIdentity(model=this.getModel(),generatorConfig=this.getContentGeneratorConfig()){const authType=generatorConfig?.authType??"";const baseUrl=generatorConfig?.baseUrl??(model===this.getModel()?this.getCurrentModelRegistryBaseUrl():void 0)??"";if(authType===""&&baseUrl==="")return model;const digest=createHash19("sha256").update(`${authType}\0${baseUrl}`).digest("hex").slice(0,8);return`${model}@${digest}`}getModelRouteIdentity(model,generatorConfig){return this.resolvedModelIdentity(model,generatorConfig)}getFastModel(){const selector=this.resolveFastModelSelector();if(!selector)return void 0;const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(model=>model.id===selector.modelId&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly)){return void 0}const rawSelector=resolveModelId(this.fastModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.fastModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}pinnedAuxEndpoint(persisted,modelId,available){const endpoint=persisted?.trim().split("\0")[1];if(!endpoint)return void 0;const hits=available.filter(model=>model.id===modelId&&model.baseUrl===endpoint);const matched=hits.find(model=>model.registryBaseUrl!==void 0)??hits[0];if(!matched){this.debugLogger.warn(`Aux endpoint pin dropped for "${modelId}": no configured entry at ${formatVisionModelSettingForLog(endpoint)}; falling back to the first same-id match.`);return void 0}return matched.registryBaseUrl}getWebSearchSettings(){return this.webSearchSettings}getWebSearchSessionUsage(){return this.webSearchSessionUsage}resolveFastModelSelector(){if(!this.fastModel)return void 0;try{const rawSelector=resolveModelId(this.fastModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare fast model resolution");return void 0}return resolveModelId(this.fastModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setFastModel(model){this.fastModel=model||void 0}getAdvisorMaxUses(){return this.advisorMaxUses}getAdvisorUseCount(){return this.advisorUsage.calls}tryConsumeAdvisorUse(){if(this.advisorMaxUses>0&&this.advisorUsage.calls>=this.advisorMaxUses)return false;this.advisorUsage.calls+=1;return true}getAdvisorModel(){return this.advisorModel}async setAdvisorModel(model){const normalizedModel=normalizeAdvisorModel(model);if(normalizedModel&&this.getDisabledTools().has(ToolNames.ADVISOR)){return false}this.advisorModel=normalizedModel;if(!this.initialized||!this.toolRegistry){return true}await this.syncAdvisorToolRegistration(this.toolRegistry);await this.llmClient?.setTools();return true}setVisionModel(model){this.visionModel=model||void 0}getCompactionModel(){const selector=this.resolveCompactionModelSelector();if(selector){const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(m2=>m2.id===selector.modelId&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!m2.visionOnly)){return void 0}const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.compactionModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}return this.getModel()}resolveCompactionModelSelector(){if(!this.compactionModel)return void 0;try{const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare compaction model resolution");return void 0}return resolveModelId(this.compactionModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setCompactionModel(model){this.compactionModel=model||void 0}async setImageModel(model){this.imageModel=model||void 0;if(!this.initialized||!this.toolRegistry){return}if(this.isImageGenerationEnabled()){await this.registerImageGenerationTool(this.toolRegistry);await this.toolRegistry.ensureTool(ToolNames.IMAGE_GEN)}await this.llmClient.setTools()}getModelFallbacks(){return this.modelFallbacks}getReasoningEffort(){const reasoning=this.getContentGeneratorConfig()?.reasoning;if(!reasoning){return void 0}return reasoning.effort}getReasoningEffortOverride(){const cfg=this.getContentGeneratorConfig();if(!cfg||!DashScopeOpenAICompatibleProvider.isDashScopeProvider(cfg)){return void 0}const configuredReasoning=resolveReasoningForModel(this,cfg);const model=getRequestModel(cfg);const tieredModel=isTieredEffortWireModel(model,configuredReasoning);if(!tieredModel)return void 0;const currentEffort=this.getReasoningEffort();const selected=selectDashScopeThinkingKnob(model,cfg.extra_body,cfg.samplingParams,currentEffort,tieredModel);if(!selected||selected.source==="reasoning"||selected.field==="reasoning_effort"&&selected.value===currentEffort){return void 0}if(selected.field==="enable_thinking"&&selected.value===true){if(selected.source!=="extra_body"){return void 0}const below=selectDashScopeThinkingKnob(model,void 0,cfg.samplingParams,currentEffort,tieredModel);if(below?.source==="samplingParams"&&below.field==="reasoning_effort"&&below.value!==currentEffort){return{source:below.source,field:below.field}}return void 0}return{source:selected.source,field:selected.field}}setReasoningEffort(effort){const applyEffort=__name(cfg=>{setGeneratorReasoningEffort(cfg,effort)},"applyEffort");applyEffort(this.contentGeneratorConfig);const runtimeCfg=getRuntimeContentGenerator()?.contentGeneratorConfig;if(runtimeCfg&&runtimeCfg!==this.contentGeneratorConfig){applyEffort(runtimeCfg)}applyEffort(this.modelsConfig?.getGenerationConfig())}isCurrentPrimaryModel(model){if(model.id!==this.getModel())return false;const cfg=this.getContentGeneratorConfig();const primaryAuthType=cfg?.authType;if(primaryAuthType===void 0)return true;if(model.authType!==primaryAuthType)return false;const primaryBaseUrl=cfg?.baseUrl;if(primaryBaseUrl!==void 0&&model.baseUrl!==void 0){return model.baseUrl===primaryBaseUrl}return true}resolveVisionModelSelection(){if(!this.visionModel)return void 0;const visionModelForLog=formatVisionModelSettingForLog(this.visionModel);const parsedSetting=parseVisionModelSetting(this.visionModel);if(!parsedSetting){this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}if(!selector){this.debugLogger.warn(`vision model pin '${visionModelForLog}' resolved to no selector; falling back to auto-select`);return void 0}const routeMatches=this.getAllConfiguredModels().filter(m2=>m2.id===selector.modelId&&(!selector.authType||m2.authType===selector.authType)&&(!parsedSetting.baseUrl||m2.baseUrl===parsedSetting.baseUrl)&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!this.isCurrentPrimaryModel(m2));if(routeMatches.length>1){this.debugLogger.warn(`vision model pin '${visionModelForLog}' matched multiple configured routes; falling back to auto-select`);return void 0}const match=routeMatches[0];if(!match){this.debugLogger.warn(`vision model pin '${visionModelForLog}' did not match a usable configured model (removed, mistyped, selector-only, or the primary itself); falling back to auto-select`);return void 0}const agentCapable=isFullTurnVisionCapable(match);return{id:getQualifiedVisionModelId(match),...(parsedSetting.baseUrl??match.baseUrl)&&{baseUrl:parsedSetting.baseUrl??match.baseUrl},...agentCapable&&{agentCapable:true}}}getDefaultVisionBridgeModel(){const explicit=this.resolveVisionModelSelection();if(explicit)return explicit;const contentGeneratorConfig=this.getContentGeneratorConfig();return selectVisionBridgeModel(this.getModel(),this.getAllConfiguredModels(),{authType:contentGeneratorConfig?.authType,baseUrl:contentGeneratorConfig?.baseUrl})}getVisionBridgeTimeoutMs(){return this.visionBridgeTimeoutMs}async setModel(newModel,metadata){await this.modelsConfig.setModel(newModel,metadata);if(this.contentGeneratorConfig){this.contentGeneratorConfig.model=newModel}this.notifyModelChangeListeners()}async handleModelChange(authType,requiresRefresh){this.initialResolvedAuthType=void 0;if(!this.contentGeneratorConfig){return}const priorReasoningEffort=this.getReasoningEffort();if(authType==="qwen-oauth"&&!requiresRefresh){const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authType,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});this.contentGeneratorConfig.reasoningRouteBaseUrl=config3.reasoningRouteBaseUrl;this.contentGeneratorConfig.model=config3.model;this.contentGeneratorConfig.samplingParams=config3.samplingParams;this.contentGeneratorConfig.contextWindowSize=config3.contextWindowSize;this.contentGeneratorConfig.enableCacheControl=config3.enableCacheControl;this.contentGeneratorConfig.enableRequestMetadata=config3.enableRequestMetadata;this.contentGeneratorConfig.forceGlobalCacheScope=config3.forceGlobalCacheScope;this.contentGeneratorConfig.cacheRetention=config3.cacheRetention;this.contentGeneratorConfig.cacheRetentionByBlock=config3.cacheRetentionByBlock;this.contentGeneratorConfig.splitToolMedia=config3.splitToolMedia;this.contentGeneratorConfig.toolResultContentFormat=config3.toolResultContentFormat;this.contentGeneratorConfig.modalities=config3.modalities;if("model"in sources){this.contentGeneratorConfigSources["model"]=sources["model"]}if("modalities"in sources){this.contentGeneratorConfigSources["modalities"]=sources["modalities"]}if("samplingParams"in sources){this.contentGeneratorConfigSources["samplingParams"]=sources["samplingParams"]}if("enableCacheControl"in sources){this.contentGeneratorConfigSources["enableCacheControl"]=sources["enableCacheControl"]}if("enableRequestMetadata"in sources){this.contentGeneratorConfigSources["enableRequestMetadata"]=sources["enableRequestMetadata"]}if("forceGlobalCacheScope"in sources){this.contentGeneratorConfigSources["forceGlobalCacheScope"]=sources["forceGlobalCacheScope"]}if("cacheRetention"in sources){this.contentGeneratorConfigSources["cacheRetention"]=sources["cacheRetention"]}if("cacheRetentionByBlock"in sources){this.contentGeneratorConfigSources["cacheRetentionByBlock"]=sources["cacheRetentionByBlock"]}if("contextWindowSize"in sources){this.contentGeneratorConfigSources["contextWindowSize"]=sources["contextWindowSize"]}if("splitToolMedia"in sources){this.contentGeneratorConfigSources["splitToolMedia"]=sources["splitToolMedia"]}if("toolResultContentFormat"in sources){this.contentGeneratorConfigSources["toolResultContentFormat"]=sources["toolResultContentFormat"]}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}resetPreloadedContentGenerator(this.contentGenerator);return}await this.refreshAuth(authType);if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}}getAvailableModels(){return this.modelsConfig.getAvailableModels()}getAvailableModelsForAuthType(authType){return this.modelsConfig.getAvailableModelsForAuthType(authType)}getAllConfiguredModels(authTypes){return this.modelsConfig.getAllConfiguredModels(authTypes)}getResolvedModelConfig(authType,modelId,baseUrl){return this.modelsConfig.getResolvedModel(authType,modelId,baseUrl)}getActiveRuntimeModelSnapshot(){return this.modelsConfig.getActiveRuntimeModelSnapshot()}async switchModel(authType,modelId,options2){await this.modelsConfig.switchModel(authType,modelId,options2);this.notifyModelChangeListeners()}getMaxSessionTurns(){return this.maxSessionTurns}getGoalTokenBudgetGrant(){return this.goalTokenBudgetGrant}getGoalTurnBudgetGrant(){return this.goalTurnBudgetGrant}getGoalActiveTimeBudgetGrantMs(){return this.goalActiveTimeBudgetGrantMs}getMaxSubagentDepth(){return this.maxSubagentDepth}getMaxWallTimeSeconds(){return this.maxWallTimeSeconds}getMaxToolCalls(){return this.maxToolCalls}getClearContextOnIdle(){return this.clearContextOnIdle}getSessionTokenLimit(){return this.sessionTokenLimit}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){const sandboxConfig=this.getSandbox();const seatbeltProfile=process8.env["SEATBELT_PROFILE"];return!!sandboxConfig&&sandboxConfig.command==="sandbox-exec"&&!!seatbeltProfile&&seatbeltProfile.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(oldStorage,newStorage){const oldChatsDir=path81.join(oldStorage.getProjectDir(),"chats");const newChatsDir=path81.join(newStorage.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`,`${this.sessionId}.pr.json`].map(fileName=>({from:path81.join(oldChatsDir,fileName),to:path81.join(newChatsDir,fileName)}))}moveFile(from,to2){try{fs76.renameSync(from,to2)}catch(error3){if(error3.code!=="EXDEV"){throw error3}let copied=false;try{fs76.copyFileSync(from,to2);copied=true;fs76.unlinkSync(from)}catch(fallbackError){if(copied){try{fs76.unlinkSync(to2)}catch{}}throw fallbackError}}}moveCurrentSessionArtifacts(oldStorage,newStorage){const moved=[];for(const{from,to:to2}of this.getCurrentSessionArtifactMoves(oldStorage,newStorage)){if(!fs76.existsSync(from)){continue}fs76.mkdirSync(path81.dirname(to2),{recursive:true});try{this.moveFile(from,to2);moved.push({from,to:to2})}catch(error3){for(const movedArtifact of moved.reverse()){try{fs76.mkdirSync(path81.dirname(movedArtifact.from),{recursive:true});this.moveFile(movedArtifact.to,movedArtifact.from)}catch(rollbackError){this.debugLogger.warn("Failed to roll back moved session artifact",rollbackError)}}throw error3}}}async prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch(error3){this.debugLogger.debug("Continuing session artifact migration after chat recording settle failed:",error3)}await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(oldStorage,newStorage)}catch(error3){if(!opts?.skipProcessChdir){try{process8.chdir(oldDir)}catch(rollbackError){this.debugLogger.warn("Failed to roll back working directory after session artifact migration failed",rollbackError)}}throw error3}}async relocateWorkingDirectory(newDir,expectedCanonicalDir,opts){if(this.shellExecutionSandbox){assertShellSandboxCwd(this.shellExecutionSandbox,path81.resolve(newDir))}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot relocate working directories")}if(this.sessionExecutionEngine==="managed"){throw new Error("A Managed session cannot change its directory.")}if(!opts?.skipArtifactMigration&&this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}const oldDir=opts?.skipProcessChdir?this.cwd:fs76.realpathSync(process8.cwd());const targetPath=path81.resolve(newDir);const expected=expectedCanonicalDir??fs76.realpathSync(targetPath);if(!fs76.statSync(targetPath).isDirectory()){throw new Error(`Path is not a directory: ${targetPath}`)}const workspaceDirectories=WorkspaceContext.resolveRootDirectories(expected,this.explicitIncludeDirectories);if(!opts?.skipProcessChdir){process8.chdir(targetPath);const actualCwd=fs76.realpathSync(process8.cwd());if(actualCwd!==expected){process8.chdir(oldDir);throw new Error(`Changed directory to ${actualCwd}, expected ${expected}.`)}}else{const actualCanonical=fs76.realpathSync(targetPath);if(actualCanonical!==expected){throw new Error(`Realpath mismatch: resolved ${actualCanonical}, expected ${expected}.`)}}const oldStorage=this.storage;if(!opts?.skipArtifactMigration){const newStorage=new Storage(expected,this.sessionRuntimeBaseDir);await this.prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts);this.storage=newStorage;this.chatRecordingService?.resetStoragePaths()}this.backgroundTaskRegistry.disposeResidentAgents();this.targetDir=expected;this.cwd=expected;resetPreloadedContentGenerator(this.contentGenerator);await this.refreshCurrentRuntimeStatus(expected);this.workspaceContext.applyRootDirectories(workspaceDirectories);this.fileDiscoveryService=null;const sessionPrBoundCallback=this.sessionService?.getSessionPrBoundCallback();this.sessionService=void 0;if(sessionPrBoundCallback){this.getSessionService().setSessionPrBoundCallback(sessionPrBoundCallback)}this.fileHistoryService=void 0;this.getFileReadCache().clear();this.memoryRecallMode="legacy";this.memoryCorpusRevision="";this.memoryRecallModeInitialized=false;this.autoMemoryPrompt="";this.autoMemoryContext="";let memoryRefreshError;try{await this.refreshHierarchicalMemory()}catch(error3){memoryRefreshError=error3}let mcpRefreshError;try{await this.waitForMcpReady();await this.refreshMcpServers()}catch(error3){mcpRefreshError=error3}return{...memoryRefreshError!==void 0&&{memoryRefreshError},...mcpRefreshError!==void 0&&{mcpRefreshError}}}setPendingStartupWorktreeNotice(notice){this.pendingStartupWorktreeNotice=notice}consumePendingStartupWorktreeNotice(){const v2=this.pendingStartupWorktreeNotice;this.pendingStartupWorktreeNotice=null;return v2}getProjectRoot(){return this.targetDir}getCwd(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return this.toolRegistry}async shutdown(options2){if(isDerivedConfig(this))return;this.shutdownRequested=true;void this.shutdownExecutionEnvironments().catch(()=>void 0);this.settingsWatcher?.stopWatching();if(this.managedRuntimeEnvironment||this.managedRuntimeClosing){try{await this.closeManagedRuntime()}catch(error3){this.debugLogger.error("Failed to stop the Managed Runtime worker:",error3)}}const closeWriter=__name(()=>this.closeSessionWriter().catch(error3=>{this.debugLogger.error("Failed to release session writer lease:",error3)}),"closeWriter");const earlyWriterClose=!options2?.skipSessionWriter&&this.initializationPromise!==void 0&&!this.initializationSucceeded?closeWriter():void 0;try{if(!options2?.skipSessionWriter&&!earlyWriterClose){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch{}}try{await this.shutdownResources(options2?.strictResourceCleanup===true)}catch(error3){if(options2?.strictResourceCleanup)throw error3}}finally{if(!options2?.skipSessionWriter){await(earlyWriterClose??closeWriter())}this.chatRecordingFailureListeners.clear();this.requestLifecycleListeners.clear();if(options2?.shutdownTelemetry!==false&&isTelemetrySdkInitialized()){await shutdownTelemetry()}}}async shutdownResources(waitForInitialization){if(waitForInitialization){try{await this.initializationPromise}catch{}}else if(this.initializationPromise&&!this.initializationSettled){this.scheduleResourceShutdownAfterInitialization();return}return this.runResourceShutdown()}scheduleResourceShutdownAfterInitialization(){if(this.resourceShutdownAfterInitializationScheduled||!this.initializationPromise){return}this.resourceShutdownAfterInitializationScheduled=true;void this.initializationPromise.then(()=>this.runResourceShutdown(),()=>this.runResourceShutdown()).catch(error3=>{this.debugLogger.error("Deferred Config resource cleanup failed:",error3)})}runResourceShutdown(){if(this.resourceShutdownPromise){return this.resourceShutdownPromise}const shutdown=this.shutdownResourcesOnce();this.resourceShutdownPromise=shutdown;const clear=__name(()=>{if(this.resourceShutdownPromise===shutdown){this.resourceShutdownPromise=void 0}},"clear");void shutdown.then(clear,clear);return shutdown}async shutdownResourcesOnce(){let resourceError;try{this.memoryManager.cancelMigrations();this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}unregisterSessionModel(this.sessionId);if(Object.hasOwn(this,"goalRuntime")){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime disposed"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Config shut down before the session writer became available"));this.goalRuntime?.dispose()}if(this.initialized){this.skillManager?.stopWatching();if(this.toolRegistry){await this.toolRegistry.stop()}this.backgroundTaskRegistry.abortAll();this.monitorRegistry.abortAll({notify:false});this.backgroundShellRegistry.abortAll();this.workflowRunRegistry.abortAll()}}catch(error3){resourceError=error3;this.debugLogger.error("Error during Config shutdown:",error3)}try{await this.shutdownExecutionEnvironments()}catch(cleanupError){const errors=cleanupError instanceof AggregateError?[...cleanupError.errors]:[cleanupError];if(resourceError!==void 0)errors.unshift(resourceError);throw new AggregateError(errors,"Container execution cleanup failed during session shutdown.")}if(resourceError!==void 0)throw resourceError;if(!this.initialized)return;try{await this.cleanupArenaRuntime();await this.cleanupTeamRuntime()}catch(error3){this.debugLogger.error("Error during session runtime cleanup:",error3);throw error3}}getPromptRegistry(){return this.promptRegistry}getResourceRegistry(){return this.resourceRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){const parts=[this.appendSystemPrompt,this.liveAppendSystemPrompt].filter(part=>Boolean(part?.trim()));return parts.length>0?parts.join("\n\n"):void 0}setLiveAppendSystemPrompt(prompt){this.liveAppendSystemPrompt=prompt}getOutputStyle(){return this.outputStyle}setOutputStyle(style){this.outputStyle=style}getCoreTools(){if(this.shellExecutionSandbox)return[ToolNames.SHELL,ToolNames.TASK_STOP,ToolNames.READ_FILE,ToolNames.WRITE_FILE,ToolNames.EDIT,ToolNames.MONITOR,ToolNames.AGENT,ToolNames.EXEC,ToolNames.GLOB,ToolNames.LS,ToolNames.ASK_USER_QUESTION,ToolNames.STRUCTURED_OUTPUT];if(this.getBareMode()){return DEFAULT_BARE_CORE_TOOLS}return this.coreTools}getPermissionsAllow(){const base2=this.permissionsAllow??[];const sdkAllow=[...this.allowedTools??[]];if(sdkAllow.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkAllow){if(t&&!merged.includes(t))merged.push(t)}return merged}getPermissionsAsk(){return this.permissionsAsk}getEagerTools(){return this.eagerTools}getPermissionsDeny(){const base2=this.permissionsDeny??[];const sdkDeny=this.excludeTools??[];if(sdkDeny.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkDeny){if(t&&!merged.includes(t))merged.push(t)}return merged}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getDisabledSlashCommands(){return this.disabledSlashCommands}getDisabledSkillNames(){return this.disabledSkillNamesProvider?.()??EMPTY_DISABLED_SKILL_NAMES}hasSkillSettingsListsProvider(){return this.skillSettingsListsProvider!==null}isSkillEnabled(skill){const registryName=skill.name.trim().toLowerCase();const authoredName=authoredSkillName(skill).trim().toLowerCase();const extension=skill.level==="extension"?this.getExtensions().find(candidate=>candidate.name===skill.extensionName&&candidate.skills?.some(owned=>owned.name.trim().toLowerCase()===authoredName&&owned.filePath===skill.filePath)):void 0;if(skill.level==="extension"&&!extension?.isActive)return false;const disabledNames=this.getDisabledSkillNames();if(skillRestrictionNames(skill).some(entry=>disabledNames.has(entry))){return false}if(!extension||this.enabledSkillNamesProvider?.().has(registryName)){return true}const state=this.extensionManager.getExtensionSkillState(extension.id,authoredSkillName(skill));return state.workspaceEnabled??state.defaultEnabled}getDisabledSkillLevels(){return this.disabledSkillLevels}getCustomSkillDirs(){return this.customSkillDirs}getDisabledTools(){return this.disabledTools}getVisibleTools(){return this.visibleTools}getToolSearchThreshold(){return this.toolSearchThreshold}getCodeModeOnly(){return this.toolMode===ToolMode.CodeModeOnly}getFreeform(){return this.freeform}getToolMode(){return this.toolMode}setDisabledTools(disabled){this.disabledTools=new Set(disabled)}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}mcpTransportPool;setMcpTransportPool(pool){this.mcpTransportPool=pool}getMcpTransportPool(){return this.mcpTransportPool}getSettingsMcpServers(){return this.mcpServers}getTopTierMcpServers(){return this.topTierMcpServers}getMergedMcpServers(){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}for(const[name,cfg]of this.runtimeMcpServers){mcpServers[name]=cfg}return mcpServers}getMcpServers(){if(this.executionEnvironment||this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return{}}let mcpServers=this.isSafeMode()?{...this.topTierMcpServers}:this.getMergedMcpServers();if(this.allowedMcpServers){mcpServers=Object.fromEntries(Object.entries(mcpServers).filter(([key])=>matchesAnyServerPattern(key,this.allowedMcpServers)))}return mcpServers}getExcludedMcpServers(){return this.excludedMcpServers}setExcludedMcpServers(excluded){this.excludedMcpServers=excluded}getMcpToolIdleTimeoutMs(){return this.mcpToolIdleTimeoutMs}isMcpServerDisabled(serverName){if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return true;if(this.mcpServers?.[serverName])return false;for(const extension of this.getActiveExtensions()){if(extension.config.mcpServers?.[serverName]){return this.extensionManager?.getDisabledMcpServers(extension.config.name).includes(serverName)??false}}return false}isMcpServerPendingApproval(serverName){return this.pendingMcpServers?.includes(serverName)??false}approveMcpServerForSession(serverName){if(!this.pendingMcpServers){return}this.pendingMcpServers=this.pendingMcpServers.filter(name=>name!==serverName)}addMcpServers(servers){if(this.shellExecutionSandbox&&Object.keys(servers).length)throw new Error("Tool execution sandbox does not support MCP servers.");if(this.initialized){throw new Error("Cannot modify mcpServers after initialization")}this.mcpServers={...this.mcpServers,...servers}}setMcpServers(servers){if(this.shellExecutionSandbox&&Object.keys(servers??{}).length)throw new Error("Tool execution sandbox does not support MCP servers.");this.mcpServers=servers}setAllowedMcpServers(allowed){this.allowedMcpServers=allowed}getAllowedMcpServers(){return this.allowedMcpServers}getCliAllowedMcpServerNames(){return this.cliAllowedMcpServerNames}setPendingMcpServers(pending){this.pendingMcpServers=pending}getMcpGating(){return{excluded:this.excludedMcpServers,allowed:this.allowedMcpServers,pending:this.pendingMcpServers}}getRecentlyRemovedMcpServers(){return[...this.recentlyRemovedMcpServers]}getMcpServerNames(){return Object.keys(this.getMergedMcpServers())}getMcpServerUnavailableReason(serverName){if(this.recentlyRemovedMcpServers.has(serverName))return"removed";if(!(serverName in this.getMergedMcpServers()))return void 0;if(this.allowedMcpServers&&!matchesAnyServerPattern(serverName,this.allowedMcpServers)){return"not_allowed"}if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return"excluded";if(this.isMcpServerPendingApproval(serverName))return"pending_approval";return void 0}async reinitializeMcpServers(servers){this.debugLogger.debug(`[mcp-hot-reload] reinitializeMcpServers: servers=[${Object.keys(servers??{}).join(", ")}] initialized=${this.initialized} inProgress=${this.mcpReconcileInProgress}`);const prevConfigured=new Set(Object.keys(this.getMergedMcpServers()));this.setMcpServers(servers);const nextConfigured=new Set(Object.keys(this.getMergedMcpServers()));for(const name of nextConfigured){this.recentlyRemovedMcpServers.delete(name)}for(const name of prevConfigured){if(!nextConfigured.has(name)){this.recentlyRemovedMcpServers.add(name)}}await this.refreshMcpServers()}async refreshMcpServers(){if(this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return}if(!this.initialized){this.debugLogger.debug("[mcp-hot-reload] not initialized yet \u2014 deferring to boot-time discovery (no-op)");return}if(this.mcpReconcileInProgress){this.mcpReconcilePending=true;this.debugLogger.debug("[mcp-hot-reload] reconcile already in flight \u2014 coalescing into a follow-up pass");return this.mcpReconcilePromise??Promise.resolve()}this.mcpReconcileInProgress=true;const registry3=this.getToolRegistry();const runReconcile=(async()=>{try{this.debugLogger.debug("[mcp-hot-reload] running incremental reconcile (pass 1)");await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this);let pass=1;while(this.mcpReconcilePending){this.mcpReconcilePending=false;pass+=1;this.debugLogger.debug(`[mcp-hot-reload] running coalesced incremental reconcile (pass ${pass})`);await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this)}this.debugLogger.debug(`[mcp-hot-reload] reconcile complete after ${pass} pass(es); live servers=[${Object.keys(this.getMcpServers()??{}).join(", ")}]`)}catch(err){this.debugLogger.error(`[mcp-hot-reload] reconcile failed: ${err instanceof Error?err.stack??err.message:String(err)}`);throw err}finally{this.mcpReconcileInProgress=false;this.mcpReconcilePending=false;this.mcpReconcilePromise=void 0}})();this.mcpReconcilePromise=runReconcile;await runReconcile}addRuntimeMcpServer(name,config3){if(this.shellExecutionSandbox)throw new Error("Tool execution sandbox does not support MCP servers.");this.runtimeMcpServers.set(name,config3)}getRuntimeMcpServers(){return Object.fromEntries(this.runtimeMcpServers)}removeRuntimeMcpServer(name){return this.runtimeMcpServers.delete(name)}isLspEnabled(){return this.lspEnabled&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.provisionalWorkspace}getLspClient(){return this.lspClient}getLspStatusSnapshot(){if(!this.isLspEnabled()){return this.createLspStatusSnapshot(false)}const clientSnapshot=this.lspClient?.getStatusSnapshot?.();if(clientSnapshot){return{...clientSnapshot,enabled:true,initializationError:this.lspInitializationError??clientSnapshot.initializationError}}if(this.lspClient){return{...this.createLspStatusSnapshot(true,this.lspInitializationError),statusUnavailable:true}}return this.createLspStatusSnapshot(true,this.lspInitializationError??"LSP client is not initialized")}createLspStatusSnapshot(enabled,initializationError){return{enabled,configuredServers:0,readyServers:0,failedServers:0,inProgressServers:0,notStartedServers:0,servers:[],...initializationError?{initializationError}:{}}}setLspClient(client){if(this.shellExecutionSandbox&&client)throw new Error("Tool execution sandbox does not support LSP.");if(this.initialized){throw new Error("Cannot set LSP client after initialization")}this.lspClient=client}setLspInitializationError(error3){if(this.initialized){throw new Error("Cannot set LSP status after initialization")}this.setRuntimeLspInitializationError(error3)}setRuntimeLspInitializationError(error3){this.lspInitializationError=error3 instanceof Error?error3.message:error3}async reinitializeLsp(){if(!this.isLspEnabled()||!this.lspClient?.reinitialize){return void 0}try{const result=await this.lspClient.reinitialize();if(result.reconcile.failed.length>0){this.setRuntimeLspInitializationError(`LSP reload partially failed: ${result.reconcile.failed.join(", ")}`)}else{this.setRuntimeLspInitializationError(void 0)}return result}catch(error3){this.setRuntimeLspInitializationError(error3 instanceof Error?error3:String(error3));throw error3}}getSessionSubagents(){return this.sessionSubagents}setSessionSubagents(subagents){if(this.initialized){throw new Error("Cannot modify sessionSubagents after initialization")}this.sessionSubagents=subagents}getSdkMode(){return this.sdkMode}setSdkMode(value){this.sdkMode=value}getUserMemory(){return this.userMemory}getStaticSystemPrefix(){return this.staticSystemPrefix}setStaticSystemPrefix(prefix){this.staticSystemPrefix=prefix}getPromptToolSnapshot(){return this.promptToolSnapshot}setPromptToolSnapshot(names){this.promptToolSnapshot=names}getPromptAgentReachable(){return this.promptAgentReachable}setPromptAgentReachable(reachable){this.promptAgentReachable=reachable}getAutoMemoryPrompt(){return this.autoMemoryPrompt}getAutoMemoryContext(){return this.memoryRecallMode==="legacy"&&this.getAutoMemoryPrompt()?this.autoMemoryContext:""}getMemoryRecallMode(){return this.memoryRecallMode}async prepareMemoryRecallTransition(){if(!this.getManagedAutoMemoryEnabled())return void 0;if(!this.getStructuredMemoryRecallEnabled())return void 0;if(this.memoryRecallMode==="structured")return void 0;const status=await this.scanMemoryRecallCorpusStatus();if(!status.ready){this.memoryCorpusRevision=status.revision;return void 0}const projectRoot=this.getProjectRoot();const teamEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();const configuredProjectRoot=getAutoMemoryRoot(projectRoot);await Promise.all([...getProjectMetadataMigrationRoots(projectRoot,this.isTrustedFolder()).map(root=>root===configuredProjectRoot?rebuildManagedAutoMemoryIndex(projectRoot):rebuildAutoMemoryIndexAtRoot(root,"project")),rebuildUserAutoMemoryIndex(),...teamEnabled?[rebuildTeamAutoMemoryIndex(projectRoot)]:[]].map(pending=>pending.catch(error3=>{this.debugLogger.debug(`Memory index rebuild failed during recall transition: ${error3 instanceof Error?error3.message:String(error3)}`)})));const autoMemoryPrompt=await buildStructuredAutoMemoryPrompt(getAutoMemoryRoot(projectRoot),getUserAutoMemoryRoot(),teamEnabled?getTeamAutoMemoryRoot(projectRoot):void 0);const confirmed=await this.scanMemoryRecallCorpusStatus();if(confirmed.revision!==status.revision)return void 0;return{from:"legacy",to:"structured",revision:confirmed.revision,autoMemoryPrompt,previousRevision:this.memoryCorpusRevision,previousAutoMemoryPrompt:this.autoMemoryPrompt}}async confirmMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return false;const status=await this.scanMemoryRecallCorpusStatus();return status.revision===transition.revision&&(status.ready?"structured":"legacy")===transition.to}commitMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return;this.memoryRecallMode=transition.to;this.memoryCorpusRevision=transition.revision;this.autoMemoryPrompt=transition.autoMemoryPrompt;this.memoryRecallModeInitialized=true}rollbackMemoryRecallTransition(transition){if(this.memoryRecallMode!==transition.to)return;this.memoryRecallMode=transition.from;this.memoryCorpusRevision=transition.previousRevision;this.autoMemoryPrompt=transition.previousAutoMemoryPrompt}scanMemoryRecallCorpusStatus(){return scanMemoryMetadataCorpusStatus({projectRoot:this.getProjectRoot(),teamMemoryEnabled:this.getTeamMemoryEnabled(),trustedProject:this.isTrustedFolder()})}getOutputLanguageFilePath(){return this.outputLanguageFilePath}setOutputLanguageFilePath(filePath){this.outputLanguageFilePath=filePath}setUserMemory(newUserMemory){this.userMemory=newUserMemory}getMemoryFileCount(){return this.memoryFileCount}setMemoryFileCount(count){this.memoryFileCount=count}getGeminiMdFileCount(){return this.getMemoryFileCount()}setGeminiMdFileCount(count){this.setMemoryFileCount(count)}getContextFilePaths(){return this.loadedContextFilePaths}setContextFilePaths(paths){this.loadedContextFilePaths=paths}getArenaManager(){return this.arenaManager}setArenaManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent arenas.");this.arenaManager=manager;this.arenaManagerChangeCallback?.(manager)}onArenaManagerChange(cb){this.arenaManagerChangeCallback=cb}getArenaAgentClient(){return this.arenaAgentClient}getAgentsSettings(){return this.agentsSettings}getTeamManager(){return this.teamManager}setTeamManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent teams.");this.teamManager=manager;for(const cb of this.teamManagerChangeCallbacks){cb(manager)}}onTeamManagerChange(cb,previous){if(previous){this.teamManagerChangeCallbacks.delete(previous)}if(cb){this.teamManagerChangeCallbacks.add(cb)}}getTeamContext(){return this.teamContext}setTeamContext(ctx){this.teamContext=ctx}async cleanupTeamRuntime(){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Team runtime")}const manager=this.teamManager;if(!manager){return}await manager.cleanup();this.setTeamManager(null);this.setTeamContext(null)}getWorktreeSymlinkDirectories(){return this.worktreeSettings.symlinkDirectories??[]}async cleanupArenaRuntime(force){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Arena runtime")}const manager=this.arenaManager;if(!manager){return}if(!force&&this.agentsSettings.arena?.preserveArtifacts){await manager.cleanupRuntime()}else{await manager.cleanup()}this.setArenaManager(null)}getApprovalMode(){return this.approvalMode}getSessionApprovalMode(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).getSessionApprovalMode()}return this.getApprovalMode()}getAutoModeSettings(){return this.permissionsAutoMode}getAutoModeDenialState(){return this.autoModeDenialState}setAutoModeDenialState(state){this.autoModeDenialState=state}getPrePlanMode(){return this.prePlanMode??"default"}getPlanExecutionMode(){return Object.hasOwn(this,"planExecutionMode")?this.planExecutionMode:void 0}setPlanMode(enabled,executionMode){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot change plan workflow mode")}if(executionMode==="plan"){throw new Error("Plan is not an execution approval mode")}if(this.isSessionAgentSession?.()===true&&executionMode!=="default"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&executionMode!=="default"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const previousMode=this.approvalMode;const previousExecutionMode=this.planExecutionMode;if(enabled)this.planExecutionMode=executionMode;try{this.setApprovalMode(enabled?"plan":executionMode)}catch(error3){this.planExecutionMode=previousExecutionMode;throw error3}if(enabled&&previousMode==="plan"&&previousExecutionMode!==executionMode){this.notifyApprovalModeChangeListeners()}}getApprovalModeRevision(){return this.approvalModeRevision}getManualPlanExitNoticeEventState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeEventState")&&Object.prototype.hasOwnProperty.call(this,"approvalMode")){const inheritedEvent=this.manualPlanExitNoticeEventState;this.manualPlanExitNoticeEventState=inheritedEvent?{...inheritedEvent}:{version:0,kind:"clear"}}return this.manualPlanExitNoticeEventState}getOwnManualPlanExitNoticeCursorState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeCursorState")){this.manualPlanExitNoticeCursorState={seenVersion:0}}return this.manualPlanExitNoticeCursorState}setApprovalMode(mode,options2){if(isDerivedConfig(this)&&!Object.prototype.hasOwnProperty.call(this,"setApprovalMode")){throw new Error("Derived Configs cannot change approval mode")}if(this.isSessionAgentSession?.()===true&&mode!=="default"&&mode!=="plan"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&mode!=="default"&&mode!=="plan"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const fromMode=this.approvalMode;if(this.permissionManager){if(mode==="auto"&&fromMode!=="auto"){this.permissionManager.stripDangerousRulesForAutoMode()}else if(fromMode==="auto"&&mode!=="auto"){this.permissionManager.restoreDangerousRules()}}let noticeEvent=_Config.prototype.getManualPlanExitNoticeEventState.call(this);if(!Object.prototype.hasOwnProperty.call(this,"approvalMode")){noticeEvent={...noticeEvent};this.manualPlanExitNoticeEventState=noticeEvent}if(mode==="plan"&&fromMode!=="plan"){if(!isDerivedConfig(this)){this.goalProposalApprovalController?.abort()}this.prePlanMode=fromMode;noticeEvent.version++;noticeEvent.kind="clear"}else if(mode!=="plan"&&fromMode==="plan"){this.prePlanMode=void 0;noticeEvent.version++;noticeEvent.kind=options2?.fromApprovedPlanExit||options2?.fromSessionRestore?"clear":"manual-exit";if(options2?.fromApprovedPlanExit&&Object.getPrototypeOf(this)===_Config.prototype){this.approveSessionWorkflowPlanRevision()}}if(fromMode!==mode){this.autoModeDenialState=resetDenialState();if(!isDerivedConfig(this)&&mode!=="plan"&&fromMode!=="plan"){clearSessionCommits()}}this.approvalMode=mode;if(mode!=="plan")this.planExecutionMode=void 0;if(fromMode!==mode){this.approvalModeRevision++;if(!isDerivedConfig(this)){this.notifyApprovalModeChangeListeners()}}}takePendingManualPlanExitNotice(){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version<=cursor.seenVersion){return void 0}cursor.seenVersion=event.version;if(event.kind!=="manual-exit"||this.approvalMode==="plan"){return void 0}return{version:event.version,currentMode:this.approvalMode}}restorePendingManualPlanExitNotice(version4){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version===version4&&event.kind==="manual-exit"&&this.approvalMode!=="plan"&&cursor.seenVersion===version4){cursor.seenVersion=Math.max(0,version4-1)}}consumePendingManualPlanExitNotice(){return _Config.prototype.takePendingManualPlanExitNotice.call(this)!==void 0}getPlansDir(){return this.plansDir}getPlansAnchorTargetDir(){if(Object.prototype.hasOwnProperty.call(this,"plansDirectoryConfigured")){return this.targetDir}let current2=Object.getPrototypeOf(this);while(current2!==null&¤t2!==_Config.prototype){if(Object.prototype.hasOwnProperty.call(current2,"plansDirectoryConfigured")){return current2.targetDir}current2=Object.getPrototypeOf(current2)}return this.targetDir}assertPlansDirWithinTargetDir(){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(this.plansDir,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}assertPlanFilePathWithinTargetDir(filePath){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(filePath,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured){return}const legacyPlansDir=Storage.getPlansDir();const legacyPlanFiles=this.getPlanFileNames(legacyPlansDir);if(legacyPlanFiles.length===0){return}const configuredPlanFiles=new Set(this.getPlanFileNames(this.plansDir));const hiddenLegacyPlanFiles=legacyPlanFiles.filter(fileName=>!configuredPlanFiles.has(fileName));if(hiddenLegacyPlanFiles.length===0){return}this.warnings.push(`Warning: Saved plan files exist at ${legacyPlansDir}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(err){const message=`Failed to check legacy plan directory migration warning: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err)}}getPlanFileNames(plansDir){try{return fs76.readdirSync(plansDir).filter(entry=>entry.endsWith(".md"))}catch(err){const code=err.code;if(code==="ENOENT"){return[]}if(code==="EACCES"||code==="EPERM"){const message=`Failed to read plan directory ${plansDir}: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err);return[]}throw err}}getPlanFilePath(){return path81.join(this.plansDir,`${Storage.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(plan){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();const dir=path81.dirname(filePath);fs76.mkdirSync(dir,{recursive:true});const tmpPath=filePath+".tmp";fs76.writeFileSync(tmpPath,plan,"utf-8");try{fs76.renameSync(tmpPath,filePath)}catch(err){if(err.code!=="EXDEV"){throw err}fs76.copyFileSync(tmpPath,filePath);fs76.unlinkSync(tmpPath)}try{this.assertPlanFilePathWithinTargetDir(filePath)}catch(err){try{fs76.unlinkSync(filePath)}catch{}throw err}}loadPlan(){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(filePath);try{return fs76.readFileSync(filePath,"utf-8")}catch(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3&&error3.code==="ENOENT"){return void 0}throw error3}}getInputFormat(){return this.inputFormat}getIncludePartialMessages(){return this.includePartialMessages}getAccessibility(){return this.accessibility}getShowResponseTokensPerSecond(){return this.showResponseTokensPerSecond}getTelemetryEnabled(){return this.telemetrySettings.enabled??false}isTelemetryInitializationDeferred(){return this.telemetryInitializationDeferred}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??true}getTelemetryUserId(){return this.telemetrySettings.userId}getTelemetryIncludeSensitiveSpanAttributes(){return this.telemetrySettings.includeSensitiveSpanAttributes??false}getTelemetrySensitiveSpanAttributeMaxLength(){return this.telemetrySettings.sensitiveSpanAttributeMaxLength}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??DEFAULT_OTLP_ENDPOINT}getTelemetryOtlpProtocol(){return this.telemetrySettings.otlpProtocol??"grpc"}getTelemetryOtlpTracesEndpoint(){return this.telemetrySettings.otlpTracesEndpoint}getTelemetryOtlpLogsEndpoint(){return this.telemetrySettings.otlpLogsEndpoint}getTelemetryOtlpMetricsEndpoint(){return this.telemetrySettings.otlpMetricsEndpoint}getTelemetryTarget(){return this.telemetrySettings.target??DEFAULT_TELEMETRY_TARGET}getTelemetryResourceAttributes(){return this.telemetrySettings.resourceAttributes??{}}getTelemetryMetricsIncludeSessionId(){return this.telemetrySettings.metrics?.includeSessionId??false}getTelemetryResourceAttributeWarnings(){return this.telemetrySettings.resourceAttributeWarnings??[]}getOutboundCorrelationPropagateTraceContext(){return this.outboundCorrelationSettings.propagateTraceContext??false}getOutboundAllowDynamicHeaderValues(){return this.outboundCorrelationSettings.allowDynamicHeaderValues??false}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGitCoAuthor(){return this.gitCoAuthor}getLlmClient(){return this.llmClient}getGeminiClient(){return this.getLlmClient()}getOwnActiveTodoReminders(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminders")){this.activeTodoReminders=new Map}return this.activeTodoReminders}getOwnActiveTodoWorkChainOwners(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoWorkChainOwners")){this.activeTodoWorkChainOwners=new Map}return this.activeTodoWorkChainOwners}getOwnActiveTodoReminderTurns(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminderTurns")){this.activeTodoReminderTurns=new Map}return this.activeTodoReminderTurns}getActiveTodoWorkChainOwner(promptId,fallbackOwner=promptId){return this.getOwnActiveTodoWorkChainOwners().get(promptId)??fallbackOwner}getActiveTodoReminder(promptId){return this.getOwnActiveTodoReminders().get(this.getActiveTodoWorkChainOwner(promptId))}getActiveTodoPlanWriterOwner(){return this.activeTodoPlanWriterOwner}recordActiveTodoPlanWriter(promptId){this.activeTodoPlanWriterOwner=this.getActiveTodoWorkChainOwner(promptId)}takeActiveTodoReminder(promptId,force=false){const owner=this.getActiveTodoWorkChainOwner(promptId);const reminder=this.getOwnActiveTodoReminders().get(owner);if(!reminder)return void 0;const turns=this.getOwnActiveTodoReminderTurns();const elapsed=(turns.get(owner)??0)+1;if(!force&&elapsed<ACTIVE_TODO_REMINDER_REFRESH_TURNS){turns.set(owner,elapsed);return void 0}turns.set(owner,0);return reminder}setActiveTodoReminder(promptId,reminder){const reminders=this.getOwnActiveTodoReminders();const owner=this.getActiveTodoWorkChainOwner(promptId);if(reminder){reminders.set(owner,reminder);this.getOwnActiveTodoReminderTurns().set(owner,0)}else{reminders.clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}}startActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();if(!continuedFrom){reminders.clear();owners.clear();this.getOwnActiveTodoReminderTurns().clear();owners.set(promptId,promptId);return}const owner=this.getActiveTodoWorkChainOwner(continuedFrom);for(const reminderOwner of reminders.keys()){if(reminderOwner!==owner)reminders.delete(reminderOwner)}for(const[mappedPromptId,mappedOwner]of owners){if(mappedOwner!==owner)owners.delete(mappedPromptId)}owners.delete(continuedFrom);owners.set(promptId,owner)}startAutomaticActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();const owner=continuedFrom?this.getActiveTodoWorkChainOwner(continuedFrom):promptId;owners.set(promptId,owner);if(owner===promptId)reminders.delete(owner)}endAutomaticActiveTodoWorkChain(promptId){const owners=this.getOwnActiveTodoWorkChainOwners();const owner=this.getActiveTodoWorkChainOwner(promptId);owners.delete(promptId);if(![...owners.values()].includes(owner)){this.getOwnActiveTodoReminders().delete(owner)}}clearActiveTodoReminders(){this.getOwnActiveTodoReminders().clear();this.getOwnActiveTodoWorkChainOwners().clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}getMemoryPressureMonitor(){if(!Object.prototype.hasOwnProperty.call(this,"memoryPressureMonitor")){const inheritedMonitor=this.memoryPressureMonitor;if(inheritedMonitor){const inheritedConfig=this.memoryPressureConfig;if(!inheritedConfig){throw new Error("Inherited memory pressure monitor is missing config")}this.memoryPressureConfig={...inheritedConfig};this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig)}}return this.memoryPressureMonitor}getCronScheduler(){if(!this.cronScheduler){this.cronScheduler=new CronScheduler(this.getProjectRoot(),this.getCronRecurringMaxAgeDays()*24*60*60*1e3)}return this.cronScheduler}getCronRecurringMaxAgeDays(){return this.cronRecurringMaxAgeDays}isCronEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_CRON"]==="1")return false;return this.cronEnabled}isLsToolEnabled(){if(this.lsToolEnabled)return true;return this.getCoreTools()?.some(name=>parseRule(name).toolName===ToolNames.LS)??false}isTodoWriteEnabled(){return this.todoWriteEnabled}isAgentTeamEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_ENABLE_AGENT_TEAM"]==="1")return true;return this.agentTeamEnabled}isAgentCollaborationEnabled(){if(process8.env["QWEN_CODE_ENABLE_AGENT_COLLABORATION"]==="1"){return true}return this.agentCollaborationEnabled}isArtifactEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(!this.interactive&&!this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}sessionSourceService;sessionSourceServiceFactory;setSessionSourceServiceFactory(factory){this.sessionSourceServiceFactory=factory;this.sessionSourceService=factory()}getSessionSourceService(){return Object.hasOwn(this,"sessionSourceService")?this.sessionSourceService:void 0}isRecordArtifactEnabled(){if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}getArtifactPublisherKind(){return this.artifactPublisher}isArtifactSnapshotsEnabled(){return this.artifactSnapshotsEnabled&&this.chatRecordingEnabled}setArtifactSnapshotsEnabled(enabled){this.artifactSnapshotsEnabled=enabled}getArtifactHostConfig(){return this.artifactHost}getArtifactOssConfig(){return this.artifactOss}isOmniEnabled(){if(this.bareMode)return false;if(process8.env["QWEN_CODE_ENABLE_OMNI"]==="1")return true;return this.omniEnabled}getOmniMaxUploadFileBytes(){return this.omniMaxUploadFileBytes}getOmniMaxEstimatedTokens(){return this.omniMaxEstimatedTokens}getOmniMaxDurationSeconds(){return this.omniMaxDurationSeconds}getOmniUrlDownloadMaxFileBytes(){return this.omniUrlDownloadMaxFileBytes}getOmniUploadUrlTtlHours(){return this.omniUploadUrlTtlHours}getOmniUploadConfig(){return this.omniUploadConfig}getOmniPolicyToolsSettings(){return this.omniPolicyTools}async loadOmniMediaReader(){return import("./omni-HV2UBGMZ.js")}getOmniProcessingConfig(){return this.omniProcessingConfig}getOmniMemoryConfig(){return this.omniMemoryConfig}async ensureOmniMemoryConfig(){if(!this.omniMemoryConfig){const{normalizeOmniMemoryConfig}=await import("./config-NOIFIDXC.js");this.omniMemoryConfig=normalizeOmniMemoryConfig(this.omniMemory)}return this.omniMemoryConfig}getOmniMediaResourceRegistry(){this.omniMediaResourceRegistry??=new MediaResourceRegistry;return this.omniMediaResourceRegistry}getOmniQuarantineRetentionDays(){const days=this.omniQuarantineRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>0?days:7}getOmniQuarantineMaxBytes(){const bytes=this.omniQuarantineMaxBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:5*1024*1024*1024}getOmniStorageRetentionDays(){const days=this.omniStorageRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>=1?days:14}getOmniStorageMaxTotalBytes(){const bytes=this.omniStorageMaxTotalBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:20*1024*1024*1024}resolveImageGenerationModel(setting){const parsedSetting=parseVisionModelSetting(setting);if(!parsedSetting)return void 0;let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{return void 0}if(!selector)return void 0;const routeMatches=this.getAllConfiguredModels().filter(model=>isImageGenerationCapable(model)&&!model.fastOnly&&!model.voiceOnly&&model.id===selector.modelId&&(!selector.authType||model.authType===selector.authType)&&(!parsedSetting.baseUrl||model.baseUrl===parsedSetting.baseUrl));if(routeMatches.length!==1)return void 0;const match=routeMatches[0];const apiKeyEnv=match.envKey?.trim();const configuredBaseUrl=match.registryBaseUrl?.trim();if(!apiKeyEnv||!configuredBaseUrl)return void 0;const baseUrl=normalizeImageGenerationBaseUrl(parsedSetting.baseUrl??configuredBaseUrl);if(!baseUrl)return void 0;return{model:match.id,baseUrl,apiKeyEnv}}getImageGenerationConfig(){if(this.bareMode||this.safeMode)return void 0;return this.resolveImageGenerationModel(this.imageModel)}isImageGenerationEnabled(){if(this.shellExecutionSandbox)return false;return this.getImageGenerationConfig()!==void 0}shouldAutoOpenArtifact(){if(this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_ARTIFACT_NO_AUTO_OPEN"]==="1")return false;return this.artifactAutoOpen&&!this.isBrowserLaunchSuppressed()}isWorkflowsEnabled(){if(this.shellExecutionSandbox)return false;if(this.provisionalWorkspace)return false;if(process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1")return false;if(process8.env["QWEN_CODE_ENABLE_WORKFLOWS"]==="1")return true;return this.workflowsEnabled??false}setWorkflowsEnabled(enabled){this.workflowsEnabled=enabled}async enableReviewWorkflow(){if(this.shellExecutionSandbox||this.workflowsEnabled===false||!isTopLevelSession()||this.getBareMode()||this.provisionalWorkspace||process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1"){return}if(await this.registerWorkflowTool(this.getToolRegistry())){this.setWorkflowsEnabled(true);await this.getLlmClient().setTools()}}isSessionWorkflowEnabled(){if(this.shellExecutionSandbox)return false;return this.sessionWorkflowEnabledProvider?.()??this.sessionWorkflowEnabled}setSessionWorkflowEnabledProvider(provider){this.sessionWorkflowEnabledProvider=provider;if(!this.isSessionWorkflowEnabled()){this.sessionWorkflowPlanRevision=void 0}}setExternalAgentExecutor(executor){this.externalAgentExecutor=executor}getExternalAgentExecutor(){return this.externalAgentExecutor}getAgentExecutionBackend(){return this.agentExecutionBackend}getExecutionEnvironmentFactory(){return this.shutdownRequested||this.executionShutdown.signal.aborted?void 0:this.executionEnvironmentFactory}getExecutionEnvironment(){return this.executionEnvironment}shutdownExecutionEnvironments(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).shutdownExecutionEnvironments()}this.executionShutdown.abort();if(this.executionCleanupPromise)return this.executionCleanupPromise;const cleanup=Promise.allSettled([...this.executionEnvironments??[]].map(async pending=>{let environment;try{environment=await pending}catch(error3){if(error3 instanceof ExecutionCleanupError){if(!error3.retryCleanup)throw error3;await error3.retryCleanup()}this.executionEnvironments?.delete(pending);return}await environment.dispose();this.executionEnvironments?.delete(pending)})).then(results=>{const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,errors.map(String).join("; "))});let timer;this.executionCleanupPromise=new Promise((resolve34,reject)=>{timer=setTimeout(()=>reject(new ExecutionCleanupError(`Container cleanup is still pending for workspace ${this.getWorkingDir()}. Keep its workspace and inspect qwen-agent-* containers and qwen-agent-executor-* temporary directories before manual removal.`)),1e3);cleanup.then(resolve34,reject)}).catch(error3=>{console.warn(`Container execution cleanup incomplete: ${String(error3)}`);throw error3}).finally(()=>clearTimeout(timer));const clear=__name(()=>{this.executionCleanupPromise=void 0},"clear");void cleanup.then(clear,clear);return this.executionCleanupPromise}registerExecutionEnvironment(pending){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).registerExecutionEnvironment(pending)}this.executionEnvironments??=new Set;this.executionEnvironments.add(pending);return()=>this.executionEnvironments?.delete(pending)}getSessionWorkflowPlanRevision(){if(!this.isSessionWorkflowEnabled())return void 0;return this.sessionWorkflowPlanRevision}setSessionWorkflowPlanRevision(revision){if(!this.isSessionWorkflowEnabled()||revision===void 0||revision.planId.trim()===""||revision.sourceCallId.trim()===""){this.sessionWorkflowPlanRevision=void 0;return}const todoIds=Array.from(new Set(revision.todoIds.filter(todoId=>typeof todoId==="string"&&todoId.trim()!=="")));this.sessionWorkflowPlanRevision=todoIds.length>0?{planId:revision.planId,sourceCallId:revision.sourceCallId,todoIds,...revision.approved?{approved:true}:{}}:void 0}clearSessionWorkflowPlanRevision(){this.sessionWorkflowPlanRevision=void 0}approveSessionWorkflowPlanRevision(){const revision=this.getSessionWorkflowPlanRevision();if(!revision||revision.approved)return;this.setSessionWorkflowPlanRevision({...revision,approved:true})}isSessionWorkflowTodoContextActive(){return this.isSessionWorkflowEnabled()&&(this.approvalMode==="plan"||this.sessionWorkflowPlanRevision!==void 0)}getModelProposedGoals(){return this.modelProposedGoals}setGoalProposalHostSupported(supported){this.goalProposalHostSupported=supported}getGoalProposalHostSupported(){return this.goalProposalHostSupported}setGoalProposalTurnKey(turnKey){if(this.goalProposalTurnKey===turnKey)return false;this.goalProposalTurnKey=turnKey;return true}isGoalProposalAvailable(){return resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported&&this.goalProposalTurnKey!==void 0}hasPendingGoalProposal(){return this.pendingGoalProposal!==void 0}setPendingGoalProposal(proposal){if(this.pendingGoalProposal)return false;this.goalProposalApprovalController=new AbortController;if(this.approvalMode==="plan"){this.goalProposalApprovalController.abort()}this.pendingGoalProposal={...proposal,approvalSignal:this.goalProposalApprovalController.signal};return true}takePendingGoalProposal(expectedTurnKey){const proposal=this.pendingGoalProposal;if(expectedTurnKey!==void 0&&proposal?.turnKey!==expectedTurnKey){return void 0}this.pendingGoalProposal=void 0;return proposal}getSkipWorkflowUsageWarning(){return this.skipWorkflowUsageWarning}getWorkflowSizeGuideline(){return resolveWorkflowSizeGuidelineSetting(this.workflowSizeGuideline)}isWorkflowNameOnly(){return this.workflowNameOnly}setWorkflowSizeGuideline(size){this.workflowSizeGuideline=isWorkflowSizeGuideline(size)?size:void 0}getEmitToolUseSummaries(){const env=process8.env["QWEN_CODE_EMIT_TOOL_USE_SUMMARIES"];if(env==="0"||env==="false")return false;if(env==="1"||env==="true")return true;return this.emitToolUseSummaries}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringEnableFuzzySearch(){return this.fileFiltering.enableFuzzySearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectQwenIgnore(){return this.fileFiltering.respectQwenIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectQwenIgnore:this.fileFiltering.respectQwenIgnore,customIgnoreFiles:[...this.fileFiltering.customIgnoreFiles]}}getCustomExcludes(){return[]}getFileCheckpointingEnabled(){return!this.shellExecutionSandbox&&this.fileCheckpointingEnabled}enableFileCheckpointing(){if(this.shellExecutionSandbox)throw new Error("File checkpointing is unavailable with tools.executionSandbox.");this.fileCheckpointingEnabled=true;this.fileHistoryService=void 0}getFileHistoryService(){if(!this.fileHistoryService){const service=new FileHistoryService(this.sessionId,this.getFileCheckpointingEnabled(),this.cwd,snapshot=>{if(this.fileHistoryService!==service)return;this.getChatRecordingService()?.recordFileHistorySnapshot(snapshot)});this.fileHistoryService=service;const snapshots=this.sessionData?.fileHistorySnapshots;if(snapshots?.length&&service.isEnabled()){service.restoreFromSnapshots(snapshots);void service.validateRestoredSnapshots().catch(e=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${e}`)})}}return this.fileHistoryService}getProxy(){return normalizeProxyUrl(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){if(!this.fileDiscoveryService){this.fileDiscoveryService=new FileDiscoveryService(this.targetDir,this.fileFiltering.customIgnoreFiles)}return this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionRuleSources(){return this.getActiveExtensions().filter(extension=>Boolean(extension.path)).map(extension=>({name:extension.name,dir:path81.join(extension.path,"rules")}))}getExtensionContextFilePaths(){const extensionContextFilePaths=this.getActiveExtensions().flatMap(e=>e.contextFiles);return[...extensionContextFilePaths,...this.outputLanguageFilePath?[this.outputLanguageFilePath]:[]]}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getRestoreAskUserQuestion(){return this.restoreAskUserQuestion}getPreserveRestorableAskUserQuestion(){return this.preserveRestorableAskUserQuestion}suppressRestorableAskUserQuestionPreservation(){this.preserveRestorableAskUserQuestion=false}isSessionWriterLeaseEnabled(){return this.sessionWriterLeaseEnabled}getListExtensions(){return this.listExtensions}getExtensionManager(){return this.extensionManager}getHookSystem(){if(this.shellExecutionSandbox)return void 0;return this.hookSystem}hasHooksForEvent(eventName,sessionId){return this.hookSystem?.hasHooksForEvent(eventName,sessionId??this.getSessionId())??false}getDisableAllHooks(){if(this.shellExecutionSandbox)return true;if(this.hookSystem?.isManaged())return false;return this.disableAllHooks||this.getBareMode()||this.isSafeMode()}getStopHookBlockingCap(){return this.stopHookBlockingCap}getManagedAutoMemoryEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()&&!this.isSafeMode()}getTeamMemoryEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemory}getTeamMemorySyncEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM_SYNC"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemorySync}getStructuredMemoryRecallEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.isSafeMode())return false;const override=process8.env["QWEN_CODE_MEMORY_STRUCTURED_RECALL"];if(override==="0"){return false}if(override==="1"){return true}return this.enableStructuredMemoryRecall}isManagedMemoryAvailable(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()}getManagedAutoDreamEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoDream&&!this.getBareMode()&&!this.isSafeMode()}getAutoSkillEnabled(){if(this.shellExecutionSandbox)return false;return this.enableAutoSkill&&!this.getBareMode()&&!this.isSafeMode()&&!this.provisionalWorkspace}setAutoSkillEnabled(enabled){this.enableAutoSkill=enabled}getAutoSkillConfirmEnabled(){return this.autoSkillConfirm&&!this.getBareMode()}getMemoryAgentTimeoutMinutes(){return this.memoryAgentTimeoutMinutes}getMemoryAgentMaxTurns(){return this.memoryAgentMaxTurns}getPreventSystemSleepEnabled(){return this.preventSystemSleep&&!this.isSafeMode()}getMemoryManager(){return this.memoryManager}getMessageBus(){return this.messageBus}setMessageBus(messageBus){if(this.messageBus===messageBus){return}this.messageBus=messageBus;this.announceMessageBus(messageBus)}onMessageBusChange(listener){this.messageBusListeners.add(listener);if(this.messageBus){this.notifyMessageBusListener(listener,this.messageBus)}return()=>{this.messageBusListeners.delete(listener)}}notifyMessageBusListener(listener,bus){try{const result=listener(bus);if(result instanceof Promise){result.catch(error3=>{this.debugLogger.debug(`MessageBus observer failed: ${error3}`)})}}catch(error3){this.debugLogger.debug(`MessageBus observer failed: ${error3}`)}}announceMessageBus(bus){for(const listener of[...this.messageBusListeners]){this.notifyMessageBusListener(listener,bus)}}getProjectHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}if(!this.isTrustedFolder()){return void 0}const hooks=this.projectHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getUserHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}const hooks=this.userHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getSystemHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}return this.systemHooks}hasScopedHooks(){return this.systemHooks!==void 0||this.userHooks!==void 0||this.projectHooks!==void 0}setHooksFromSettings(hooks){this.systemHooks=hooks.systemHooks;this.userHooks=hooks.userHooks;this.projectHooks=hooks.projectHooks;this.hooks=hooks.hooks}getExtensions(){if(this.shellExecutionSandbox)return[];const extensions=this.extensionManager.getLoadedExtensions();if(this.overrideExtensions){const overrideExtensionNames=new Set(this.overrideExtensions.map(name=>name.toLowerCase()));return extensions.filter(e=>overrideExtensionNames.has(e.name.toLowerCase()))}else{return extensions}}getActiveExtensions(){return this.getExtensions().filter(e=>e.isActive)}getBlockedMcpServers(){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}const blockedMcpServers=[];if(this.allowedMcpServers){Object.entries(mcpServers).forEach(([key,server])=>{const isAllowed=matchesAnyServerPattern(key,this.allowedMcpServers);if(!isAllowed){blockedMcpServers.push({name:key,extensionName:server.extensionName||""})}})}return blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!shouldAttemptBrowserLaunch()}getIdeMode(){return!this.shellExecutionSandbox&&this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()||this.isSafeMode()?[]:this.allowedHttpHookUrls}getAllowPrivateNetworkHooks(){return this.getBareMode()||this.isSafeMode()?false:this.allowPrivateNetworkHooks}isTrustedFolder(){const context2=ideContextStore.get();if(context2?.workspaceState?.isTrusted!==void 0){return context2.workspaceState.isTrusted}return this.trustedFolder??!this.folderTrust}setIdeMode(value){if(this.shellExecutionSandbox&&value)throw new Error("Tool execution sandbox does not support IDE integration.");this.ideMode=value}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(fileSystemService){if(this.shellExecutionSandbox){throw new Error("Internal sandbox does not support delegated filesystem services.")}this.fileSystemService=fileSystemService}getChatCompression(){return this.chatCompression}getAutoCompactThreshold(){const threshold=this.autoCompactThreshold;if(typeof threshold==="number"&&threshold>0&&threshold<=1){return threshold}return void 0}isInteractive(){return this.interactive}async getTerminalImageRenderSupport(){return this.terminalImageRenderSupportProvider?this.terminalImageRenderSupportProvider():{available:false,reason:"No terminal image renderer is configured."}}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(config3){this.shellExecutionConfig={terminalWidth:config3.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:config3.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:config3.showColor??this.shellExecutionConfig.showColor,pager:Object.prototype.hasOwnProperty.call(config3,"pager")?config3.pager:this.shellExecutionConfig.pager,maxBufferedOutputBytes:config3.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??false}getSkipLoopDetection(){return this.skipLoopDetection}getMaxToolCallsPerTurn(){if(this.maxToolCallsPerTurn<=0){return Number.POSITIVE_INFINITY}return this.maxToolCallsPerTurn}isMaxToolCallsPerTurnExplicit(){return this.maxToolCallsPerTurnExplicit}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}isSafeMode(){return this.safeMode}getTruncateToolOutputThreshold(){if(this.truncateToolOutputThreshold<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputThreshold}isTruncateToolOutputThresholdExplicit(){return this.truncateToolOutputThresholdExplicit}getTruncateToolOutputLines(){if(this.truncateToolOutputLines<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputLines}getShellDefaultTimeoutMs(){return this.shellDefaultTimeoutMs}getShellHeartbeatIntervalMs(){return this.shellHeartbeatIntervalMs}getToolOutputBatchBudget(){if(this.toolOutputBatchBudget<=0){return Number.POSITIVE_INFINITY}return this.toolOutputBatchBudget}trackToolResultBytes(n){this.toolResultBudget.bytesWritten+=n}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(!this.chatRecordingEnabled){return void 0}if(!this.chatRecordingService){this.chatRecordingService=this.createChatRecordingService()}return this.chatRecordingService}getGoalRuntime(){if(!Object.hasOwn(this,"goalRuntime")||!this.chatRecordingEnabled||!this.chatRecordingService||!this.goalRuntime){throw new GoalPersistenceUnavailableError}return this.goalRuntime}async getGoalRuntimeReady(){const runtime=this.getGoalRuntime();if(!Object.hasOwn(this,"goalRuntimeReady")||!this.goalRuntimeReady){throw new GoalPersistenceUnavailableError}return this.goalRuntimeReady.then(()=>runtime)}async getGoalRuntimePrepared(){const runtime=this.getGoalRuntime();if(!this.sessionRestoreRuntime)return this.getGoalRuntimeReady();return runtime.getPreparedRestore().then(()=>runtime)}async rebaseGoalRuntimeFromActiveTranscript(){const runtime=this.getGoalRuntime();const recordingService=this.chatRecordingService;if(!recordingService){throw new GoalPersistenceUnavailableError}const records=await recordingService.readActiveTranscriptChain();this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;runtime.dispose();this.initializeGoalRuntime(records);await this.goalRuntimeReady}bindGoalTurnHost(host){if(!Object.hasOwn(this,"goalRuntime")){throw new GoalPersistenceUnavailableError}const generation=this.goalTurnHostGeneration+1;this.goalTurnHostGeneration=generation;this.goalTurnHostUnbind?.();this.goalTurnHost=host;this.goalTurnHostUnbind=this.goalRuntime?.bindHost(host);return()=>{if(this.goalTurnHostGeneration!==generation||this.goalTurnHost!==host){return}this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalTurnHost=void 0}}onChatRecordingFailure(listener){this.chatRecordingFailureListeners.add(listener);return()=>{this.chatRecordingFailureListeners.delete(listener)}}onRequestLifecycle(listener){this.requestLifecycleListeners.add(listener);return()=>this.requestLifecycleListeners.delete(listener)}notifyRequestLifecycle(event){for(const listener of this.requestLifecycleListeners){try{listener(event)}catch(error3){this.debugLogger.warn("Request lifecycle listener failed:",error3)}}}createChatRecordingService(){return new ChatRecordingService(this,event=>{this.notifyChatRecordingFailure(event)},this.sessionWriterLeaseEnabled,this.sessionRestoreRuntime?.recording)}initializeGoalRuntime(records,restoreRuntime){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime replaced"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));this.goalProposalApprovalController?.abort();this.goalProposalApprovalController=void 0;this.pendingGoalProposal=void 0;if(!this.chatRecordingService){this.goalRuntime=void 0;this.goalRuntimeReady=void 0;return}const recorder=this.chatRecordingService;const runtime=createGoalRuntime({journal:recorder,evidenceSource:recorder,ledger:recorder,verifier:createGoalVerifier(this),tokenBudgetGrant:this.goalTokenBudgetGrant,turnBudgetGrant:this.goalTurnBudgetGrant,activeTimeBudgetGrantMs:this.goalActiveTimeBudgetGrantMs});runtime.subscribe((snapshot,cause,meta4)=>{if(meta4?.replayed)return;const event=goalStateEventFromSnapshot(snapshot,cause);if(event)logGoalState(this,event)});this.goalRuntime=runtime;if(this.goalTurnHost){this.goalTurnHostUnbind=runtime.bindHost(this.goalTurnHost)}if(restoreRuntime){const preparation=runtime.prepareRestore(records??[]);let resolveActivation;let rejectActivation;const activation=new Promise((resolve34,reject)=>{resolveActivation=resolve34;rejectActivation=reject});this.rejectGoalRestoreActivation=rejectActivation;this.goalRestoreActivation=()=>{const started=runtime.activateRestoredWork();void started.then(resolveActivation,rejectActivation);return started};this.goalRuntimeReady=Promise.all([preparation,activation]).then(()=>runtime)}else if(this.sessionWriterLeaseEnabled&&!recorder.hasWriteOwnership()){const ready=new Promise((resolve34,reject)=>{this.pendingGoalRestore={runtime,resolve:resolve34,reject}});this.goalRuntimeReady=ready}else{this.goalRuntimeReady=runtime.restore(records??[]).then(()=>runtime)}void this.goalRuntimeReady.catch(()=>void 0)}startPendingGoalRestore(){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;if(pending.runtime!==this.goalRuntime){pending.reject(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));return}void pending.runtime.restore(this.sessionData?.conversation.messages??[]).then(()=>pending.resolve(pending.runtime),error3=>pending.reject(error3))}settlePendingGoalRestore(error3){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;pending.reject(error3)}setSessionRestoreProjection(projection){this.pendingSessionRestoreProjection=projection;this.sessionRestoreRuntime=projection?.runtime;this.restoredFileHistory=false}clearSessionRestoreProjection(){this.pendingSessionRestoreProjection=void 0;this.sessionRestoreRuntime=void 0;this.restoredFileHistory=false;this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Session restore was abandoned"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0}notifyChatRecordingFailure(event){for(const listener of[...this.chatRecordingFailureListeners]){try{const notification=listener(event);if(notification){void notification.catch(error3=>{this.debugLogger.debug("Chat recording failure listener rejected:",error3)})}}catch(error3){this.debugLogger.debug("Chat recording failure listener threw:",error3)}}}getTranscriptPath(){if(!this.chatRecordingEnabled){return""}const projectDir=this.storage.getProjectDir();const sessionId=this.getSessionId();const safeFilename=`${sessionId}.jsonl`;return path81.join(projectDir,"chats",safeFilename)}async assertCanStartTurn(){if(isDerivedConfig(this))return;if(this.chatRecordingService?.hasWriteOwnership()){await this.chatRecordingService.assertCanStartTurn()}}hasSessionWriteOwnership(){if(isDerivedConfig(this))return false;return this.pendingSessionWriterLease!==void 0&&!this.pendingSessionWriterLease.isReleased||this.chatRecordingService?.hasWriteOwnership()===true}setSessionWriterReclaimPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterReclaimPolicy=policy}setSessionWriterTakeoverPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterTakeoverPolicy=policy}closeSessionWriter(options2){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(options2?.handoff&&this.sessionWriterTakeoverPolicy==="certified"){this.sessionWriterHandoffRequested=true}this.sessionWriterShutdownRequested=true;this.chatRecordingService?.beginClose({handoff:this.sessionWriterHandoffRequested});this.startPendingSessionWriterRelease();if(this.sessionWriterClosePromise)return this.sessionWriterClosePromise;const pending=this.closeSessionWriterOnce();this.sessionWriterClosePromise=pending;void pending.catch(()=>{if(this.sessionWriterClosePromise===pending){this.sessionWriterClosePromise=void 0}});return pending}async closeSessionWriterOnce(){const failures=[];const activation=this.sessionWriterActivationPromise;try{await activation}catch(error3){if(!(error3 instanceof SessionWriterShutdownError)){failures.push(error3)}}try{await this.chatRecordingService?.close({handoff:this.sessionWriterHandoffRequested})}catch(error3){failures.push(error3)}const pendingLease=activation?void 0:this.pendingSessionWriterLease;if(pendingLease){try{await this.startPendingSessionWriterRelease(pendingLease);if(this.pendingSessionWriterLease===pendingLease&&pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}}catch(error3){if(error3 instanceof SessionWriterLostError||pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}failures.push(error3)}finally{if(this.pendingSessionWriterRelease?.lease===pendingLease){this.pendingSessionWriterRelease=void 0}}}if(failures.length===1){throw failures[0]}if(failures.length>1){throw new AggregateError(failures,"Session writer shutdown failed")}}startPendingSessionWriterRelease(lease=this.pendingSessionWriterLease){if(!lease)return void 0;const existing=this.pendingSessionWriterRelease;if(existing?.lease===lease)return existing.promise;if(this.sessionExecutionEngine==="managed")return void 0;const promise=lease.release();this.pendingSessionWriterRelease={lease,promise};void promise.catch(()=>void 0);return promise}getSessionRuntimeBaseDir(){return this.sessionRuntimeBaseDir}getSessionService(){if(!this.sessionService){this.sessionService=new SessionService(this.storage.getProjectRoot(),{runtimeBaseDir:this.sessionRuntimeBaseDir})}return this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){if(!this.backgroundAgentResumeService){this.backgroundAgentResumeService=new BackgroundAgentResumeService(this)}return this.backgroundAgentResumeService}async loadPausedBackgroundAgents(sessionId=this.getSessionId()){if(sessionId!==this.getSessionId()){this.debugLogger.warn(`Refusing to restore background agents for non-current session ${sessionId}.`);return[]}const service=this.getBackgroundAgentResumeService();let recovered;try{recovered=await service.loadPausedBackgroundAgents(sessionId)}catch(error3){this.debugLogger.warn(`Background agent restore failed for session ${sessionId}; continuing without restored agents.`,error3);return[]}if(recovered.length>0&&!this.getBareMode()){this.pendingRecoveredAgentsNotice=service.buildRecoveredBackgroundAgentsModelNotice(recovered.length)}return recovered}consumePendingRecoveredAgentsNotice(){const notice=this.pendingRecoveredAgentsNotice;this.pendingRecoveredAgentsNotice=null;return notice}async resumeBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().resumeBackgroundAgent(agentId,initialInput)}async reviveCompletedBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().reviveCompletedBackgroundAgent(agentId,initialInput)}abandonBackgroundAgent(agentId){return this.getBackgroundAgentResumeService().abandonBackgroundAgent(agentId)}getBackgroundShellRegistry(){return this.backgroundShellRegistry}getWorkflowRunRegistry(){return this.workflowRunRegistry}getTurnBudget(){return this.turnBudget}getFileReadCache(){if(!Object.prototype.hasOwnProperty.call(this,"fileReadCache")){this.fileReadCache=new FileReadCache}return this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return false}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(provider){this.modelInvocableCommandsProvider=provider}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(executor){this.modelInvocableCommandsExecutor=executor}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(keys){for(const k2 of keys){this.pendingInlineAnnouncedSkillKeys.add(k2)}}consumeInlineAnnouncedSkillKeys(){const result=this.pendingInlineAnnouncedSkillKeys;this.pendingInlineAnnouncedSkillKeys=new Set;return result}getPermissionManager(){return this.permissionManager}isWorkspaceAgentSession(){return this.isAgentCollaborationEnabled()&&this.sessionSourceType==="agent"}getWorkflowAncestorTrustProvider(){return this.workflowAncestorTrustProvider}getToolInvocationGuard(){if(this.sessionSourceType==="agent-host"){return createAgentHostToolInvocationGuard(this.toolInvocationGuard,this.getTargetDir(),candidate=>this.getWorkspaceContext().isPathWithinWorkspace(candidate))}if(this.isWorkspaceAgentSession()&&this.isSessionAgentSession()){return createSessionAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools,this.workspaceAgentDisallowedTools)}return this.isWorkspaceAgentSession()?createAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools):this.toolInvocationGuard}getShellExecutionSandbox(){return this.shellExecutionSandbox}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}async registerLazyTool(registry3,toolName,factory){let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(toolName):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${toolName}", skipping registration:`,error3);return}if(status==="deferred"){registry3.registerPermissionDeferredFactory(toolName,factory)}else if(status==="registered"){registry3.registerFactory(toolName,factory)}}async registerManagedRuntimeTools(registry3){const environment=this.getManagedRuntimeEnvironment();if(!environment)return;const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-4LDKFNC4.js"),import("./execution-tool-P7CBXSGZ.js")]);const tools=createExecutionTools(this);for(const name of MANAGED_RUNTIME_TOOL_NAMES){const tool=tools.get(name);if(!tool)continue;let status;try{status=await this.getPermissionManager()?.getToolRegistrationStatus(name)??"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${name}", skipping registration:`,error3);continue}if(status==="disabled")continue;registry3.registerRuntimeBackedFactory(name,async()=>wrapExecutionTool(tool,environment,this),environment,status==="deferred")}}async registerWorkflowTool(registry3){if(registry3.getAllToolNames().includes(ToolNames.WORKFLOW))return true;await this.registerLazyTool(registry3,ToolNames.WORKFLOW,async()=>{const{WorkflowTool}=await import("./workflow-UQ4V3NBZ.js");return new WorkflowTool(this)});return registry3.getAllToolNames().includes(ToolNames.WORKFLOW)}async registerImageGenerationTool(registry3){if(!this.isImageGenerationEnabled()||registry3.getAllToolNames().includes(ToolNames.IMAGE_GEN)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.IMAGE_GEN):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.IMAGE_GEN}", skipping registration:`,error3);return}if(status==="disabled")return;const factory=__name(async()=>{const{ImageGenTool}=await import("./image-gen-F5BMNMYK.js");return new ImageGenTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.IMAGE_GEN,factory)}else{registry3.registerFactory(ToolNames.IMAGE_GEN,factory)}}async syncAdvisorToolRegistration(registry3){if(!this.getAdvisorModel()||this.getBareMode()||this.isSafeMode()){registry3.unregisterTool(ToolNames.ADVISOR);return}if(this.getDisabledTools().has(ToolNames.ADVISOR))return;registry3.unregisterTool(ToolNames.ADVISOR);await this.registerLazyTool(registry3,ToolNames.ADVISOR,async()=>{const{AdvisorTool}=await import("./advisor-GCH2MBXT.js");return new AdvisorTool(this)});await registry3.ensureTool(ToolNames.ADVISOR)}async registerSessionSourceTool(registry3=this.toolRegistry){if(!this.getSessionSourceService()||this.sdkMode||this.getBareMode()||this.isSafeMode()||registry3.getAllToolNames().includes(ToolNames.RECORD_SOURCE)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.RECORD_SOURCE):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.RECORD_SOURCE}", skipping registration:`,error3);return}const factory=__name(async()=>{const{RecordSourceTool}=await import("./record-source-S2552VVB.js");return new RecordSourceTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.RECORD_SOURCE,factory)}else if(status==="registered"){registry3.registerFactory(ToolNames.RECORD_SOURCE,factory)}}async createToolRegistry(sendSdkMcpMessage,options2){const registry3=new ToolRegistry(this,this.eventEmitter,sendSdkMcpMessage);if(this.sessionExecutionEngine==="managed"){this.applyPendingMcpBudgetCallback(registry3);await this.registerManagedRuntimeTools(registry3);return registry3}const registerLazy=__name((toolName,factory)=>this.registerLazyTool(registry3,toolName,factory),"registerLazy");const registerStructuredOutputIfRequested=__name(async()=>{if(!this.jsonSchema)return;if(options2?.forSubAgent)return;const schema=this.jsonSchema;await registerLazy(ToolNames.STRUCTURED_OUTPUT,async()=>{const{SyntheticOutputTool}=await import("./syntheticOutput-IETGBFDA.js");return new SyntheticOutputTool(schema)})},"registerStructuredOutputIfRequested");const registerGoalWorkerTools=__name(async()=>{if(options2?.forSubAgent)return;await registerLazy(ToolNames.GET_GOAL,async()=>{const{GetGoalTool:GetGoalTool2}=await import("./goal-tools-K6XBCE5E.js");return new GetGoalTool2(this)});await registerLazy(ToolNames.UPDATE_GOAL,async()=>{const{UpdateGoalTool:UpdateGoalTool2}=await import("./goal-tools-K6XBCE5E.js");return new UpdateGoalTool2(this)});if(this.getModelProposedGoals()!=="disabled"&&(resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported)){await registerLazy(ToolNames.PROPOSE_GOAL,async()=>{const{ProposeGoalTool:ProposeGoalTool2}=await import("./goal-tools-K6XBCE5E.js");return new ProposeGoalTool2(this)})}},"registerGoalWorkerTools");const registerExecIfEnabled=__name(async()=>{if(this.getToolMode()!==ToolMode.CodeModeOnly)return;await registerLazy(ToolNames.EXEC,async()=>{const{ExecTool}=await import("./exec-KO2K3GTK.js");return new ExecTool(this)})},"registerExecIfEnabled");const registerHostSessionTools=__name(async()=>{if(this.isTodoWriteEnabled()){await registerLazy(ToolNames.TODO_WRITE,async()=>{const{TodoWriteTool}=await import("./todoWrite-U2EPDDWF.js");return new TodoWriteTool(this)})}await registerLazy(ToolNames.WEB_FETCH,async()=>{const{WebFetchTool}=await import("./web-fetch-UPMJ3XIZ.js");return new WebFetchTool(this)});const hasExplicitWebSearchBackend=!!this.webSearchSettings?.model?.trim()||!!this.webSearchSettings?.baseUrl;if(!this.getBareMode()&&!this.isSafeMode()&&this.webSearchSettings?.enabled!==false&&(this.webSearchSettings?.enabled===true||!hasExplicitWebSearchBackend)){const{evaluateWebSearchGate}=await import("./web-search-PXABWQVC.js");const gate=evaluateWebSearchGate(this);if(gate.ok){await registerLazy(ToolNames.WEB_SEARCH,async()=>{const{WebSearchTool}=await import("./web-search-PXABWQVC.js");return new WebSearchTool(this)})}else if(!gate.silent&&!this.webSearchNoticeEmitted&&!options2?.forSubAgent){this.webSearchNoticeEmitted=true;this.warnings.push(gate.notice)}}},"registerHostSessionTools");const environment=this.getExecutionEnvironment();if(environment){if(this.getCodeModeOnly()){throw new Error("Container execution cannot be combined with tools.codeModeOnly.")}const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-4LDKFNC4.js"),import("./execution-tool-P7CBXSGZ.js")]);for(const[name,tool]of createExecutionTools(this)){if(environment.toolNames&&!environment.toolNames.has(name))continue;if(name===ToolNames.LS&&!this.isLsToolEnabled())continue;await registerLazy(name,async()=>wrapExecutionTool(tool,environment,this))}await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-XG4CAD5X.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-KBINGEWV.js");return new ToolSearchTool(this)});if(this.executionEnvironment&&!options2?.forSubAgent){await registerStructuredOutputIfRequested();await registerGoalWorkerTools();if(!this.getBareMode())await registerHostSessionTools()}return registry3}if(this.shellExecutionSandbox){await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-A7NLPS2W.js");return new ShellTool2(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-WMSWQFRF.js");return new TaskStopTool(this)});await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-OJNGPNTQ.js");return new ReadFileTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-FDBR76G5.js");return new WriteFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-7YBQLILC.js");return new EditTool(this)});await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool}=await import("./monitor-ZHOFTN7N.js");return new MonitorTool(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-57T4YAYP.js");return new AgentTool2(this)});await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-RH7XXSYE.js");return new GlobTool(this)});await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-V7A2PC3T.js");return new LSTool(this)});if(resolveInteractionMode(this)!=="headless"){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-B5E4RG6M.js");return new AskUserQuestionTool2(this)})}await registerExecIfEnabled();await registerStructuredOutputIfRequested();return registry3}if(this.getBareMode()){await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-OJNGPNTQ.js");return new ReadFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-7YBQLILC.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-ETUOQH6G.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-A7NLPS2W.js");return new ShellTool2(this)});await registerGoalWorkerTools();await registerStructuredOutputIfRequested();await registerExecIfEnabled();this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}await registerHostSessionTools();await registerExecIfEnabled();await registerGoalWorkerTools();await this.syncAdvisorToolRegistration(registry3);await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-XG4CAD5X.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-KBINGEWV.js");return new ToolSearchTool(this)});await registerLazy(ToolNames.READ_MCP_RESOURCE,async()=>{const{ReadMcpResourceTool}=await import("./read-mcp-resource-ANPZBEC4.js");return new ReadMcpResourceTool(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-57T4YAYP.js");return new AgentTool2(this)});await registerLazy(ToolNames.LIST_AGENTS,async()=>{const{ListAgentsTool}=await import("./list-agents-5Z7ZEBYP.js");return new ListAgentsTool(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-WMSWQFRF.js");return new TaskStopTool(this)});await registerLazy(ToolNames.SEND_MESSAGE,async()=>{const{SendMessageTool}=await import("./send-message-OZCCCH2F.js");return new SendMessageTool(this)});if(!options2?.forSubAgent||this.getSkillManager()){await registerLazy(ToolNames.SKILL,async()=>{const{SkillTool}=await import("./skill-VGANGVOD.js");return new SkillTool(this)})}if(this.isLsToolEnabled()){await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-V7A2PC3T.js");return new LSTool(this)})}await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-OJNGPNTQ.js");return new ReadFileTool(this)});await registerLazy(ToolNames.MANAGE_MEMORY,async()=>{const{ManageMemoryTool}=await import("./manage-memory-2ZTIVKNU.js");return new ManageMemoryTool(this)});await registerLazy(ToolNames.SEARCH_MEMORY,async()=>{const{SearchMemoryTool}=await import("./search-memory-HX6E23JC.js");return new SearchMemoryTool(this)});await registerLazy(ToolNames.ZOOM_IMAGE,async()=>{const{ZoomImageTool}=await import("./zoom-image-MYKWCCXO.js");return new ZoomImageTool(this)});if(this.getUseRipgrep()){let useRipgrep=false;let errorString=void 0;recordStartupEvent("config_initialize_ripgrep_probe_start");try{useRipgrep=await canUseRipgrep(this.getUseBuiltinRipgrep())}catch(error3){errorString=getErrorMessage(error3)}recordStartupEvent("config_initialize_ripgrep_probe_end");if(useRipgrep){await registerLazy(ToolNames.GREP,async()=>{const{RipGrepTool}=await import("./ripGrep-Y4PY2MQF.js");return new RipGrepTool(this)})}else{logRipgrepFallback(this,new RipgrepFallbackEvent(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),errorString||"ripgrep is not available"));await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-6ACG2X2D.js");return new GrepTool(this)})}}else{recordStartupEvent("config_initialize_ripgrep_probe_start");recordStartupEvent("config_initialize_ripgrep_probe_end");await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-6ACG2X2D.js");return new GrepTool(this)})}await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-RH7XXSYE.js");return new GlobTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-7YBQLILC.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-ETUOQH6G.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-FDBR76G5.js");return new WriteFileTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-A7NLPS2W.js");return new ShellTool2(this)});await registerLazy(ToolNames.REPORT_FINDINGS,async()=>{const{ReportFindingsTool}=await import("./report-findings-67OAIS2F.js");return new ReportFindingsTool});const supportsUserInteraction=resolveInteractionMode(this)!=="headless";if(supportsUserInteraction){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-B5E4RG6M.js");return new AskUserQuestionTool2(this)})}if(!this.sdkMode&&(supportsUserInteraction||options2?.forSubAgent)){await registerLazy(ToolNames.EXIT_PLAN_MODE,async()=>{const{ExitPlanModeTool:ExitPlanModeTool2}=await import("./exitPlanMode-MBUTM3NW.js");return new ExitPlanModeTool2(this)})}if(!this.sdkMode&&supportsUserInteraction){await registerLazy(ToolNames.ENTER_PLAN_MODE,async()=>{const{EnterPlanModeTool}=await import("./enterPlanMode-L3PVSD2P.js");return new EnterPlanModeTool(this)})}await registerLazy(ToolNames.ENTER_WORKTREE,async()=>{const{EnterWorktreeTool}=await import("./enter-worktree-OYEYIBHG.js");return new EnterWorktreeTool(this)});await registerLazy(ToolNames.EXIT_WORKTREE,async()=>{const{ExitWorktreeTool}=await import("./exit-worktree-XGLOXMHT.js");return new ExitWorktreeTool(this)});if(resolveInteractionMode(this)==="interactive"&&!this.sdkMode&&!this.getScreenReader()&&!options2?.forSubAgent){await registerLazy(ToolNames.DISPLAY_IMAGE,async()=>{const{DisplayImageTool}=await import("./display-image-D7L3HAX2.js");return new DisplayImageTool(this)})}await this.registerImageGenerationTool(registry3);if(this.isArtifactEnabled()){await registerLazy(ToolNames.ARTIFACT,async()=>{const{ArtifactTool}=await import("./artifact-tool-C7SXUVAD.js");return new ArtifactTool(this)})}if(!options2?.forSubAgent){await this.registerSessionSourceTool(registry3)}if(this.isRecordArtifactEnabled()){await registerLazy(ToolNames.RECORD_ARTIFACT,async()=>{const{RecordArtifactTool}=await import("./record-artifact-B5ZMCBZR.js");return new RecordArtifactTool(this)})}if(this.isLspEnabled()&&this.getLspClient()){await registerLazy(ToolNames.LSP,async()=>{const{LspTool}=await import("./lsp-KC7CEAXE.js");return new LspTool(this)})}await registerStructuredOutputIfRequested();if(this.isCronEnabled()){await registerLazy(ToolNames.CRON_CREATE,async()=>{const{CronCreateTool}=await import("./cron-create-CFCMKKF6.js");return new CronCreateTool(this)});await registerLazy(ToolNames.CRON_LIST,async()=>{const{CronListTool}=await import("./cron-list-3NXRSQKN.js");return new CronListTool(this)});await registerLazy(ToolNames.CRON_DELETE,async()=>{const{CronDeleteTool}=await import("./cron-delete-5QRFSNES.js");return new CronDeleteTool(this)});await registerLazy(ToolNames.LOOP_WAKEUP,async()=>{const{LoopWakeupTool}=await import("./loop-wakeup-R3MS4W4A.js");return new LoopWakeupTool(this)})}if(this.getSubSessionSpawner()){await registerLazy(ToolNames.CREATE_SUB_SESSION,async()=>{const{CreateSubSessionTool}=await import("./create-sub-session-6IRYZOGY.js");return new CreateSubSessionTool(this)})}if(this.isAgentTeamEnabled()){await registerLazy(ToolNames.TEAM_CREATE,async()=>{const{TeamCreateTool}=await import("./team-create-5MU6BGXX.js");return new TeamCreateTool(this)});await registerLazy(ToolNames.TEAM_DELETE,async()=>{const{TeamDeleteTool}=await import("./team-delete-LVJPX4CM.js");return new TeamDeleteTool(this)});await registerLazy(ToolNames.TEAM_PLAN_APPROVAL,async()=>{const{TeamPlanApprovalTool}=await import("./team-plan-approval-NZUJ6FSA.js");return new TeamPlanApprovalTool(this)});if(!options2?.forSubAgent){await registerLazy(ToolNames.REQUEST_SHUTDOWN,async()=>{const{RequestShutdownTool}=await import("./request-shutdown-VJPXPFRB.js");return new RequestShutdownTool(this)})}await registerLazy(ToolNames.TASK_CREATE,async()=>{const{TaskCreateTool}=await import("./task-create-2BNUK636.js");return new TaskCreateTool(this)});await registerLazy(ToolNames.TASK_UPDATE,async()=>{const{TaskUpdateTool}=await import("./task-update-YNIRBBU7.js");return new TaskUpdateTool(this)});await registerLazy(ToolNames.TASK_LIST,async()=>{const{TaskListTool}=await import("./task-list-UQKC23DG.js");return new TaskListTool(this)})}if(this.isWorkflowsEnabled()){await this.registerWorkflowTool(registry3)}if(this.isOmniEnabled()){const omniPolicyToolFactories=[[ToolNames.OMNI_DOWNSAMPLE_IMAGE,async()=>new(await import("./downsample-image-Y6BWJFSA.js")).OmniDownsampleImageTool(this)],[ToolNames.OMNI_DOWNSCALE_VIDEO,async()=>new(await import("./downscale-video-WEUPQZUG.js")).OmniDownscaleVideoTool(this)],[ToolNames.OMNI_DOWNSAMPLE_AUDIO,async()=>new(await import("./downsample-audio-KA3MINGD.js")).OmniDownsampleAudioTool(this)],[ToolNames.OMNI_EXTRACT_KEYFRAMES,async()=>new(await import("./extract-keyframes-VLHSMGTR.js")).OmniExtractKeyframesTool(this)],[ToolNames.OMNI_EXTRACT_AUDIO,async()=>new(await import("./extract-audio-YQDXPJLW.js")).OmniExtractAudioTool(this)],[ToolNames.OMNI_CLIP_VIDEO,async()=>new(await import("./clip-video-4FXV4BGI.js")).OmniClipVideoTool(this)],[ToolNames.OMNI_CONVERT_IMAGE,async()=>new(await import("./convert-image-JI2ICEFQ.js")).OmniConvertImageTool(this)],[ToolNames.OMNI_TRANSCRIBE_AUDIO,async()=>new(await import("./transcribe-audio-PAEN23DB.js")).OmniTranscribeAudioTool(this)],[ToolNames.OMNI_CLIP_IMAGE,async()=>new(await import("./clip-image-X5W3KSTA.js")).OmniClipImageTool(this)],[ToolNames.OMNI_CLIP_AUDIO,async()=>new(await import("./clip-audio-6YBATJFU.js")).OmniClipAudioTool(this)],[ToolNames.OMNI_CAPTION_IMAGE,async()=>new(await import("./caption-image-5NODVPQP.js")).OmniCaptionImageTool(this)],[ToolNames.OMNI_CAPTION_AUDIO,async()=>new(await import("./caption-audio-FSHF5JWX.js")).OmniCaptionAudioTool(this)],[ToolNames.OMNI_OCR_IMAGE,async()=>new(await import("./ocr-image-76FNJ7ZC.js")).OmniOcrImageTool(this)],[ToolNames.OMNI_UNDERSTAND_VIDEO_SEGMENTS,async()=>new(await import("./understand-video-segments-CEHQZNK3.js")).OmniUnderstandVideoSegmentsTool(this)]];for(const[name,factory]of omniPolicyToolFactories){await registerLazy(name,factory)}const memoryConfig=await this.ensureOmniMemoryConfig();if(memoryConfig.recall.mode==="active"){await registerLazy(ToolNames.OMNI_RECALL_MEDIA_MEMORY,async()=>{const{OmniRecallMediaMemoryTool}=await import("./recall-media-memory-tool-DSUGPS7U.js");return new OmniRecallMediaMemoryTool(this)})}}await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool}=await import("./monitor-ZHOFTN7N.js");return new MonitorTool(this)});this.applyPendingMcpBudgetCallback(registry3);if(!options2?.skipDiscovery){await registry3.discoverAllTools()}this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}applyPendingMcpBudgetCallback(registry3){if(!this.pendingMcpBudgetCallback)return;const mgr=registry3.getMcpClientManager();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(this.pendingMcpBudgetCallback)}this.pendingMcpBudgetCallback=void 0}setMcpBudgetEventCallback(cb){if(this.toolRegistry){const mgr=this.toolRegistry.getMcpClientManager?.();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(cb)}this.pendingMcpBudgetCallback=void 0;return}this.pendingMcpBudgetCallback=cb}subSessionSpawner;currentSessionScheduledTaskCreator;setSubSessionSpawner(spawner){this.subSessionSpawner=spawner}getSubSessionSpawner(){return this.subSessionSpawner}setCurrentSessionScheduledTaskCreator(creator){this.currentSessionScheduledTaskCreator=creator}getCurrentSessionScheduledTaskCreator(){return this.currentSessionScheduledTaskCreator}};function installSessionWorkflowRevisionWriteThrough(wrapper,base2){const ov=wrapper;ov.setSessionWorkflowPlanRevision=revision=>{base2.setSessionWorkflowPlanRevision(revision)};ov.clearSessionWorkflowPlanRevision=()=>{base2.clearSessionWorkflowPlanRevision()}}__name(installSessionWorkflowRevisionWriteThrough,"installSessionWorkflowRevisionWriteThrough");var debugLogger118=createDebugLogger("EXIT_PLAN_MODE");var exitPlanModeToolDescription=`Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.
|
|
2110
2110
|
|
|
2111
2111
|
## When to Use This Tool
|
|
2112
2112
|
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
|