@qwen-code/qwen-code 0.27.2-preview.0 → 0.27.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
- package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
- package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
- package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
- package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
- package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
- package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
- package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
- package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
- package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
- package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
- package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
- package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
- package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
- package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
- package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
- package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
- package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
- package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
- package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
- package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
- package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
- package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
- package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
- package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
- package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
- package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
- package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
- package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
- package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
- package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
- package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
- package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
- package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
- package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
- package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
- package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
- package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
- package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
- package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
- package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
- package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
- package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
- package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
- package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
- package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
- package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
- package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
- package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
- package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
- package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
- package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
- package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
- package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
- package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
- package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
- package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
- package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
- package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
- package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
- package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
- package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
- package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
- package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
- package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
- package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
- package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
- package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
- package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
- package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
- package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
- package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
- package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
- package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
- package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
- package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
- package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
- package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
- package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
- package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
- package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
- package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
- package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
- package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
- package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
- package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
- package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
- package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
- package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
- package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
- package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
- package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
- package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
- package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
- package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
- package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
- package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
- package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
- package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
- package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
- package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
- package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
- package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
- package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
- package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
- package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
- package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
- package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
- package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
- package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
- package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
- package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
- package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
- package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
- package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
- package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
- package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
- package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
- package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
- package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
- package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
- package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
- package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
- package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
- package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
- package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
- package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
- package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
- package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
- package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
- package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
- package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
- package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
- package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
- package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
- package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
- package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
- package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
- package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
- package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
- package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
- package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
- package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
- package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
- package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
- package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
- package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
- package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
- package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
- package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
- package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
- package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
- package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
- package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
- package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
- package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
- package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
- package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
- package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
- package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
- package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
- package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
- package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
- package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
- package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
- package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
- package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
- package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
- package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
- package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
- package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
- package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
- package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
- package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
- package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
- package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
- package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
- package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
- package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
- package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
- package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
- package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
- package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
- package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
- package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
- package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
- package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
- package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
- package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
- package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
- package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
- package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
- package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
- package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
- package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
- package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
- package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
- package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
- package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
- package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
- package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
- package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
- package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
- package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
- package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
- package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
- package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
- package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
- package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
- package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
- package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
- package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
- package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
- package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
- package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
- package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
- package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
- package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +3 -3
- package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
- package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
- package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
- package/web-shell/assets/channel-DtcoR96T.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
- package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
- package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
- package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
- package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
- package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
- package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
- package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-B31dxYCL.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-XUB4JKSR.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-HAALYXUJ.js";import{getMemoryBaseDir}from"./chunk-CQGP2BAW.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-LWVCLDHV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
|
|
3
|
+
import{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-3NR3JBMA.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-HAALYXUJ.js";import{getMemoryBaseDir}from"./chunk-CQGP2BAW.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-LWVCLDHV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-B7CYUTAO.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-4RGPHRL7.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-A4CHYJUQ.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-XUB4JKSR.js";import{backgroundFixHolding}from"./chunk-BPDVCOZ5.js";import{getCurrentAgentId}from"./chunk-WXQQVXYN.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-R5AA46IX.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-TQGZS3WN.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-5KGH76NL.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
3
|
+
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-AKDODQCI.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-4RGPHRL7.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-A4CHYJUQ.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-3NR3JBMA.js";import{backgroundFixHolding}from"./chunk-BPDVCOZ5.js";import{getCurrentAgentId}from"./chunk-WXQQVXYN.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-R5AA46IX.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-TQGZS3WN.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-5KGH76NL.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
4
4
|
|
|
5
5
|
${WRITE_FILE_ARTIFACT_DESCRIPTION}
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{AUTO_THEME_NAME,themeManager}from"./chunk-RWFZREYT.js";import{getSubscriptionStartupFallbackModel}from"./chunk-
|
|
3
|
+
import{AUTO_THEME_NAME,themeManager}from"./chunk-RWFZREYT.js";import{getSubscriptionStartupFallbackModel}from"./chunk-AEX3XSTE.js";import{initializeI18n,resolveLanguageSetting,t}from"./chunk-73TSS7KS.js";import{IdeClient}from"./chunk-3NR3JBMA.js";import{QwenSubscriptionSession,SubscriptionOAuthError,isSubscriptionSessionExpired,subscriptionErrorMessage,subscriptionModelUnavailable}from"./chunk-N3AKLLXG.js";import{AuthEvent,IdeConnectionEvent,logAuth,logIdeConnection}from"./chunk-R5AA46IX.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function performInitialAuth(config,authType,subscriptionFallbackModel,allowUnlistedSubscriptionModel){if(!authType){return null}if(authType==="qwen-subscription"&&!new QwenSubscriptionSession().isSignedIn())return null;try{await config.refreshAuth(authType,true,subscriptionFallbackModel,allowUnlistedSubscriptionModel);const authEvent=new AuthEvent(authType,"auto","success");logAuth(config,authEvent)}catch(e){if(authType==="qwen-subscription"&&isSubscriptionSessionExpired(e))return null;const errorMessage=e instanceof SubscriptionOAuthError?t(subscriptionErrorMessage(e)):`Failed to login. Message: ${getErrorMessage(e)}`;const authEvent=new AuthEvent(authType,"auto","error",errorMessage);logAuth(config,authEvent);return errorMessage}return null}__name(performInitialAuth,"performInitialAuth");init_esbuild_shims();function validateTheme(settings){const effectiveTheme=settings.merged.ui?.theme;if(effectiveTheme&&effectiveTheme!==AUTO_THEME_NAME&&!themeManager.findThemeByName(effectiveTheme)){return t('Theme "{{themeName}}" not found.',{themeName:effectiveTheme})}return null}__name(validateTheme,"validateTheme");async function connectIdeForStartup(config){if(!config.getIdeMode())return;const ideClient=await IdeClient.getInstance();await ideClient.connect();logIdeConnection(config,new IdeConnectionEvent("start"))}__name(connectIdeForStartup,"connectIdeForStartup");async function initializeApp(config,settings,options={}){await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const authType=config.getModelsConfig().getCurrentAuthType();const subscriptionFallbackModel=options.allowSubscriptionStartupFallback?getSubscriptionStartupFallbackModel(settings,authType,config):void 0;const authError=await performInitialAuth(config,authType,subscriptionFallbackModel,options.allowUnlistedSubscriptionModel&&Boolean(settings.merged.model?.name));const inactiveSubscription=authType==="qwen-subscription"&&!config.getAuthType();const authNotice=inactiveSubscription&&authError?.includes(subscriptionModelUnavailable(config.getModel()))?authError:void 0;const skipStartupAuthDialog=inactiveSubscription&&(authError===null||authNotice!==void 0);const themeError=validateTheme(settings);const shouldOpenAuthDialog=!config.getModelsConfig().wasAuthTypeExplicitlyProvided()||!!authError;if(!options.deferIdeConnection){await connectIdeForStartup(config)}return{authError,...authNotice?{authNotice}:{},...skipStartupAuthDialog?{skipStartupAuthDialog}:{},themeError,shouldOpenAuthDialog,memoryFileCount:config.getMemoryFileCount()}}__name(initializeApp,"initializeApp");export{connectIdeForStartup,initializeApp};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{HistoryReplayer,observeAcpToolResultProjection}from"./chunk-XB7DJWOJ.js";import{JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,truncateJsonStringPayload}from"./chunk-WQUA4G2X.js";import{isA2uiToolMeta}from"./chunk-BAPIZCC7.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-XUB4JKSR.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-6NQMNEZN.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var MAX_REMEMBER_ERROR_DETAILS_CHARS=1e3;var MAX_REMEMBER_ERROR_CAUSE_DEPTH=50;var REMEMBER_ERROR_FORMAT_RE=new RegExp("[\\p{Cf}]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_SPACE_SEPARATOR_RE=/[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE=new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE=new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])","giu");var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)","giu");var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+","gu");var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE=new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+","gu");var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","giu");var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","gu");var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE=new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@","giu");var REMEMBER_ERROR_CONTROL_RE=/[\x00-\x1f\x7f-\x9f]/g;var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES=new Set(["managed_memory_unavailable"]);function createWorkspaceMemoryExtractionErrorLogger(logger){return(target,err)=>{logger.warn(`Failed to extract workspace memory error ${target}:`,{extractionError:err instanceof Error?err.message:String(err)})}}__name(createWorkspaceMemoryExtractionErrorLogger,"createWorkspaceMemoryExtractionErrorLogger");function reportRememberErrorExtractionFailure(onExtractionError,target,err){try{onExtractionError?.(target,err)}catch{}}__name(reportRememberErrorExtractionFailure,"reportRememberErrorExtractionFailure");function errorCodeFromRecord(record){if(typeof record["code"]==="string")return record["code"];const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;if(typeof dataRecord["errorKind"]==="string"){return dataRecord["errorKind"]}if(typeof dataRecord["code"]==="string")return dataRecord["code"]}return void 0}__name(errorCodeFromRecord,"errorCodeFromRecord");function rawRememberErrorCode(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);const record=err;const direct=errorCodeFromRecord(record);if(direct)return direct;const cause=record["cause"];if(cause!=null){return rawRememberErrorCode(cause,seen,depth+1)}return void 0}__name(rawRememberErrorCode,"rawRememberErrorCode");function extractRememberErrorCode(err,fallback="remember_failed"){return rawRememberErrorCode(err,new WeakSet,0)??fallback}__name(extractRememberErrorCode,"extractRememberErrorCode");function workspaceMemoryFailureCode(err,fallback="remember_failed",onExtractionError){try{return extractRememberErrorCode(err,fallback)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"code",extractionErr);return fallback}}__name(workspaceMemoryFailureCode,"workspaceMemoryFailureCode");function detailFromRecord(record,seen,depth){const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;const details=dataRecord["details"];if(typeof details==="string"&&details.length>0)return details;const message2=dataRecord["message"];if(typeof message2==="string"&&message2.length>0)return message2}const message=record["message"];if(typeof message==="string"&&message.length>0)return message;if(typeof data==="string"&&data.length>0)return data;const cause=record["cause"];if(cause!=null){return rawRememberErrorDetails(cause,seen,depth+1)}return void 0}__name(detailFromRecord,"detailFromRecord");function rawRememberErrorDetails(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(typeof err==="string"&&err.length>0)return err;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);return detailFromRecord(err,seen,depth)}__name(rawRememberErrorDetails,"rawRememberErrorDetails");function replaceControlChars(details){return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE," ")}__name(replaceControlChars,"replaceControlChars");function replaceStackControlChars(stack){return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE,char=>char==="\n"||char==="\r"||char===" "?char:" ")}__name(replaceStackControlChars,"replaceStackControlChars");function collapseCredentialSeparators(text){return text.replace(REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,(_match,scheme,userinfo)=>`${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}@`).replace(REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,(_match,scheme,token)=>`${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`)}__name(collapseCredentialSeparators,"collapseCredentialSeparators");function collapseCredentialSeparatorsByStackLine(stack){return stack.split(/(\r\n|\n|\r)/).map(part=>part==="\r\n"||part==="\n"||part==="\r"?part:collapseCredentialSeparators(part)).join("")}__name(collapseCredentialSeparatorsByStackLine,"collapseCredentialSeparatorsByStackLine");function isHighSurrogate(codeUnit){return codeUnit>=55296&&codeUnit<=56319}__name(isHighSurrogate,"isHighSurrogate");function isLowSurrogate(codeUnit){return codeUnit>=56320&&codeUnit<=57343}__name(isLowSurrogate,"isLowSurrogate");function truncateBeforeDanglingSurrogate(details,cutPoint){const beforeCut=details.charCodeAt(cutPoint-1);const atCut=details.charCodeAt(cutPoint);if(isHighSurrogate(beforeCut)&&isLowSurrogate(atCut)){return cutPoint-1}return cutPoint}__name(truncateBeforeDanglingSurrogate,"truncateBeforeDanglingSurrogate");function capRememberErrorText(redacted){if(redacted.length<=MAX_REMEMBER_ERROR_DETAILS_CHARS)return redacted;const truncationSuffix="... [truncated]";const cutPoint=truncateBeforeDanglingSurrogate(redacted,MAX_REMEMBER_ERROR_DETAILS_CHARS-truncationSuffix.length);return`${redacted.slice(0,cutPoint)}${truncationSuffix}`}__name(capRememberErrorText,"capRememberErrorText");function redactAndCapRememberErrorText(normalized){const redacted=redactLogCredentials(normalized).trim();if(!redacted)return void 0;return capRememberErrorText(redacted)}__name(redactAndCapRememberErrorText,"redactAndCapRememberErrorText");function sanitizeRememberErrorDetails(details){return redactAndCapRememberErrorText(replaceControlChars(collapseCredentialSeparators(details)))}__name(sanitizeRememberErrorDetails,"sanitizeRememberErrorDetails");function sanitizeRememberErrorStack(stack){return redactAndCapRememberErrorText(replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack)))}__name(sanitizeRememberErrorStack,"sanitizeRememberErrorStack");function extractRememberErrorDetails(err){const raw=rawRememberErrorDetails(err,new WeakSet,0);if(!raw)return void 0;return sanitizeRememberErrorDetails(raw)}__name(extractRememberErrorDetails,"extractRememberErrorDetails");function extractRememberErrorStack(err){if(!(err instanceof Error)||!err.stack)return void 0;return sanitizeRememberErrorStack(err.stack)}__name(extractRememberErrorStack,"extractRememberErrorStack");function shouldSuppressRememberErrorDetails(code){return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code)}__name(shouldSuppressRememberErrorDetails,"shouldSuppressRememberErrorDetails");function workspaceMemoryFailureDiagnostics(err,onExtractionError){let details;let stack;try{details=extractRememberErrorDetails(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"details",extractionErr);details=void 0}try{stack=extractRememberErrorStack(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"stack",extractionErr);stack=void 0}return{...details?{details}:{},debugDetails:details??"<details unavailable>",...stack?{stack}:{}}}__name(workspaceMemoryFailureDiagnostics,"workspaceMemoryFailureDiagnostics");init_esbuild_shims();var MAX_REMEMBER_CONTENT_BYTES=64*1024;init_esbuild_shims();function formatWorkspaceMemoryForgetSummary(removedEntryCount){return removedEntryCount>0?`Forgot ${removedEntryCount} memory entr${removedEntryCount===1?"y":"ies"}.`:"No managed auto-memory entries matched."}__name(formatWorkspaceMemoryForgetSummary,"formatWorkspaceMemoryForgetSummary");function formatWorkspaceMemoryDreamSummary(touchedTopicCount){return touchedTopicCount>0?"Managed auto-memory dream completed.":"No managed auto-memory topics changed."}__name(formatWorkspaceMemoryDreamSummary,"formatWorkspaceMemoryDreamSummary");init_esbuild_shims();var VALID_SERVER_NAME=/^[A-Za-z0-9_-]+$/;var RESERVED_SERVER_NAMES=new Set(["__proto__","constructor","prototype"]);function isValidServerName(name){return typeof name==="string"&&name.length>0&&name.length<=256&&VALID_SERVER_NAME.test(name)&&!RESERVED_SERVER_NAMES.has(name)}__name(isValidServerName,"isValidServerName");init_esbuild_shims();var GENERATION_MAX_PROMPT_BYTES=32*1024;var GENERATION_TIMEOUT_MS=6e4;async function executeGeneration(config,requestId,prompt,signal,emit){const fastModel=config.getFastModel();const mainModel=config.getModel();const client=config.getBaseLlmClient();let modelSource=fastModel?"fast":"main";let resolved;if(fastModel){try{resolved=await client.resolveForModel(fastModel,{failClosed:true})}catch{modelSource="main"}}resolved??=await client.resolveForModel(mainModel,{failClosed:true});const{contentGenerator,model}=resolved;await emit({type:"started",model,modelSource});const stream=await contentGenerator.generateContentStream({model,contents:[{role:"user",parts:[{text:prompt}]}],config:{abortSignal:signal,tools:[],thinkingConfig:{thinkingBudget:0,includeThoughts:false},temperature:.2}},`generation:${requestId}`);let seq=0;let thinkingEmitted=false;let usage;for await(const chunk of stream){if(!thinkingEmitted&&chunk.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.thought===true))){thinkingEmitted=true;await emit({type:"thinking"})}const text=getResponseText(chunk)??"";if(text){await emit({type:"delta",seq:seq++,text})}if(chunk.usageMetadata)usage=chunk.usageMetadata}return{model,modelSource,...usage?.promptTokenCount!==void 0?{inputTokens:usage.promptTokenCount}:{},...usage?.candidatesTokenCount!==void 0?{outputTokens:usage.candidatesTokenCount}:{}}}__name(executeGeneration,"executeGeneration");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";init_esbuild_shims();import{Buffer}from"node:buffer";import{isDeepStrictEqual}from"node:util";var ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for ACP transport ...]\n";var EMPTY_CONTENT_ARRAY_JSON_BYTES=Buffer.byteLength("[]","utf8");var EMPTY_TEXT_BLOCK_JSON_BYTES=Buffer.byteLength(JSON.stringify(createTextBlock("")),"utf8");var JSON_ARRAY_SEPARATOR_BYTES=1;var TRUNCATION_MARKER_PAYLOAD_BYTES=jsonStringJsonByteLength(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)-JSON_STRING_DELIMITER_BYTES;var MAX_CANONICAL_TEXT_BLOCKS=Math.floor((ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-EMPTY_CONTENT_ARRAY_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES)/(EMPTY_TEXT_BLOCK_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES));function createTextBlock(text){return{type:"content",content:{type:"text",text}}}__name(createTextBlock,"createTextBlock");function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord,"isObjectRecord");function hasExactKeys(value,first,second){const keys=Object.keys(value);return keys.length===2&&Object.hasOwn(value,first)&&Object.hasOwn(value,second)}__name(hasExactKeys,"hasExactKeys");function canonicalTextBlocks(value){if(!Array.isArray(value))return void 0;for(const block of value){if(!isObjectRecord(block)||!hasExactKeys(block,"type","content")||block["type"]!=="content"||!isObjectRecord(block["content"])||!hasExactKeys(block["content"],"type","text")||block["content"]["type"]!=="text"||typeof block["content"]["text"]!=="string"){return void 0}}return value}__name(canonicalTextBlocks,"canonicalTextBlocks");function contentSkeletonBytes(blockCount){if(blockCount===0)return EMPTY_CONTENT_ARRAY_JSON_BYTES;return EMPTY_CONTENT_ARRAY_JSON_BYTES+blockCount*EMPTY_TEXT_BLOCK_JSON_BYTES+(blockCount-1)*JSON_ARRAY_SEPARATOR_BYTES}__name(contentSkeletonBytes,"contentSkeletonBytes");function fallbackContent(){return[createTextBlock(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)]}__name(fallbackContent,"fallbackContent");function jsonByteLength(value){return Buffer.byteLength(JSON.stringify(value),"utf8")}__name(jsonByteLength,"jsonByteLength");function allocatePayloadBudgets(payloadBytes,availableBytes){const base=payloadBytes.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));let remaining=availableBytes-base.reduce((sum,bytes)=>sum+bytes,0);if(remaining<0)return void 0;const capacities=payloadBytes.map((bytes,index)=>({index,capacity:bytes-base[index]}));const sorted=capacities.filter(({capacity})=>capacity>0).sort((left,right)=>left.capacity===right.capacity?left.index-right.index:left.capacity-right.capacity);let active=sorted.length;let position=0;let level=0;let remainder=0;while(position<sorted.length&&active>0&&remaining>0){const nextLevel=sorted[position].capacity;const cost=(nextLevel-level)*active;if(cost>remaining){level+=Math.floor(remaining/active);remainder=remaining%active;remaining=0;break}level=nextLevel;remaining-=cost;while(position<sorted.length&&sorted[position].capacity===nextLevel){position++;active--}}const allocations=base.map((bytes,index)=>bytes+Math.min(capacities[index].capacity,level));if(remainder>0){for(const{index,capacity}of capacities){if(remainder===0)break;if(capacity>level){allocations[index]++;remainder--}}}return allocations}__name(allocatePayloadBudgets,"allocatePayloadBudgets");function projectContent(original){if(original.length>MAX_CANONICAL_TEXT_BLOCKS)return fallbackContent();const skeletonBytes=contentSkeletonBytes(original.length);const availablePayloadBytes=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-skeletonBytes;let remainingPayloadBytes=availablePayloadBytes;let needsProjection=false;for(const block of original){const payloadBytes2=jsonStringPayloadByteLength(block.content.text,remainingPayloadBytes);if(payloadBytes2>remainingPayloadBytes){needsProjection=true;break}remainingPayloadBytes-=payloadBytes2}if(!needsProjection)return original;const baseScans=original.map(block=>jsonStringPayloadByteLength(block.content.text,TRUNCATION_MARKER_PAYLOAD_BYTES));const basePayloadBytes=baseScans.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));const baseTotal=basePayloadBytes.reduce((sum,bytes)=>sum+bytes,0);if(baseTotal>availablePayloadBytes)return fallbackContent();const payloadBytes=original.map((block,index)=>{if(baseScans[index]<=TRUNCATION_MARKER_PAYLOAD_BYTES){return baseScans[index]}const maximumAllocation=availablePayloadBytes-baseTotal+basePayloadBytes[index];const bytes=jsonStringPayloadByteLength(block.content.text,maximumAllocation);return bytes<=maximumAllocation?bytes:maximumAllocation+1});const allocations=allocatePayloadBudgets(payloadBytes,availablePayloadBytes);if(!allocations)return fallbackContent();const projected=original.map((block,index)=>{if(payloadBytes[index]<=allocations[index])return block;return createTextBlock(truncateJsonStringPayload(block.content.text,payloadBytes[index],allocations[index],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))});return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:fallbackContent()}__name(projectContent,"projectContent");function projectRawOutput(value){const payloadBudget=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-JSON_STRING_DELIMITER_BYTES;const payloadBytes=jsonStringPayloadByteLength(value,payloadBudget);if(payloadBytes<=payloadBudget)return value;const projected=truncateJsonStringPayload(value,payloadBytes,payloadBudget,ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER);return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER}__name(projectRawOutput,"projectRawOutput");function a2uiMeta(meta){if(!meta)return void 0;const toolName=typeof meta["toolName"]==="string"?meta["toolName"]:void 0;const serverId=typeof meta["serverId"]==="string"?meta["serverId"]:void 0;return toolName===void 0&&serverId===void 0?void 0:{...toolName===void 0?{}:{toolName},...serverId===void 0?{}:{serverId}}}__name(a2uiMeta,"a2uiMeta");function projectAcpToolResultUpdate(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return update;const meta=isObjectRecord(record["_meta"])?record["_meta"]:void 0;if(isA2uiToolMeta(a2uiMeta(meta)))return update;const content=canonicalTextBlocks(record["content"]);const rawOutput=record["rawOutput"];if(content?.length===1&&typeof rawOutput==="string"&&rawOutput===content[0].content.text){const projectedContent2=projectContent(content);if(projectedContent2===content)return update;const projectedText=projectedContent2[0].content.text;return{...record,content:projectedContent2,rawOutput:projectedText}}const projectedContent=content?projectContent(content):void 0;let projectedRawOutput=typeof rawOutput==="string"?projectRawOutput(rawOutput):void 0;if(isShellResultDisplay(rawOutput)){const structured=mapShellResultText(rawOutput,text=>text);projectedRawOutput=isDeepStrictEqual(structured,rawOutput)?rawOutput:structured;if(Buffer.byteLength(JSON.stringify(structured),"utf8")>ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET){const payloadBytes=[];const skeleton=mapShellResultText(structured,text=>{payloadBytes.push(jsonStringPayloadByteLength(text));return""});const budgets=allocatePayloadBudgets(payloadBytes,ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-Buffer.byteLength(JSON.stringify(skeleton),"utf8"));let index=0;projectedRawOutput=mapShellResultText(structured,text=>truncateJsonStringPayload(text,jsonStringPayloadByteLength(text),budgets[index++],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))}}const contentChanged=projectedContent!==void 0&&projectedContent!==content;const rawOutputChanged=projectedRawOutput!==void 0&&projectedRawOutput!==rawOutput;if(!contentChanged&&!rawOutputChanged)return update;return{...record,...contentChanged?{content:projectedContent}:{},...rawOutputChanged?{rawOutput:projectedRawOutput}:{}}}__name(projectAcpToolResultUpdate,"projectAcpToolResultUpdate");var HistoryReplayLimitError=class extends Error{constructor(sessionId,reason,observed,limit){super(`Transcript replay for session ${sessionId} exceeds the ${reason} limit (${observed}, max ${limit})`);this.sessionId=sessionId;this.reason=reason;this.observed=observed;this.limit=limit;this.name="HistoryReplayLimitError"}static{__name(this,"HistoryReplayLimitError")}};function createReplayCumulativeUsage(){return{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}}__name(createReplayCumulativeUsage,"createReplayCumulativeUsage");function copyCumulativeUsage(target,source){target.promptTokens=source.promptTokens;target.cachedTokens=source.cachedTokens;target.candidateTokens=source.candidateTokens;target.apiTimeMs=source.apiTimeMs}__name(copyCumulativeUsage,"copyCumulativeUsage");function isObjectRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord2,"isObjectRecord");function isCumulativeUsage(value){if(!isObjectRecord2(value))return false;return typeof value["promptTokens"]==="number"&&Number.isFinite(value["promptTokens"])&&typeof value["cachedTokens"]==="number"&&Number.isFinite(value["cachedTokens"])&&typeof value["candidateTokens"]==="number"&&Number.isFinite(value["candidateTokens"])&&typeof value["apiTimeMs"]==="number"&&Number.isFinite(value["apiTimeMs"])}__name(isCumulativeUsage,"isCumulativeUsage");function isPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&(value["timestamp"]===void 0||typeof value["timestamp"]==="string")&&typeof value["recordId"]==="string"}__name(isPendingReplayToolCall,"isPendingReplayToolCall");function isCurrentPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&typeof value["sourceRecordId"]==="string"&&(value["sourceTimestamp"]===void 0||typeof value["sourceTimestamp"]==="string")}__name(isCurrentPendingReplayToolCall,"isCurrentPendingReplayToolCall");function parseTranscriptReplayState(replay,logger){if(!isObjectRecord2(replay)){return{pendingToolCalls:[],cumulativeUsage:createReplayCumulativeUsage()}}if("v"in replay&&replay["v"]!==1){throw new TypeError("Unsupported transcript replay state version.")}const rawPending=replay["pendingToolCalls"];const pendingToolCalls=Array.isArray(rawPending)?rawPending.flatMap(pending=>{if(isPendingReplayToolCall(pending))return[pending];if(isCurrentPendingReplayToolCall(pending)){return[{callId:pending.callId,toolName:pending.toolName,...pending.resolvedToolName?{resolvedToolName:pending.resolvedToolName}:{},recordId:pending.sourceRecordId,...pending.sourceTimestamp?{timestamp:pending.sourceTimestamp}:{},...pending.rawCallId?{rawCallId:pending.rawCallId}:{},...pending.timingMatched?{timingMatched:true}:{}}]}return[]}):[];if(logger&&Array.isArray(rawPending)&&pendingToolCalls.length!==rawPending.length){const dropped=rawPending.length-pendingToolCalls.length;logger.warn(`[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`)}const cumulativeUsage=isCumulativeUsage(replay["cumulativeUsage"])?{...replay["cumulativeUsage"]}:createReplayCumulativeUsage();const rawGoalState=replay["goalState"];const goalState=rawGoalState===void 0?void 0:parseGoalSnapshotV2(rawGoalState);if(logger&&rawGoalState!==void 0&&!goalState){logger.warn("[transcript] replay state dropped a malformed Goal state")}const rawGoalCause=replay["goalCause"];const goalCause=rawGoalCause===void 0?void 0:parseGoalStateCause(rawGoalCause);if(logger&&rawGoalCause!==void 0&&!goalCause){logger.warn("[transcript] replay state dropped a malformed Goal cause")}return{pendingToolCalls,cumulativeUsage,...goalState?{goalState}:{},...goalCause?{goalCause}:{}}}__name(parseTranscriptReplayState,"parseTranscriptReplayState");function blankReplayedMcpAppHtml(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return void 0;const rawOutput=record["rawOutput"];if(!isObjectRecord2(rawOutput)||rawOutput["type"]!=="mcp_app"||typeof rawOutput["html"]!=="string"||rawOutput["html"]===""){return void 0}const blanked={...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}};if(Buffer2.byteLength(JSON.stringify(blanked),"utf8")>=Buffer2.byteLength(JSON.stringify(record),"utf8")){return void 0}return blanked}__name(blankReplayedMcpAppHtml,"blankReplayedMcpAppHtml");function degradeReplayEnvelopeAppHtml(envelope,maxBytes){let pageBytes=Buffer2.byteLength(JSON.stringify(envelope),"utf8");for(let i=0;i<envelope.updates.length&&pageBytes>maxBytes;i++){const update=envelope.updates[i];const blanked=blankReplayedMcpAppHtml(update);if(blanked===void 0)continue;pageBytes+=Buffer2.byteLength(JSON.stringify(blanked),"utf8")-Buffer2.byteLength(JSON.stringify(update),"utf8");envelope.updates[i]=blanked}}__name(degradeReplayEnvelopeAppHtml,"degradeReplayEnvelopeAppHtml");function replayContext(sessionId,updates,cumulativeUsage,config,limits){let activeRecordId=null;let serializedUpdateBytes=2;return{sessionId,sendUpdate:__name(async update=>{const projectedUpdate=projectAcpToolResultUpdate(update);const updateWithRecordId=(()=>{if(activeRecordId===null)return projectedUpdate;const record=projectedUpdate;const meta=isObjectRecord2(record["_meta"])?record["_meta"]:{};return{...record,_meta:{...meta,"qwen.session.recordId":activeRecordId}}})();let deliveredUpdate=liftSessionUpdateTimestamp(updateWithRecordId);observeAcpToolResultProjection(update,projectedUpdate,sessionId,deliveredUpdate);if(limits){const updateCount=updates.length+1;if(updateCount>limits.maxUpdates){throw new HistoryReplayLimitError(sessionId,"updates",updateCount,limits.maxUpdates)}let updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(deliveredUpdate),"utf8");if(serializedUpdateBytes+updateBytes>limits.maxBytes){for(let i=0;i<updates.length&&serializedUpdateBytes+updateBytes>limits.maxBytes;i++){const blanked=blankReplayedMcpAppHtml(updates[i]);if(blanked===void 0)continue;serializedUpdateBytes-=Buffer2.byteLength(JSON.stringify(updates[i]),"utf8")-Buffer2.byteLength(JSON.stringify(blanked),"utf8");updates[i]=blanked}if(serializedUpdateBytes+updateBytes>limits.maxBytes){const blanked=blankReplayedMcpAppHtml(deliveredUpdate);if(blanked!==void 0){deliveredUpdate=blanked;updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(blanked),"utf8")}}}serializedUpdateBytes+=updateBytes;if(serializedUpdateBytes>limits.maxBytes){throw new HistoryReplayLimitError(sessionId,"bytes",serializedUpdateBytes,limits.maxBytes)}}updates.push(deliveredUpdate)},"sendUpdate"),setActiveRecordId:__name(recordId=>{activeRecordId=recordId},"setActiveRecordId"),cumulativeUsage,...config?{config}:{}}}__name(replayContext,"replayContext");async function collectHistoryReplayUpdates({sessionId,config,records,gaps,cumulativeUsage,logger,replayState,goalBootstrap,limits,suppressRestoreAskUserQuestion,finalizeDangling,branchPointsByAssistantUuid}){const updates=[];let replayError;try{const initial=parseTranscriptReplayState(replayState,logger);let skipFinalizeCallIds;if(suppressRestoreAskUserQuestion!==true&&config?.getRestoreAskUserQuestion?.()===true){const replayClient=config.getLlmClient?.();const lastHistoryContent=replayClient?.isInitialized?.()===true?replayClient.getChat?.()?.peekLastHistoryEntry?.()??lastHistoryContentFromRecords(records):lastHistoryContentFromRecords(records);skipFinalizeCallIds=restorableAskUserQuestionCallIds(lastHistoryContent)}await new HistoryReplayer(replayContext(sessionId,updates,cumulativeUsage,config,limits)).replay(records,gaps,{...initial.goalState?{initialGoalState:initial.goalState}:{},...initial.goalCause?{initialGoalCause:initial.goalCause}:{},...goalBootstrap?{goalBootstrap}:{},...skipFinalizeCallIds?{skipFinalizeCallIds}:{},...finalizeDangling===void 0?{}:{finalizeDangling}})}catch(error){if(error instanceof HistoryReplayLimitError)throw error;replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error)}if(branchPointsByAssistantUuid){stampBranchPoints(updates,branchPointsByAssistantUuid)}return replayError===void 0?{updates}:{updates,replayError}}__name(collectHistoryReplayUpdates,"collectHistoryReplayUpdates");function liftSessionUpdateTimestamp(update){const record=update;const meta=record["_meta"];const timestamp=isObjectRecord2(meta)?meta["timestamp"]:void 0;return typeof timestamp==="number"||typeof timestamp==="string"?{...record,timestamp}:update}__name(liftSessionUpdateTimestamp,"liftSessionUpdateTimestamp");function readTranscriptSourceRecordIds(update){const value=update;const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;const sourceRecordIds=transcript?.["sourceRecordIds"];if(!Array.isArray(sourceRecordIds))return void 0;return sourceRecordIds.filter(id=>typeof id==="string")}__name(readTranscriptSourceRecordIds,"readTranscriptSourceRecordIds");function stampBranchPoints(updates,branchPoints){const lastChunkIndexByRecordId=new Map;updates.forEach((update,index)=>{if(update.sessionUpdate!=="agent_message_chunk")return;const text=update.content?.text;if(typeof text!=="string"||text.length===0)return;for(const recordId of readTranscriptSourceRecordIds(update)??[]){if(Object.hasOwn(branchPoints,recordId)){lastChunkIndexByRecordId.set(recordId,index)}}});const decoratedIndexes=new Set;for(const[recordId,index]of lastChunkIndexByRecordId){if(decoratedIndexes.has(index))continue;decoratedIndexes.add(index);const value=updates[index];const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;value["_meta"]={...meta,qwenTranscript:{...transcript,branchRecordId:branchPoints[recordId]}}}}__name(stampBranchPoints,"stampBranchPoints");async function replayTranscriptRecordPage({sessionId,page,config,encodeCursor,logger,finalizeDangling=true}){const state=parseTranscriptReplayState(page.replay,logger);const updates=[];const replayer=new HistoryReplayer(replayContext(sessionId,updates,state.cumulativeUsage,config));let replayState;let replayError;try{const replayPageState=await replayer.replayPage(page.records,{pendingToolCalls:page.direction==="backward"?[]:state.pendingToolCalls,finalizeDangling:finalizeDangling&&(page.direction==="backward"||!page.hasMore),gaps:page.gaps,includeTiming:true,...state.goalState?{goalState:state.goalState}:{},...state.goalCause?{goalCause:state.goalCause}:{}});replayState=replayPageState.replay}catch(error){logger?.warn("[historyReplay] Paged history replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);replayState=replayer.getReplayState();replayError="Replay conversion failed for this page"}if(page.branchPointsByAssistantUuid){stampBranchPoints(updates,page.branchPointsByAssistantUuid)}const nextCursor=page.nextCursorState&&replayError===void 0?encodeCursor({...page.nextCursorState,...page.direction==="backward"?{}:{replay:replayState}}):void 0;return{updates,...nextCursor?{nextCursor}:{},hasMore:replayError===void 0&&page.hasMore,startTime:page.startTime,lastUpdated:page.lastUpdated,...replayError?{partial:true,replayError}:{}}}__name(replayTranscriptRecordPage,"replayTranscriptRecordPage");export{createWorkspaceMemoryExtractionErrorLogger,extractRememberErrorCode,workspaceMemoryFailureCode,shouldSuppressRememberErrorDetails,workspaceMemoryFailureDiagnostics,MAX_REMEMBER_CONTENT_BYTES,formatWorkspaceMemoryForgetSummary,formatWorkspaceMemoryDreamSummary,isValidServerName,GENERATION_MAX_PROMPT_BYTES,GENERATION_TIMEOUT_MS,executeGeneration,projectAcpToolResultUpdate,HistoryReplayLimitError,createReplayCumulativeUsage,copyCumulativeUsage,degradeReplayEnvelopeAppHtml,collectHistoryReplayUpdates,replayTranscriptRecordPage};
|
|
3
|
+
import{HistoryReplayer,observeAcpToolResultProjection}from"./chunk-UG5B4UOQ.js";import{JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,truncateJsonStringPayload}from"./chunk-WQUA4G2X.js";import{isA2uiToolMeta}from"./chunk-LTJLPYFS.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-3NR3JBMA.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-6NQMNEZN.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var MAX_REMEMBER_ERROR_DETAILS_CHARS=1e3;var MAX_REMEMBER_ERROR_CAUSE_DEPTH=50;var REMEMBER_ERROR_FORMAT_RE=new RegExp("[\\p{Cf}]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_SPACE_SEPARATOR_RE=/[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE=new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE=new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])","giu");var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)","giu");var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+","gu");var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE=new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+","gu");var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","giu");var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","gu");var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE=new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@","giu");var REMEMBER_ERROR_CONTROL_RE=/[\x00-\x1f\x7f-\x9f]/g;var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES=new Set(["managed_memory_unavailable"]);function createWorkspaceMemoryExtractionErrorLogger(logger){return(target,err)=>{logger.warn(`Failed to extract workspace memory error ${target}:`,{extractionError:err instanceof Error?err.message:String(err)})}}__name(createWorkspaceMemoryExtractionErrorLogger,"createWorkspaceMemoryExtractionErrorLogger");function reportRememberErrorExtractionFailure(onExtractionError,target,err){try{onExtractionError?.(target,err)}catch{}}__name(reportRememberErrorExtractionFailure,"reportRememberErrorExtractionFailure");function errorCodeFromRecord(record){if(typeof record["code"]==="string")return record["code"];const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;if(typeof dataRecord["errorKind"]==="string"){return dataRecord["errorKind"]}if(typeof dataRecord["code"]==="string")return dataRecord["code"]}return void 0}__name(errorCodeFromRecord,"errorCodeFromRecord");function rawRememberErrorCode(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);const record=err;const direct=errorCodeFromRecord(record);if(direct)return direct;const cause=record["cause"];if(cause!=null){return rawRememberErrorCode(cause,seen,depth+1)}return void 0}__name(rawRememberErrorCode,"rawRememberErrorCode");function extractRememberErrorCode(err,fallback="remember_failed"){return rawRememberErrorCode(err,new WeakSet,0)??fallback}__name(extractRememberErrorCode,"extractRememberErrorCode");function workspaceMemoryFailureCode(err,fallback="remember_failed",onExtractionError){try{return extractRememberErrorCode(err,fallback)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"code",extractionErr);return fallback}}__name(workspaceMemoryFailureCode,"workspaceMemoryFailureCode");function detailFromRecord(record,seen,depth){const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;const details=dataRecord["details"];if(typeof details==="string"&&details.length>0)return details;const message2=dataRecord["message"];if(typeof message2==="string"&&message2.length>0)return message2}const message=record["message"];if(typeof message==="string"&&message.length>0)return message;if(typeof data==="string"&&data.length>0)return data;const cause=record["cause"];if(cause!=null){return rawRememberErrorDetails(cause,seen,depth+1)}return void 0}__name(detailFromRecord,"detailFromRecord");function rawRememberErrorDetails(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(typeof err==="string"&&err.length>0)return err;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);return detailFromRecord(err,seen,depth)}__name(rawRememberErrorDetails,"rawRememberErrorDetails");function replaceControlChars(details){return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE," ")}__name(replaceControlChars,"replaceControlChars");function replaceStackControlChars(stack){return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE,char=>char==="\n"||char==="\r"||char===" "?char:" ")}__name(replaceStackControlChars,"replaceStackControlChars");function collapseCredentialSeparators(text){return text.replace(REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,(_match,scheme,userinfo)=>`${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}@`).replace(REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,(_match,scheme,token)=>`${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`)}__name(collapseCredentialSeparators,"collapseCredentialSeparators");function collapseCredentialSeparatorsByStackLine(stack){return stack.split(/(\r\n|\n|\r)/).map(part=>part==="\r\n"||part==="\n"||part==="\r"?part:collapseCredentialSeparators(part)).join("")}__name(collapseCredentialSeparatorsByStackLine,"collapseCredentialSeparatorsByStackLine");function isHighSurrogate(codeUnit){return codeUnit>=55296&&codeUnit<=56319}__name(isHighSurrogate,"isHighSurrogate");function isLowSurrogate(codeUnit){return codeUnit>=56320&&codeUnit<=57343}__name(isLowSurrogate,"isLowSurrogate");function truncateBeforeDanglingSurrogate(details,cutPoint){const beforeCut=details.charCodeAt(cutPoint-1);const atCut=details.charCodeAt(cutPoint);if(isHighSurrogate(beforeCut)&&isLowSurrogate(atCut)){return cutPoint-1}return cutPoint}__name(truncateBeforeDanglingSurrogate,"truncateBeforeDanglingSurrogate");function capRememberErrorText(redacted){if(redacted.length<=MAX_REMEMBER_ERROR_DETAILS_CHARS)return redacted;const truncationSuffix="... [truncated]";const cutPoint=truncateBeforeDanglingSurrogate(redacted,MAX_REMEMBER_ERROR_DETAILS_CHARS-truncationSuffix.length);return`${redacted.slice(0,cutPoint)}${truncationSuffix}`}__name(capRememberErrorText,"capRememberErrorText");function redactAndCapRememberErrorText(normalized){const redacted=redactLogCredentials(normalized).trim();if(!redacted)return void 0;return capRememberErrorText(redacted)}__name(redactAndCapRememberErrorText,"redactAndCapRememberErrorText");function sanitizeRememberErrorDetails(details){return redactAndCapRememberErrorText(replaceControlChars(collapseCredentialSeparators(details)))}__name(sanitizeRememberErrorDetails,"sanitizeRememberErrorDetails");function sanitizeRememberErrorStack(stack){return redactAndCapRememberErrorText(replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack)))}__name(sanitizeRememberErrorStack,"sanitizeRememberErrorStack");function extractRememberErrorDetails(err){const raw=rawRememberErrorDetails(err,new WeakSet,0);if(!raw)return void 0;return sanitizeRememberErrorDetails(raw)}__name(extractRememberErrorDetails,"extractRememberErrorDetails");function extractRememberErrorStack(err){if(!(err instanceof Error)||!err.stack)return void 0;return sanitizeRememberErrorStack(err.stack)}__name(extractRememberErrorStack,"extractRememberErrorStack");function shouldSuppressRememberErrorDetails(code){return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code)}__name(shouldSuppressRememberErrorDetails,"shouldSuppressRememberErrorDetails");function workspaceMemoryFailureDiagnostics(err,onExtractionError){let details;let stack;try{details=extractRememberErrorDetails(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"details",extractionErr);details=void 0}try{stack=extractRememberErrorStack(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"stack",extractionErr);stack=void 0}return{...details?{details}:{},debugDetails:details??"<details unavailable>",...stack?{stack}:{}}}__name(workspaceMemoryFailureDiagnostics,"workspaceMemoryFailureDiagnostics");init_esbuild_shims();var MAX_REMEMBER_CONTENT_BYTES=64*1024;init_esbuild_shims();function formatWorkspaceMemoryForgetSummary(removedEntryCount){return removedEntryCount>0?`Forgot ${removedEntryCount} memory entr${removedEntryCount===1?"y":"ies"}.`:"No managed auto-memory entries matched."}__name(formatWorkspaceMemoryForgetSummary,"formatWorkspaceMemoryForgetSummary");function formatWorkspaceMemoryDreamSummary(touchedTopicCount){return touchedTopicCount>0?"Managed auto-memory dream completed.":"No managed auto-memory topics changed."}__name(formatWorkspaceMemoryDreamSummary,"formatWorkspaceMemoryDreamSummary");init_esbuild_shims();var VALID_SERVER_NAME=/^[A-Za-z0-9_-]+$/;var RESERVED_SERVER_NAMES=new Set(["__proto__","constructor","prototype"]);function isValidServerName(name){return typeof name==="string"&&name.length>0&&name.length<=256&&VALID_SERVER_NAME.test(name)&&!RESERVED_SERVER_NAMES.has(name)}__name(isValidServerName,"isValidServerName");init_esbuild_shims();var GENERATION_MAX_PROMPT_BYTES=32*1024;var GENERATION_TIMEOUT_MS=6e4;async function executeGeneration(config,requestId,prompt,signal,emit){const fastModel=config.getFastModel();const mainModel=config.getModel();const client=config.getBaseLlmClient();let modelSource=fastModel?"fast":"main";let resolved;if(fastModel){try{resolved=await client.resolveForModel(fastModel,{failClosed:true})}catch{modelSource="main"}}resolved??=await client.resolveForModel(mainModel,{failClosed:true});const{contentGenerator,model}=resolved;await emit({type:"started",model,modelSource});const stream=await contentGenerator.generateContentStream({model,contents:[{role:"user",parts:[{text:prompt}]}],config:{abortSignal:signal,tools:[],thinkingConfig:{thinkingBudget:0,includeThoughts:false},temperature:.2}},`generation:${requestId}`);let seq=0;let thinkingEmitted=false;let usage;for await(const chunk of stream){if(!thinkingEmitted&&chunk.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.thought===true))){thinkingEmitted=true;await emit({type:"thinking"})}const text=getResponseText(chunk)??"";if(text){await emit({type:"delta",seq:seq++,text})}if(chunk.usageMetadata)usage=chunk.usageMetadata}return{model,modelSource,...usage?.promptTokenCount!==void 0?{inputTokens:usage.promptTokenCount}:{},...usage?.candidatesTokenCount!==void 0?{outputTokens:usage.candidatesTokenCount}:{}}}__name(executeGeneration,"executeGeneration");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";init_esbuild_shims();import{Buffer}from"node:buffer";import{isDeepStrictEqual}from"node:util";var ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for ACP transport ...]\n";var EMPTY_CONTENT_ARRAY_JSON_BYTES=Buffer.byteLength("[]","utf8");var EMPTY_TEXT_BLOCK_JSON_BYTES=Buffer.byteLength(JSON.stringify(createTextBlock("")),"utf8");var JSON_ARRAY_SEPARATOR_BYTES=1;var TRUNCATION_MARKER_PAYLOAD_BYTES=jsonStringJsonByteLength(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)-JSON_STRING_DELIMITER_BYTES;var MAX_CANONICAL_TEXT_BLOCKS=Math.floor((ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-EMPTY_CONTENT_ARRAY_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES)/(EMPTY_TEXT_BLOCK_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES));function createTextBlock(text){return{type:"content",content:{type:"text",text}}}__name(createTextBlock,"createTextBlock");function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord,"isObjectRecord");function hasExactKeys(value,first,second){const keys=Object.keys(value);return keys.length===2&&Object.hasOwn(value,first)&&Object.hasOwn(value,second)}__name(hasExactKeys,"hasExactKeys");function canonicalTextBlocks(value){if(!Array.isArray(value))return void 0;for(const block of value){if(!isObjectRecord(block)||!hasExactKeys(block,"type","content")||block["type"]!=="content"||!isObjectRecord(block["content"])||!hasExactKeys(block["content"],"type","text")||block["content"]["type"]!=="text"||typeof block["content"]["text"]!=="string"){return void 0}}return value}__name(canonicalTextBlocks,"canonicalTextBlocks");function contentSkeletonBytes(blockCount){if(blockCount===0)return EMPTY_CONTENT_ARRAY_JSON_BYTES;return EMPTY_CONTENT_ARRAY_JSON_BYTES+blockCount*EMPTY_TEXT_BLOCK_JSON_BYTES+(blockCount-1)*JSON_ARRAY_SEPARATOR_BYTES}__name(contentSkeletonBytes,"contentSkeletonBytes");function fallbackContent(){return[createTextBlock(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)]}__name(fallbackContent,"fallbackContent");function jsonByteLength(value){return Buffer.byteLength(JSON.stringify(value),"utf8")}__name(jsonByteLength,"jsonByteLength");function allocatePayloadBudgets(payloadBytes,availableBytes){const base=payloadBytes.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));let remaining=availableBytes-base.reduce((sum,bytes)=>sum+bytes,0);if(remaining<0)return void 0;const capacities=payloadBytes.map((bytes,index)=>({index,capacity:bytes-base[index]}));const sorted=capacities.filter(({capacity})=>capacity>0).sort((left,right)=>left.capacity===right.capacity?left.index-right.index:left.capacity-right.capacity);let active=sorted.length;let position=0;let level=0;let remainder=0;while(position<sorted.length&&active>0&&remaining>0){const nextLevel=sorted[position].capacity;const cost=(nextLevel-level)*active;if(cost>remaining){level+=Math.floor(remaining/active);remainder=remaining%active;remaining=0;break}level=nextLevel;remaining-=cost;while(position<sorted.length&&sorted[position].capacity===nextLevel){position++;active--}}const allocations=base.map((bytes,index)=>bytes+Math.min(capacities[index].capacity,level));if(remainder>0){for(const{index,capacity}of capacities){if(remainder===0)break;if(capacity>level){allocations[index]++;remainder--}}}return allocations}__name(allocatePayloadBudgets,"allocatePayloadBudgets");function projectContent(original){if(original.length>MAX_CANONICAL_TEXT_BLOCKS)return fallbackContent();const skeletonBytes=contentSkeletonBytes(original.length);const availablePayloadBytes=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-skeletonBytes;let remainingPayloadBytes=availablePayloadBytes;let needsProjection=false;for(const block of original){const payloadBytes2=jsonStringPayloadByteLength(block.content.text,remainingPayloadBytes);if(payloadBytes2>remainingPayloadBytes){needsProjection=true;break}remainingPayloadBytes-=payloadBytes2}if(!needsProjection)return original;const baseScans=original.map(block=>jsonStringPayloadByteLength(block.content.text,TRUNCATION_MARKER_PAYLOAD_BYTES));const basePayloadBytes=baseScans.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));const baseTotal=basePayloadBytes.reduce((sum,bytes)=>sum+bytes,0);if(baseTotal>availablePayloadBytes)return fallbackContent();const payloadBytes=original.map((block,index)=>{if(baseScans[index]<=TRUNCATION_MARKER_PAYLOAD_BYTES){return baseScans[index]}const maximumAllocation=availablePayloadBytes-baseTotal+basePayloadBytes[index];const bytes=jsonStringPayloadByteLength(block.content.text,maximumAllocation);return bytes<=maximumAllocation?bytes:maximumAllocation+1});const allocations=allocatePayloadBudgets(payloadBytes,availablePayloadBytes);if(!allocations)return fallbackContent();const projected=original.map((block,index)=>{if(payloadBytes[index]<=allocations[index])return block;return createTextBlock(truncateJsonStringPayload(block.content.text,payloadBytes[index],allocations[index],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))});return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:fallbackContent()}__name(projectContent,"projectContent");function projectRawOutput(value){const payloadBudget=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-JSON_STRING_DELIMITER_BYTES;const payloadBytes=jsonStringPayloadByteLength(value,payloadBudget);if(payloadBytes<=payloadBudget)return value;const projected=truncateJsonStringPayload(value,payloadBytes,payloadBudget,ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER);return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER}__name(projectRawOutput,"projectRawOutput");function a2uiMeta(meta){if(!meta)return void 0;const toolName=typeof meta["toolName"]==="string"?meta["toolName"]:void 0;const serverId=typeof meta["serverId"]==="string"?meta["serverId"]:void 0;return toolName===void 0&&serverId===void 0?void 0:{...toolName===void 0?{}:{toolName},...serverId===void 0?{}:{serverId}}}__name(a2uiMeta,"a2uiMeta");function projectAcpToolResultUpdate(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return update;const meta=isObjectRecord(record["_meta"])?record["_meta"]:void 0;if(isA2uiToolMeta(a2uiMeta(meta)))return update;const content=canonicalTextBlocks(record["content"]);const rawOutput=record["rawOutput"];if(content?.length===1&&typeof rawOutput==="string"&&rawOutput===content[0].content.text){const projectedContent2=projectContent(content);if(projectedContent2===content)return update;const projectedText=projectedContent2[0].content.text;return{...record,content:projectedContent2,rawOutput:projectedText}}const projectedContent=content?projectContent(content):void 0;let projectedRawOutput=typeof rawOutput==="string"?projectRawOutput(rawOutput):void 0;if(isShellResultDisplay(rawOutput)){const structured=mapShellResultText(rawOutput,text=>text);projectedRawOutput=isDeepStrictEqual(structured,rawOutput)?rawOutput:structured;if(Buffer.byteLength(JSON.stringify(structured),"utf8")>ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET){const payloadBytes=[];const skeleton=mapShellResultText(structured,text=>{payloadBytes.push(jsonStringPayloadByteLength(text));return""});const budgets=allocatePayloadBudgets(payloadBytes,ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-Buffer.byteLength(JSON.stringify(skeleton),"utf8"));let index=0;projectedRawOutput=mapShellResultText(structured,text=>truncateJsonStringPayload(text,jsonStringPayloadByteLength(text),budgets[index++],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))}}const contentChanged=projectedContent!==void 0&&projectedContent!==content;const rawOutputChanged=projectedRawOutput!==void 0&&projectedRawOutput!==rawOutput;if(!contentChanged&&!rawOutputChanged)return update;return{...record,...contentChanged?{content:projectedContent}:{},...rawOutputChanged?{rawOutput:projectedRawOutput}:{}}}__name(projectAcpToolResultUpdate,"projectAcpToolResultUpdate");var HistoryReplayLimitError=class extends Error{constructor(sessionId,reason,observed,limit){super(`Transcript replay for session ${sessionId} exceeds the ${reason} limit (${observed}, max ${limit})`);this.sessionId=sessionId;this.reason=reason;this.observed=observed;this.limit=limit;this.name="HistoryReplayLimitError"}static{__name(this,"HistoryReplayLimitError")}};function createReplayCumulativeUsage(){return{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}}__name(createReplayCumulativeUsage,"createReplayCumulativeUsage");function copyCumulativeUsage(target,source){target.promptTokens=source.promptTokens;target.cachedTokens=source.cachedTokens;target.candidateTokens=source.candidateTokens;target.apiTimeMs=source.apiTimeMs}__name(copyCumulativeUsage,"copyCumulativeUsage");function isObjectRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord2,"isObjectRecord");function isCumulativeUsage(value){if(!isObjectRecord2(value))return false;return typeof value["promptTokens"]==="number"&&Number.isFinite(value["promptTokens"])&&typeof value["cachedTokens"]==="number"&&Number.isFinite(value["cachedTokens"])&&typeof value["candidateTokens"]==="number"&&Number.isFinite(value["candidateTokens"])&&typeof value["apiTimeMs"]==="number"&&Number.isFinite(value["apiTimeMs"])}__name(isCumulativeUsage,"isCumulativeUsage");function isPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&(value["timestamp"]===void 0||typeof value["timestamp"]==="string")&&typeof value["recordId"]==="string"}__name(isPendingReplayToolCall,"isPendingReplayToolCall");function isCurrentPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&typeof value["sourceRecordId"]==="string"&&(value["sourceTimestamp"]===void 0||typeof value["sourceTimestamp"]==="string")}__name(isCurrentPendingReplayToolCall,"isCurrentPendingReplayToolCall");function parseTranscriptReplayState(replay,logger){if(!isObjectRecord2(replay)){return{pendingToolCalls:[],cumulativeUsage:createReplayCumulativeUsage()}}if("v"in replay&&replay["v"]!==1){throw new TypeError("Unsupported transcript replay state version.")}const rawPending=replay["pendingToolCalls"];const pendingToolCalls=Array.isArray(rawPending)?rawPending.flatMap(pending=>{if(isPendingReplayToolCall(pending))return[pending];if(isCurrentPendingReplayToolCall(pending)){return[{callId:pending.callId,toolName:pending.toolName,...pending.resolvedToolName?{resolvedToolName:pending.resolvedToolName}:{},recordId:pending.sourceRecordId,...pending.sourceTimestamp?{timestamp:pending.sourceTimestamp}:{},...pending.rawCallId?{rawCallId:pending.rawCallId}:{},...pending.timingMatched?{timingMatched:true}:{}}]}return[]}):[];if(logger&&Array.isArray(rawPending)&&pendingToolCalls.length!==rawPending.length){const dropped=rawPending.length-pendingToolCalls.length;logger.warn(`[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`)}const cumulativeUsage=isCumulativeUsage(replay["cumulativeUsage"])?{...replay["cumulativeUsage"]}:createReplayCumulativeUsage();const rawGoalState=replay["goalState"];const goalState=rawGoalState===void 0?void 0:parseGoalSnapshotV2(rawGoalState);if(logger&&rawGoalState!==void 0&&!goalState){logger.warn("[transcript] replay state dropped a malformed Goal state")}const rawGoalCause=replay["goalCause"];const goalCause=rawGoalCause===void 0?void 0:parseGoalStateCause(rawGoalCause);if(logger&&rawGoalCause!==void 0&&!goalCause){logger.warn("[transcript] replay state dropped a malformed Goal cause")}return{pendingToolCalls,cumulativeUsage,...goalState?{goalState}:{},...goalCause?{goalCause}:{}}}__name(parseTranscriptReplayState,"parseTranscriptReplayState");function blankReplayedMcpAppHtml(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return void 0;const rawOutput=record["rawOutput"];if(!isObjectRecord2(rawOutput)||rawOutput["type"]!=="mcp_app"||typeof rawOutput["html"]!=="string"||rawOutput["html"]===""){return void 0}const blanked={...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}};if(Buffer2.byteLength(JSON.stringify(blanked),"utf8")>=Buffer2.byteLength(JSON.stringify(record),"utf8")){return void 0}return blanked}__name(blankReplayedMcpAppHtml,"blankReplayedMcpAppHtml");function degradeReplayEnvelopeAppHtml(envelope,maxBytes){let pageBytes=Buffer2.byteLength(JSON.stringify(envelope),"utf8");for(let i=0;i<envelope.updates.length&&pageBytes>maxBytes;i++){const update=envelope.updates[i];const blanked=blankReplayedMcpAppHtml(update);if(blanked===void 0)continue;pageBytes+=Buffer2.byteLength(JSON.stringify(blanked),"utf8")-Buffer2.byteLength(JSON.stringify(update),"utf8");envelope.updates[i]=blanked}}__name(degradeReplayEnvelopeAppHtml,"degradeReplayEnvelopeAppHtml");function replayContext(sessionId,updates,cumulativeUsage,config,limits){let activeRecordId=null;let serializedUpdateBytes=2;return{sessionId,sendUpdate:__name(async update=>{const projectedUpdate=projectAcpToolResultUpdate(update);const updateWithRecordId=(()=>{if(activeRecordId===null)return projectedUpdate;const record=projectedUpdate;const meta=isObjectRecord2(record["_meta"])?record["_meta"]:{};return{...record,_meta:{...meta,"qwen.session.recordId":activeRecordId}}})();let deliveredUpdate=liftSessionUpdateTimestamp(updateWithRecordId);observeAcpToolResultProjection(update,projectedUpdate,sessionId,deliveredUpdate);if(limits){const updateCount=updates.length+1;if(updateCount>limits.maxUpdates){throw new HistoryReplayLimitError(sessionId,"updates",updateCount,limits.maxUpdates)}let updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(deliveredUpdate),"utf8");if(serializedUpdateBytes+updateBytes>limits.maxBytes){for(let i=0;i<updates.length&&serializedUpdateBytes+updateBytes>limits.maxBytes;i++){const blanked=blankReplayedMcpAppHtml(updates[i]);if(blanked===void 0)continue;serializedUpdateBytes-=Buffer2.byteLength(JSON.stringify(updates[i]),"utf8")-Buffer2.byteLength(JSON.stringify(blanked),"utf8");updates[i]=blanked}if(serializedUpdateBytes+updateBytes>limits.maxBytes){const blanked=blankReplayedMcpAppHtml(deliveredUpdate);if(blanked!==void 0){deliveredUpdate=blanked;updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(blanked),"utf8")}}}serializedUpdateBytes+=updateBytes;if(serializedUpdateBytes>limits.maxBytes){throw new HistoryReplayLimitError(sessionId,"bytes",serializedUpdateBytes,limits.maxBytes)}}updates.push(deliveredUpdate)},"sendUpdate"),setActiveRecordId:__name(recordId=>{activeRecordId=recordId},"setActiveRecordId"),cumulativeUsage,...config?{config}:{}}}__name(replayContext,"replayContext");async function collectHistoryReplayUpdates({sessionId,config,records,gaps,cumulativeUsage,logger,replayState,goalBootstrap,limits,suppressRestoreAskUserQuestion,finalizeDangling,branchPointsByAssistantUuid}){const updates=[];let replayError;try{const initial=parseTranscriptReplayState(replayState,logger);let skipFinalizeCallIds;if(suppressRestoreAskUserQuestion!==true&&config?.getRestoreAskUserQuestion?.()===true){const replayClient=config.getLlmClient?.();const lastHistoryContent=replayClient?.isInitialized?.()===true?replayClient.getChat?.()?.peekLastHistoryEntry?.()??lastHistoryContentFromRecords(records):lastHistoryContentFromRecords(records);skipFinalizeCallIds=restorableAskUserQuestionCallIds(lastHistoryContent)}await new HistoryReplayer(replayContext(sessionId,updates,cumulativeUsage,config,limits)).replay(records,gaps,{...initial.goalState?{initialGoalState:initial.goalState}:{},...initial.goalCause?{initialGoalCause:initial.goalCause}:{},...goalBootstrap?{goalBootstrap}:{},...skipFinalizeCallIds?{skipFinalizeCallIds}:{},...finalizeDangling===void 0?{}:{finalizeDangling}})}catch(error){if(error instanceof HistoryReplayLimitError)throw error;replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error)}if(branchPointsByAssistantUuid){stampBranchPoints(updates,branchPointsByAssistantUuid)}return replayError===void 0?{updates}:{updates,replayError}}__name(collectHistoryReplayUpdates,"collectHistoryReplayUpdates");function liftSessionUpdateTimestamp(update){const record=update;const meta=record["_meta"];const timestamp=isObjectRecord2(meta)?meta["timestamp"]:void 0;return typeof timestamp==="number"||typeof timestamp==="string"?{...record,timestamp}:update}__name(liftSessionUpdateTimestamp,"liftSessionUpdateTimestamp");function readTranscriptSourceRecordIds(update){const value=update;const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;const sourceRecordIds=transcript?.["sourceRecordIds"];if(!Array.isArray(sourceRecordIds))return void 0;return sourceRecordIds.filter(id=>typeof id==="string")}__name(readTranscriptSourceRecordIds,"readTranscriptSourceRecordIds");function stampBranchPoints(updates,branchPoints){const lastChunkIndexByRecordId=new Map;updates.forEach((update,index)=>{if(update.sessionUpdate!=="agent_message_chunk")return;const text=update.content?.text;if(typeof text!=="string"||text.length===0)return;for(const recordId of readTranscriptSourceRecordIds(update)??[]){if(Object.hasOwn(branchPoints,recordId)){lastChunkIndexByRecordId.set(recordId,index)}}});const decoratedIndexes=new Set;for(const[recordId,index]of lastChunkIndexByRecordId){if(decoratedIndexes.has(index))continue;decoratedIndexes.add(index);const value=updates[index];const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;value["_meta"]={...meta,qwenTranscript:{...transcript,branchRecordId:branchPoints[recordId]}}}}__name(stampBranchPoints,"stampBranchPoints");async function replayTranscriptRecordPage({sessionId,page,config,encodeCursor,logger,finalizeDangling=true}){const state=parseTranscriptReplayState(page.replay,logger);const updates=[];const replayer=new HistoryReplayer(replayContext(sessionId,updates,state.cumulativeUsage,config));let replayState;let replayError;try{const replayPageState=await replayer.replayPage(page.records,{pendingToolCalls:page.direction==="backward"?[]:state.pendingToolCalls,finalizeDangling:finalizeDangling&&(page.direction==="backward"||!page.hasMore),gaps:page.gaps,includeTiming:true,...state.goalState?{goalState:state.goalState}:{},...state.goalCause?{goalCause:state.goalCause}:{}});replayState=replayPageState.replay}catch(error){logger?.warn("[historyReplay] Paged history replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);replayState=replayer.getReplayState();replayError="Replay conversion failed for this page"}if(page.branchPointsByAssistantUuid){stampBranchPoints(updates,page.branchPointsByAssistantUuid)}const nextCursor=page.nextCursorState&&replayError===void 0?encodeCursor({...page.nextCursorState,...page.direction==="backward"?{}:{replay:replayState}}):void 0;return{updates,...nextCursor?{nextCursor}:{},hasMore:replayError===void 0&&page.hasMore,startTime:page.startTime,lastUpdated:page.lastUpdated,...replayError?{partial:true,replayError}:{}}}__name(replayTranscriptRecordPage,"replayTranscriptRecordPage");export{createWorkspaceMemoryExtractionErrorLogger,extractRememberErrorCode,workspaceMemoryFailureCode,shouldSuppressRememberErrorDetails,workspaceMemoryFailureDiagnostics,MAX_REMEMBER_CONTENT_BYTES,formatWorkspaceMemoryForgetSummary,formatWorkspaceMemoryDreamSummary,isValidServerName,GENERATION_MAX_PROMPT_BYTES,GENERATION_TIMEOUT_MS,executeGeneration,projectAcpToolResultUpdate,HistoryReplayLimitError,createReplayCumulativeUsage,copyCumulativeUsage,degradeReplayEnvelopeAppHtml,collectHistoryReplayUpdates,replayTranscriptRecordPage};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{JsonFormatter}from"./chunk-
|
|
3
|
+
import{JsonFormatter}from"./chunk-CXPRHT3E.js";import{parseAndFormatApiError}from"./chunk-5AORBHSX.js";import{runExitCleanup}from"./chunk-ZSPOFXP3.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{FatalBudgetExceededError,FatalCancellationError,FatalTurnLimitedError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("CLI_ERRORS");var AlreadyReportedError=class extends Error{static{__name(this,"AlreadyReportedError")}exitCode;constructor(message,exitCode=1){super(message);this.name="AlreadyReportedError";this.exitCode=exitCode}};function getErrorMessage(error){if(error instanceof Error){return error.message}if(error!==null&&typeof error==="object"&&"message"in error&&typeof error.message==="string"){return error.message}if(error!==null&&typeof error==="object"){try{const stringified=JSON.stringify(error);return stringified??String(error)}catch{return String(error)}}return String(error)}__name(getErrorMessage,"getErrorMessage");function extractErrorCode(error){const errorWithCode=error;if(typeof errorWithCode.exitCode==="number"){return errorWithCode.exitCode}if(errorWithCode.code!==void 0){return errorWithCode.code}if(errorWithCode.status!==void 0){return errorWithCode.status}return 1}__name(extractErrorCode,"extractErrorCode");function getNumericExitCode(errorCode){return typeof errorCode==="number"?errorCode:1}__name(getNumericExitCode,"getNumericExitCode");var exiting=false;async function exitAfterCleanup(code,onExitCommitted){if(exiting)return new Promise(()=>{});exiting=true;onExitCommitted?.();await runExitCleanup();return process.exit(code)}__name(exitAfterCleanup,"exitAfterCleanup");function _resetExitLatchForTest(){exiting=false}__name(_resetExitLatchForTest,"_resetExitLatchForTest");async function handleError(error,config,customErrorCode,translate){if(error instanceof AlreadyReportedError){if(config.getOutputFormat()==="json"){const formatter=new JsonFormatter;const errorCode=customErrorCode??error.exitCode;const formattedError=formatter.formatError(error,errorCode);writeStderrLine(formattedError);return exitAfterCleanup(getNumericExitCode(errorCode))}await runExitCleanup();throw error}const errorMessage=parseAndFormatApiError(error,config.getContentGeneratorConfig()?.authType,translate);if(config.getOutputFormat()==="json"){const formatter=new JsonFormatter;const errorCode=customErrorCode??extractErrorCode(error);const formattedError=formatter.formatError(error instanceof Error?error:new Error(getErrorMessage(error)),errorCode);writeStderrLine(formattedError);return exitAfterCleanup(getNumericExitCode(errorCode))}else{writeStderrLine(errorMessage);await runExitCleanup();throw error}}__name(handleError,"handleError");var TOOL_NAME_ECHO_LIMIT=64;var DENIAL_REASON_ECHO_LIMIT=500;function sanitizeForStderr(text,limit){const clean=stripAnsiAndControl(text.replace(/\s+/g," ")).replace(new RegExp("\\p{Cf}","gu"),"").trim();return clean.length>limit?`${clean.slice(0,limit)}\u2026`:clean}__name(sanitizeForStderr,"sanitizeForStderr");function handleToolError(toolName,toolError,config,errorCode,resultDisplay,options={}){const isExecutionDenied=errorCode==="execution_denied";const isNonInteractive=!config.isInteractive();const isTextMode=config.getOutputFormat()==="text";if(isExecutionDenied&&isNonInteractive&&isTextMode){const displayName=sanitizeForStderr(toolName,TOOL_NAME_ECHO_LIMIT);if(options.approvalRequired){process.stderr.write(`Warning: Tool "${displayName}" requires user approval but cannot execute in non-interactive mode.
|
|
4
4
|
To enable automatic tool execution, use the -y flag (YOLO mode):
|
|
5
5
|
Example: qwen -p 'your prompt' -y
|
|
6
6
|
|