@qwen-code/qwen-code 0.25.4-preview.0 → 0.25.4-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled/browser-use/runtime/native-host.js +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/cli.js +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
- package/bundled/browser-use/runtime/node_modules/playwright-core/lib/xdg-open +0 -0
- package/bundled/browser-use/runtime/scripts/native-host-setup.js +0 -0
- package/chunks/{MaxSizedBox-M27H235V.js → MaxSizedBox-E4RKSA7W.js} +1 -1
- package/chunks/{StandaloneSessionPicker-LWWDDYOW.js → StandaloneSessionPicker-2D3UKLVS.js} +1 -1
- package/chunks/{acp-subagent-executor-NUV52JVS.js → acp-subagent-executor-UQYUN6AB.js} +1 -1
- package/chunks/{acpAgent-IUJDXLZM.js → acpAgent-P7WGK2BP.js} +3 -3
- package/chunks/{advisor-MSOUBMJ6.js → advisor-GCH2MBXT.js} +1 -1
- package/chunks/{agent-H7XIWYWQ.js → agent-57T4YAYP.js} +1 -1
- package/chunks/{agent-headless-XDN3D3S3.js → agent-headless-IBON3A7N.js} +1 -1
- package/chunks/{agent-host-client-AZP3PZXS.js → agent-host-client-LE7P72FR.js} +1 -1
- package/chunks/{agent-host-connections-JRVX7I6I.js → agent-host-connections-4DM57L26.js} +1 -1
- package/chunks/{anthropicContentGenerator-N7TV53LD.js → anthropicContentGenerator-C4TPFXUK.js} +1 -1
- package/chunks/{batch-MKSJFJUH.js → batch-YJJGMJWO.js} +1 -1
- package/chunks/{bridge-GNMKKHQ4.js → bridge-FIO2ENBG.js} +1 -1
- package/chunks/{channel-settings-store-Y4YCS7JX.js → channel-settings-store-TEBCLK2B.js} +1 -1
- package/chunks/{chunk-GPOUP5OK.js → chunk-27MTSS3T.js} +1 -1
- package/chunks/{chunk-C4ANA47H.js → chunk-2MGCRPM3.js} +1 -1
- package/chunks/{chunk-6DQNNRRC.js → chunk-2WBKWPSO.js} +1 -1
- package/chunks/{chunk-CATL2PQS.js → chunk-34WLYVDK.js} +5 -5
- package/chunks/{chunk-B7CXPNCV.js → chunk-3J2YNEHG.js} +1 -1
- package/chunks/{chunk-VTNHPXNL.js → chunk-3TBFTELA.js} +1 -1
- package/chunks/{chunk-7JT34VGK.js → chunk-46I6JBVL.js} +1 -1
- package/chunks/{chunk-FEMWELCV.js → chunk-4ZKFLOEH.js} +1 -1
- package/chunks/{chunk-7AYXAVTZ.js → chunk-5DUJIOOX.js} +3 -3
- package/chunks/{chunk-6QLHJSVW.js → chunk-6PWOLWTH.js} +1 -1
- package/chunks/{chunk-OW4QBRSR.js → chunk-6UZ65Z2P.js} +1 -1
- package/chunks/{chunk-V2JZO5MS.js → chunk-7DSJE3CL.js} +1 -1
- package/chunks/{chunk-TJMHIEYI.js → chunk-7LCY7GGX.js} +1 -1
- package/chunks/{chunk-TLJHBK3A.js → chunk-7RNTXEWH.js} +1 -1
- package/chunks/{chunk-YZ7OO4AQ.js → chunk-A3IF6IOB.js} +1 -1
- package/chunks/{chunk-VTF6AVZB.js → chunk-A6OQSOUO.js} +1 -1
- package/chunks/{chunk-Y7YDHCON.js → chunk-AJ6JUUP7.js} +1 -1
- package/chunks/{chunk-QTMHQGWQ.js → chunk-AOMEBVFW.js} +1 -1
- package/chunks/{chunk-KVTG2ZNH.js → chunk-AUNAS7AS.js} +1 -1
- package/chunks/{chunk-BOFD4CN3.js → chunk-AVIDPC5K.js} +1 -1
- package/chunks/{chunk-ETYTRKB2.js → chunk-BOLPBPWC.js} +1 -1
- package/chunks/{chunk-OAPA66DR.js → chunk-BQQBFDBY.js} +1 -1
- package/chunks/{chunk-NOS2CNOI.js → chunk-CN22ATWU.js} +1 -1
- package/chunks/{chunk-XYBEQRSZ.js → chunk-DIHJELGW.js} +1 -1
- package/chunks/{chunk-XCEL3EDX.js → chunk-DJFCI7TU.js} +1 -1
- package/chunks/{chunk-VKEL2XTM.js → chunk-DQPDMFS3.js} +1 -1
- package/chunks/{chunk-DJRFEZBY.js → chunk-DSYKB77N.js} +1 -1
- package/chunks/{chunk-UEW7Q26E.js → chunk-EDNOGHMN.js} +2 -2
- package/chunks/{chunk-RXNGYG64.js → chunk-EE36D2EV.js} +1 -1
- package/chunks/{chunk-NZKX7HYL.js → chunk-EGQDN3FJ.js} +1 -1
- package/chunks/{chunk-DFRSQK5Q.js → chunk-FHFBCG6N.js} +1 -1
- package/chunks/{chunk-PECV2VVZ.js → chunk-GI6T3RBV.js} +1 -1
- package/chunks/{chunk-37BNHIUB.js → chunk-GOLT5JXA.js} +1 -1
- package/chunks/{chunk-KITFF4GL.js → chunk-IDGXHMNL.js} +1 -1
- package/chunks/{chunk-6HIOSLUM.js → chunk-IIZWK7ZP.js} +1 -1
- package/chunks/{chunk-MPGEAX4K.js → chunk-IJC6ZH2S.js} +1 -1
- package/chunks/{chunk-TLYJVB5H.js → chunk-IO6LSEPV.js} +1 -1
- package/chunks/{chunk-QIJKEZZR.js → chunk-IYVNCBMS.js} +1 -1
- package/chunks/{chunk-S4GOHFRN.js → chunk-JHGOWK7M.js} +1 -1
- package/chunks/{chunk-GHRD2MMC.js → chunk-JRJY343T.js} +1 -1
- package/chunks/{chunk-WCYZSCG7.js → chunk-JVUXQU3W.js} +1 -1
- package/chunks/{chunk-DMCTJUIJ.js → chunk-K2K2YYWO.js} +1 -1
- package/chunks/{chunk-37OHWQHB.js → chunk-KF6HU732.js} +2 -2
- package/chunks/{chunk-5LSV73BG.js → chunk-KVWUOBH7.js} +1 -1
- package/chunks/{chunk-7V4BAHFT.js → chunk-LBWBGFHD.js} +1 -1
- package/chunks/{chunk-RKPHDO42.js → chunk-LDXZT3SG.js} +5 -5
- package/chunks/{chunk-BGFA2SAQ.js → chunk-LFOZ6AIH.js} +1 -1
- package/chunks/{chunk-4322TZID.js → chunk-LGQHT42X.js} +2 -2
- package/chunks/{chunk-PDXZ2CUO.js → chunk-M3O2XDHA.js} +1 -1
- package/chunks/{chunk-47K2NMP6.js → chunk-M3UC46LS.js} +1 -1
- package/chunks/{chunk-UFRY7WND.js → chunk-M7JLPTQI.js} +1 -1
- package/chunks/{chunk-SATEKHQP.js → chunk-MBUXP3IS.js} +1 -1
- package/chunks/{chunk-RN6JS263.js → chunk-MEZA3VVH.js} +1 -1
- package/chunks/{chunk-OBFKP7RI.js → chunk-MWN6TR36.js} +1 -1
- package/chunks/{chunk-VHJ43ZYJ.js → chunk-O7XRQWCG.js} +1 -1
- package/chunks/{chunk-H224LNV3.js → chunk-OYFRLT5E.js} +1 -1
- package/chunks/{chunk-3NWFV2YF.js → chunk-PMBGV76N.js} +1 -1
- package/chunks/{chunk-YFAPACDE.js → chunk-PVM4IVFL.js} +6 -6
- package/chunks/{chunk-7WS2EYMQ.js → chunk-PWHD4NK3.js} +1 -1
- package/chunks/{chunk-JZIQSEFO.js → chunk-Q54NROBX.js} +1 -1
- package/chunks/{chunk-FCLAPJ22.js → chunk-QE7R4DPT.js} +1 -1
- package/chunks/{chunk-J6TW7GNF.js → chunk-QIUTQICH.js} +1 -1
- package/chunks/{chunk-TWDCN5H2.js → chunk-QK63EULE.js} +1 -1
- package/chunks/{chunk-HZZT75LI.js → chunk-QTAC4W7J.js} +1 -1
- package/chunks/{chunk-P7DIAJNX.js → chunk-R7HBR4QQ.js} +1 -1
- package/chunks/{chunk-U2FJSKS3.js → chunk-RHEMFKMX.js} +1 -1
- package/chunks/{chunk-TRRY3QMM.js → chunk-RL57IU47.js} +1 -1
- package/chunks/{chunk-SPWDYRDH.js → chunk-S2OOQRLJ.js} +1 -1
- package/chunks/{chunk-QBRADQ7L.js → chunk-SWTMWNTZ.js} +1 -1
- package/chunks/{chunk-AZUDF52L.js → chunk-SXTKQHFZ.js} +1 -1
- package/chunks/{chunk-5RQRSPPD.js → chunk-T5S3MJIK.js} +1 -1
- package/chunks/{chunk-I3ORWQ2U.js → chunk-UDGDEIBB.js} +1 -1
- package/chunks/{chunk-EMDEBV33.js → chunk-UIFBF3E7.js} +1 -1
- package/chunks/{chunk-BGEMWNES.js → chunk-UQDPWI7D.js} +1 -1
- package/chunks/{chunk-I5LKOTZT.js → chunk-VON4MVIM.js} +1 -1
- package/chunks/{chunk-HJPO6MEW.js → chunk-W5D2T2JK.js} +1 -1
- package/chunks/{chunk-F6YYDRMH.js → chunk-WNGYYU67.js} +1 -1
- package/chunks/{chunk-S2GKUZZZ.js → chunk-WO3F62ZD.js} +1 -1
- package/chunks/{chunk-K7KW3ZJQ.js → chunk-WVY5Q6YY.js} +1 -1
- package/chunks/{chunk-GH6DPLWU.js → chunk-Y4Q667BW.js} +1 -1
- package/chunks/{chunk-FH74N7Y7.js → chunk-YJLMFUCS.js} +2 -2
- package/chunks/{chunk-C3Y2S5AM.js → chunk-YKHRCSKP.js} +1 -1
- package/chunks/{chunk-P4UJ7CXJ.js → chunk-YLIS36QA.js} +1 -1
- package/chunks/{chunk-4QIFOIBS.js → chunk-YVZ4XZRB.js} +1 -1
- package/chunks/{chunk-KGRD6G5J.js → chunk-Z27JJPKN.js} +1 -1
- package/chunks/{chunk-KOHHDB2L.js → chunk-ZCIS6MJZ.js} +1 -1
- package/chunks/{chunk-QNNDZYVW.js → chunk-ZHLQ222N.js} +1 -1
- package/chunks/{chunk-KWRZ3WJO.js → chunk-ZP7MTWMR.js} +1 -1
- package/chunks/{codex-subagent-executor-H44VDB5E.js → codex-subagent-executor-6OJVGF2S.js} +1 -1
- package/chunks/{config-utils-4X4SV4RL.js → config-utils-FI3A4QAN.js} +1 -1
- package/chunks/{contextCommand-4KVOHTAJ.js → contextCommand-YEBZQHG4.js} +1 -1
- package/chunks/{core-runtime-4RARI4NX.js → core-runtime-CFMHUAS7.js} +1 -1
- package/chunks/{create-sub-session-CNSRJFYG.js → create-sub-session-G26337FT.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-6XQQPP2H.js → daemon-git-worktree-guard-ITU6NQIV.js} +1 -1
- package/chunks/{daemon-status-provider-PRTEQT5T.js → daemon-status-provider-CSWRGMRX.js} +1 -1
- package/chunks/{daemon-trust-policy-GXKJVZDU.js → daemon-trust-policy-IYD7NOGK.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-L2ORKHMM.js → daemon-trust-policy-monitor-OWUP5SYB.js} +1 -1
- package/chunks/{deferred-core-runtime-RZQFUSPX.js → deferred-core-runtime-CVCQU7O4.js} +1 -1
- package/chunks/{edit-W44XQCIS.js → edit-7YBQLILC.js} +1 -1
- package/chunks/{enterPlanMode-B456A2XO.js → enterPlanMode-L3PVSD2P.js} +1 -1
- package/chunks/{environment-DSGQSQFS.js → environment-BVEOYQHO.js} +1 -1
- package/chunks/{errors-KL725247.js → errors-VQWBGR6D.js} +1 -1
- package/chunks/{execution-tool-KT3EBWHG.js → execution-tool-P7CBXSGZ.js} +1 -1
- package/chunks/{execution-worker-LPQ4HMN4.js → execution-worker-RZXNYK4B.js} +1 -1
- package/chunks/{exitPlanMode-JLKS76IA.js → exitPlanMode-MBUTM3NW.js} +1 -1
- package/chunks/{fast-path-5UD52IHH.js → fast-path-T2FDUSHV.js} +1 -1
- package/chunks/{glob-LYA2H6X3.js → glob-RH7XXSYE.js} +1 -1
- package/chunks/{goal-tools-SHSIDLZX.js → goal-tools-K6XBCE5E.js} +1 -1
- package/chunks/{handleAutoUpdate-T4RE6CZN.js → handleAutoUpdate-PG7R3KPH.js} +1 -1
- package/chunks/{i18n-5DK327WA.js → i18n-EGTBMA3N.js} +1 -1
- package/chunks/{initializer-TJGE4OJA.js → initializer-RIKH4PCP.js} +1 -1
- package/chunks/{installationInfo-MZ62GDIC.js → installationInfo-BBADHZLD.js} +1 -1
- package/chunks/{interactive-mod-session-YCUBQ6RM.js → interactive-mod-session-7RDKAHZ4.js} +1 -1
- package/chunks/{list-4L3LYDQM.js → list-YEGWEHJX.js} +1 -1
- package/chunks/{llm-3JQWBZXV.js → llm-D3LHPY27.js} +4 -4
- package/chunks/{llm-content-generator-6UPJWPOM.js → llm-content-generator-BLTBMV66.js} +1 -1
- package/chunks/{loadedSettingsAdapter-STPKAFJG.js → loadedSettingsAdapter-PLGMKMFO.js} +1 -1
- package/chunks/{local-execution-environment-IE5BOI7Y.js → local-execution-environment-4LDKFNC4.js} +1 -1
- package/chunks/{loggingContentGenerator-4KKWPZJA.js → loggingContentGenerator-376R7DRI.js} +1 -1
- package/chunks/{manage-memory-CRV5SXZZ.js → manage-memory-2ZTIVKNU.js} +1 -1
- package/chunks/{managed-execution-engine-FHLEWVND.js → managed-execution-engine-5LOM3MXG.js} +1 -1
- package/chunks/{managed-npm-update-BRHPOKDU.js → managed-npm-update-2C5JYEXW.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-GIQKZ5BH.js → managed-runtime-attestation-worker-R2FECMZK.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-P72BT46H.js → managed-runtime-bootstrap-KPLGH4UE.js} +1 -1
- package/chunks/{managed-runtime-session-worker-IYCJDB5K.js → managed-runtime-session-worker-EVKNPK3V.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-ONT4V5ZG.js → managed-runtime-ssh-worker-IA4HZ3PD.js} +1 -1
- package/chunks/{mcp-NXCQVE2Y.js → mcp-S67IJLI6.js} +1 -1
- package/chunks/{model-call-collection-3DNL45M5.js → model-call-collection-6OGPDTPG.js} +1 -1
- package/chunks/{model-configuration-6HRNYBWV.js → model-configuration-6RWVBOQS.js} +1 -1
- package/chunks/{modelConfigUtils-SKBN64ZW.js → modelConfigUtils-M3TVVYAO.js} +1 -1
- package/chunks/{monitor-7I7Q73UR.js → monitor-ZHOFTN7N.js} +1 -1
- package/chunks/{nonInteractiveCli-YLYRJUBE.js → nonInteractiveCli-6SUGPTJ4.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-U2ASWT63.js → nonInteractiveToolExecutor-SAHBGO3A.js} +1 -1
- package/chunks/{notebook-edit-WAD7IQCF.js → notebook-edit-ETUOQH6G.js} +1 -1
- package/chunks/{omni-POUUDVU3.js → omni-HV2UBGMZ.js} +1 -1
- package/chunks/{openaiContentGenerator-L7X6IVPL.js → openaiContentGenerator-RZCG7E4M.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-7XCMFI6P.js → openaiResponsesContentGenerator-X23L5JV3.js} +1 -1
- package/chunks/{pidfile-MQQT2ZDA.js → pidfile-26WXQCHG.js} +1 -1
- package/chunks/{processUtils-OZLF72NC.js → processUtils-WXLFGNBT.js} +1 -1
- package/chunks/{prompt-terminal-ledger-IYUF6SUU.js → prompt-terminal-ledger-EIZZHF4A.js} +1 -1
- package/chunks/{qwenContentGenerator-DKH3ILUO.js → qwenContentGenerator-GOY7Y6KH.js} +1 -1
- package/chunks/{reactive-degrade-KSNGHMBN.js → reactive-degrade-MNMTTHO5.js} +1 -1
- package/chunks/{read-file-VEELW4OQ.js → read-file-OJNGPNTQ.js} +1 -1
- package/chunks/{resumeHistoryUtils-4SFDTBXU.js → resumeHistoryUtils-QWOWF4VY.js} +1 -1
- package/chunks/{review-QA6HRLVU.js → review-5S24HP2V.js} +1 -1
- package/chunks/{ripGrep-4J6ASSE3.js → ripGrep-Y4PY2MQF.js} +1 -1
- package/chunks/{run-qwen-serve-EJ67LA5O.js → run-qwen-serve-EOUUDZUK.js} +2 -2
- package/chunks/{runtime-6E2FSB5U.js → runtime-ZBPOQX6E.js} +1 -1
- package/chunks/{sandboxConfig-4VE4LNRI.js → sandboxConfig-R7KDS3P5.js} +1 -1
- package/chunks/{scheduled-tasks-GM5EJMK7.js → scheduled-tasks-Q6V7D6K6.js} +1 -1
- package/chunks/{scheduler-HOSVIIOE.js → scheduler-EBQY6BOK.js} +1 -1
- package/chunks/{search-memory-HEAQCHIK.js → search-memory-HX6E23JC.js} +1 -1
- package/chunks/{send-message-FAQ7XEZ5.js → send-message-OZCCCH2F.js} +1 -1
- package/chunks/{serve-VNKPOWSW.js → serve-CMGCI4BK.js} +1 -1
- package/chunks/{server-U2XBJLOV.js → server-7LOAKPDN.js} +3 -3
- package/chunks/{session-AZGROSFX.js → session-LVQYZSJE.js} +1 -1
- package/chunks/{session-attachments-root-6M2ECUNK.js → session-attachments-root-NWG7JOMN.js} +1 -1
- package/chunks/{session-execution-engine-selector-PYDVOSJF.js → session-execution-engine-selector-PHH47ZMA.js} +1 -1
- package/chunks/{session-pr-refresh-3IS7DLEV.js → session-pr-refresh-5IACZPCY.js} +1 -1
- package/chunks/{sessionService-3FWNA4ZB.js → sessionService-7PFAWLHC.js} +1 -1
- package/chunks/{settings-VHKT7JJC.js → settings-CPZBOHN5.js} +1 -1
- package/chunks/{shell-TYOPVB7H.js → shell-A7NLPS2W.js} +1 -1
- package/chunks/{skill-GJQIE5AX.js → skill-VGANGVOD.js} +1 -1
- package/chunks/{skill-settings-76NI6SF3.js → skill-settings-TSZO3X6N.js} +1 -1
- package/chunks/{spawnChannel-FMSYLDKB.js → spawnChannel-2JQYNQKT.js} +1 -1
- package/chunks/{standalone-update-BPZQDQHD.js → standalone-update-QXC3RM6I.js} +1 -1
- package/chunks/{start-opentui-ui-X7XYV5N3.js → start-opentui-ui-BKJ4JHVK.js} +1 -1
- package/chunks/{startInteractiveUI-UZDF4JUB.js → startInteractiveUI-4QIPR7ZY.js} +1 -1
- package/chunks/{team-create-RFZNEF76.js → team-create-5MU6BGXX.js} +1 -1
- package/chunks/{team-plan-approval-MGW3JGSC.js → team-plan-approval-NZUJ6FSA.js} +1 -1
- package/chunks/{terminal-image-renderer-3UED5GZV.js → terminal-image-renderer-CTMJULJ2.js} +1 -1
- package/chunks/{theme-manager-SF6FSSZW.js → theme-manager-6H7GA6QR.js} +1 -1
- package/chunks/{tool-call-W2CJR74U.js → tool-call-XG4CAD5X.js} +1 -1
- package/chunks/{tool-result-media-XSFON2ZQ.js → tool-result-media-RJ5ONO7R.js} +1 -1
- package/chunks/{tool-search-7GY5YTOU.js → tool-search-KBINGEWV.js} +1 -1
- package/chunks/{total-session-admission-OATGW6M5.js → total-session-admission-XNWYCO7G.js} +1 -1
- package/chunks/{trustedFolders-AM4PSGUB.js → trustedFolders-JT5MOB3A.js} +1 -1
- package/chunks/{update-relaunch-YKY52XUT.js → update-relaunch-HXMQI3HO.js} +1 -1
- package/chunks/{updateCheck-RKQ5CPZM.js → updateCheck-XWE3TWL5.js} +1 -1
- package/chunks/{upload-config-CBT7ARZY.js → upload-config-ET7NRHU7.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-Z3YWPUNO.js → useAutoAcceptIndicator-TPMYKNJX.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-7CQHU2RF.js → validateNonInterActiveAuth-U52KMEDS.js} +1 -1
- package/chunks/{version-N2OB6KWP.js → version-CW4RTJ3H.js} +1 -1
- package/chunks/{web-fetch-L5XCBCBA.js → web-fetch-UPMJ3XIZ.js} +1 -1
- package/chunks/{web-search-4EHUA3LJ.js → web-search-PXABWQVC.js} +1 -1
- package/chunks/{workflow-FGAUAYIP.js → workflow-UQ4V3NBZ.js} +1 -1
- package/chunks/{workflow-ancestor-trust-F7RRN6I3.js → workflow-ancestor-trust-QII5KTUJ.js} +1 -1
- package/chunks/{workspace-agents-QW4TKC52.js → workspace-agents-Q3KKMDX2.js} +1 -1
- package/chunks/{workspace-providers-status-MFSZT3YA.js → workspace-providers-status-3ASB64FB.js} +1 -1
- package/chunks/{workspace-registration-store-WQRDSIEI.js → workspace-registration-store-2NPD6U3B.js} +1 -1
- package/chunks/{workspace-registry-FXZFRSCH.js → workspace-registry-6QJKRCDR.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-LJ5YAT3A.js → workspace-runtime-coordinator-ZXUWDQIB.js} +1 -1
- package/chunks/{workspace-service-U632SUWU.js → workspace-service-YPYTYYUN.js} +1 -1
- package/chunks/{workspace-skills-status-M7YXM3LF.js → workspace-skills-status-VTFHQ6R7.js} +1 -1
- package/chunks/{workspace-trust-reconciler-NLJGGI4K.js → workspace-trust-reconciler-52CZVPKH.js} +1 -1
- package/chunks/{write-file-BJCKSXX7.js → write-file-FDBR76G5.js} +1 -1
- package/chunks/{zoom-image-TLJPD4DB.js → zoom-image-MYKWCCXO.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +4 -4
- package/vendor/landlock-run/arm64-linux/qwen-landlock-run +0 -0
- package/vendor/landlock-run/x64-linux/qwen-landlock-run +0 -0
- package/vendor/ripgrep/arm64-darwin/rg +0 -0
- package/vendor/ripgrep/arm64-linux/rg +0 -0
- package/vendor/ripgrep/x64-darwin/rg +0 -0
- package/vendor/ripgrep/x64-linux/rg +0 -0
- package/vendor/tree-sitter/tree-sitter-bash.wasm +0 -0
- package/vendor/tree-sitter/tree-sitter.wasm +0 -0
- package/web-shell/assets/{PierreFilePreview-D9tbdFw8.js → PierreFilePreview-DGTp45Z4.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-CeFAk2s-.js → SpreadsheetPreview-DVC_YVei.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-iaURw8SR.js → WorkspaceFileBrowser-DaQNpS06.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-Z4CT1NCF.js → abnfDiagram-VCTEODGH-wJbiOoPK.js} +1 -1
- package/web-shell/assets/{agents-route-B7o2Rq-a.js → agents-route-DUhhA1KI.js} +1 -1
- package/web-shell/assets/{arc-DcHBdUJQ.js → arc-CvpNMy1d.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-DRDhEC81.js → architectureDiagram-5GKGNRK7-DIhi3dIz.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-CYRE6WIc.js → blockDiagram-NRAW4CY4-CoeyTlVJ.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-CIM8N_Sj.js → c4Diagram-UCG6FXSJ-BYoK_I9M.js} +1 -1
- package/web-shell/assets/channel-DvtGOCg6.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-Bbfka9Fe.js → chunk-2Q5K7J3B-BeD4GwPg.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-C02zF3RY.js → chunk-5VM5RSS4-BpkJsB_y.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-Dn0wRD2F.js → chunk-F27PBJKO-BROEWQ1J.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-Dwpl3l0W.js → chunk-G27WJ6UU-DA8Wtppt.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-sQbzSoTR.js → chunk-JWPE2WC7-GqB-QFh5.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-DNlNDtfr.js → chunk-LCL6LL3I-DIPUwYsX.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-BOgf1Dl3.js → chunk-POPQ4Y6H-DbnU-jxX.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-DOofWP00.js → chunk-SVP7TREG-DvH7bQ-w.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-Bj9FxhWU.js → chunk-XXDRQBXY-DdVWVo3U.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-9NR5W1rE.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-9NR5W1rE.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-CUlPjyww.js → cose-bilkent-JH36ORCC-JgMKxP9H.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-5noArzI7.js → cynefin-OW5HDTMX-BVUpNgVm.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-DELvTqmf.js → cynefinDiagram-5FMLGOSQ-CxAdk-iS.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-CAL6Z3hL.js → dagre-3AP2YEHR-CvXWkM86.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-DQC2gaIi.js → diagram-S7CK7UJ4-DD_PS4nm.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-CkU6M-3R.js → diagram-UQ7AKVKN-EVZkTODD.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-CvHpHwVx.js → diagram-VSXAHHWV-CGZc1pZU.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-D9l5F9iB.js → diagram-VX7I27RA-DjNql499.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-DW-VFvYx.js → diagram-Z3DM3KII-CCa0WtmR.js} +1 -1
- package/web-shell/assets/{docx-preview-8MQfOGQh.js → docx-preview-DpVElxvj.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-C0Q71wC_.js → ebnfDiagram-PWID7BFC-W2hoOJZF.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-DWDLRh1S.js → erDiagram-SSCWMZ5O-Dz5NxxEb.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-CVzJnl1P.js → flowDiagram-A5DVABFB-BTMAn8b5.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-B320pcgR.js → ganttDiagram-EL5Y4UJY-BaFrd5ZY.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Di4uZh-J.js → gitGraphDiagram-WWUBYQGX-IlmdUqRk.js} +1 -1
- package/web-shell/assets/{index-Csr8Hx_O.js → index-C2ez0ZjE.js} +1 -1
- package/web-shell/assets/{index-C9BecA_H.js → index-Cs-XBNmB.js} +101 -101
- package/web-shell/assets/{infoDiagram-RXCK75RN-CbafhxET.js → infoDiagram-RXCK75RN-BHs9kpar.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-DrQuIDeR.js → ishikawaDiagram-5VMMS53U-DWCEQ85v.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-BschmjBj.js → journeyDiagram-EYS64GPL-RTDAw9yc.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-B7x9BU9N.js → kanban-definition-3QL26DDD-B7Nl9bq6.js} +1 -1
- package/web-shell/assets/{layout-BewPaOyO.js → layout-BabjFEb1.js} +1 -1
- package/web-shell/assets/{linear-CnLILCVp.js → linear-CZuGjuQd.js} +1 -1
- package/web-shell/assets/{mermaid.core-Csj9KPfJ.js → mermaid.core-CK78bIGt.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-CIGTi5gg.js → mindmap-definition-FBJOCRG2-BbcCi_jP.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-CuWBRQzb.js → pegDiagram-XKGWAZYB-DpLQ7u8i.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-Co5ukXCE.js → pieDiagram-E7YTZNPT-BpWFVtM0.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-B0hzjh6o.js → quadrantDiagram-AXDQQJYC-CGzYlaN1.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-nhkJB0xD.js → railroadDiagram-O6MQD6OU-BNQYW-Zi.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-C7NpxjVR.js → requirementDiagram-EFPCY7ZU-C4fCdIDW.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CUWlnhZC.js → sankeyDiagram-P5KCCOFB-BvbbAnMA.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BoykH0_J.js → sequenceDiagram-WJ2MYXX4-DGXNc6E1.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-aF-PkSe5.js → sizeCapture-X5ZJPWSS-C4W45Xf5.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-g5q0b922.js → stateDiagram-HBIQ2CUA-D3q0fen-.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-XKoYIi05.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-BbASszfe.js → swimlanes-XN3QIQJK-D8n-ResR.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-C7qJMSzs.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-AXIV0TJJ.js → timeline-definition-24CTP7MA-Cio4y1mM.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-B-E0rj1h.js → vennDiagram-4TSXK5OY-DVlg0xnc.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DiOOYJ2D.js → wardleyDiagram-VM6X3IG4-CgeIsimQ.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-De_z7HkS.js → xychartDiagram-S5SC5T6Z-UXjyTLnU.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-Bwr9aS_E.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-BmY8Mmyo.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-BmY8Mmyo.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CTOjUMow.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bz6ia3oL.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DEFAULT_RING_SIZE,EVENT_SCHEMA_VERSION,EventBus,isSummaryReplayEvent,logEventSizingFailed,mcpAppTextFallback,serializedBridgeEventByteLength,summarizeReplay,summarizeReplayEvent}from"./chunk-BWQ5AIEA.js";import{JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeJournalGrowthPoolBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{MCP_RESTART_SERVER_DEADLINE_MS}from"./chunk-IFPLGH5C.js";import{channelFactoryForwardsChildEnv,defaultSpawnChannelFactory}from"./chunk-SC6ZKUED.js";import{BridgeChannelClosedError,BridgeTimeoutError,SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS,STATUS_SCHEMA_VERSION,SessionRestoreTimeoutError,createIdleWorkspaceExtensionsStatus,createIdleWorkspaceHooksStatus}from"./chunk-YQ4ID2TH.js";import{ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM,ACTIVE_WORK_CLOSE_TIMEOUT_MS,ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,ACTIVE_WORK_HEARTBEAT_META_KEY,ACTIVE_WORK_HEARTBEAT_VERSION,ACTIVE_WORK_HOLD_CATEGORIES,ACTIVE_WORK_MAX_SESSION_HOLDS,ACTIVE_WORK_MAX_SNAPSHOT_SESSIONS,ACTIVE_WORK_NOTIFICATION_METHOD,ACTIVE_WORK_STALE_INTERVALS,CHANNEL_LIVENESS_META_KEY,CHANNEL_LIVENESS_VERSION,CHANNEL_OUTPUT_MODE_META_KEY,CHANNEL_PROMPT_META_KEY,CHANNEL_STARTUP_PROFILE_META_KEY,CHANNEL_STARTUP_PROFILE_VERSION,DAEMON_ATTACHMENT_CONTEXT_META_KEY,DAEMON_ATTACHMENT_REFERENCES_META_KEY,DAEMON_CHANNEL_DELIVERY_META_KEY,DAEMON_INPUT_ANNOTATIONS_META_KEY,DAEMON_MODEL_PROMPT_META_KEY,DAEMON_PERMISSION_CANCEL_REASON_META_KEY,DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUBMITTED_PROMPT_META_KEY,DAEMON_SUPPRESS_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUPPRESS_WORKTREE_CONTEXT_RESTORE_META_KEY,IMAGE_ONLY_PROMPT_TEXT,LOAD_REPLAY_BULK_MODE,LOAD_REPLAY_HIDE_INHERITED_META_KEY,LOAD_REPLAY_MAX_UPDATES,LOAD_REPLAY_META_KEY,LOAD_REPLAY_MODE_META_KEY,LOAD_REPLAY_PAGE_SIZE_META_KEY,LOAD_REPLAY_VERSION,MID_TURN_QUEUE_DRAIN_METHOD,MID_TURN_RECONCILIATION_RING_SIZE,MID_TURN_SEND_NOW_METHOD,PROMPT_CANCEL_METHOD,PROMPT_CANCEL_REASON_META_KEY,REQUESTED_SESSION_ID_META_KEY,SESSION_INITIALIZATION_DEADLINE_META_KEY,SESSION_INITIALIZATION_TIMEOUT_ERROR_KIND,SESSION_MODEL_PERSIST_DEFAULT_META_KEY,SUBMITTED_PROMPT_META_KEY,TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,USER_CANCEL_ABORT_REASON,WORKTREE_MCP_DEFER_META_KEY,activeWorkCloseRetryDelayMs,clampActiveWorkIntervalMs,getPromptCancelAbortReason,isValidTrustedModelPrompt,parseBackgroundNotificationTurn,sessionCloseDrainBudgetMs}from"./chunk-WBDNGVHU.js";import{BranchWhilePromptActiveError,BridgeChannelQuarantinedError,CancelSentinelCollisionError,CdWhilePromptActiveError,InvalidClientIdError,InvalidPermissionOptionError,InvalidRewindTargetError,InvalidSessionMetadataError,InvalidSessionScopeError,ManagedSessionBranchUnsupportedError,McpAuthenticationInProgressError,PermissionForbiddenError,PromptDeadlineExceededError,PromptQueueFullError,RequestedSessionIdRejectedError,RestoreInProgressError,SessionBusyError,SessionLimitExceededError,SessionNotFoundError,SessionResetPendingError,SessionShellClientRequiredError,SessionShellDisabledError,StandaloneSessionSpawnError,WorkspaceChangePartiallyAppliedError,WorkspaceDrainingError,WorkspaceMismatchError,WorkspaceRuntimeStopError,isNotCurrentlyGeneratingCancelError}from"./chunk-VTZZXEWA.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{CHANNEL_DELIVERY_ERROR_CODES,LIVE_TASK_TOOL_NAMES,MAX_LIVE_SCREEN_CONTEXT_TEXT_CHARS,MAX_LIVE_SPEAK_TO_USER_MESSAGE_CHARS,MAX_SUB_SESSION_NAME_CHARS}from"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_READY_META_KEY,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,isValidExternalToolGuardDenialReason}from"./chunk-NIEO2TBE.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError}from"./chunk-WSOEJTOC.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import{MAX_SUB_SESSION_PROMPT_CHARS}from"./chunk-MD3ZEOBX.js";import{MAX_DIRECTORY_ARTIFACT_DEPTH,MAX_DIRECTORY_ARTIFACT_FILES,collectRecordableWorkspaceFiles,isOfficeDocumentExtension,isRecordableDerivedChild,pathHasSkippedDirectoryComponent}from"./chunk-NZFR5IY7.js";import{SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SESSION_TRANSCRIPT_MAX_LIMIT,TURN_RESULT_CODE_TEXT_TRUNCATED,TURN_RESULT_TEXT_MAX_CHARS,TrustGateError,canonicalSessionPrUrl,normalizeTurnResultError,toSessionPrInfo}from"./chunk-RKPHDO42.js";import{SESSION_EXECUTION_ENGINE_META_KEY}from"./chunk-VZDZ34KK.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{PUBLISHED_CONTENT_SHA256_METADATA_KEY,SESSION_ARTIFACT_PERSISTENCE_VERSION,WORKSPACE_CONTENT_MTIME_MS_METADATA_KEY,WORKSPACE_CONTENT_SHA256_METADATA_KEY,WORKSPACE_CONTENT_SIZE_BYTES_METADATA_KEY,deleteArtifactSnapshot,getWebPreviewSnapshotId,isAdoptableContentFingerprintKey,isPrototypeMetadataKey,isReservedWorkspaceMetadataKey,metadataBudgetBytes,normalizeSnapshotPayload,retainArtifactSnapshot,sessionArtifactIdentityKey,stableSessionArtifactId}from"./chunk-AG3SSCAF.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,isValidCronTaskRoutingId}from"./chunk-VMQO3VPA.js";import{SessionSourceError,validateSessionSourceInput}from"./chunk-G5PYYZMM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ShellExecutionService}from"./chunk-3X7DP5W3.js";import{DAEMON_TRACEPARENT_META_KEY,DAEMON_TRACESTATE_META_KEY}from"./chunk-VTDSLBET.js";import{getSpecificMimeType}from"./chunk-JU2HHQR5.js";import{INVOCATION_CONTEXT_META_KEY,PRIVATE_ACP_CAPABILITY_ENV,PRIVATE_PARENT_CAPABILITY_META_KEY}from"./chunk-SLD7H2FA.js";import{REASONING_EFFORT_TIERS}from"./chunk-TAAJ7TDB.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{inspect}from"node:util";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var LogSafeAcpRequestError=class extends RequestError{constructor(code,message,data,reservePreparedResponse){super(code,message,data);this.reservePreparedResponse=reservePreparedResponse}static{__name(this,"LogSafeAcpRequestError")}toResult(){const result=super.toResult();if("error"in result){Object.defineProperty(result.error,inspect.custom,{configurable:true,value:__name(()=>({code:result.error.code,payloadOmitted:true}),"value")});try{this.reservePreparedResponse?.(result.error)}catch{}}return result}};var MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS=1024;var MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS=128;var MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS=512;function logSafeAcpErrorDetails(error){const details=error instanceof Error?error.message:isRecord(error)&&typeof error["message"]==="string"?error["message"]:void 0;if(!details)return void 0;return{details:details.length<=MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS?details:`${details.slice(0,MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS)}\u2026`}}__name(logSafeAcpErrorDetails,"logSafeAcpErrorDetails");function boundedAcpErrorString(value,maxChars){return value.length<=maxChars?value:`${value.slice(0,maxChars)}\u2026`}__name(boundedAcpErrorString,"boundedAcpErrorString");function logSafeRequestErrorMessage(code){switch(code){case-32700:return"Parse error";case-32600:return"Invalid request";case-32601:return"Method not found";case-32602:return"Invalid params";case-32603:return"Internal error";case-32e3:return"Authentication required";case-32002:return"Resource not found";default:return"ACP client request failed"}}__name(logSafeRequestErrorMessage,"logSafeRequestErrorMessage");function logSafeRequestErrorData(data){if(!isRecord(data)||typeof data["errorKind"]!=="string"){return void 0}const status=data["status"];const hint=data["hint"];return{errorKind:boundedAcpErrorString(data["errorKind"],MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS),...typeof status==="number"&&Number.isFinite(status)?{status}:{},...typeof hint==="string"?{hint:boundedAcpErrorString(hint,MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS)}:{}}}__name(logSafeRequestErrorData,"logSafeRequestErrorData");var AcpInboundHandlerLimitError=class extends Error{constructor(maxActiveHandlers,maxActiveHandlerBytes,requiredBytes,availableBytes){super("ACP inbound handler capacity exceeded");this.maxActiveHandlers=maxActiveHandlers;this.maxActiveHandlerBytes=maxActiveHandlerBytes;this.requiredBytes=requiredBytes;this.availableBytes=availableBytes;this.name="AcpInboundHandlerLimitError"}static{__name(this,"AcpInboundHandlerLimitError")}code="acp_handler_limit_exceeded"};function estimateAcpHandlerBytes(value,limitBytes){let bytes=0;const stack=[value];const seen=new WeakSet;while(stack.length>0){const current=stack.pop();if(current===null){bytes+=4}else if(typeof current==="string"){bytes+=Buffer.byteLength(current)+2}else if(typeof current==="number"){bytes+=24}else if(typeof current==="boolean"){bytes+=5}else if(Array.isArray(current)){if(seen.has(current))return limitBytes+1;seen.add(current);bytes+=2+Math.max(0,current.length-1);if(bytes+current.length>limitBytes)return limitBytes+1;for(let index=current.length-1;index>=0;index--){stack.push(current[index])}}else if(isRecord(current)){if(seen.has(current))return limitBytes+1;seen.add(current);const entries=Object.entries(current);bytes+=2+Math.max(0,entries.length-1);for(const[key,entryValue]of entries){bytes+=Buffer.byteLength(key)+3;stack.push(entryValue)}}else{bytes+=4}if(bytes>limitBytes)return limitBytes+1}return Math.max(1,bytes)}__name(estimateAcpHandlerBytes,"estimateAcpHandlerBytes");var AcpInboundHandlerAdmission=class{constructor(guard){this.guard=guard}static{__name(this,"AcpInboundHandlerAdmission")}activeHandlers=0;activeBytes=0;async run(params,operation){const envelopeBytes=Math.min(2048,this.guard.maxActiveHandlerBytes);const requiredBytes=envelopeBytes+estimateAcpHandlerBytes(params,Math.max(0,this.guard.maxActiveHandlerBytes-envelopeBytes));const availableBytes=Math.max(0,this.guard.maxActiveHandlerBytes-this.activeBytes);if(this.activeHandlers>=this.guard.maxActiveHandlers||requiredBytes>availableBytes){const error=new AcpInboundHandlerLimitError(this.guard.maxActiveHandlers,this.guard.maxActiveHandlerBytes,requiredBytes,availableBytes);this.guard.fail(error);throw error}this.activeHandlers++;this.activeBytes+=requiredBytes;try{return await operation()}finally{this.activeHandlers--;this.activeBytes-=requiredBytes}}};async function withLogSafeAcpError(operation,reservePreparedResponse){try{return await operation()}catch(error){if(error instanceof RequestError){const code=Number.isFinite(error.code)?error.code:-32603;throw new LogSafeAcpRequestError(code,logSafeRequestErrorMessage(code),logSafeRequestErrorData(error.data),reservePreparedResponse)}throw new LogSafeAcpRequestError(-32603,"Internal error",logSafeAcpErrorDetails(error),reservePreparedResponse)}}__name(withLogSafeAcpError,"withLogSafeAcpError");function createLogSafeAcpClient(client,transportGuard){const admission=new AcpInboundHandlerAdmission(transportGuard);const runNotification=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,operation)),"runNotification");const runRequest=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,async()=>{const result=await operation();transportGuard.reservePreparedResponse(result??null);return result}),transportGuard.reservePreparedResponse),"runRequest");return{requestPermission:__name(params=>runRequest(params,()=>client.requestPermission(params)),"requestPermission"),sessionUpdate:__name(params=>runNotification(params,()=>client.sessionUpdate(params)),"sessionUpdate"),writeTextFile:client.writeTextFile?params=>runRequest(params,()=>client.writeTextFile(params)):void 0,readTextFile:client.readTextFile?params=>runRequest(params,()=>client.readTextFile(params)):void 0,createTerminal:client.createTerminal?params=>runRequest(params,()=>client.createTerminal(params)):void 0,terminalOutput:client.terminalOutput?params=>runRequest(params,()=>client.terminalOutput(params)):void 0,releaseTerminal:client.releaseTerminal?params=>runRequest(params,async()=>await client.releaseTerminal(params)??{}):void 0,waitForTerminalExit:client.waitForTerminalExit?params=>runRequest(params,()=>client.waitForTerminalExit(params)):void 0,killTerminal:client.killTerminal?params=>runRequest(params,async()=>await client.killTerminal(params)??{}):void 0,extMethod:client.extMethod?(method,params)=>runRequest(params,()=>client.extMethod(method,params)):void 0,extNotification:client.extNotification?(method,params)=>runNotification(params,()=>client.extNotification(method,params)):void 0}}__name(createLogSafeAcpClient,"createLogSafeAcpClient");var OUTBOUND_GUARDED_CONNECTION_METHODS=new Set(["initialize","newSession","loadSession","unstable_forkSession","unstable_listSessions","unstable_resumeSession","setSessionMode","unstable_setSessionModel","setSessionConfigOption","authenticate","prompt","cancel","extMethod","extNotification"]);function createOutboundGuardedConnection(connection,transportGuard){const wrappers=new Map;return new Proxy(connection,{get(target,property){const value=Reflect.get(target,property,target);if(typeof value!=="function"||!OUTBOUND_GUARDED_CONNECTION_METHODS.has(property)){return value}let wrapper=wrappers.get(property);if(!wrapper){wrapper=__name(async(...args)=>{const release=transportGuard.reserveOutboundOperation(args);try{return await Reflect.apply(value,target,args)}finally{release()}},"wrapper");wrappers.set(property,wrapper)}return wrapper}})}__name(createOutboundGuardedConnection,"createOutboundGuardedConnection");function createHarnessConnection(client,channel){const rawConnection=new ClientSideConnection(()=>channel.transportGuard?createLogSafeAcpClient(client,channel.transportGuard):client,channel.stream);return channel.transportGuard?createOutboundGuardedConnection(rawConnection,channel.transportGuard):rawConnection}__name(createHarnessConnection,"createHarnessConnection");init_esbuild_shims();function createChannelLifecycle(defaultEngine){const channels=new Map;const aliveChannels=new Set;const starting=new Map;return{get current(){return channels.get(defaultEngine)},get starting(){return starting.get(defaultEngine)},currentFor:__name((engine=defaultEngine)=>channels.get(engine),"currentFor"),startingFor:__name((engine=defaultEngine)=>starting.get(engine),"startingFor"),startups:__name(()=>starting.values(),"startups"),get size(){return aliveChannels.size},has(info){return aliveChannels.has(info)},values(){return aliveChannels.values()},track(info){aliveChannels.add(info)},publish(info){channels.set(info.executionEngine,info)},remove(info){aliveChannels.delete(info);if(channels.get(info.executionEngine)===info)channels.delete(info.executionEngine)},startSpawn(spawn,engine=defaultEngine){let promise=starting.get(engine);if(!promise){promise=spawn();starting.set(engine,promise)}return promise},finishSpawn(engine=defaultEngine){starting.delete(engine)}}}__name(createChannelLifecycle,"createChannelLifecycle");init_esbuild_shims();import{randomBytes,randomUUID}from"node:crypto";init_esbuild_shims();function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient){return{protocolVersion:PROTOCOL_VERSION,_meta:{[ACTIVE_WORK_HEARTBEAT_META_KEY]:{v:ACTIVE_WORK_HEARTBEAT_VERSION,intervalMs:ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,categories:[...ACTIVE_WORK_HOLD_CATEGORIES]},[CHANNEL_STARTUP_PROFILE_META_KEY]:{v:CHANNEL_STARTUP_PROFILE_VERSION},[CHANNEL_LIVENESS_META_KEY]:{v:CHANNEL_LIVENESS_VERSION},[PRIVATE_PARENT_CAPABILITY_META_KEY]:privateParentCapability},clientCapabilities:{_meta:{"qwen.goalProposals":true},fs:{readTextFile:delegateReadTextFileToClient,writeTextFile:true}},clientInfo:{name:"qwen-serve-bridge",version:"0"}}}__name(createChannelInitializeRequest,"createChannelInitializeRequest");function negotiateChannelCapabilities(response,requireExternalToolGuard){if(requireExternalToolGuard){const guardAck=response._meta?.[EXTERNAL_TOOL_GUARD_READY_META_KEY];if(guardAck!==EXTERNAL_TOOL_GUARD_REQUIRED_VALUE){throw new Error(`ACP child did not acknowledge the required external tool guard (received: ${JSON.stringify(guardAck)}).`)}}let activeWork;const activeWorkCapability=isRecord2(response._meta)?response._meta[ACTIVE_WORK_HEARTBEAT_META_KEY]:void 0;if(isRecord2(activeWorkCapability)&&activeWorkCapability["v"]===ACTIVE_WORK_HEARTBEAT_VERSION){const advertised=activeWorkCapability["categories"];activeWork={intervalMs:clampActiveWorkIntervalMs(activeWorkCapability["intervalMs"]),categories:Array.isArray(advertised)?ACTIVE_WORK_HOLD_CATEGORIES.filter(category=>advertised.includes(category)):[]}}const channelLivenessCapability=isRecord2(response._meta)?response._meta[CHANNEL_LIVENESS_META_KEY]:void 0;return{activeWork,channelLiveness:isRecord2(channelLivenessCapability)&&channelLivenessCapability["v"]===CHANNEL_LIVENESS_VERSION}}__name(negotiateChannelCapabilities,"negotiateChannelCapabilities");init_esbuild_shims();init_esbuild_shims();async function withTimeout(p,ms,label){let timer;const timeoutP=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BridgeTimeoutError(label,ms)),ms)});try{return await Promise.race([p,timeoutP])}finally{if(timer)clearTimeout(timer)}}__name(withTimeout,"withTimeout");async function terminateChannel(channel,timeoutMs,context){try{await withTimeout(channel.kill(),timeoutMs,`${context} teardown`)}catch(error){try{channel.killSync()}catch(forceError){throw new AggregateError([error,forceError],`ACP channel teardown failed (${context})`)}throw error}}__name(terminateChannel,"terminateChannel");function channelUnavailableReject(channel,context){const unavailable=channel.transportFailed?Promise.race([channel.exited,channel.transportFailed]):channel.exited;const reject=__name(()=>{throw new BridgeChannelClosedError(context)},"reject");return unavailable.then(reject,reject)}__name(channelUnavailableReject,"channelUnavailableReject");init_esbuild_shims();import{performance as performance2}from"node:perf_hooks";var CHANNEL_LIVENESS_INTERVAL_MS=15e3;var CHANNEL_LIVENESS_PROBE_TIMEOUT_MS=1e4;var CHANNEL_LIVENESS_FAILURE_THRESHOLD=2;var CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS=1e3;var CHANNEL_LIVENESS_TIMEOUT_CODE="acp_channel_liveness_timeout";var CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE="acp_channel_liveness_protocol_error";var ChannelLivenessFailure=class extends Error{constructor(code){super(code===CHANNEL_LIVENESS_TIMEOUT_CODE?"ACP channel failed consecutive liveness probes":"ACP channel returned an invalid liveness response");this.code=code;this.name="ChannelLivenessFailure"}static{__name(this,"ChannelLivenessFailure")}};function isValidResponse(response,nonce){return typeof response==="object"&&response!==null&&!Array.isArray(response)&&response["v"]===CHANNEL_LIVENESS_VERSION&&response["nonce"]===nonce}__name(isValidResponse,"isValidResponse");function startChannelLivenessMonitor(options){const now=options.now??(()=>performance2.now());let stopped=false;let timer;let consecutiveTimeouts=0;let nextNonce=0;let resolveStopped;const stoppedOutcome=new Promise(resolve3=>{resolveStopped=resolve3});const isActive=__name(()=>!stopped&&options.isActive(),"isActive");const stop=__name(()=>{stopped=true;if(timer!==void 0){clearTimeout(timer);timer=void 0}resolveStopped({kind:"stopped"})},"stop");const fail=__name(error=>{if(!isActive())return;stop();options.onFailure(error)},"fail");const timerWasLate=__name(expectedAt=>now()>expectedAt+CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS,"timerWasLate");const runProbe=__name(async()=>{if(!isActive())return;const nonce=nextNonce;nextNonce=nonce===Number.MAX_SAFE_INTEGER?0:Math.max(0,nonce+1);const response=Promise.resolve().then(()=>options.probe(nonce)).then(value=>({kind:"response",response:value}),()=>({kind:"rejected"}));let outcome;while(true){const expectedAt=now()+CHANNEL_LIVENESS_PROBE_TIMEOUT_MS;const timeout=new Promise(resolve3=>{timer=setTimeout(()=>{timer=void 0;resolve3(timerWasLate(expectedAt)?{kind:"local_delay"}:{kind:"timeout"})},CHANNEL_LIVENESS_PROBE_TIMEOUT_MS);timer.unref()});outcome=await Promise.race([response,timeout,stoppedOutcome]);if(timer!==void 0){clearTimeout(timer);timer=void 0}if(outcome.kind==="stopped"||!isActive())return;if(outcome.kind!=="local_delay")break;consecutiveTimeouts=0}if(outcome.kind==="response"){if(!isValidResponse(outcome.response,nonce)){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}if(outcome.kind==="rejected"){await Promise.resolve();fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts++;if(consecutiveTimeouts>=CHANNEL_LIVENESS_FAILURE_THRESHOLD){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_TIMEOUT_CODE));return}void runProbe()},"runProbe");function schedule(delayMs){if(!isActive())return;const expectedAt=now()+delayMs;timer=setTimeout(()=>{timer=void 0;if(!isActive())return;if(timerWasLate(expectedAt)){consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}void runProbe()},delayMs);timer.unref()}__name(schedule,"schedule");schedule(CHANNEL_LIVENESS_INTERVAL_MS);return{stop}}__name(startChannelLivenessMonitor,"startChannelLivenessMonitor");init_esbuild_shims();var MAX_PROFILE_DURATION_MS=6e5;var ATTRIBUTE_PREFIX="qwen-code.daemon.acp_startup";function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord3,"isRecord");function readDuration(source,key){const value=source[key];return typeof value==="number"&&Number.isFinite(value)&&value>=0&&value<=MAX_PROFILE_DURATION_MS?value:void 0}__name(readDuration,"readDuration");function readDurations(source,keys){if(!isRecord3(source)){return{values:{},complete:false}}const values={};let complete=true;for(const key of keys){const value=readDuration(source,key);if(value===void 0){complete=false}else{values[key]=value}}return{values,complete}}__name(readDurations,"readDurations");function addDurationAttributes(attributes,group,values){for(const[key,value]of Object.entries(values)){if(group==="phase"&&key==="unattributedMs")continue;const attributeKey=key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`);attributes[`${ATTRIBUTE_PREFIX}.${group}.${attributeKey}`]=value}}__name(addDurationAttributes,"addDurationAttributes");var PHASE_KEYS=["processToProfilerReadyMs","geminiImportMs","argsParseMs","settingsLoadMs","configConstructionMs","appInitializationMs","acpImportMs","bootstrapConfigInitializationMs","transportSetupMs","initializeHandlerMs","unattributedMs"];var CONFIG_KEYS=["extensionsInitialMs","hooksMs","skillsMs","extensionsFinalMs","hierarchicalMemoryMs","toolRegistryMs","ripgrepProbeMs","toolWarmupMs","otherMs"];function getChannelStartupProfileAttributes(response,receivedAtEpochMs,initializeTimeoutMs){if(!isRecord3(response)||!isRecord3(response["_meta"])){return void 0}const profile=response["_meta"][CHANNEL_STARTUP_PROFILE_META_KEY];if(!isRecord3(profile)||profile["v"]!==CHANNEL_STARTUP_PROFILE_VERSION){return void 0}const phases=readDurations(profile["phases"],PHASE_KEYS);const config=readDurations(profile["config"],CONFIG_KEYS);const processToResponseMs=readDuration(profile,"processToResponseMs");const responseBuiltAtEpochMs=profile["responseBuiltAtEpochMs"];const childComplete=profile["complete"]===true;const validResponseEpoch=typeof responseBuiltAtEpochMs==="number"&&Number.isFinite(responseBuiltAtEpochMs)&&responseBuiltAtEpochMs>=0;const effectiveComplete=childComplete&&phases.complete&&config.complete&&processToResponseMs!==void 0&&validResponseEpoch;const attributes={[`${ATTRIBUTE_PREFIX}.profile.version`]:CHANNEL_STARTUP_PROFILE_VERSION,[`${ATTRIBUTE_PREFIX}.profile.complete`]:effectiveComplete};if(processToResponseMs!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.process_to_response_ms`]=processToResponseMs}if(phases.values["unattributedMs"]!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.unattributed_ms`]=phases.values["unattributedMs"]}addDurationAttributes(attributes,"phase",phases.values);addDurationAttributes(attributes,"config",config.values);if(validResponseEpoch){const transportMs=receivedAtEpochMs-responseBuiltAtEpochMs;if(Number.isFinite(transportMs)&&transportMs>=0&&transportMs<=initializeTimeoutMs){attributes[`${ATTRIBUTE_PREFIX}.response_transport_ms`]=transportMs}}return attributes}__name(getChannelStartupProfileAttributes,"getChannelStartupProfileAttributes");init_esbuild_shims();function writeStderrLine(message){process.stderr.write(message.endsWith("\n")?message:`${message}
|
|
3
|
+
import{DEFAULT_RING_SIZE,EVENT_SCHEMA_VERSION,EventBus,isSummaryReplayEvent,logEventSizingFailed,mcpAppTextFallback,serializedBridgeEventByteLength,summarizeReplay,summarizeReplayEvent}from"./chunk-BWQ5AIEA.js";import{JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeJournalGrowthPoolBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{MCP_RESTART_SERVER_DEADLINE_MS}from"./chunk-IFPLGH5C.js";import{channelFactoryForwardsChildEnv,defaultSpawnChannelFactory}from"./chunk-SC6ZKUED.js";import{BridgeChannelClosedError,BridgeTimeoutError,SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS,STATUS_SCHEMA_VERSION,SessionRestoreTimeoutError,createIdleWorkspaceExtensionsStatus,createIdleWorkspaceHooksStatus}from"./chunk-YQ4ID2TH.js";import{ACTIVE_WORK_CLOSE_IF_UNHELD_PARAM,ACTIVE_WORK_CLOSE_TIMEOUT_MS,ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,ACTIVE_WORK_HEARTBEAT_META_KEY,ACTIVE_WORK_HEARTBEAT_VERSION,ACTIVE_WORK_HOLD_CATEGORIES,ACTIVE_WORK_MAX_SESSION_HOLDS,ACTIVE_WORK_MAX_SNAPSHOT_SESSIONS,ACTIVE_WORK_NOTIFICATION_METHOD,ACTIVE_WORK_STALE_INTERVALS,CHANNEL_LIVENESS_META_KEY,CHANNEL_LIVENESS_VERSION,CHANNEL_OUTPUT_MODE_META_KEY,CHANNEL_PROMPT_META_KEY,CHANNEL_STARTUP_PROFILE_META_KEY,CHANNEL_STARTUP_PROFILE_VERSION,DAEMON_ATTACHMENT_CONTEXT_META_KEY,DAEMON_ATTACHMENT_REFERENCES_META_KEY,DAEMON_CHANNEL_DELIVERY_META_KEY,DAEMON_INPUT_ANNOTATIONS_META_KEY,DAEMON_MODEL_PROMPT_META_KEY,DAEMON_PERMISSION_CANCEL_REASON_META_KEY,DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUBMITTED_PROMPT_META_KEY,DAEMON_SUPPRESS_RESTORE_ASK_USER_QUESTION_META_KEY,DAEMON_SUPPRESS_WORKTREE_CONTEXT_RESTORE_META_KEY,IMAGE_ONLY_PROMPT_TEXT,LOAD_REPLAY_BULK_MODE,LOAD_REPLAY_HIDE_INHERITED_META_KEY,LOAD_REPLAY_MAX_UPDATES,LOAD_REPLAY_META_KEY,LOAD_REPLAY_MODE_META_KEY,LOAD_REPLAY_PAGE_SIZE_META_KEY,LOAD_REPLAY_VERSION,MID_TURN_QUEUE_DRAIN_METHOD,MID_TURN_RECONCILIATION_RING_SIZE,MID_TURN_SEND_NOW_METHOD,PROMPT_CANCEL_METHOD,PROMPT_CANCEL_REASON_META_KEY,REQUESTED_SESSION_ID_META_KEY,SESSION_INITIALIZATION_DEADLINE_META_KEY,SESSION_INITIALIZATION_TIMEOUT_ERROR_KIND,SESSION_MODEL_PERSIST_DEFAULT_META_KEY,SUBMITTED_PROMPT_META_KEY,TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,TODO_STOP_GUARD_QUEUE_RELEASE_METHOD,USER_CANCEL_ABORT_REASON,WORKTREE_MCP_DEFER_META_KEY,activeWorkCloseRetryDelayMs,clampActiveWorkIntervalMs,getPromptCancelAbortReason,isValidTrustedModelPrompt,parseBackgroundNotificationTurn,sessionCloseDrainBudgetMs}from"./chunk-WBDNGVHU.js";import{BranchWhilePromptActiveError,BridgeChannelQuarantinedError,CancelSentinelCollisionError,CdWhilePromptActiveError,InvalidClientIdError,InvalidPermissionOptionError,InvalidRewindTargetError,InvalidSessionMetadataError,InvalidSessionScopeError,ManagedSessionBranchUnsupportedError,McpAuthenticationInProgressError,PermissionForbiddenError,PromptDeadlineExceededError,PromptQueueFullError,RequestedSessionIdRejectedError,RestoreInProgressError,SessionBusyError,SessionLimitExceededError,SessionNotFoundError,SessionResetPendingError,SessionShellClientRequiredError,SessionShellDisabledError,StandaloneSessionSpawnError,WorkspaceChangePartiallyAppliedError,WorkspaceDrainingError,WorkspaceMismatchError,WorkspaceRuntimeStopError,isNotCurrentlyGeneratingCancelError}from"./chunk-VTZZXEWA.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{CHANNEL_DELIVERY_ERROR_CODES,LIVE_TASK_TOOL_NAMES,MAX_LIVE_SCREEN_CONTEXT_TEXT_CHARS,MAX_LIVE_SPEAK_TO_USER_MESSAGE_CHARS,MAX_SUB_SESSION_NAME_CHARS}from"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_READY_META_KEY,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,isValidExternalToolGuardDenialReason}from"./chunk-NIEO2TBE.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError}from"./chunk-WSOEJTOC.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import{MAX_SUB_SESSION_PROMPT_CHARS}from"./chunk-MD3ZEOBX.js";import{MAX_DIRECTORY_ARTIFACT_DEPTH,MAX_DIRECTORY_ARTIFACT_FILES,collectRecordableWorkspaceFiles,isOfficeDocumentExtension,isRecordableDerivedChild,pathHasSkippedDirectoryComponent}from"./chunk-NZFR5IY7.js";import{SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SESSION_TRANSCRIPT_MAX_LIMIT,TURN_RESULT_CODE_TEXT_TRUNCATED,TURN_RESULT_TEXT_MAX_CHARS,TrustGateError,canonicalSessionPrUrl,normalizeTurnResultError,toSessionPrInfo}from"./chunk-LDXZT3SG.js";import{SESSION_EXECUTION_ENGINE_META_KEY}from"./chunk-VZDZ34KK.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-QXQGUM3Y.js";import{PUBLISHED_CONTENT_SHA256_METADATA_KEY,SESSION_ARTIFACT_PERSISTENCE_VERSION,WORKSPACE_CONTENT_MTIME_MS_METADATA_KEY,WORKSPACE_CONTENT_SHA256_METADATA_KEY,WORKSPACE_CONTENT_SIZE_BYTES_METADATA_KEY,deleteArtifactSnapshot,getWebPreviewSnapshotId,isAdoptableContentFingerprintKey,isPrototypeMetadataKey,isReservedWorkspaceMetadataKey,metadataBudgetBytes,normalizeSnapshotPayload,retainArtifactSnapshot,sessionArtifactIdentityKey,stableSessionArtifactId}from"./chunk-AG3SSCAF.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,isValidCronTaskRoutingId}from"./chunk-VMQO3VPA.js";import{SessionSourceError,validateSessionSourceInput}from"./chunk-G5PYYZMM.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ShellExecutionService}from"./chunk-3X7DP5W3.js";import{DAEMON_TRACEPARENT_META_KEY,DAEMON_TRACESTATE_META_KEY}from"./chunk-VTDSLBET.js";import{getSpecificMimeType}from"./chunk-JU2HHQR5.js";import{INVOCATION_CONTEXT_META_KEY,PRIVATE_ACP_CAPABILITY_ENV,PRIVATE_PARENT_CAPABILITY_META_KEY}from"./chunk-SLD7H2FA.js";import{REASONING_EFFORT_TIERS}from"./chunk-TAAJ7TDB.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{inspect}from"node:util";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var LogSafeAcpRequestError=class extends RequestError{constructor(code,message,data,reservePreparedResponse){super(code,message,data);this.reservePreparedResponse=reservePreparedResponse}static{__name(this,"LogSafeAcpRequestError")}toResult(){const result=super.toResult();if("error"in result){Object.defineProperty(result.error,inspect.custom,{configurable:true,value:__name(()=>({code:result.error.code,payloadOmitted:true}),"value")});try{this.reservePreparedResponse?.(result.error)}catch{}}return result}};var MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS=1024;var MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS=128;var MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS=512;function logSafeAcpErrorDetails(error){const details=error instanceof Error?error.message:isRecord(error)&&typeof error["message"]==="string"?error["message"]:void 0;if(!details)return void 0;return{details:details.length<=MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS?details:`${details.slice(0,MAX_LOG_SAFE_ACP_ERROR_DETAILS_CHARS)}\u2026`}}__name(logSafeAcpErrorDetails,"logSafeAcpErrorDetails");function boundedAcpErrorString(value,maxChars){return value.length<=maxChars?value:`${value.slice(0,maxChars)}\u2026`}__name(boundedAcpErrorString,"boundedAcpErrorString");function logSafeRequestErrorMessage(code){switch(code){case-32700:return"Parse error";case-32600:return"Invalid request";case-32601:return"Method not found";case-32602:return"Invalid params";case-32603:return"Internal error";case-32e3:return"Authentication required";case-32002:return"Resource not found";default:return"ACP client request failed"}}__name(logSafeRequestErrorMessage,"logSafeRequestErrorMessage");function logSafeRequestErrorData(data){if(!isRecord(data)||typeof data["errorKind"]!=="string"){return void 0}const status=data["status"];const hint=data["hint"];return{errorKind:boundedAcpErrorString(data["errorKind"],MAX_LOG_SAFE_ACP_ERROR_KIND_CHARS),...typeof status==="number"&&Number.isFinite(status)?{status}:{},...typeof hint==="string"?{hint:boundedAcpErrorString(hint,MAX_LOG_SAFE_ACP_ERROR_HINT_CHARS)}:{}}}__name(logSafeRequestErrorData,"logSafeRequestErrorData");var AcpInboundHandlerLimitError=class extends Error{constructor(maxActiveHandlers,maxActiveHandlerBytes,requiredBytes,availableBytes){super("ACP inbound handler capacity exceeded");this.maxActiveHandlers=maxActiveHandlers;this.maxActiveHandlerBytes=maxActiveHandlerBytes;this.requiredBytes=requiredBytes;this.availableBytes=availableBytes;this.name="AcpInboundHandlerLimitError"}static{__name(this,"AcpInboundHandlerLimitError")}code="acp_handler_limit_exceeded"};function estimateAcpHandlerBytes(value,limitBytes){let bytes=0;const stack=[value];const seen=new WeakSet;while(stack.length>0){const current=stack.pop();if(current===null){bytes+=4}else if(typeof current==="string"){bytes+=Buffer.byteLength(current)+2}else if(typeof current==="number"){bytes+=24}else if(typeof current==="boolean"){bytes+=5}else if(Array.isArray(current)){if(seen.has(current))return limitBytes+1;seen.add(current);bytes+=2+Math.max(0,current.length-1);if(bytes+current.length>limitBytes)return limitBytes+1;for(let index=current.length-1;index>=0;index--){stack.push(current[index])}}else if(isRecord(current)){if(seen.has(current))return limitBytes+1;seen.add(current);const entries=Object.entries(current);bytes+=2+Math.max(0,entries.length-1);for(const[key,entryValue]of entries){bytes+=Buffer.byteLength(key)+3;stack.push(entryValue)}}else{bytes+=4}if(bytes>limitBytes)return limitBytes+1}return Math.max(1,bytes)}__name(estimateAcpHandlerBytes,"estimateAcpHandlerBytes");var AcpInboundHandlerAdmission=class{constructor(guard){this.guard=guard}static{__name(this,"AcpInboundHandlerAdmission")}activeHandlers=0;activeBytes=0;async run(params,operation){const envelopeBytes=Math.min(2048,this.guard.maxActiveHandlerBytes);const requiredBytes=envelopeBytes+estimateAcpHandlerBytes(params,Math.max(0,this.guard.maxActiveHandlerBytes-envelopeBytes));const availableBytes=Math.max(0,this.guard.maxActiveHandlerBytes-this.activeBytes);if(this.activeHandlers>=this.guard.maxActiveHandlers||requiredBytes>availableBytes){const error=new AcpInboundHandlerLimitError(this.guard.maxActiveHandlers,this.guard.maxActiveHandlerBytes,requiredBytes,availableBytes);this.guard.fail(error);throw error}this.activeHandlers++;this.activeBytes+=requiredBytes;try{return await operation()}finally{this.activeHandlers--;this.activeBytes-=requiredBytes}}};async function withLogSafeAcpError(operation,reservePreparedResponse){try{return await operation()}catch(error){if(error instanceof RequestError){const code=Number.isFinite(error.code)?error.code:-32603;throw new LogSafeAcpRequestError(code,logSafeRequestErrorMessage(code),logSafeRequestErrorData(error.data),reservePreparedResponse)}throw new LogSafeAcpRequestError(-32603,"Internal error",logSafeAcpErrorDetails(error),reservePreparedResponse)}}__name(withLogSafeAcpError,"withLogSafeAcpError");function createLogSafeAcpClient(client,transportGuard){const admission=new AcpInboundHandlerAdmission(transportGuard);const runNotification=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,operation)),"runNotification");const runRequest=__name((params,operation)=>withLogSafeAcpError(()=>admission.run(params,async()=>{const result=await operation();transportGuard.reservePreparedResponse(result??null);return result}),transportGuard.reservePreparedResponse),"runRequest");return{requestPermission:__name(params=>runRequest(params,()=>client.requestPermission(params)),"requestPermission"),sessionUpdate:__name(params=>runNotification(params,()=>client.sessionUpdate(params)),"sessionUpdate"),writeTextFile:client.writeTextFile?params=>runRequest(params,()=>client.writeTextFile(params)):void 0,readTextFile:client.readTextFile?params=>runRequest(params,()=>client.readTextFile(params)):void 0,createTerminal:client.createTerminal?params=>runRequest(params,()=>client.createTerminal(params)):void 0,terminalOutput:client.terminalOutput?params=>runRequest(params,()=>client.terminalOutput(params)):void 0,releaseTerminal:client.releaseTerminal?params=>runRequest(params,async()=>await client.releaseTerminal(params)??{}):void 0,waitForTerminalExit:client.waitForTerminalExit?params=>runRequest(params,()=>client.waitForTerminalExit(params)):void 0,killTerminal:client.killTerminal?params=>runRequest(params,async()=>await client.killTerminal(params)??{}):void 0,extMethod:client.extMethod?(method,params)=>runRequest(params,()=>client.extMethod(method,params)):void 0,extNotification:client.extNotification?(method,params)=>runNotification(params,()=>client.extNotification(method,params)):void 0}}__name(createLogSafeAcpClient,"createLogSafeAcpClient");var OUTBOUND_GUARDED_CONNECTION_METHODS=new Set(["initialize","newSession","loadSession","unstable_forkSession","unstable_listSessions","unstable_resumeSession","setSessionMode","unstable_setSessionModel","setSessionConfigOption","authenticate","prompt","cancel","extMethod","extNotification"]);function createOutboundGuardedConnection(connection,transportGuard){const wrappers=new Map;return new Proxy(connection,{get(target,property){const value=Reflect.get(target,property,target);if(typeof value!=="function"||!OUTBOUND_GUARDED_CONNECTION_METHODS.has(property)){return value}let wrapper=wrappers.get(property);if(!wrapper){wrapper=__name(async(...args)=>{const release=transportGuard.reserveOutboundOperation(args);try{return await Reflect.apply(value,target,args)}finally{release()}},"wrapper");wrappers.set(property,wrapper)}return wrapper}})}__name(createOutboundGuardedConnection,"createOutboundGuardedConnection");function createHarnessConnection(client,channel){const rawConnection=new ClientSideConnection(()=>channel.transportGuard?createLogSafeAcpClient(client,channel.transportGuard):client,channel.stream);return channel.transportGuard?createOutboundGuardedConnection(rawConnection,channel.transportGuard):rawConnection}__name(createHarnessConnection,"createHarnessConnection");init_esbuild_shims();function createChannelLifecycle(defaultEngine){const channels=new Map;const aliveChannels=new Set;const starting=new Map;return{get current(){return channels.get(defaultEngine)},get starting(){return starting.get(defaultEngine)},currentFor:__name((engine=defaultEngine)=>channels.get(engine),"currentFor"),startingFor:__name((engine=defaultEngine)=>starting.get(engine),"startingFor"),startups:__name(()=>starting.values(),"startups"),get size(){return aliveChannels.size},has(info){return aliveChannels.has(info)},values(){return aliveChannels.values()},track(info){aliveChannels.add(info)},publish(info){channels.set(info.executionEngine,info)},remove(info){aliveChannels.delete(info);if(channels.get(info.executionEngine)===info)channels.delete(info.executionEngine)},startSpawn(spawn,engine=defaultEngine){let promise=starting.get(engine);if(!promise){promise=spawn();starting.set(engine,promise)}return promise},finishSpawn(engine=defaultEngine){starting.delete(engine)}}}__name(createChannelLifecycle,"createChannelLifecycle");init_esbuild_shims();import{randomBytes,randomUUID}from"node:crypto";init_esbuild_shims();function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient){return{protocolVersion:PROTOCOL_VERSION,_meta:{[ACTIVE_WORK_HEARTBEAT_META_KEY]:{v:ACTIVE_WORK_HEARTBEAT_VERSION,intervalMs:ACTIVE_WORK_HEARTBEAT_INTERVAL_MS,categories:[...ACTIVE_WORK_HOLD_CATEGORIES]},[CHANNEL_STARTUP_PROFILE_META_KEY]:{v:CHANNEL_STARTUP_PROFILE_VERSION},[CHANNEL_LIVENESS_META_KEY]:{v:CHANNEL_LIVENESS_VERSION},[PRIVATE_PARENT_CAPABILITY_META_KEY]:privateParentCapability},clientCapabilities:{_meta:{"qwen.goalProposals":true},fs:{readTextFile:delegateReadTextFileToClient,writeTextFile:true}},clientInfo:{name:"qwen-serve-bridge",version:"0"}}}__name(createChannelInitializeRequest,"createChannelInitializeRequest");function negotiateChannelCapabilities(response,requireExternalToolGuard){if(requireExternalToolGuard){const guardAck=response._meta?.[EXTERNAL_TOOL_GUARD_READY_META_KEY];if(guardAck!==EXTERNAL_TOOL_GUARD_REQUIRED_VALUE){throw new Error(`ACP child did not acknowledge the required external tool guard (received: ${JSON.stringify(guardAck)}).`)}}let activeWork;const activeWorkCapability=isRecord2(response._meta)?response._meta[ACTIVE_WORK_HEARTBEAT_META_KEY]:void 0;if(isRecord2(activeWorkCapability)&&activeWorkCapability["v"]===ACTIVE_WORK_HEARTBEAT_VERSION){const advertised=activeWorkCapability["categories"];activeWork={intervalMs:clampActiveWorkIntervalMs(activeWorkCapability["intervalMs"]),categories:Array.isArray(advertised)?ACTIVE_WORK_HOLD_CATEGORIES.filter(category=>advertised.includes(category)):[]}}const channelLivenessCapability=isRecord2(response._meta)?response._meta[CHANNEL_LIVENESS_META_KEY]:void 0;return{activeWork,channelLiveness:isRecord2(channelLivenessCapability)&&channelLivenessCapability["v"]===CHANNEL_LIVENESS_VERSION}}__name(negotiateChannelCapabilities,"negotiateChannelCapabilities");init_esbuild_shims();init_esbuild_shims();async function withTimeout(p,ms,label){let timer;const timeoutP=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BridgeTimeoutError(label,ms)),ms)});try{return await Promise.race([p,timeoutP])}finally{if(timer)clearTimeout(timer)}}__name(withTimeout,"withTimeout");async function terminateChannel(channel,timeoutMs,context){try{await withTimeout(channel.kill(),timeoutMs,`${context} teardown`)}catch(error){try{channel.killSync()}catch(forceError){throw new AggregateError([error,forceError],`ACP channel teardown failed (${context})`)}throw error}}__name(terminateChannel,"terminateChannel");function channelUnavailableReject(channel,context){const unavailable=channel.transportFailed?Promise.race([channel.exited,channel.transportFailed]):channel.exited;const reject=__name(()=>{throw new BridgeChannelClosedError(context)},"reject");return unavailable.then(reject,reject)}__name(channelUnavailableReject,"channelUnavailableReject");init_esbuild_shims();import{performance as performance2}from"node:perf_hooks";var CHANNEL_LIVENESS_INTERVAL_MS=15e3;var CHANNEL_LIVENESS_PROBE_TIMEOUT_MS=1e4;var CHANNEL_LIVENESS_FAILURE_THRESHOLD=2;var CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS=1e3;var CHANNEL_LIVENESS_TIMEOUT_CODE="acp_channel_liveness_timeout";var CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE="acp_channel_liveness_protocol_error";var ChannelLivenessFailure=class extends Error{constructor(code){super(code===CHANNEL_LIVENESS_TIMEOUT_CODE?"ACP channel failed consecutive liveness probes":"ACP channel returned an invalid liveness response");this.code=code;this.name="ChannelLivenessFailure"}static{__name(this,"ChannelLivenessFailure")}};function isValidResponse(response,nonce){return typeof response==="object"&&response!==null&&!Array.isArray(response)&&response["v"]===CHANNEL_LIVENESS_VERSION&&response["nonce"]===nonce}__name(isValidResponse,"isValidResponse");function startChannelLivenessMonitor(options){const now=options.now??(()=>performance2.now());let stopped=false;let timer;let consecutiveTimeouts=0;let nextNonce=0;let resolveStopped;const stoppedOutcome=new Promise(resolve3=>{resolveStopped=resolve3});const isActive=__name(()=>!stopped&&options.isActive(),"isActive");const stop=__name(()=>{stopped=true;if(timer!==void 0){clearTimeout(timer);timer=void 0}resolveStopped({kind:"stopped"})},"stop");const fail=__name(error=>{if(!isActive())return;stop();options.onFailure(error)},"fail");const timerWasLate=__name(expectedAt=>now()>expectedAt+CHANNEL_LIVENESS_TIMER_LATE_TOLERANCE_MS,"timerWasLate");const runProbe=__name(async()=>{if(!isActive())return;const nonce=nextNonce;nextNonce=nonce===Number.MAX_SAFE_INTEGER?0:Math.max(0,nonce+1);const response=Promise.resolve().then(()=>options.probe(nonce)).then(value=>({kind:"response",response:value}),()=>({kind:"rejected"}));let outcome;while(true){const expectedAt=now()+CHANNEL_LIVENESS_PROBE_TIMEOUT_MS;const timeout=new Promise(resolve3=>{timer=setTimeout(()=>{timer=void 0;resolve3(timerWasLate(expectedAt)?{kind:"local_delay"}:{kind:"timeout"})},CHANNEL_LIVENESS_PROBE_TIMEOUT_MS);timer.unref()});outcome=await Promise.race([response,timeout,stoppedOutcome]);if(timer!==void 0){clearTimeout(timer);timer=void 0}if(outcome.kind==="stopped"||!isActive())return;if(outcome.kind!=="local_delay")break;consecutiveTimeouts=0}if(outcome.kind==="response"){if(!isValidResponse(outcome.response,nonce)){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}if(outcome.kind==="rejected"){await Promise.resolve();fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_PROTOCOL_ERROR_CODE));return}consecutiveTimeouts++;if(consecutiveTimeouts>=CHANNEL_LIVENESS_FAILURE_THRESHOLD){fail(new ChannelLivenessFailure(CHANNEL_LIVENESS_TIMEOUT_CODE));return}void runProbe()},"runProbe");function schedule(delayMs){if(!isActive())return;const expectedAt=now()+delayMs;timer=setTimeout(()=>{timer=void 0;if(!isActive())return;if(timerWasLate(expectedAt)){consecutiveTimeouts=0;schedule(CHANNEL_LIVENESS_INTERVAL_MS);return}void runProbe()},delayMs);timer.unref()}__name(schedule,"schedule");schedule(CHANNEL_LIVENESS_INTERVAL_MS);return{stop}}__name(startChannelLivenessMonitor,"startChannelLivenessMonitor");init_esbuild_shims();var MAX_PROFILE_DURATION_MS=6e5;var ATTRIBUTE_PREFIX="qwen-code.daemon.acp_startup";function isRecord3(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord3,"isRecord");function readDuration(source,key){const value=source[key];return typeof value==="number"&&Number.isFinite(value)&&value>=0&&value<=MAX_PROFILE_DURATION_MS?value:void 0}__name(readDuration,"readDuration");function readDurations(source,keys){if(!isRecord3(source)){return{values:{},complete:false}}const values={};let complete=true;for(const key of keys){const value=readDuration(source,key);if(value===void 0){complete=false}else{values[key]=value}}return{values,complete}}__name(readDurations,"readDurations");function addDurationAttributes(attributes,group,values){for(const[key,value]of Object.entries(values)){if(group==="phase"&&key==="unattributedMs")continue;const attributeKey=key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`);attributes[`${ATTRIBUTE_PREFIX}.${group}.${attributeKey}`]=value}}__name(addDurationAttributes,"addDurationAttributes");var PHASE_KEYS=["processToProfilerReadyMs","geminiImportMs","argsParseMs","settingsLoadMs","configConstructionMs","appInitializationMs","acpImportMs","bootstrapConfigInitializationMs","transportSetupMs","initializeHandlerMs","unattributedMs"];var CONFIG_KEYS=["extensionsInitialMs","hooksMs","skillsMs","extensionsFinalMs","hierarchicalMemoryMs","toolRegistryMs","ripgrepProbeMs","toolWarmupMs","otherMs"];function getChannelStartupProfileAttributes(response,receivedAtEpochMs,initializeTimeoutMs){if(!isRecord3(response)||!isRecord3(response["_meta"])){return void 0}const profile=response["_meta"][CHANNEL_STARTUP_PROFILE_META_KEY];if(!isRecord3(profile)||profile["v"]!==CHANNEL_STARTUP_PROFILE_VERSION){return void 0}const phases=readDurations(profile["phases"],PHASE_KEYS);const config=readDurations(profile["config"],CONFIG_KEYS);const processToResponseMs=readDuration(profile,"processToResponseMs");const responseBuiltAtEpochMs=profile["responseBuiltAtEpochMs"];const childComplete=profile["complete"]===true;const validResponseEpoch=typeof responseBuiltAtEpochMs==="number"&&Number.isFinite(responseBuiltAtEpochMs)&&responseBuiltAtEpochMs>=0;const effectiveComplete=childComplete&&phases.complete&&config.complete&&processToResponseMs!==void 0&&validResponseEpoch;const attributes={[`${ATTRIBUTE_PREFIX}.profile.version`]:CHANNEL_STARTUP_PROFILE_VERSION,[`${ATTRIBUTE_PREFIX}.profile.complete`]:effectiveComplete};if(processToResponseMs!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.process_to_response_ms`]=processToResponseMs}if(phases.values["unattributedMs"]!==void 0){attributes[`${ATTRIBUTE_PREFIX}.child.unattributed_ms`]=phases.values["unattributedMs"]}addDurationAttributes(attributes,"phase",phases.values);addDurationAttributes(attributes,"config",config.values);if(validResponseEpoch){const transportMs=receivedAtEpochMs-responseBuiltAtEpochMs;if(Number.isFinite(transportMs)&&transportMs>=0&&transportMs<=initializeTimeoutMs){attributes[`${ATTRIBUTE_PREFIX}.response_transport_ms`]=transportMs}}return attributes}__name(getChannelStartupProfileAttributes,"getChannelStartupProfileAttributes");init_esbuild_shims();function writeStderrLine(message){process.stderr.write(message.endsWith("\n")?message:`${message}
|
|
4
4
|
`)}__name(writeStderrLine,"writeStderrLine");function isRecord4(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord4,"isRecord");function safeTransportFailureCode(error){if(!isRecord4(error))return void 0;const code=error["code"];return typeof code==="string"&&/^[a-z0-9_.-]{1,64}$/iu.test(code)?code:void 0}__name(safeTransportFailureCode,"safeTransportFailureCode");function safeTransportFailureDetail(error){if(!isRecord4(error)||error["code"]!=="ndjson_queue_limit_exceeded"){return void 0}const queueError=error;const budget=typeof queueError.budget==="string"&&/^[a-z0-9_.-]{1,64}$/iu.test(queueError.budget)?queueError.budget:"unknown";const numbers=[];for(const value of[queueError.requiredBytes,queueError.availableBytes,queueError.maxQueuedBytes]){numbers.push(typeof value==="number"&&Number.isFinite(value)?String(Math.max(0,Math.floor(value))):"?")}return`${budget}:required=${numbers[0]}:available=${numbers[1]}:cap=${numbers[2]}`}__name(safeTransportFailureDetail,"safeTransportFailureDetail");function createChannelStartup({channelFactory,executionEngines,boundWorkspace,childEnvOverrides,initTimeoutMs,telemetry,channelLifecycle,initialRuntimeEpoch,runtimeEpochSource,delegateReadTextFileToClient,isExternalToolGuardRequired,isShuttingDown,constructHarnessChannel,handleChannelTransportUnavailable,handleChannelExit,killChannelWithLog,sessionCount}){let runtimeEpoch=initialRuntimeEpoch;async function start(engine){const factory=engine===void 0?channelFactory:executionEngines[engine];const privateParentCapability=randomBytes(32).toString("base64url");const acpChannelId=randomUUID();const startupStartedAt=Date.now();const startupAbort=new AbortController;const startup={};const factoryPromise=telemetry.withSpan("channel.spawn",{"qwen-code.daemon.bridge.operation":"channel.spawn","qwen-code.daemon.channel.reused":false,"qwen-code.daemon.acp_channel.id":acpChannelId},async()=>await factory(boundWorkspace,{...childEnvOverrides,[PRIVATE_ACP_CAPABILITY_ENV]:privateParentCapability},startupAbort.signal,startup));let channel;try{channel=await withTimeout(factoryPromise,initTimeoutMs,"channel factory")}catch(error){const failure=error instanceof BridgeTimeoutError?startup.getTimeoutError?.()??error:error;startupAbort.abort(failure);void factoryPromise.then(lateChannel=>terminateChannel(lateChannel,initTimeoutMs,"late channel factory result").catch(teardownError=>{writeStderrLine(`qwen serve: late ACP channel teardown failed: ${String(teardownError)}`)}),()=>void 0);throw failure}let info;try{info=constructHarnessChannel(channel,acpChannelId,engine)}catch(error){try{channel.killSync()}catch{}try{await Promise.race([channel.exited.then(()=>void 0),terminateChannel(channel,initTimeoutMs,"channel construction failure")])}catch(teardownError){throw new AggregateError([error,teardownError],"ACP channel construction and teardown failed")}throw error}const{connection}=info;const markTransportFailed=__name(error=>{if(!info.isDying){info.transportFailureInitiatedTeardown=true}info.transportFailed=true;info.transportFailureCode=safeTransportFailureCode(error);info.transportFailureDetail=safeTransportFailureDetail(error);info.isDying=true;info.channelLiveness?.stop();handleChannelTransportUnavailable(info)},"markTransportFailed");void channel.transportFailed?.then(markTransportFailed,markTransportFailed);channelLifecycle.track(info);const engineChannelCount=[...channelLifecycle.values()].filter(candidate=>candidate.executionEngine===engine).length;if(engineChannelCount>2){writeStderrLine(`qwen serve: WARNING engine=${engine??"single"} channelCount=${engineChannelCount} (expected 1, max 2 per engine during killSession-then-spawnOrAttach overlap) \u2014 possible channel leak; check that prior channels' channel.exited fired and the handler ran cleanup.`)}void channel.exited.then(exitInfo=>{handleChannelExit(info,exitInfo)});let channelLivenessNegotiated=false;try{await telemetry.withSpan("channel.initialize",{"qwen-code.daemon.bridge.operation":"channel.initialize","qwen-code.daemon.acp_channel.id":acpChannelId},async()=>{const remainingStartupMs=Math.max(1,initTimeoutMs-(Date.now()-startupStartedAt));const response=await withTimeout(Promise.race([connection.initialize(createChannelInitializeRequest(privateParentCapability,delegateReadTextFileToClient)),channelUnavailableReject(channel,"during initialize")]),remainingStartupMs,"initialize");const capabilities=negotiateChannelCapabilities(response,isExternalToolGuardRequired());if(capabilities.activeWork){info.activeWork={...capabilities.activeWork,seq:0}}channelLivenessNegotiated=capabilities.channelLiveness;try{const attributes=getChannelStartupProfileAttributes(response,Date.now(),initTimeoutMs);if(attributes&&telemetry.setActiveSpanAttributes){telemetry.setActiveSpanAttributes(attributes)}}catch{}return response})}catch(err){info.isDying=true;startupAbort.abort(err);await terminateChannel(channel,initTimeoutMs,"channel initialization failure").catch(()=>void 0);throw err}if(info.isDying){await channel.kill().catch(()=>{});throw new BridgeChannelClosedError("during initialize")}if(isShuttingDown()){info.isDying=true;startupAbort.abort(new Error("AcpSessionBridge is shutting down"));await terminateChannel(channel,initTimeoutMs,"late shutdown").catch(()=>void 0);throw new Error("AcpSessionBridge is shutting down")}if(!channelLifecycle.has(info)){info.isDying=true;const error=new BridgeChannelClosedError("during channel initialization");startupAbort.abort(error);await terminateChannel(channel,initTimeoutMs,"exited during initialization").catch(()=>void 0);throw error}const previousRuntimeEpoch=runtimeEpochSource.current();const nextRuntimeEpoch=runtimeEpochSource.allocate();if(!Number.isSafeInteger(previousRuntimeEpoch)||previousRuntimeEpoch<runtimeEpoch||!Number.isSafeInteger(nextRuntimeEpoch)||nextRuntimeEpoch<=previousRuntimeEpoch){info.isDying=true;const epochError=new Error(`Runtime epoch source must increase monotonically (local=${runtimeEpoch}, current=${previousRuntimeEpoch}, next=${nextRuntimeEpoch}).`);startupAbort.abort(epochError);await terminateChannel(channel,initTimeoutMs,"invalid runtime epoch").catch(()=>void 0);throw epochError}runtimeEpoch=nextRuntimeEpoch;info.runtimeEpoch=nextRuntimeEpoch;info.lastUsedAt=Date.now();channelLifecycle.publish(info);info.handshakeComplete=true;if(channelLivenessNegotiated){const failChannelLiveness=__name(error=>{if(info.isDying||!channelLifecycle.has(info))return;markTransportFailed(error);telemetry.event("channel.liveness_failed",{"qwen-code.daemon.acp_channel.id":info.id,"qwen-code.daemon.channel.session_count":sessionCount(info),"qwen-code.daemon.channel.transport_error_code":error.code});writeStderrLine(`qwen serve: channel liveness failed (${error.code}); killing channel`);if(info.channel.transportGuard){info.channel.transportGuard.fail(error)}else{void killChannelWithLog(info,"channel liveness failure")}},"failChannelLiveness");info.channelLiveness=startChannelLivenessMonitor({probe:__name(nonce=>info.connection.extMethod(SERVE_STATUS_EXT_METHODS.channelPing,{v:CHANNEL_LIVENESS_VERSION,nonce}),"probe"),onFailure:failChannelLiveness,isActive:__name(()=>channelLifecycle.currentFor(engine)===info&&channelLifecycle.has(info)&&!info.isDying&&!isShuttingDown(),"isActive")})}telemetry.metrics?.channelLifecycle("spawn");return info}__name(start,"start");return{get epoch(){return runtimeEpoch},start}}__name(createChannelStartup,"createChannelStartup");function isRecord5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord5,"isRecord");function createChannelHarness(options){const{initTimeoutMs,telemetry,isShuttingDown,hasNoSessionWork,hasNoWorkspaceWork,channelShouldReapWhenIdle,sessionCount}=options;const defaultEngine=options.executionEngines?"legacy":void 0;const channelLifecycle=createChannelLifecycle(defaultEngine);let keepAliveUntil=0;const runtimeOperationReservations=new Map;const pendingKeepAliveDeadlines=new Map;const idleTimers=new Map;const pendingIdleTimers=new Set;function liveHarnessChannel(engine=defaultEngine){const channel=channelLifecycle.currentFor(engine);return channel&&!channel.isDying?channel:void 0}__name(liveHarnessChannel,"liveHarnessChannel");function hasNoChannelWork(ci,exclusions){if(!hasNoSessionWork(ci,exclusions))return false;if(ci.retireWhenSessionsDrain)return true;return ci.workspaceControlInFlight===0&&hasNoWorkspaceWork(ci)&&(runtimeOperationReservations.get(ci.executionEngine)??0)===0}__name(hasNoChannelWork,"hasNoChannelWork");function cancelIdleTimer(channel){if(channel)pendingIdleTimers.delete(channel);else pendingIdleTimers.clear();for(const[owner,timer]of idleTimers){if(channel!==void 0&&owner!==channel)continue;clearTimeout(timer);idleTimers.delete(owner)}}__name(cancelIdleTimer,"cancelIdleTimer");async function killChannelWithLog(ci,context){ci.isDying=true;options.onChannelTerminationStart?.(ci);cancelIdleTimer(ci);ci.channelLiveness?.stop();await terminateChannel(ci.channel,initTimeoutMs,context??"channel kill").catch(err=>{writeStderrLine(`qwen serve: channel kill failed${context?` (${context})`:""}: ${String(err)}`)})}__name(killChannelWithLog,"killChannelWithLog");async function retireChannelAfterSessionsDrain(ci,context){if(ci.isDying)return;if(hasNoSessionWork(ci)){await killChannelWithLog(ci,context);return}ci.retireWhenSessionsDrain=true;writeStderrLine(`qwen serve: ${context}; deferring channel retirement until ${sessionCount(ci)} active session(s) drain`)}__name(retireChannelAfterSessionsDrain,"retireChannelAfterSessionsDrain");async function retireChannelOnTimeout(ci,error,context){if(error instanceof BridgeTimeoutError&&!ci.isDying){await retireChannelAfterSessionsDrain(ci,context)}}__name(retireChannelOnTimeout,"retireChannelOnTimeout");function configuredChannelIdleTimeoutMs(){const raw=options.getChannelIdleTimeoutMs();return raw!==void 0&&Number.isFinite(raw)&&raw>0?Math.min(raw,2147483647):0}__name(configuredChannelIdleTimeoutMs,"configuredChannelIdleTimeoutMs");function resolvedChannelIdleTimeoutMs(engine=defaultEngine){const configured=configuredChannelIdleTimeoutMs();if(engine!==defaultEngine)return configured;const now=Date.now();let pendingKeepAliveMs=0;for(const deadline of pendingKeepAliveDeadlines.values()){pendingKeepAliveMs=Math.max(pendingKeepAliveMs,deadline-now)}return Math.max(configured,keepAliveUntil-now,pendingKeepAliveMs)}__name(resolvedChannelIdleTimeoutMs,"resolvedChannelIdleTimeoutMs");async function startIdleTimer(ci,context,exclusions){if(options.isRuntimeStopping()||ci.isDying||liveHarnessChannel(ci.executionEngine)!==ci)return;if(!hasNoChannelWork(ci,exclusions)){pendingIdleTimers.add(ci);return}cancelIdleTimer(ci);const timeoutMs=resolvedChannelIdleTimeoutMs(ci.executionEngine);if(timeoutMs<=0){await killChannelWithLog(ci,context);return}const idleTimer=setTimeout(()=>{idleTimers.delete(ci);if(hasNoChannelWork(ci)){writeStderrLine(`qwen serve: idle timeout (${timeoutMs}ms) expired, killing channel`);void killChannelWithLog(ci,"idle timeout")}else{pendingIdleTimers.add(ci)}},timeoutMs);idleTimers.set(ci,idleTimer);idleTimer.unref()}__name(startIdleTimer,"startIdleTimer");function retireChannel(info,context){info.isDying=true;cancelIdleTimer(info);if(info.executionEngine===defaultEngine)keepAliveUntil=0;info.channelLiveness?.stop();return terminateChannel(info.channel,initTimeoutMs,context)}__name(retireChannel,"retireChannel");async function reapPendingEmptyChannel(ci,opts){if(!channelShouldReapWhenIdle(ci)||!hasNoChannelWork(ci,opts))return;ci.emptyReapPending=false;ci.isDying=true;options.onChannelTerminationStart?.(ci);ci.channelLiveness?.stop();await terminateChannel(ci.channel,initTimeoutMs,"pending empty channel").catch(()=>{})}__name(reapPendingEmptyChannel,"reapPendingEmptyChannel");async function withWorkspaceControl(ci,fn,recordUse=true){if(options.isRuntimeStopping())throw new WorkspaceDrainingError(options.boundWorkspace??"");if(liveHarnessChannel(ci.executionEngine)===ci)cancelIdleTimer(ci);if(recordUse)ci.lastUsedAt=Date.now();ci.workspaceControlInFlight++;try{return await fn()}catch(error){await retireChannelOnTimeout(ci,error,"workspace control timeout");throw error}finally{if(recordUse)ci.lastUsedAt=Date.now();ci.workspaceControlInFlight=Math.max(0,ci.workspaceControlInFlight-1);await reapPendingEmptyChannel(ci);if(!ci.isDying&&liveHarnessChannel(ci.executionEngine)===ci){await startIdleTimer(ci,"workspace control")}}}__name(withWorkspaceControl,"withWorkspaceControl");async function settleReleasedRuntimeWork(context){const channels=Array.from(channelLifecycle.values());for(const ci of channels){await reapPendingEmptyChannel(ci)}for(const ci of channels){if(!ci.isDying&&pendingIdleTimers.has(ci)&&!idleTimers.has(ci)&&hasNoChannelWork(ci)){await startIdleTimer(ci,context)}}}__name(settleReleasedRuntimeWork,"settleReleasedRuntimeWork");function reserveRuntimeOperation(engine=defaultEngine){runtimeOperationReservations.set(engine,(runtimeOperationReservations.get(engine)??0)+1)}__name(reserveRuntimeOperation,"reserveRuntimeOperation");function decrementRuntimeOperationReservation(engine=defaultEngine){const remaining=(runtimeOperationReservations.get(engine)??0)-1;if(remaining>0)runtimeOperationReservations.set(engine,remaining);else runtimeOperationReservations.delete(engine)}__name(decrementRuntimeOperationReservation,"decrementRuntimeOperationReservation");async function releaseRuntimeOperationReservation(context,engine=defaultEngine){decrementRuntimeOperationReservation(engine);const channel=liveHarnessChannel(engine);if(channel)pendingIdleTimers.add(channel);await settleReleasedRuntimeWork(context)}__name(releaseRuntimeOperationReservation,"releaseRuntimeOperationReservation");async function ensureChannel(engine=defaultEngine){if(options.isRuntimeStopping())throw new WorkspaceDrainingError(options.boundWorkspace??"");if(isShuttingDown()){throw new Error("AcpSessionBridge is shutting down")}const current=channelLifecycle.currentFor(engine);if(current)cancelIdleTimer(current);if(current&&!current.isDying)return current;const starting=channelLifecycle.startingFor(engine);if(starting)return await starting;const promise=channelLifecycle.startSpawn(()=>channelStartup.start(engine),engine);try{return await promise}finally{channelLifecycle.finishSpawn(engine)}}__name(ensureChannel,"ensureChannel");const preheat=__name(async options2=>{if(isShuttingDown()){throw new Error("AcpSessionBridge is shutting down")}reserveRuntimeOperation();const rawKeepAliveMs=options2?.keepAliveMs;const keepAliveMs=rawKeepAliveMs!==void 0&&Number.isFinite(rawKeepAliveMs)&&rawKeepAliveMs>0?Math.min(rawKeepAliveMs,2147483647):void 0;const pendingKeepAliveToken=keepAliveMs===void 0?void 0:Symbol();if(pendingKeepAliveToken&&keepAliveMs!==void 0){pendingKeepAliveDeadlines.set(pendingKeepAliveToken,Date.now()+keepAliveMs)}let channel;try{await telemetry.withSpan("channel.preheat",{"qwen-code.daemon.bridge.operation":"channel.preheat"},async()=>{const info=await ensureChannel();channel=info;info.lastUsedAt=Date.now();if(keepAliveMs!==void 0){keepAliveUntil=Math.max(keepAliveUntil,Date.now()+keepAliveMs)}})}finally{if(pendingKeepAliveToken){pendingKeepAliveDeadlines.delete(pendingKeepAliveToken)}decrementRuntimeOperationReservation();if(channel&&channelLifecycle.has(channel)&&resolvedChannelIdleTimeoutMs()>0){pendingIdleTimers.add(channel)}await settleReleasedRuntimeWork("channel preheat")}},"preheat");const channelStartup=createChannelStartup({...options,channelLifecycle,killChannelWithLog,handleChannelExit(info,exitInfo){info.channelLiveness?.stop();options.handleChannelTransportUnavailable(info);cancelIdleTimer(info);options.beforeChannelExit(info);channelLifecycle.remove(info);options.handleChannelExit(info,exitInfo)}});return{get current(){return channelLifecycle.current},get starting(){return channelLifecycle.starting},currentFor:channelLifecycle.currentFor,startingFor:channelLifecycle.startingFor,startups:channelLifecycle.startups,get epoch(){return channelStartup.epoch},get runtimeOperationReservations(){return Array.from(runtimeOperationReservations.values()).reduce((total,count)=>total+count,0)},get pendingKeepAliveCount(){return pendingKeepAliveDeadlines.size},createConnection:createHarnessConnection,withWorktreeInitialization(request,worktree){return worktree?{...request,_meta:{...isRecord5(request._meta)?request._meta:{},[WORKTREE_MCP_DEFER_META_KEY]:true}}:request},changeSessionCwd(channel,sessionId,req){return channel.connection.extMethod(SERVE_CONTROL_EXT_METHODS.sessionCd,{sessionId,path:req.path,...req.allowedRoots?{allowedRoots:req.allowedRoots}:{},...req.managedRelocation?{managedRelocation:req.managedRelocation}:{},...req.conversationDirectoryExpectation?{conversationDirectoryExpectation:req.conversationDirectoryExpectation}:{}})},executeShell(command,cwd,onOutput,signal){return ShellExecutionService.execute(command,cwd,onOutput,signal,false,{terminalWidth:120,terminalHeight:40},{streamStdout:true})},values:channelLifecycle.values,has:channelLifecycle.has,ensure:ensureChannel,configuredChannelIdleTimeoutMs,cancelIdleTimer,startIdleTimer,killChannelWithLog,retireChannelAfterSessionsDrain,retireChannelOnTimeout,hasNoChannelWork,reapPendingEmptyChannel,withWorkspaceControl,reserveRuntimeOperation,releaseRuntimeOperationReservation,settleReleasedRuntimeWork,preheat,reclaimIdleChannel(info){writeStderrLine(`qwen serve: reclaiming idle ACP channel ${info.id}`);return retireChannel(info,"capacity reclamation")},stopChannel(info){return retireChannel(info,"user-confirmed workspace stop")},markDying(channels){for(const ci of channels){ci.isDying=true;ci.channelLiveness?.stop()}},killAllSync(channels){for(const info of channels){info.channelLiveness?.stop();try{info.channel.killSync()}catch{}}},terminate(channel){return terminateChannel(channel.channel,initTimeoutMs,"bridge shutdown")}}}__name(createChannelHarness,"createChannelHarness");init_esbuild_shims();init_esbuild_shims();var SessionStartupConfigError=class extends Error{constructor(code,message,sessionId){super(message);this.code=code;this.sessionId=sessionId}static{__name(this,"SessionStartupConfigError")}name="SessionStartupConfigError"};function isReasoningSelection(value){return typeof value==="string"&&(value==="default"||value==="none"||REASONING_EFFORT_TIERS.some(tier=>tier===value))}__name(isReasoningSelection,"isReasoningSelection");function parseSessionStartupConfig(value,request={}){if(value===void 0)return void 0;const config=value;if(!config||typeof config!=="object"||Array.isArray(config)||Object.keys(config).some(key=>key!=="modelServiceId"&&key!=="reasoningEffort")||typeof config.modelServiceId!=="string"||!config.modelServiceId.trim()||config.modelServiceId.length>MAX_CRON_TASK_ROUTING_ID_LENGTH||new RegExp("\\p{Cc}","u").test(config.modelServiceId)||config.reasoningEffort!==void 0&&!isReasoningSelection(config.reasoningEffort)||request.modelServiceId!==void 0||request.sessionScope==="single"){throw new SessionStartupConfigError("invalid_startup_config","startupConfig requires modelServiceId (1-256 characters) and an optional valid reasoningEffort, without unknown fields, a legacy modelServiceId or single session scope.")}return{modelServiceId:config.modelServiceId.trim(),...config.reasoningEffort!==void 0?{reasoningEffort:config.reasoningEffort}:{}}}__name(parseSessionStartupConfig,"parseSessionStartupConfig");function rejectInvalidSelection(error,sessionId){if(error===null||typeof error!=="object"||!("code"in error)||!("message"in error)||typeof error.message!=="string"){throw error}if(error.code===-32602){throw new SessionStartupConfigError("startup_config_rejected",error.message,sessionId)}throw error}__name(rejectInvalidSelection,"rejectInvalidSelection");async function applySessionStartupConfig(bridge,sessionId,config){const model=await bridge.setSessionConfigOption(sessionId,{sessionId,configId:"model",value:config.modelServiceId}).catch(error=>rejectInvalidSelection(error,sessionId));const modelServiceId=model.configOptions?.find(option=>option.id==="model")?.currentValue;if(!modelServiceId){throw new SessionStartupConfigError("startup_config_rejected","The session did not confirm its model selection.",sessionId)}if(config.reasoningEffort===void 0)return{modelServiceId};const result=await bridge.setSessionConfigOption(sessionId,{sessionId,configId:"reasoning_effort",value:config.reasoningEffort}).catch(error=>rejectInvalidSelection(error,sessionId));const reasoning=result.configOptions?.find(option=>option.id==="reasoning_effort");const currentModel=result.configOptions?.find(option=>option.id==="model")?.currentValue;const selection=reasoning?.currentValue;if(currentModel!==modelServiceId||!isReasoningSelection(selection)||config.reasoningEffort!=="default"&&selection!==config.reasoningEffort){throw new SessionStartupConfigError("startup_config_rejected","The session did not confirm its model and reasoning selection.",sessionId)}const meta=reasoning?._meta?.["qwenCode/reasoning"];const toggleOnly=meta!==null&&typeof meta==="object"&&"toggleOnly"in meta&&meta.toggleOnly===true;return{modelServiceId,reasoningEffort:config.reasoningEffort,effectiveReasoning:selection==="none"?{state:"disabled"}:selection==="default"?toggleOnly?{state:"enabled"}:{state:"provider-default"}:{state:"enabled",effort:selection}}}__name(applySessionStartupConfig,"applySessionStartupConfig");import{randomUUID as randomUUID4}from"node:crypto";import*as path5 from"node:path";init_esbuild_shims();var TURN_BOUNDARY_TYPES=new Set(["turn_complete","turn_error"]);var TRANSIENT_TYPES=new Set(["history_truncated","slow_client_warning","client_evicted","replay_complete","stream_error"]);var LATEST_WINS_UPDATES=new Set(["available_commands_update","current_mode_update"]);var REPLAY_SEGMENT_COMPACT_THRESHOLD=64;var LIVE_JOURNAL_TEXT_CHUNKS_PER_EVENT=256;function createLiveJournalState(){return{entries:[],entryBytes:[],entryEvents:[],totalBytes:0,totalEvents:0,truncatedEvents:0}}__name(createLiveJournalState,"createLiveJournalState");function replayRecordId(event){if(event.type!=="session_update")return void 0;const data=event.data;if(!data||typeof data!=="object"||Array.isArray(data))return void 0;const update=data["update"];if(!update||typeof update!=="object"||Array.isArray(update)){return void 0}const meta=update["_meta"];if(!meta||typeof meta!=="object"||Array.isArray(meta)){return void 0}const recordId=meta["qwen.session.recordId"];return typeof recordId==="string"?recordId:void 0}__name(replayRecordId,"replayRecordId");function lastRecordIdIn(events){for(let i=events.length-1;i>=0;i--){const id=replayRecordId(events[i]);if(id!==void 0)return id}return void 0}__name(lastRecordIdIn,"lastRecordIdIn");function lastSummaryRecordIdIn(events){for(let i=events.length-1;i>=0;i--){if(!isSummaryReplayEvent(events[i]))continue;const id=replayRecordId(events[i]);if(id!==void 0)return id}return void 0}__name(lastSummaryRecordIdIn,"lastSummaryRecordIdIn");var JOURNAL_GROWTH_REASK_INTERVAL_MS=1e4;var JOURNAL_GROWTH_MAX_GRANTS_PER_BREACH=64;var TurnBoundaryCompactionEngine=class{static{__name(this,"TurnBoundaryCompactionEngine")}maxReplayBytes;maxJournalEvents;maxJournalBytes;onJournalGrowth;now;journalGrowthDeniedAt;onReplayWindowEviction;replaySegments=[];replaySegmentStart=0;replayBytes=0;fullJournal=createLiveJournalState();summaryJournal=createLiveJournalState();lastEventId=0;closed=false;truncatedEvents=0;truncatedTurns=0;activeRecordId;summaryRecordId;replayAnchorRecordId;slots=[];toolSlotIndex=new Map;textSlotIndex={text:new Map,thought:new Map};constructor(opts={}){this.maxReplayBytes=normalizeCompactedReplayMaxBytes(opts.maxReplayBytes);this.maxJournalEvents=normalizeMaxJournalEvents(opts.maxJournalEvents);this.maxJournalBytes=normalizeMaxJournalBytes(opts.maxJournalBytes);this.onJournalGrowth=opts.onJournalGrowth;this.now=opts.now??(()=>performance.now());this.onReplayWindowEviction=opts.onReplayWindowEviction}journalLimits(){return{maxEvents:this.maxJournalEvents,maxBytes:this.maxJournalBytes}}ingest(event,byteLength){if(this.closed)return;if(event.id!==void 0){this.lastEventId=event.id}if(TRANSIENT_TYPES.has(event.type))return;const summaryEvent=summarizeReplayEvent(event);const seenRecordId=replayRecordId(event);if(seenRecordId!==void 0){this.activeRecordId=seenRecordId;if(summaryEvent)this.summaryRecordId=seenRecordId}this.appendLiveJournal(this.fullJournal,event,byteLength);if(summaryEvent){this.appendLiveJournal(this.summaryJournal,summaryEvent,summaryEvent===event?byteLength:void 0)}if(TURN_BOUNDARY_TYPES.has(event.type)){this.compactCurrentTurn(event);return}if(event.type==="session_update"){this.classifySessionUpdate(event);return}this.slots.push({kind:"misc",event})}snapshot(liveReplayMode="full"){const compactedTurns=this.flattenReplaySegments();if(this.truncatedEvents>0){compactedTurns.unshift(this.makeHistoryTruncatedEvent(compactedTurns.length))}return{compactedTurns,liveJournal:this.liveJournalSnapshot(liveReplayMode),lastEventId:this.lastEventId}}liveJournalSnapshot(liveReplayMode="full"){const journal=liveReplayMode==="summary"?this.summaryJournal:this.fullJournal;const journalRecordId=liveReplayMode==="summary"?this.summaryRecordId:this.activeRecordId;const liveJournal=journal.entries.map(entry=>isLiveJournalTextSegment(entry)?mergeLiveJournalTextEvent(entry.firstEvent,entry.lastEvent,entry.chunks):entry);if(journal.truncatedEvents>0){liveJournal.unshift({v:EVENT_SCHEMA_VERSION,type:"history_truncated",data:{reason:"replay_window_exceeded",scope:"live_journal",truncatedEvents:journal.truncatedEvents,retainedEvents:journal.totalEvents,maxBytes:this.maxJournalBytes,maxEvents:this.maxJournalEvents,...journalRecordId!==void 0?{recordId:journalRecordId}:{},fullTranscriptAvailable:true}})}return liveJournal}seed(snapshot){if(this.closed)return;this.resetReplayWindow();this.lastEventId=snapshot.lastEventId;this.activeRecordId=void 0;this.summaryRecordId=void 0;this.activeRecordId=lastRecordIdIn(snapshot.compactedTurns);this.summaryRecordId=lastSummaryRecordIdIn(snapshot.compactedTurns);for(const event of snapshot.compactedTurns){if(TRANSIENT_TYPES.has(event.type))continue;this.addReplaySegment([event],0)}this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}seedReplayEvents(events){if(this.closed)return;this.resetReplayWindow();this.activeRecordId=void 0;this.summaryRecordId=void 0;this.activeRecordId=lastRecordIdIn(events);this.summaryRecordId=lastSummaryRecordIdIn(events);let recordEvents=[];let recordId;const flushRecord=__name(()=>{this.addReplaySegment(recordEvents,0);recordEvents=[];recordId=void 0},"flushRecord");for(const event of events){this.recordLastEventId(event);if(TRANSIENT_TYPES.has(event.type))continue;const nextRecordId=replayRecordId(event);if(nextRecordId===void 0){flushRecord();this.addReplaySegment([event],0);continue}if(recordId!==void 0&&recordId!==nextRecordId){flushRecord()}recordId=nextRecordId;recordEvents.push(event)}flushRecord();this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}close(){if(this.closed)return;this.closed=true;this.resetReplayWindow();this.resetJournal();this.activeRecordId=void 0;this.summaryRecordId=void 0;this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}appendLiveJournal(journal,event,byteLength){const bytes=byteLength??serializedBridgeEventByteLength(event)??0;const textChunk=liveJournalTextChunk(event);const current=journal.textSegment;const currentIndex=journal.entries.length-1;if(textChunk&¤t&&journal.entries[currentIndex]===current&¤t.chunks.length<LIVE_JOURNAL_TEXT_CHUNKS_PER_EVENT&&journal.entryBytes[currentIndex]+bytes<=this.maxJournalBytes&¤t.sessionUpdate===textChunk.sessionUpdate&¤t.parentToolCallId===textChunk.parentToolCallId&&stringArraysEqual(current.sourceRecordIds,textChunk.sourceRecordIds)&¤t.promptId===event.promptId&¤t.originatorClientId===event.originatorClientId&¤t.sessionId===captureSessionId(event)&&hasOnlyTimestampEnvelopeMeta(current.lastEvent._meta)&&hasOnlyTimestampEnvelopeMeta(event._meta)){current.chunks.push(textChunk.text);current.lastEvent=event;journal.entryBytes[currentIndex]+=bytes;journal.entryEvents[currentIndex]+=1;journal.totalBytes+=bytes;journal.totalEvents+=1}else{let entry=event;if(textChunk){const segment={sessionUpdate:textChunk.sessionUpdate,chunks:[textChunk.text],sourceRecordIds:textChunk.sourceRecordIds,parentToolCallId:textChunk.parentToolCallId,promptId:event.promptId,originatorClientId:event.originatorClientId,sessionId:captureSessionId(event),firstEvent:event,lastEvent:event};entry=segment;journal.textSegment=segment}else{journal.textSegment=void 0}journal.entries.push(entry);journal.entryBytes.push(bytes);journal.entryEvents.push(1);journal.totalBytes+=bytes;journal.totalEvents+=1}if(!TURN_BOUNDARY_TYPES.has(event.type)&&(journal.entries.length>this.maxJournalEvents||journal.totalBytes>this.maxJournalBytes&&journal.entries.length>1)){this.maybeGrowJournalLimits(journal)}while(journal.entries.length>this.maxJournalEvents||journal.totalBytes>this.maxJournalBytes&&journal.entries.length>1){const dropped=journal.entries.shift();journal.totalBytes-=journal.entryBytes.shift()??0;const droppedEvents=journal.entryEvents.shift()??0;journal.totalEvents-=droppedEvents;journal.truncatedEvents+=droppedEvents;if(dropped===journal.textSegment){journal.textSegment=void 0}}}maybeGrowJournalLimits(journal){const advisor=this.onJournalGrowth;if(!advisor||this.closed)return;const now=this.now();if(this.journalGrowthDeniedAt!==void 0){const sinceDenialMs=now-this.journalGrowthDeniedAt;if(sinceDenialMs>=0&&sinceDenialMs<JOURNAL_GROWTH_REASK_INTERVAL_MS){return}}const originalEvents=this.maxJournalEvents;const originalBytes=this.maxJournalBytes;const originalRetained=this.retainedTailCount(journal,originalEvents,originalBytes);for(let step=0;step<JOURNAL_GROWTH_MAX_GRANTS_PER_BREACH;step++){let grant;try{grant=advisor({maxEvents:this.maxJournalEvents,maxBytes:this.maxJournalBytes})}catch{grant=void 0}if(!grant||!Number.isSafeInteger(grant.maxBytes)||!Number.isSafeInteger(grant.maxEvents)||grant.maxBytes<=this.maxJournalBytes||grant.maxEvents<this.maxJournalEvents){break}this.maxJournalBytes=grant.maxBytes;this.maxJournalEvents=grant.maxEvents;if(this.retainedTailCount(journal,grant.maxEvents,grant.maxBytes)>originalRetained){this.journalGrowthDeniedAt=void 0;return}}this.maxJournalEvents=originalEvents;this.maxJournalBytes=originalBytes;this.journalGrowthDeniedAt=now}retainedTailCount(journal,maxEvents,maxBytes){let count=0;let bytes=0;for(let i=journal.entries.length-1;i>=0;i--){const entryBytes=journal.entryBytes[i]??0;if(count+1>maxEvents)break;if(count>=1&&bytes+entryBytes>maxBytes)break;count+=1;bytes+=entryBytes}return count}classifySessionUpdate(event){const data=event.data;const updateType=data?.update?.sessionUpdate;if(!updateType){this.slots.push({kind:"misc",event});return}switch(updateType){case"agent_message_chunk":{const meta=data?.update?._meta;if(hasDiscreteMessageMeta(data?.update?._meta)||meta?.["executionLifecycle"]!==void 0){this.slots.push({kind:"misc",event});break}this.mergeTextSlot("text",event,data);break}case"agent_thought_chunk":{if(hasDiscreteMessageMeta(data?.update?._meta)){this.slots.push({kind:"misc",event});break}this.mergeTextSlot("thought",event,data);break}case"tool_call":case"tool_call_update":{const update=data?.update;const meta=update?.["_meta"];if(meta?.["toolLifecycle"]!==void 0&&update?.["status"]===void 0&&update?.["content"]===void 0){this.slots.push({kind:"misc",event});break}const toolCallId=data?.update?.toolCallId;if(!toolCallId){this.slots.push({kind:"misc",event});break}const existingIdx=this.toolSlotIndex.get(toolCallId);if(existingIdx!==void 0){const slot=this.slots[existingIdx];slot.event=mergeToolCallEvent(slot.event,event)}else{const normalizedEvent=normalizeToolCallType(event);this.toolSlotIndex.set(toolCallId,this.slots.length);this.slots.push({kind:"tool",toolCallId,event:normalizedEvent});const toolParent=extractParentToolCallIdFromMeta(data?.update?._meta);if(toolParent){this.textSlotIndex.text.delete(toolParent);this.textSlotIndex.thought.delete(toolParent)}}break}default:{if(LATEST_WINS_UPDATES.has(updateType)){const existingIdx=this.slots.findIndex(s=>s.kind==="latestWins"&&s.key===updateType);if(existingIdx!==-1){this.slots[existingIdx].event=event}else{this.slots.push({kind:"latestWins",key:updateType,event})}}else{this.slots.push({kind:"misc",event})}break}}}mergeTextSlot(kind,event,data){const text=data?.update?.content?.text??"";const meta=data?.update?._meta;const parentToolCallId=extractParentToolCallIdFromMeta(meta);const sourceRecordIds=extractSourceRecordIdsFromMeta(meta);if(parentToolCallId!=null){const entries=this.textSlotIndex[kind].get(parentToolCallId)??[];const existingIdx=entries.find(entry=>stringArraysEqual(entry.sourceRecordIds,sourceRecordIds))?.index;if(existingIdx!==void 0){const slot=this.slots[existingIdx];slot.chunks.push(text);if(event.id!==void 0)slot.lastEventId=event.id;slot.lastMeta=mergeTranscriptUpdateMeta(slot.lastMeta,meta);slot.lastEnvelopeMeta=event._meta??slot.lastEnvelopeMeta;slot.lastTurn=captureTurnFields(event,slot.lastTurn);slot.lastSessionId=captureSessionId(event)??slot.lastSessionId}else{entries.push({sourceRecordIds,index:this.slots.length});this.textSlotIndex[kind].set(parentToolCallId,entries);this.slots.push({kind,parentToolCallId,chunks:[text],sourceRecordIds,lastEventId:event.id??0,lastMeta:meta,lastEnvelopeMeta:event._meta,lastTurn:captureTurnFields(event),lastSessionId:captureSessionId(event)})}}else{const lastSlot=this.slots[this.slots.length-1];if(lastSlot&&lastSlot.kind===kind&&lastSlot.parentToolCallId==null&&stringArraysEqual(lastSlot.sourceRecordIds,sourceRecordIds)){lastSlot.chunks.push(text);if(event.id!==void 0)lastSlot.lastEventId=event.id;lastSlot.lastMeta=mergeTranscriptUpdateMeta(lastSlot.lastMeta,meta);lastSlot.lastEnvelopeMeta=event._meta??lastSlot.lastEnvelopeMeta;lastSlot.lastTurn=captureTurnFields(event,lastSlot.lastTurn);lastSlot.lastSessionId=captureSessionId(event)??lastSlot.lastSessionId}else{this.slots.push({kind,parentToolCallId:void 0,chunks:[text],sourceRecordIds,lastEventId:event.id??0,lastMeta:meta,lastEnvelopeMeta:event._meta,lastTurn:captureTurnFields(event),lastSessionId:captureSessionId(event)})}}}compactCurrentTurn(boundaryEvent){const compacted=[];for(const slot of this.slots){switch(slot.kind){case"text":case"thought":compacted.push(makeMergedSessionUpdateEvent(slot.kind==="text"?"agent_message_chunk":"agent_thought_chunk",slot.chunks.join(""),slot.lastEventId,slot.lastMeta,slot.lastEnvelopeMeta,slot.lastTurn,slot.lastSessionId));break;case"tool":case"misc":case"latestWins":compacted.push(slot.event);break;default:break}}compacted.push(boundaryEvent);this.addReplaySegment(compacted,1);this.resetJournal();this.slots=[];this.toolSlotIndex.clear();this.clearTextSlotIndex()}recordLastEventId(event){if(event.id!==void 0){this.lastEventId=event.id}}resetJournal(){this.fullJournal=createLiveJournalState();this.summaryJournal=createLiveJournalState();this.journalGrowthDeniedAt=void 0}addReplaySegment(events,turnCount){if(events.length===0)return;const bytes=events.reduce((sum,event)=>{const size=serializedBridgeEventByteLength(event);if(size===void 0){logEventSizingFailed(event.type);return sum}return sum+size},0);this.replaySegments.push({events:events.slice(),bytes,turnCount});this.replayBytes+=bytes;this.enforceReplayWindow()}enforceReplayWindow(){this.degradeReplayAppHtml(this.replaySegments.length-1);let droppedSegmentCount=0;let droppedBytes=0;let droppedEvents=0;let droppedTurns=0;let lastDroppedRecordId;while(this.replayBytes>this.maxReplayBytes&&this.activeReplaySegmentCount()>1){const dropped=this.replaySegments[this.replaySegmentStart];this.replaySegmentStart+=1;droppedSegmentCount+=1;droppedBytes+=dropped.bytes;droppedEvents+=dropped.events.length;droppedTurns+=dropped.turnCount;this.replayBytes-=dropped.bytes;this.truncatedEvents+=dropped.events.length;this.truncatedTurns+=dropped.turnCount;const droppedRecordId=lastRecordIdIn(dropped.events);if(droppedRecordId!==void 0){lastDroppedRecordId=droppedRecordId}}this.degradeReplayAppHtml(this.replaySegments.length);if(droppedSegmentCount>0){this.replayAnchorRecordId??=this.firstRetainedReplayRecordId()??lastDroppedRecordId;this.compactReplaySegmentQueueIfNeeded();this.notifyReplayWindowEviction({droppedBytes,droppedEvents,droppedSegments:droppedSegmentCount,droppedTurns,maxBytes:this.maxReplayBytes,retainedBytes:this.replayBytes,retainedEvents:this.flattenReplaySegments().length})}}firstRetainedReplayRecordId(){for(let i=this.replaySegmentStart;i<this.replaySegments.length;i++){const recordId=lastRecordIdIn(this.replaySegments[i].events);if(recordId!==void 0)return recordId}return void 0}flattenReplaySegments(){return this.replaySegments.slice(this.replaySegmentStart).flatMap(segment=>segment.events)}degradeReplayAppHtml(end){for(let i=this.replaySegmentStart;i<end&&this.replayBytes>this.maxReplayBytes;i++){const segment=this.replaySegments[i];for(let j=0;j<segment.events.length&&this.replayBytes>this.maxReplayBytes;j++){const event=segment.events[j];const degraded=mcpAppTextFallback(event);if(degraded===void 0)continue;const originalBytes=serializedBridgeEventByteLength(event);const degradedBytes=serializedBridgeEventByteLength(degraded);if(originalBytes===void 0||degradedBytes===void 0)continue;segment.events[j]=degraded;segment.bytes+=degradedBytes-originalBytes;this.replayBytes+=degradedBytes-originalBytes}}}activeReplaySegmentCount(){return this.replaySegments.length-this.replaySegmentStart}compactReplaySegmentQueueIfNeeded(){if(this.replaySegmentStart<REPLAY_SEGMENT_COMPACT_THRESHOLD)return;this.replaySegments.splice(0,this.replaySegmentStart);this.replaySegmentStart=0}notifyReplayWindowEviction(eviction){try{this.onReplayWindowEviction?.(eviction)}catch{}}makeHistoryTruncatedEvent(retainedEvents){return{v:EVENT_SCHEMA_VERSION,type:"history_truncated",data:{reason:"replay_window_exceeded",truncatedEvents:this.truncatedEvents,retainedEvents,maxBytes:this.maxReplayBytes,...this.truncatedTurns>0?{truncatedTurns:this.truncatedTurns}:{},...this.replayAnchorRecordId!==void 0?{recordId:this.replayAnchorRecordId}:{},fullTranscriptAvailable:true}}}resetReplayWindow(){this.replaySegments=[];this.replaySegmentStart=0;this.replayBytes=0;this.truncatedEvents=0;this.truncatedTurns=0;this.replayAnchorRecordId=void 0}clearTextSlotIndex(){this.textSlotIndex.text.clear();this.textSlotIndex.thought.clear()}};function isLiveJournalTextSegment(entry){return"firstEvent"in entry}__name(isLiveJournalTextSegment,"isLiveJournalTextSegment");function liveJournalTextChunk(event){if(event.type!=="session_update")return void 0;const data=event.data;const sessionUpdate=data?.update?.sessionUpdate;if(sessionUpdate!=="agent_message_chunk"&&sessionUpdate!=="agent_thought_chunk"){return void 0}if(!hasOnlyModeledChunkKeys(data)){return void 0}if(hasDiscreteMessageMeta(data?.update?._meta)||hasUnmodeledTextMeta(data?.update?._meta)){return void 0}const content=data?.update?.content;if(content?.type!=="text"||typeof content.text!=="string"){return void 0}return{sessionUpdate,text:content.text,sourceRecordIds:extractSourceRecordIdsFromMeta(data?.update?._meta),parentToolCallId:extractParentToolCallIdFromMeta(data?.update?._meta)}}__name(liveJournalTextChunk,"liveJournalTextChunk");function hasOnlyModeledChunkKeys(data){if(!data||!data.update)return false;const content=data.update.content;return Object.keys(data).every(key=>key==="sessionId"||key==="update")&&Object.keys(data.update).every(key=>key==="sessionUpdate"||key==="content"||key==="_meta")&&(content===void 0||typeof content==="object"&&content!==null&&Object.keys(content).every(key=>key==="type"||key==="text"))}__name(hasOnlyModeledChunkKeys,"hasOnlyModeledChunkKeys");function mergeLiveJournalTextEvent(existing,incoming,chunks){const existingData=existing.data;const incomingData=incoming.data;return{...existing,...incoming,data:{...existingData,...incomingData,update:{...existingData.update,...incomingData.update,content:{type:"text",text:chunks.join("")}}}}}__name(mergeLiveJournalTextEvent,"mergeLiveJournalTextEvent");function makeMergedSessionUpdateEvent(sessionUpdate,text,eventId,meta,envelopeMeta,turn,sessionId){return{id:eventId||void 0,v:EVENT_SCHEMA_VERSION,type:"session_update",...turn?.promptId!==void 0?{promptId:turn.promptId}:{},...turn?.originatorClientId!==void 0?{originatorClientId:turn.originatorClientId}:{},...envelopeMeta!==void 0?{_meta:envelopeMeta}:{},data:{...sessionId!==void 0?{sessionId}:{},update:{sessionUpdate,content:{type:"text",text},...meta!=null?{_meta:meta}:{}}}}}__name(makeMergedSessionUpdateEvent,"makeMergedSessionUpdateEvent");function captureTurnFields(event,previous){const promptId=event.promptId??previous?.promptId;const originatorClientId=event.originatorClientId??previous?.originatorClientId;if(promptId===void 0&&originatorClientId===void 0){return void 0}return{...promptId!==void 0?{promptId}:{},...originatorClientId!==void 0?{originatorClientId}:{}}}__name(captureTurnFields,"captureTurnFields");function captureSessionId(event){const sessionId=event.data?.sessionId;return typeof sessionId==="string"?sessionId:void 0}__name(captureSessionId,"captureSessionId");function normalizeToolCallType(event){const data=event.data;if(data?.update?.sessionUpdate==="tool_call_update"){return{...event,data:{...data,update:{...data.update,sessionUpdate:"tool_call"}}}}return event}__name(normalizeToolCallType,"normalizeToolCallType");function extractParentToolCallIdFromMeta(meta){if(typeof meta==="object"&&meta!==null){const val=meta["parentToolCallId"];return typeof val==="string"&&val.length>0?val:void 0}return void 0}__name(extractParentToolCallIdFromMeta,"extractParentToolCallIdFromMeta");function extractSourceRecordIdsFromMeta(meta){if(typeof meta!=="object"||meta===null)return void 0;const transcript=meta["qwenTranscript"];if(typeof transcript!=="object"||transcript===null)return void 0;const ids=transcript["sourceRecordIds"];if(!Array.isArray(ids))return void 0;const normalized=[...new Set(ids.filter(id=>typeof id==="string"))];return normalized.length>0?normalized:void 0}__name(extractSourceRecordIdsFromMeta,"extractSourceRecordIdsFromMeta");function stringArraysEqual(left,right){if(left===right)return true;if(!left||!right||left.length!==right.length)return false;return left.every((value,index)=>value===right[index])}__name(stringArraysEqual,"stringArraysEqual");function hasDiscreteMessageMeta(meta){return typeof meta==="object"&&meta!==null&&meta["qwenDiscreteMessage"]===true}__name(hasDiscreteMessageMeta,"hasDiscreteMessageMeta");function hasOnlyTimestampEnvelopeMeta(meta){if(meta===void 0)return true;if(typeof meta!=="object"||meta===null)return false;return Object.keys(meta).every(key=>key==="timestamp"||key==="serverTimestamp")}__name(hasOnlyTimestampEnvelopeMeta,"hasOnlyTimestampEnvelopeMeta");function hasUnmodeledTextMeta(meta){if(meta===void 0)return false;if(typeof meta!=="object"||meta===null)return true;const record=meta;for(const[key,value]of Object.entries(record)){if(key==="timestamp"||key==="serverTimestamp"){continue}if(key==="parentToolCallId"){if(typeof value!=="string")return true;continue}if(key==="subagentType"){if(typeof value!=="string")return true;continue}if(key==="qwenTranscript"){if(typeof value!=="object"||value===null)return true;const transcript=value;for(const[field,fieldValue]of Object.entries(transcript)){if(field==="sourceRecordIds"){if(!Array.isArray(fieldValue)||fieldValue.some(id=>typeof id!=="string")){return true}continue}if(field==="planToolCallId"){if(typeof fieldValue!=="string")return true;continue}return true}continue}return true}return false}__name(hasUnmodeledTextMeta,"hasUnmodeledTextMeta");function mergeToolCallEvent(existing,incoming){const existingData=existing.data;const incomingData=incoming.data;const existingUpdate=existingData?.update??{};const incomingUpdate=incomingData?.update??{};const merged={...existingUpdate};for(const[key,value]of Object.entries(incomingUpdate)){if(value!==void 0&&value!==null){merged[key]=value}}const updateMeta=mergeTranscriptUpdateMeta(existingUpdate["_meta"],incomingUpdate["_meta"]);if(updateMeta!==void 0)merged["_meta"]=updateMeta;merged["sessionUpdate"]="tool_call";const mergedMeta=existing._meta||incoming._meta?{...existing._meta??{},...incoming._meta??{}}:void 0;const promptId=incoming.promptId??existing.promptId;const originatorClientId=incoming.originatorClientId??existing.originatorClientId;return{id:incoming.id??existing.id,v:EVENT_SCHEMA_VERSION,type:"session_update",...promptId!==void 0?{promptId}:{},...originatorClientId!==void 0?{originatorClientId}:{},...mergedMeta?{_meta:mergedMeta}:{},data:{...existingData,...incomingData,update:merged}}}__name(mergeToolCallEvent,"mergeToolCallEvent");function mergeTranscriptUpdateMeta(existing,incoming){const existingRecord=typeof existing==="object"&&existing!==null?existing:void 0;const incomingRecord=typeof incoming==="object"&&incoming!==null?incoming:void 0;if(!existingRecord&&!incomingRecord)return void 0;const sourceRecordIds=[...new Set([...extractSourceRecordIdsFromMeta(existingRecord)??[],...extractSourceRecordIdsFromMeta(incomingRecord)??[]])];const existingTranscript=extractTranscriptMeta(existingRecord);const incomingTranscript=extractTranscriptMeta(incomingRecord);return{...existingRecord??{},...incomingRecord??{},...existingTranscript||incomingTranscript||sourceRecordIds.length>0?{qwenTranscript:{...existingTranscript??{},...incomingTranscript??{},...sourceRecordIds.length>0?{sourceRecordIds}:{}}}:{}}}__name(mergeTranscriptUpdateMeta,"mergeTranscriptUpdateMeta");function extractTranscriptMeta(meta){const transcript=meta?.["qwenTranscript"];return typeof transcript==="object"&&transcript!==null?transcript:void 0}__name(extractTranscriptMeta,"extractTranscriptMeta");init_esbuild_shims();function createJournalGrowthPolicy(opts){const hardCapEvents=Math.min(Number.MAX_SAFE_INTEGER,Math.max(opts.baselineEvents,Math.ceil(opts.hardCapBytes/opts.baselineBytes*opts.baselineEvents)));return{grant(request){if(request.currentMaxBytes>=opts.hardCapBytes)return void 0;const extraGranted=request.allSessionLimits.reduce((sum,session)=>sum+Math.max(0,session.limitBytes-session.baselineBytes),0);const available=opts.poolBytes-extraGranted;if(available<=0)return void 0;const maxBytes=Math.min(request.currentMaxBytes*2,request.currentMaxBytes+available,opts.hardCapBytes);if(maxBytes<=request.currentMaxBytes)return void 0;const maxEvents=Math.min(Math.max(request.currentMaxEvents,Math.ceil(maxBytes/opts.baselineBytes*opts.baselineEvents)),hardCapEvents);return{maxBytes,maxEvents}}}}__name(createJournalGrowthPolicy,"createJournalGrowthPolicy");init_esbuild_shims();var DEFAULT_SESSION_RESTORE_TIMEOUT_MS=6e4;var MAX_SESSION_RESTORE_TIMEOUT_MS=2147483647;var MIN_RESTORE_RETRY_AFTER_SECONDS=5;var MAX_RESTORE_RETRY_AFTER_SECONDS=120;function restoreRetryAfterSeconds(timeoutMs){return Math.min(MAX_RESTORE_RETRY_AFTER_SECONDS,Math.max(MIN_RESTORE_RETRY_AFTER_SECONDS,Math.ceil(timeoutMs/1e3)))}__name(restoreRetryAfterSeconds,"restoreRetryAfterSeconds");function assertValidTimeoutMs(field,timeoutMs){if(!Number.isFinite(timeoutMs)||!Number.isInteger(timeoutMs)||timeoutMs<=0||timeoutMs>MAX_SESSION_RESTORE_TIMEOUT_MS){throw new TypeError(`Invalid ${field}: ${timeoutMs}. Must be a positive integer no greater than ${MAX_SESSION_RESTORE_TIMEOUT_MS}.`)}}__name(assertValidTimeoutMs,"assertValidTimeoutMs");function resolveSessionRestoreTimeoutMs(opts){if(opts.sessionRestoreTimeoutMs!==void 0){assertValidTimeoutMs("sessionRestoreTimeoutMs",opts.sessionRestoreTimeoutMs);return opts.sessionRestoreTimeoutMs}if(opts.initializeTimeoutMs!==void 0){assertValidTimeoutMs("initializeTimeoutMs",opts.initializeTimeoutMs);return Math.max(opts.initializeTimeoutMs,DEFAULT_SESSION_RESTORE_TIMEOUT_MS)}return DEFAULT_SESSION_RESTORE_TIMEOUT_MS}__name(resolveSessionRestoreTimeoutMs,"resolveSessionRestoreTimeoutMs");init_esbuild_shims();var SESSION_SOURCE_META_KEY="qwen.session.source";var SESSION_SOURCE_TYPE_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/;var MAX_SESSION_SOURCE_ID_LENGTH=256;var STANDALONE_SESSION_SOURCE_TYPE="standalone";var DAEMON_OWNED_STANDALONE_CREATION_KEY="daemonOwnedStandaloneCreation";function isReservedStandaloneSessionSourceType(sourceType){return sourceType===STANDALONE_SESSION_SOURCE_TYPE}__name(isReservedStandaloneSessionSourceType,"isReservedStandaloneSessionSourceType");var SCHEDULED_TASK_RUN_SOURCE_TYPE="default";var SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX="scheduled_task_run:";function isScheduledTaskRunSource(source){return source.sourceType===SCHEDULED_TASK_RUN_SOURCE_TYPE&&source.sourceId?.startsWith(SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX)===true}__name(isScheduledTaskRunSource,"isScheduledTaskRunSource");function parseSessionSource(sourceType,sourceId){if(sourceType===void 0&&sourceId===void 0)return{};if(typeof sourceType!=="string"||!SESSION_SOURCE_TYPE_PATTERN.test(sourceType)){return{error:"`sourceType` must match [a-z][a-z0-9_-]{0,63} when provided"}}if(sourceId===void 0)return{sourceType};if(typeof sourceId!=="string"||sourceId.length===0||sourceId.length>MAX_SESSION_SOURCE_ID_LENGTH||[...sourceId].some(character=>{const code=character.charCodeAt(0);return code<=31||code===127})){return{error:`\`sourceId\` must be a non-empty string of at most ${MAX_SESSION_SOURCE_ID_LENGTH} characters without control characters`}}return{sourceType,sourceId}}__name(parseSessionSource,"parseSessionSource");init_esbuild_shims();import{constants as fsConstants,promises as fs,statSync}from"node:fs";import{tmpdir}from"node:os";import*as path from"node:path";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";var SESSION_ATTACHMENT_CHUNK_BYTES=512*1024;var UPLOAD_LIFETIME_MS=5*60*1e3;var MAX_STAGED_BYTES=128*1024*1024;var MAX_ACTIVE_UPLOADS=32;var MAX_SESSION_UPLOADS=8;var MAX_RECEIPTS=1024;var SessionAttachmentUploadError=class extends Error{constructor(status,code,message,cause){super(message,{cause});this.status=status;this.code=code;this.name="SessionAttachmentUploadError"}static{__name(this,"SessionAttachmentUploadError")}};var uploads=new Set;var receipts=new Set;var stagedBytes=0;var activeUploads=0;var sweepTimer;function sweep(){const now=Date.now();for(const upload of uploads){if(upload.state!=="completing"&&upload.expiresAt<=now){upload.owner.discard(upload)}}}__name(sweep,"sweep");function notFound(){return new SessionAttachmentUploadError(404,"attachment_upload_not_found","Attachment upload is unavailable")}__name(notFound,"notFound");var SessionAttachmentUploads=class{static{__name(this,"SessionAttachmentUploads")}records=new Map;active=0;closed=false;create(metadata,clientId){if(this.closed)throw notFound();sweep();if(this.active>=MAX_SESSION_UPLOADS||activeUploads>=MAX_ACTIVE_UPLOADS||stagedBytes+metadata.size>MAX_STAGED_BYTES){throw new SessionAttachmentUploadError(429,"attachment_upload_capacity_exceeded","Attachment upload capacity is exhausted; try again later")}stagedBytes+=metadata.size;activeUploads++;this.active++;let data;try{data=Buffer.alloc(metadata.size)}catch(error){stagedBytes-=metadata.size;activeUploads--;this.active--;throw error}const upload={id:randomUUID2(),owner:this,clientId,metadata:{...metadata},data,offset:0,previousOffset:-1,expiresAt:Date.now()+UPLOAD_LIFETIME_MS,state:"receiving"};this.records.set(upload.id,upload);uploads.add(upload);if(!sweepTimer){sweepTimer=setInterval(sweep,3e4);sweepTimer.unref()}return{uploadId:upload.id}}append(id,offset,data,clientId){const upload=this.get(id,clientId);if(upload.state!=="receiving"||!upload.data){throw new SessionAttachmentUploadError(409,"attachment_upload_finalizing","Attachment upload no longer accepts chunks")}if(!Number.isSafeInteger(offset)||offset<0||data.length===0){throw new SessionAttachmentUploadError(400,"invalid_attachment_upload_chunk","A nonempty chunk and a non-negative integer offset are required")}if(data.length>SESSION_ATTACHMENT_CHUNK_BYTES||offset+data.length>upload.metadata.size){throw new SessionAttachmentUploadError(413,"attachment_upload_too_large","Chunk exceeds the attachment upload size limit")}if(offset===upload.previousOffset&&offset+data.length===upload.offset&&upload.data.subarray(offset,upload.offset).equals(data)){return{offset:upload.offset}}if(offset!==upload.offset||data.length!==Math.min(SESSION_ATTACHMENT_CHUNK_BYTES,upload.metadata.size-offset)){throw new SessionAttachmentUploadError(409,"attachment_upload_offset_conflict","Chunk does not match the expected attachment offset or length")}data.copy(upload.data,offset);upload.previousOffset=offset;upload.offset+=data.length;return{offset:upload.offset}}complete(id,clientId,commit){const upload=this.get(id,clientId);if(upload.completion)return upload.completion;if(upload.offset!==upload.metadata.size){throw new SessionAttachmentUploadError(409,"attachment_upload_incomplete","Attachment upload has not received all bytes")}upload.state="completing";let retryableFailure=false;const assertActive=__name(()=>{if(this.closed||this.records.get(id)!==upload)throw notFound()},"assertActive");upload.completion=Promise.resolve().then(()=>{assertActive();return commit(upload.data,upload.metadata,assertActive)}).then(reference=>{upload.state="completed";return reference},error=>{if(error instanceof SessionAttachmentUploadError&&error.code==="attachment_upload_store_busy"){upload.state="receiving";upload.completion=void 0;retryableFailure=true}else{upload.state="failed"}throw error}).finally(()=>{if(retryableFailure){if(this.closed||this.records.get(id)!==upload){this.discard(upload)}return}this.releaseBuffer(upload);if(this.closed||this.records.get(id)!==upload){this.discard(upload);return}upload.expiresAt=Date.now()+UPLOAD_LIFETIME_MS;receipts.add(upload);while(receipts.size>MAX_RECEIPTS){const oldest2=receipts.values().next().value;oldest2.owner.discard(oldest2)}});return upload.completion}cancel(id,clientId){sweep();const upload=this.records.get(id);if(!upload||upload.clientId!==clientId)return;if(upload.state==="completing"||upload.state==="completed"){throw new SessionAttachmentUploadError(409,upload.state==="completing"?"attachment_upload_finalizing":"attachment_upload_completed","Attachment completion cannot be cancelled")}this.discard(upload)}cancelClient(clientId){for(const upload of this.records.values()){if(upload.clientId===clientId)this.discard(upload)}}close(){this.closed=true;for(const upload of this.records.values())this.discard(upload)}discard(upload){this.records.delete(upload.id);if(upload.state==="completing")return;this.releaseBuffer(upload);uploads.delete(upload);receipts.delete(upload);if(uploads.size===0&&sweepTimer){clearInterval(sweepTimer);sweepTimer=void 0}}get(id,clientId){const upload=this.records.get(id);if(!upload||upload.clientId!==clientId)throw notFound();if(upload.state!=="completing"&&upload.expiresAt<=Date.now()){this.discard(upload);throw notFound()}return upload}releaseBuffer(upload){if(!upload.data)return;upload.data=void 0;stagedBytes-=upload.metadata.size;activeUploads--;this.active--}};var SESSION_ATTACHMENT_MAX_ITEM_BYTES=8*1024*1024;var SESSION_ATTACHMENT_MAX_NAME_BYTES=255;var SUPPORTED_IMAGE_MIME_TYPES=new Set(["image/bmp","image/gif","image/jpeg","image/png","image/webp"]);function hasVerifiableInode(ino){return Number.isSafeInteger(ino)&&ino>0}__name(hasVerifiableInode,"hasVerifiableInode");async function openDurableAttachmentDirectory(directory,openedHandle){const handle=openedHandle??await fs.open(directory,fsConstants.O_RDONLY|(process.platform==="win32"?0:fsConstants.O_NOFOLLOW??0));try{const opened=await handle.stat();const current=await fs.stat(directory);const openedInodeVerifiable=hasVerifiableInode(opened.ino);const currentInodeVerifiable=hasVerifiableInode(current.ino);if(!opened.isDirectory()||!current.isDirectory()||opened.dev!==current.dev||openedInodeVerifiable!==currentInodeVerifiable||openedInodeVerifiable&&opened.ino!==current.ino){throw new Error("Session attachment parent directory changed.")}return{path:directory,handle,dev:opened.dev,ino:opened.ino,inodeVerifiable:openedInodeVerifiable}}catch(error){await handle.close().catch(()=>void 0);throw error}}__name(openDurableAttachmentDirectory,"openDurableAttachmentDirectory");async function openDurableAttachmentDirectoryIfPresent(directory){let handle;try{handle=await fs.open(directory,fsConstants.O_RDONLY|(process.platform==="win32"?0:fsConstants.O_NOFOLLOW??0))}catch(error){if(error.code==="ENOENT")return void 0;throw error}return openDurableAttachmentDirectory(directory,handle)}__name(openDurableAttachmentDirectoryIfPresent,"openDurableAttachmentDirectoryIfPresent");async function syncDurableAttachmentDirectory(expected){const opened=await expected.handle.stat();const openedInodeVerifiable=hasVerifiableInode(opened.ino);const current=await fs.stat(expected.path);const currentInodeVerifiable=hasVerifiableInode(current.ino);if(!opened.isDirectory()||!current.isDirectory()||opened.dev!==expected.dev||openedInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&&opened.ino!==expected.ino||current.dev!==expected.dev||currentInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&¤t.ino!==expected.ino){throw new Error("Session attachment parent directory changed.")}try{await expected.handle.sync()}catch(error){if(process.platform!=="win32"||!["EACCES","EINVAL","EPERM"].includes(error.code??"")){throw error}}const after=await fs.stat(expected.path);const afterInodeVerifiable=hasVerifiableInode(after.ino);if(!after.isDirectory()||after.dev!==expected.dev||afterInodeVerifiable!==expected.inodeVerifiable||expected.inodeVerifiable&&after.ino!==expected.ino){throw new Error("Session attachment parent directory changed.")}}__name(syncDurableAttachmentDirectory,"syncDurableAttachmentDirectory");var SESSION_ATTACHMENT_UNAVAILABLE_TEXT="[Attachment is no longer available]";var SessionAttachmentReferenceError=class extends Error{constructor(message,code){super(message);this.code=code;this.name="SessionAttachmentReferenceError"}static{__name(this,"SessionAttachmentReferenceError")}};function isSessionAttachmentReference(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const record=value;return(record["type"]==="image"||record["type"]==="resource")&&typeof record["attachmentId"]==="string"&&record["attachmentId"].length>0&&typeof record["mimeType"]==="string"&&record["mimeType"].length>0&&(record["type"]!=="image"||record["mimeType"].startsWith("image/"))&&typeof record["size"]==="number"&&Number.isSafeInteger(record["size"])&&record["size"]>=0&&(record["type"]!=="image"||record["size"]>0)}__name(isSessionAttachmentReference,"isSessionAttachmentReference");function safeAttachmentName(name){const safeName=path.basename(name.replaceAll("\\","/")).trim();const isWindowsReserved=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(safeName);const hasInvalidCharacter=Array.from(safeName).some(character=>{const codePoint=character.codePointAt(0);return codePoint!==void 0&&(codePoint<=31||codePoint===127||codePoint>=55296&&codePoint<=57343)});return!safeName||safeName==="."||safeName===".."||safeName.endsWith(".")||isWindowsReserved||/[<>:"|?*]/.test(safeName)||hasInvalidCharacter||Buffer.byteLength(safeName)>SESSION_ATTACHMENT_MAX_NAME_BYTES?void 0:safeName}__name(safeAttachmentName,"safeAttachmentName");function truncateUtf8(value,maxBytes){let bytes=0;let result="";for(const character of value){const characterBytes=Buffer.byteLength(character);if(bytes+characterBytes>maxBytes)break;result+=character;bytes+=characterBytes}return result}__name(truncateUtf8,"truncateUtf8");function deduplicatedName(name,suffix){if(suffix===0)return name;const extension=path.extname(name);const suffixText=` (${suffix})`;const stem=name.slice(0,-extension.length||void 0);const extensionBudget=SESSION_ATTACHMENT_MAX_NAME_BYTES-Buffer.byteLength(suffixText)-1;const safeExtension=truncateUtf8(extension,extensionBudget).replace(/[. ]+$/u,"");const stemBudget=SESSION_ATTACHMENT_MAX_NAME_BYTES-Buffer.byteLength(suffixText)-Buffer.byteLength(safeExtension);return`${truncateUtf8(stem,stemBudget)}${suffixText}${safeExtension}`}__name(deduplicatedName,"deduplicatedName");function imageName(mimeType){const extension=mimeType.slice("image/".length).split(/[;+]/,1)[0];return`image.${extension==="jpg"?"jpeg":extension||"img"}`}__name(imageName,"imageName");function mimeTypeForName(name){if([".ts",".mts",".cts",".tsx"].includes(path.extname(name).toLowerCase())){return"text/plain"}return getSpecificMimeType(name)??"application/octet-stream"}__name(mimeTypeForName,"mimeTypeForName");function isSupportedImageMimeType(mimeType){return SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)}__name(isSupportedImageMimeType,"isSupportedImageMimeType");function isTextMimeType(mimeType){return mimeType.startsWith("text/")||mimeType==="application/json"||mimeType.endsWith("+json")||mimeType==="application/xml"||mimeType.endsWith("+xml")||mimeType==="application/javascript"||mimeType==="application/typescript"||mimeType==="application/yaml"||mimeType==="application/x-yaml"||mimeType==="application/toml"}__name(isTextMimeType,"isTextMimeType");function isTextAttachment(data,mimeType){if(isTextMimeType(mimeType))return true;if(mimeType.startsWith("image/")||mimeType.startsWith("audio/")||mimeType.startsWith("video/")||mimeType.startsWith("font/")||mimeType==="application/pdf"||data.includes(0)){return false}return Buffer.from(data.toString("utf8"),"utf8").equals(data)}__name(isTextAttachment,"isTextAttachment");function statSize(filePath){try{return statSync(filePath).size}catch{return void 0}}__name(statSize,"statSize");function statSizeStrict(filePath){try{return statSync(filePath).size}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(statSizeStrict,"statSizeStrict");function withAttachmentDegradationMarker(blocks){for(let i=blocks.length-1;i>=0;i--){const block=blocks[i];if(block.type==="text"){if(block.text.endsWith(SESSION_ATTACHMENT_UNAVAILABLE_TEXT)){return[...blocks]}const next=[...blocks];next[i]={type:"text",text:`${block.text}
|
|
5
5
|
${SESSION_ATTACHMENT_UNAVAILABLE_TEXT}`};return next}}return[...blocks,{type:"text",text:SESSION_ATTACHMENT_UNAVAILABLE_TEXT}]}__name(withAttachmentDegradationMarker,"withAttachmentDegradationMarker");function validateAttachmentName(mimeType,name){const isImage=isSupportedImageMimeType(mimeType);const safeName=safeAttachmentName(name??(isImage?imageName(mimeType):""));if(!safeName){throw new TypeError("Session attachment name is invalid")}const storedMimeType=mimeTypeForName(safeName);if(isImage&&storedMimeType!==mimeType||isSupportedImageMimeType(storedMimeType)&&!isImage){throw new TypeError("Attachment name and Content-Type do not match")}return safeName}__name(validateAttachmentName,"validateAttachmentName");var SessionAttachmentStore=class{constructor(directoryRoot,sessionId,fallbackDirectoryRoot){this.directoryRoot=directoryRoot;if(!directoryRoot||!sessionId)return;this.persistentDirectory=path.join(directoryRoot,`session-${encodeURIComponent(sessionId)}`);if(fallbackDirectoryRoot){this.persistentFallbackDirectory=path.join(fallbackDirectoryRoot,`session-${encodeURIComponent(sessionId)}`)}}static{__name(this,"SessionAttachmentStore")}uploads=new SessionAttachmentUploads;publication=Promise.resolve();readerBatch;directoryPromise;persistentDirectory;persistentFallbackDirectory;activeDirectory;pendingItems=0;pendingNames=new Map;queuedNames=new Map;removingNames=new Set;pendingDrainWaiters=[];copyDrainWaiters=[];copying=false;closing=false;closed=false;createUpload(metadata,clientId){if(this.closed||this.closing)throw new Error("Session attachment store is closed");if(this.copying)throw new Error("Session attachments are being copied");const name=validateAttachmentName(metadata.mimeType,metadata.name);if(!Number.isSafeInteger(metadata.size)||metadata.size<0){throw new TypeError("Attachment size must be a non-negative integer")}if(metadata.size>SESSION_ATTACHMENT_MAX_ITEM_BYTES){throw new RangeError("Session attachment must be at most 8 MiB")}if(metadata.size===0&&isSupportedImageMimeType(metadata.mimeType)){throw new TypeError("Image attachments cannot be empty")}return this.uploads.create({...metadata,name},clientId)}appendUpload(id,offset,data,clientId){return this.uploads.append(id,offset,data,clientId)}completeUpload(id,clientId,assertCanCommit){const assertAvailable=__name(()=>{if(this.closed||this.closing){throw new SessionAttachmentUploadError(404,"attachment_upload_not_found","Attachment upload is unavailable")}if(this.copying){throw new SessionAttachmentUploadError(503,"attachment_upload_store_busy","Session attachments are being copied")}},"assertAvailable");return this.uploads.complete(id,clientId,(data,metadata,assertActive)=>{assertAvailable();return this.putAttachment(data,metadata.mimeType,metadata.name,()=>{assertActive();assertCanCommit()})})}cancelUpload(id,clientId){this.uploads.cancel(id,clientId)}cancelClientUploads(clientId){this.uploads.cancelClient(clientId)}acquirePublication(){this.readerBatch=void 0;const previous=this.publication;let release;this.publication=new Promise(resolve3=>{release=resolve3});return previous.then(()=>release)}acquireReadPublication(){let batch=this.readerBatch;if(!batch){const previous=this.publication;let release;this.publication=new Promise(resolve3=>{release=resolve3});batch={previous,release,count:0};this.readerBatch=batch}batch.count+=1;return batch.previous.then(()=>()=>{if(--batch.count===0){if(this.readerBatch===batch)this.readerBatch=void 0;batch.release()}})}async putAttachment(data,mimeType,name,assertCanCommit){const isImage=isSupportedImageMimeType(mimeType);const safeName=validateAttachmentName(mimeType,name);if(this.closed||this.closing){throw new Error("Session attachment store is closed")}if(this.copying)throw new Error("Session attachments are being copied");if(isImage&&data.byteLength===0||data.byteLength>SESSION_ATTACHMENT_MAX_ITEM_BYTES){throw new RangeError(`Session attachment must be at most ${SESSION_ATTACHMENT_MAX_ITEM_BYTES} bytes and images cannot be empty`)}let filePath;let pendingName;let removeFileOnFailure=false;this.pendingItems+=1;this.queuedNames.set(safeName,(this.queuedNames.get(safeName)??0)+1);const releasePublication=await this.acquirePublication();try{if(this.closed||this.closing)throw new Error("Session attachment store is closed");assertCanCommit?.();const directory=await this.directory();let suffix=0;for(;;){const candidateName=deduplicatedName(safeName,suffix);if(safeAttachmentName(candidateName)!==candidateName){throw new TypeError("Session attachment name is invalid")}if(this.removingNames.has(candidateName)||statSizeStrict(path.join(directory,candidateName))!==void 0){suffix+=1;continue}if(this.persistentFallbackDirectory&&statSizeStrict(path.join(this.persistentFallbackDirectory,candidateName))!==void 0){suffix+=1;continue}if(pendingName!==candidateName){if(pendingName)this.releasePendingName(pendingName);this.reservePendingName(candidateName);pendingName=candidateName}if(this.closed||this.closing)throw new Error("Session attachment store is closed");assertCanCommit?.();filePath=path.join(directory,candidateName);removeFileOnFailure=true;try{await fs.writeFile(filePath,data,{flag:"wx"});break}catch(error){if(error.code!=="EEXIST")throw error;removeFileOnFailure=false;this.releasePendingName(candidateName);pendingName=void 0;filePath=void 0;suffix+=1}}if(this.closed||this.closing){throw new Error("Session attachment store is closed")}assertCanCommit?.();const name2=path.basename(filePath);const storedMimeType=mimeTypeForName(name2);const reference={type:isSupportedImageMimeType(storedMimeType)?"image":"resource",attachmentId:name2,mimeType:storedMimeType,size:data.byteLength};return reference}catch(error){if(removeFileOnFailure&&filePath){await fs.rm(filePath,{force:true}).catch(()=>{pendingName=void 0})}if(assertCanCommit&&error instanceof Error&&"code"in error&&typeof error.code==="string"&&/^E[A-Z]+$/.test(error.code)){throw new SessionAttachmentUploadError(500,"attachment_upload_storage_failed","Could not store attachment",error)}throw error}finally{if(pendingName)this.releasePendingName(pendingName);const queued=this.queuedNames.get(safeName);if(queued===1)this.queuedNames.delete(safeName);else this.queuedNames.set(safeName,queued-1);releasePublication();if(!this.closed){this.pendingItems-=1;if(this.pendingItems===0){this.resolvePendingDrainWaiters()}}}}assertReference(block){if(!block||typeof block!=="object"||Array.isArray(block)||!("attachmentId"in block)){return}if(!isSessionAttachmentReference(block)){throw new SessionAttachmentReferenceError("Invalid session attachment reference","invalid_session_attachment_reference")}this.assertStored(block)}assertReferences(content){const seenIds=new Set;for(const block of content){if(!block||typeof block!=="object"||Array.isArray(block)||!("attachmentId"in block)){continue}if(!isSessionAttachmentReference(block)){throw new SessionAttachmentReferenceError("Invalid session attachment reference","invalid_session_attachment_reference")}const id=block.attachmentId;if(seenIds.has(id)){throw new SessionAttachmentReferenceError(`Session attachment referenced more than once: ${id}`,"invalid_session_attachment_reference")}seenIds.add(id);this.assertStored(block)}}async resolveContent(content,memo){const pendingById=memo??new Map;return await Promise.all(content.map(async block=>{if(!isSessionAttachmentReference(block))return block;const id=block.attachmentId;let pending=pendingById.get(id);if(!pending){const created=this.resolve(block);pendingById.set(id,created);void created.catch(()=>{if(pendingById.get(id)===created){pendingById.delete(id)}});pending=created}return await pending}))}async resolveContentDegrading(content,memo){const retainedBlocks=[];const resolvedBlocks=[];let degraded=0;for(const block of content){if(!isSessionAttachmentReference(block)){retainedBlocks.push(block);resolvedBlocks.push(block);continue}try{const[resolved]=await this.resolveContent([block],memo);if(resolved)resolvedBlocks.push(resolved);retainedBlocks.push(block)}catch(error){if(!(error instanceof SessionAttachmentReferenceError))throw error;degraded+=1}}return{retainedBlocks,resolvedBlocks,degraded}}async read(attachmentId){const attachment=await this.readStored(attachmentId);if(!attachment)return void 0;return{data:attachment.data,mimeType:attachment.mimeType}}async readStored(attachmentId){const releasePublication=await this.acquireReadPublication();try{return await this.readPublished(attachmentId)}finally{releasePublication()}}async readPublished(attachmentId){const name=safeAttachmentName(attachmentId);if(!name||name!==attachmentId||this.pendingNames.has(name))return void 0;let primary;try{primary=await this.tryRead(await this.peekDirectory(),name)}catch(error){if(!this.persistentFallbackDirectory)throw error;primary=void 0}if(primary)return primary;return await this.tryRead(this.persistentFallbackDirectory,name)}async tryRead(directory,name){if(!directory)return void 0;const absolutePath=path.resolve(directory,name);try{return{data:await fs.readFile(absolutePath),mimeType:mimeTypeForName(name),absolutePath}}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async list(){const found=[];const directories=[this.persistentDirectory??this.activeDirectory,this.persistentFallbackDirectory].filter(directory=>Boolean(directory));const foundNames=new Set;let directoryRead=false;let directoryError;for(const directory of directories){let entries;try{entries=await fs.readdir(directory,{withFileTypes:true})}catch(error){if(error.code!=="ENOENT"){directoryError??=error}continue}directoryRead=true;for(const entry of entries){if(!entry.isFile()||this.pendingNames.has(entry.name)||this.removingNames.has(entry.name)||foundNames.has(entry.name)){continue}const name=safeAttachmentName(entry.name);if(!name||name!==entry.name)continue;try{const stat=await fs.stat(path.join(directory,entry.name));const mimeType=mimeTypeForName(entry.name);found.push({reference:{type:isSupportedImageMimeType(mimeType)?"image":"resource",attachmentId:entry.name,mimeType,size:stat.size},mtimeMs:stat.mtimeMs});foundNames.add(entry.name)}catch{}}}if(!directoryRead&&directoryError!==void 0){throw directoryError}found.sort((a,b)=>a.mtimeMs-b.mtimeMs||a.reference.attachmentId.localeCompare(b.reference.attachmentId));return found.map(({reference})=>reference)}async copyFrom(source){if(source===this)return;if(this.closed||this.closing){throw new Error("Session attachment store is closed")}if(this.copying)throw new Error("Session attachments are being copied");if(source.closed||source.closing){throw new Error("Session attachment store is closed")}if(source.copying){throw new Error("Session attachments are being copied")}this.copying=true;source.copying=true;try{if(this.pendingItems>0){await new Promise(resolve3=>this.pendingDrainWaiters.push(resolve3))}if(source.pendingItems>0){await new Promise(resolve3=>source.pendingDrainWaiters.push(resolve3))}if(this.closed)throw new Error("Session attachment store is closed");const sourceDirectories=[source.persistentDirectory??source.activeDirectory,source.persistentFallbackDirectory].filter(directory=>Boolean(directory));if(sourceDirectories.length===0)return;const targetDirectory=await this.directory();const copiedNames=new Set;let sourceDirectoryRead=false;let sourceDirectoryError;for(const sourceDirectory of sourceDirectories){let entries;try{entries=await fs.readdir(sourceDirectory,{withFileTypes:true})}catch(error){if(error.code==="ENOENT")continue;sourceDirectoryError??=error;continue}sourceDirectoryRead=true;await Promise.all(entries.filter(entry=>entry.isFile()&&!source.pendingNames.has(entry.name)&&!source.removingNames.has(entry.name)&&!copiedNames.has(entry.name)).map(async entry=>{const sourcePath=path.join(sourceDirectory,entry.name);try{await fs.copyFile(sourcePath,path.join(targetDirectory,entry.name));copiedNames.add(entry.name)}catch(error){if(error.code==="ENOENT"){try{await fs.stat(sourcePath)}catch(sourceError){if(sourceError.code==="ENOENT"){return}}}throw error}}))}if(!sourceDirectoryRead&&sourceDirectoryError!==void 0){throw sourceDirectoryError}}finally{source.copying=false;this.copying=false;source.resolveCopyDrainWaiters();this.resolveCopyDrainWaiters()}}async remove(attachmentId){const name=safeAttachmentName(attachmentId);if(!name||name!==attachmentId||this.copying||this.pendingNames.has(name)||this.queuedNames.has(name)||this.removingNames.has(name)){return false}this.removingNames.add(name);try{const primaryDirectory=await this.peekDirectory();const[fallbackExists,primaryExists]=await Promise.all([this.hasAttachment(this.persistentFallbackDirectory,name),this.hasAttachment(primaryDirectory,name)]);const fallbackHit=fallbackExists&&await this.tryUnlink(this.persistentFallbackDirectory,name)===true;const primaryHit=primaryExists&&await this.tryUnlink(primaryDirectory,name)===true;return primaryHit||fallbackHit}finally{this.removingNames.delete(name)}}async hasAttachment(directory,name){if(!directory)return false;try{await fs.stat(path.join(directory,name));return true}catch(error){if(error.code==="ENOENT")return false;throw error}}async tryUnlink(directory,name){if(!directory)return void 0;try{await fs.unlink(path.join(directory,name));return true}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async close(){this.closing=true;this.uploads.close();await this.waitForCopy();if(this.closed)return;this.closed=true;this.pendingItems=0;this.resolvePendingDrainWaiters();if(this.persistentDirectory||!this.directoryPromise)return;const directory=await this.directoryPromise.catch(()=>void 0);if(!directory)return;await fs.rm(directory,{recursive:true,force:true})}async delete(options={}){options.assertCanCommit?.();this.closing=true;this.uploads.close();await this.waitForCopy();options.assertCanCommit?.();if(!this.closed){this.closed=true;this.pendingItems=0;this.resolvePendingDrainWaiters()}let fallbackError;if(this.persistentFallbackDirectory){try{await this.removeDirectoryDurably(this.persistentFallbackDirectory,options.assertCanCommit)}catch(error){fallbackError=error}}const directory=this.persistentDirectory??await this.directoryPromise?.catch(()=>void 0);if(directory){await this.removeDirectoryDurably(directory,options.assertCanCommit)}if(fallbackError!==void 0)throw fallbackError}async removeDirectoryDurably(directory,assertCanCommit){assertCanCommit?.();const parent=await openDurableAttachmentDirectoryIfPresent(path.dirname(directory));if(!parent)return;const tombstone=path.join(path.dirname(directory),`.${path.basename(directory)}.deleting`);try{assertCanCommit?.();let tombstoneExists=false;try{const stats=await fs.lstat(tombstone);if(!stats.isDirectory()||stats.isSymbolicLink()){throw new Error("Session attachment tombstone is not a directory.")}tombstoneExists=true}catch(error){if(error.code!=="ENOENT")throw error}if(tombstoneExists){assertCanCommit?.();await fs.rm(tombstone,{recursive:true,force:true});await syncDurableAttachmentDirectory(parent);return}assertCanCommit?.();try{await fs.rename(directory,tombstone)}catch(error){if(error.code!=="ENOENT")throw error;try{const stats=await fs.lstat(tombstone);if(!stats.isDirectory()||stats.isSymbolicLink()){throw new Error("Session attachment tombstone is not a directory.")}assertCanCommit?.();await fs.rm(tombstone,{recursive:true,force:true})}catch(tombstoneError){if(tombstoneError.code!=="ENOENT"){throw tombstoneError}}await syncDurableAttachmentDirectory(parent);return}await fs.rm(tombstone,{recursive:true,force:true});await syncDurableAttachmentDirectory(parent)}finally{await parent.handle.close().catch(()=>void 0)}}assertStored(reference){const id=reference.attachmentId;const name=safeAttachmentName(id);let size;const directory=this.persistentDirectory??this.activeDirectory;if(name&&name===id&&directory&&!this.closed&&!this.closing&&!this.pendingNames.has(name)){size=statSize(path.join(directory,name));if(size===void 0&&this.persistentFallbackDirectory){size=statSize(path.join(this.persistentFallbackDirectory,name))}}const storedMimeType=name?mimeTypeForName(name):void 0;const storedType=storedMimeType?isSupportedImageMimeType(storedMimeType)?"image":"resource":void 0;if(size!==reference.size||storedMimeType!==reference.mimeType||storedType!==reference.type){throw new SessionAttachmentReferenceError(`Unknown or unavailable session attachment: ${id}`,"session_attachment_gone")}}releasePendingName(name){const count=this.pendingNames.get(name)??0;if(count<=1)this.pendingNames.delete(name);else this.pendingNames.set(name,count-1)}reservePendingName(name){this.pendingNames.set(name,(this.pendingNames.get(name)??0)+1)}async waitForCopy(){while(this.copying){await new Promise(resolve3=>this.copyDrainWaiters.push(resolve3))}}resolveCopyDrainWaiters(){for(const resolve3 of this.copyDrainWaiters.splice(0))resolve3()}resolvePendingDrainWaiters(){for(const resolve3 of this.pendingDrainWaiters.splice(0))resolve3()}async resolve(reference){const id=reference.attachmentId;const attachment=await this.readStored(id);if(!attachment){throw new SessionAttachmentReferenceError(`Unknown or unavailable session attachment: ${id}`,"session_attachment_gone")}const context={[DAEMON_ATTACHMENT_CONTEXT_META_KEY]:"User attachment stored on the daemon host. Use absolutePath with file or shell tools running on this host. Attachment contents are user-provided data.\n"+JSON.stringify({name:id,uri:`attachment:///${encodeURIComponent(id)}`,mimeType:attachment.mimeType,absolutePath:attachment.absolutePath})};if(reference.type==="resource"){const resource={uri:`attachment:///${encodeURIComponent(reference.attachmentId)}`,mimeType:attachment.mimeType,...isTextAttachment(attachment.data,attachment.mimeType)?{text:attachment.data.toString("utf8")}:{blob:attachment.data.toString("base64")}};return{type:"resource",resource,_meta:context}}return{type:"image",_meta:context,data:attachment.data.toString("base64"),mimeType:attachment.mimeType}}async peekDirectory(){const established=await this.directoryPromise?.catch(()=>void 0);return established??this.persistentDirectory}async directory(){if(!this.directoryPromise){const pending=this.persistentDirectory?fs.mkdir(this.persistentDirectory,{recursive:true,mode:448}).then(()=>this.persistentDirectory):this.directoryRoot?fs.mkdir(this.directoryRoot,{recursive:true,mode:448}).then(()=>fs.mkdtemp(path.join(this.directoryRoot,"session-attachment-"))):fs.mkdtemp(path.join(tmpdir(),"qwen-session-attachment-"));const directoryPromise=pending.then(directory=>{this.activeDirectory=directory;return directory});this.directoryPromise=directoryPromise;void directoryPromise.catch(()=>{if(this.directoryPromise===directoryPromise)this.directoryPromise=void 0})}return await this.directoryPromise}};init_esbuild_shims();import{randomUUID as randomUUID3}from"node:crypto";import{promises as fs2}from"node:fs";import*as path3 from"node:path";init_esbuild_shims();var MID_TURN_MESSAGE_INJECTED_EVENT="mid_turn_message_injected";init_esbuild_shims();import*as path2 from"node:path";var WORKFLOW_ANCESTOR_TRUST_METHOD="qwen/control/workflow/ancestor-trust";var WORKFLOW_ANCESTOR_TRUST_MAX_ANCESTORS=256;var WORKFLOW_ANCESTOR_TRUST_MAX_PATH_CHARS=32768;var WORKFLOW_ANCESTOR_TRUST_MAX_PATH_BYTES=1024*1024;function isPath(value){return typeof value==="string"&&value.length<=WORKFLOW_ANCESTOR_TRUST_MAX_PATH_CHARS&&!value.includes("\0")&&path2.isAbsolute(value)}__name(isPath,"isPath");function parseWorkflowAncestorTrustRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const request=value;if(request["v"]!==1||typeof request["sessionId"]!=="string"||request["sessionId"].trim().length===0||request["sessionId"].includes("\0")||!isPath(request["canonicalTargetDir"])||!Array.isArray(request["ancestorDirs"])||request["ancestorDirs"].length>WORKFLOW_ANCESTOR_TRUST_MAX_ANCESTORS)return;const ancestorDirs=[];let bytes=Buffer.byteLength(request["canonicalTargetDir"],"utf8");for(let index=0;index<request["ancestorDirs"].length;index++){if(!Object.hasOwn(request["ancestorDirs"],index))return;const ancestor=request["ancestorDirs"][index];if(!isPath(ancestor))return;bytes+=Buffer.byteLength(ancestor,"utf8");if(bytes>WORKFLOW_ANCESTOR_TRUST_MAX_PATH_BYTES)return;ancestorDirs.push(ancestor)}return{v:1,sessionId:request["sessionId"],canonicalTargetDir:request["canonicalTargetDir"],ancestorDirs}}__name(parseWorkflowAncestorTrustRequest,"parseWorkflowAncestorTrustRequest");function isWorkflowAncestorTrustResponse(value,expectedLength){if(!value||typeof value!=="object"||Array.isArray(value))return false;const response=value;const trusted=response["trusted"];if(response["v"]!==1||!Array.isArray(trusted)||trusted.length!==expectedLength)return false;for(let index=0;index<trusted.length;index++){if(!Object.hasOwn(trusted,index)||typeof trusted[index]!=="boolean")return false}return true}__name(isWorkflowAncestorTrustResponse,"isWorkflowAncestorTrustResponse");init_esbuild_shims();init_esbuild_shims();var CANCEL_VOTE_SENTINEL="__cancelled__";var MAX_RESOLVED_PERMISSION_RECORDS=512;function stringifyError(err){try{if(err instanceof Error)return`${err.name}: ${err.message}`;return String(err)}catch{return"[unstringifiable error]"}}__name(stringifyError,"stringifyError");function createNoOpPermissionAuditPublisher(){return{recordRequested(){},recordVoted(){},recordForbidden(){},recordResolved(){},recordTimeout(){}}}__name(createNoOpPermissionAuditPublisher,"createNoOpPermissionAuditPublisher");var MultiClientPermissionMediator=class{static{__name(this,"MultiClientPermissionMediator")}policy;deps;pending=new Map;resolved=new Map;resolvedOrder=[];unanimityBreadcrumbEmitted=false;constructor(policy,deps){this.policy=policy;this.deps=deps}request(record,timeoutMs){if(record.allowedOptionIds.has(CANCEL_VOTE_SENTINEL)){throw new CancelSentinelCollisionError(record.requestId,CANCEL_VOTE_SENTINEL)}return new Promise(resolve3=>{const policy=this.policy;const votersAtIssue=this.deps.votersForSession(record.sessionId);const pending={requestId:record.requestId,sessionId:record.sessionId,promptId:record.promptId,policy,originatorClientId:record.originatorClientId,allowedOptionIds:record.allowedOptionIds,issuedAtMs:record.issuedAtMs,timeoutMs,resolve:resolve3,tallies:new Map,votersAtIssue,timer:void 0,consensusQuorumCapNoted:false};this.pending.set(record.requestId,pending);this.safeAudit(()=>this.deps.audit.recordRequested(record,policy,votersAtIssue));const unresolvedWithoutDecision=timeoutMs>0?`voter cancellation, session cancellation, or permissionTimeoutMs (${timeoutMs}ms)`:"voter or session cancellation because permissionTimeoutMs is disabled";if(policy==="consensus"&&votersAtIssue.size===0){try{process.stderr.write(`permissionMediator: consensus request ${record.requestId} for session ${record.sessionId} issued with empty votersAtIssue; can only resolve via ${unresolvedWithoutDecision}
|
|
6
6
|
`)}catch{}}if(policy==="consensus"&&this.deps.consensusQuorum===void 0&&votersAtIssue.size>=2&&Math.floor(votersAtIssue.size/2)+1===votersAtIssue.size&&!this.unanimityBreadcrumbEmitted){this.unanimityBreadcrumbEmitted=true;try{process.stderr.write(`permissionMediator: consensus request ${record.requestId} for session ${record.sessionId} requires unanimity (votersAtIssue.size=${votersAtIssue.size}, default quorum=floor(M/2)+1=${votersAtIssue.size}); split votes will only resolve via ${unresolvedWithoutDecision}. This breadcrumb fires once per mediator lifetime; subsequent unanimity-required requests are silent.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-5F22H4WJ.js";import{getCliVersion}from"./chunk-OAPA66DR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHmac,randomUUID}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function readWorkspaceFiles(root,cwdRelative,value,expected){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const cwd=workspaceFilePath(cwdRelative);const anchors=new Map;async function directory(relative2){const segments=relative2==="."?[]:relative2.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative2=>cwd==="."?relative2:relative2==="."?cwd:`${cwd}/${relative2}`,"rooted");if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(rooted(parent));const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(rooted(next.relative));const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated}}__name(readWorkspaceFiles,"readWorkspaceFiles");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse2(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse2,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse2("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse2("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path2.isAbsolute(directory)||path2.resolve(directory)!==directory)return refuse2("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path2.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path2.sep}`)&&!path2.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse2("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs2.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse2("Runtime state file is not owner-private.");return JSON.parse(await fs2.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs2.open(path2.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse2("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path2.join(path2.dirname(file),`.${path2.basename(file)}.${randomUUID()}.tmp`);const handle=await fs2.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs2.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs2.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs2.mkdir(directory,{recursive:true,mode:448});const stat=await fs2.lstat(directory);if(!stat.isDirectory()||await fs2.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse2("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path2.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse2("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse2("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs2.realpath(root))refuse2("Storage root is not canonical.");const stat=await fs2.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse2("Storage directory has no independent birth identity.");await fs2.access(root,constants2.R_OK|constants2.W_OK|constants2.X_OK);const machine=hostId?void 0:process.platform==="linux"?(await fs2.readFile("/etc/machine-id","utf8")).trim():/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1];if(!hostId){if(!machine||machine.length>256)refuse2("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse2("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path2.join(identity.root,MARKER)),marker))refuse2("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse2("Runtime resource identity is invalid.");return path2.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path2.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse2("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:1,resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path2.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse2("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path2.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs2.lstat(path2.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse2("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse2("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse2("A retired launch claim cannot own a worker process.");const failed=await optionalJson(path2.join(directory,"launch-failed.json"));if(failed!==void 0&&(!isDeepStrictEqual(failed,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path2.join(directory,"ready.json"))!==void 0))refuse2("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path2.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path2.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse2("Runtime clean proof conflicts.");if((neverStarted||failed!==void 0)&&pid===null&&(failed!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path2.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse2("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse2("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse2("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path2.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse2("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path2.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path2.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs2.open(path2.join(directory,"stdout.log"),"ax",384);try{const errors=await fs2.open(path2.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path2.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path2.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path2.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse2("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse2("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse2("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse2("Storage root conflicts.");if(identity2)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{const files=await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],{device:text(expected.device),inode:text(expected.inode)});if(identity2)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path2.resolve(root,relative);if(path2.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs2.realpath(cwd)||!(await fs2.stat(cwd)).isDirectory())refuse2("Working directory is unavailable.");await fs2.access(cwd,constants2.R_OK|constants2.W_OK|constants2.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path2.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse2("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path2.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse2("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse2("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse2("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path2.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path2.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse2("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path2.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path2.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path2.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path2.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1}})}
|
|
3
|
+
import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-5F22H4WJ.js";import{getCliVersion}from"./chunk-BQQBFDBY.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHmac,randomUUID}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function readWorkspaceFiles(root,cwdRelative,value,expected){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const cwd=workspaceFilePath(cwdRelative);const anchors=new Map;async function directory(relative2){const segments=relative2==="."?[]:relative2.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative2=>cwd==="."?relative2:relative2==="."?cwd:`${cwd}/${relative2}`,"rooted");if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(rooted(parent));const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(rooted(next.relative));const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated}}__name(readWorkspaceFiles,"readWorkspaceFiles");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse2(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse2,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse2("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse2("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path2.isAbsolute(directory)||path2.resolve(directory)!==directory)return refuse2("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path2.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path2.sep}`)&&!path2.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse2("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs2.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse2("Runtime state file is not owner-private.");return JSON.parse(await fs2.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs2.open(path2.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse2("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path2.join(path2.dirname(file),`.${path2.basename(file)}.${randomUUID()}.tmp`);const handle=await fs2.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs2.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs2.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs2.mkdir(directory,{recursive:true,mode:448});const stat=await fs2.lstat(directory);if(!stat.isDirectory()||await fs2.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse2("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path2.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse2("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse2("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs2.realpath(root))refuse2("Storage root is not canonical.");const stat=await fs2.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse2("Storage directory has no independent birth identity.");await fs2.access(root,constants2.R_OK|constants2.W_OK|constants2.X_OK);const machine=hostId?void 0:process.platform==="linux"?(await fs2.readFile("/etc/machine-id","utf8")).trim():/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1];if(!hostId){if(!machine||machine.length>256)refuse2("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse2("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path2.join(identity.root,MARKER)),marker))refuse2("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse2("Runtime resource identity is invalid.");return path2.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path2.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse2("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:1,resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path2.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse2("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path2.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs2.lstat(path2.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse2("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse2("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse2("A retired launch claim cannot own a worker process.");const failed=await optionalJson(path2.join(directory,"launch-failed.json"));if(failed!==void 0&&(!isDeepStrictEqual(failed,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path2.join(directory,"ready.json"))!==void 0))refuse2("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path2.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path2.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse2("Runtime clean proof conflicts.");if((neverStarted||failed!==void 0)&&pid===null&&(failed!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path2.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse2("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse2("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse2("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path2.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse2("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path2.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path2.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs2.open(path2.join(directory,"stdout.log"),"ax",384);try{const errors=await fs2.open(path2.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path2.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path2.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path2.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse2("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse2("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse2("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse2("Storage root conflicts.");if(identity2)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{const files=await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],{device:text(expected.device),inode:text(expected.inode)});if(identity2)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path2.resolve(root,relative);if(path2.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs2.realpath(cwd)||!(await fs2.stat(cwd)).isDirectory())refuse2("Working directory is unavailable.");await fs2.access(cwd,constants2.R_OK|constants2.W_OK|constants2.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path2.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse2("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path2.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse2("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse2("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse2("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path2.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path2.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse2("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path2.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path2.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path2.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path2.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1}})}
|
|
4
4
|
`);return}let response;try{const chunks=[];let size=0;for await(const chunk of process.stdin){const bytes=Buffer.from(chunk);size+=bytes.length;if(size>MAX_BYTES)refuse2("Runtime bootstrap request exceeds its limit.");chunks.push(bytes)}const source=new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks));response={protocolVersion:1,ok:true,result:await executeSshBootstrap(JSON.parse(source))}}catch(error){const known=error instanceof SshBootstrapError?error:new SshBootstrapError("ssh_runtime_state_unavailable","Runtime bootstrap state is unavailable.");response={protocolVersion:1,ok:false,error:{code:known.code,message:known.message,retryable:known.retryable}}}process.stdout.write(`${JSON.stringify(response)}
|
|
5
5
|
`)}__name(runManagedRuntimeBootstrap,"runManagedRuntimeBootstrap");function sshResourcePath(record){return resourceDirectory(record.stateDirectory,record.resourceId)}__name(sshResourcePath,"sshResourcePath");export{SSH_RETIRE_PATH,SshBootstrapError,readSshPrivateJson,writeSshPrivateJson,inspectSshStorage,verifySshStorage,readSshRuntimeRecord,sshCleanProof,sshRuntimeHeaders,executeSshBootstrap,runManagedRuntimeBootstrap,sshResourcePath};
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS,MAX_AGENT_MESSAGE_STEPS,SESSION_AGENTS_SCHEMA_VERSION}from"./chunk-BOFD4CN3.js";import{STORE_DIR_MODE,STORE_FILE_OPTIONS,getAgentsDir,withAgentStoreTransaction}from"./chunk-RKPHDO42.js";import{atomicWriteJSON}from"./chunk-BMHYEQTI.js";import{isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";var SESSIONS_DIRNAME="sessions";var MAX_TERMINAL_SESSION_AGENT_RUNS=50;var SESSION_ID_PATTERN=/^[0-9a-fA-F-]{32,36}$/;var MAX_BINDING_SCAN_FILES=5e3;var LIVE_RUN_STATUSES=new Set(["queued","running","awaiting_approval"]);var TERMINAL_RUN_STATUSES=new Set(["completed","failed","cancelled","offline"]);var EXECUTING_RUN_STATUSES=new Set(["running","awaiting_approval"]);function isValidSessionAgentsSessionId(value){return typeof value==="string"&&SESSION_ID_PATTERN.test(value)}__name(isValidSessionAgentsSessionId,"isValidSessionAgentsSessionId");function isTerminalSessionAgentRunStatus(status){return TERMINAL_RUN_STATUSES.has(status)}__name(isTerminalSessionAgentRunStatus,"isTerminalSessionAgentRunStatus");function getSessionAgentsDir(projectRoot){return path.join(getAgentsDir(projectRoot),SESSIONS_DIRNAME)}__name(getSessionAgentsDir,"getSessionAgentsDir");function getSessionAgentsFilePath(projectRoot,sessionId){if(!isValidSessionAgentsSessionId(sessionId)){throw new Error(`Invalid chat session id: ${JSON.stringify(sessionId)}`)}return path.join(getSessionAgentsDir(projectRoot),`${sessionId}.json`)}__name(getSessionAgentsFilePath,"getSessionAgentsFilePath");function emptySessionAgentsFile(sessionId){return{schemaVersion:SESSION_AGENTS_SCHEMA_VERSION,sessionId,bindings:{},runs:[]}}__name(emptySessionAgentsFile,"emptySessionAgentsFile");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function isOptionalString(value){return value===void 0||typeof value==="string"}__name(isOptionalString,"isOptionalString");function isOptionalFiniteNumber(value){return value===void 0||typeof value==="number"&&Number.isFinite(value)}__name(isOptionalFiniteNumber,"isOptionalFiniteNumber");var RUN_STATUSES=new Set([...LIVE_RUN_STATUSES,...TERMINAL_RUN_STATUSES]);function isValidBinding(value){return isRecord(value)&&typeof value["agentId"]==="string"&&isOptionalString(value["nativeSessionId"])&&isOptionalString(value["runtimeId"])&&(value["program"]===void 0||value["program"]==="qwen"||value["program"]==="claude"||value["program"]==="codex")&&isOptionalString(value["readThroughRecordId"])&&(value["remotePersona"]===void 0||isRecord(value["remotePersona"])&&typeof value["remotePersona"]["name"]==="string"&&isOptionalString(value["remotePersona"]["instructions"])&&isOptionalString(value["remotePersona"]["model"]))}__name(isValidBinding,"isValidBinding");function isValidLease(value){return value===void 0||isRecord(value)&&typeof value["hostId"]==="string"&&typeof value["leaseId"]==="string"&&typeof value["attempt"]==="number"&&typeof value["expiresAt"]==="number"&&isOptionalFiniteNumber(value["lastSequence"])}__name(isValidLease,"isValidLease");function isValidRun(value){return isRecord(value)&&typeof value["id"]==="string"&&typeof value["agentId"]==="string"&&typeof value["status"]==="string"&&RUN_STATUSES.has(value["status"])&&Array.isArray(value["triggerRecordIds"])&&value["triggerRecordIds"].every(id=>typeof id==="string")&&typeof value["chainDepth"]==="number"&&typeof value["createdAt"]==="number"&&typeof value["attempts"]==="number"&&isOptionalFiniteNumber(value["startedAt"])&&isOptionalFiniteNumber(value["endedAt"])&&isOptionalString(value["error"])&&isOptionalFiniteNumber(value["totalTokens"])&&isOptionalString(value["retryOf"])&&isOptionalString(value["squadId"])&&(value["recorded"]===void 0||typeof value["recorded"]==="boolean")&&isValidLease(value["lease"])}__name(isValidRun,"isValidRun");function isValidEngagement(value){return isRecord(value)&&typeof value["leaderAgentId"]==="string"&&typeof value["startedByRecordId"]==="string"&&Array.isArray(value["outstandingRunIds"])&&value["outstandingRunIds"].every(id=>typeof id==="string")&&(value["pendingWakeRunIds"]===void 0||Array.isArray(value["pendingWakeRunIds"])&&value["pendingWakeRunIds"].every(id=>typeof id==="string"))&&typeof value["active"]==="boolean"}__name(isValidEngagement,"isValidEngagement");function isValidEngagements(value){return value===void 0||isRecord(value)&&Object.values(value).every(isValidEngagement)}__name(isValidEngagements,"isValidEngagements");function parseSessionAgentsFile(value,sessionId,filePath="<memory>"){if(!isRecord(value)){throw new Error(`Malformed session agents file ${filePath}.`)}if(value["schemaVersion"]!==SESSION_AGENTS_SCHEMA_VERSION){throw new Error(`Unsupported session agents schema version ${JSON.stringify(value["schemaVersion"])} in ${filePath}; this build supports version ${SESSION_AGENTS_SCHEMA_VERSION}.`)}if(value["sessionId"]!==sessionId){throw new Error(`Session agents file ${filePath} names session ${JSON.stringify(value["sessionId"])}, not ${sessionId}.`)}const bindings=value["bindings"];const runs=value["runs"];if(!isRecord(bindings)||!Object.entries(bindings).every(([agentId,binding])=>isValidBinding(binding)&&binding.agentId===agentId)||!Array.isArray(runs)||!runs.every(isValidRun)||!isValidEngagements(value["squads"])){throw new Error(`Malformed session agents file ${filePath}.`)}const squads=value["squads"];return{schemaVersion:SESSION_AGENTS_SCHEMA_VERSION,sessionId,bindings,runs,...typeof value["chainTokens"]==="number"&&Number.isFinite(value["chainTokens"])&&value["chainTokens"]>0?{chainTokens:value["chainTokens"]}:{},...squads&&Object.keys(squads).length>0?{squads}:{}}}__name(parseSessionAgentsFile,"parseSessionAgentsFile");function trimTerminalRuns(runs,max=MAX_TERMINAL_SESSION_AGENT_RUNS){const terminal=runs.filter(run=>isTerminalSessionAgentRunStatus(run.status)&&run.recorded!==false);if(terminal.length<=max)return[...runs];const keep=new Set([...terminal].sort((a,b)=>(b.endedAt??b.createdAt)-(a.endedAt??a.createdAt)).slice(0,Math.max(0,max)).map(run=>run.id));return runs.filter(run=>!isTerminalSessionAgentRunStatus(run.status)||run.recorded===false||keep.has(run.id))}__name(trimTerminalRuns,"trimTerminalRuns");async function readFileUnlocked(projectRoot,sessionId){const filePath=getSessionAgentsFilePath(projectRoot,sessionId);let raw;try{raw=await fs.readFile(filePath,"utf-8")}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return void 0;throw error}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`Malformed JSON in ${filePath} \u2014 fix or delete the file; refusing to treat it as empty.`)}return parseSessionAgentsFile(parsed,sessionId,filePath)}__name(readFileUnlocked,"readFileUnlocked");async function readSessionAgents(projectRoot,sessionId){return await readFileUnlocked(projectRoot,sessionId)??emptySessionAgentsFile(sessionId)}__name(readSessionAgents,"readSessionAgents");async function updateSessionAgents(projectRoot,sessionId,mutate){const filePath=getSessionAgentsFilePath(projectRoot,sessionId);return withAgentStoreTransaction(projectRoot,async()=>{const current=await readFileUnlocked(projectRoot,sessionId)??emptySessionAgentsFile(sessionId);const mutated=mutate(current)??current;const next={schemaVersion:SESSION_AGENTS_SCHEMA_VERSION,sessionId,bindings:mutated.bindings,runs:trimTerminalRuns(mutated.runs),...mutated.chainTokens?{chainTokens:mutated.chainTokens}:{},...mutated.squads&&Object.keys(mutated.squads).length>0?{squads:mutated.squads}:{}};parseSessionAgentsFile(next,sessionId,filePath);await fs.mkdir(getSessionAgentsDir(projectRoot),{recursive:true,mode:STORE_DIR_MODE});await atomicWriteJSON(filePath,next,STORE_FILE_OPTIONS);return next})}__name(updateSessionAgents,"updateSessionAgents");async function writeSessionAgents(projectRoot,file){return updateSessionAgents(projectRoot,file.sessionId,()=>({...file,bindings:structuredClone(file.bindings),runs:structuredClone(file.runs),...file.chainTokens?{chainTokens:file.chainTokens}:{},...file.squads?{squads:structuredClone(file.squads)}:{}}))}__name(writeSessionAgents,"writeSessionAgents");async function listSessionAgentsSessionIds(projectRoot){let names;try{names=await fs.readdir(getSessionAgentsDir(projectRoot))}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return[];throw error}return names.filter(name=>name.endsWith(".json")).map(name=>name.slice(0,-".json".length)).filter(isValidSessionAgentsSessionId)}__name(listSessionAgentsSessionIds,"listSessionAgentsSessionIds");async function findSessionAgentBinding(projectRoot,nativeSessionId,agentId){if(!nativeSessionId||!agentId)return void 0;const ids=(await listSessionAgentsSessionIds(projectRoot)).slice(0,MAX_BINDING_SCAN_FILES);for(const chatSessionId of ids){let file;try{file=await readFileUnlocked(projectRoot,chatSessionId)}catch{continue}if(!file)continue;const binding=file.bindings[agentId];if(binding?.nativeSessionId!==nativeSessionId)continue;const run=file.runs.find(candidate=>candidate.agentId===agentId&&EXECUTING_RUN_STATUSES.has(candidate.status)&&candidate.lease===void 0);if(!run)continue;return{chatSessionId,agentId,runId:run.id,status:run.status,...binding.remotePersona?{remotePersona:{...binding.remotePersona}}:{}}}return void 0}__name(findSessionAgentBinding,"findSessionAgentBinding");function canReuseNativeSession(binding,runtimeId,program){return(binding.runtimeId===void 0||binding.runtimeId===runtimeId)&&(binding.program===void 0||binding.program===program)}__name(canReuseNativeSession,"canReuseNativeSession");init_esbuild_shims();var MAX_EXTERNAL_RECORD_KEY_LENGTH=256;var MAX_EXTERNAL_RECORD_TEXT_LENGTH=65536;var MAX_EXTERNAL_RECORD_DISPLAY_TEXT_LENGTH=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS;var MAX_EXTERNAL_RECORD_STEPS=MAX_AGENT_MESSAGE_STEPS;var MAX_EXTERNAL_RECORD_MENTION_IDS=32;var MAX_EXTERNAL_RECORD_ID_LENGTH=256;var MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH=1024;var STEP_STATUSES=new Set(["running","completed","failed"]);var TERMINAL_STATUSES=new Set(["completed","failed","cancelled","offline"]);function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObject,"isObject");function isBoundedString(value,maxLength){return typeof value==="string"&&value.length<=maxLength}__name(isBoundedString,"isBoundedString");function isIdList(value){return Array.isArray(value)&&value.length<=MAX_EXTERNAL_RECORD_MENTION_IDS&&value.every(id=>isBoundedString(id,MAX_EXTERNAL_RECORD_ID_LENGTH))}__name(isIdList,"isIdList");function isSteps(value){return Array.isArray(value)&&value.length<=MAX_EXTERNAL_RECORD_STEPS&&value.every(step=>isObject(step)&&isBoundedString(step["id"],MAX_EXTERNAL_RECORD_ID_LENGTH)&&typeof step["title"]==="string"&&step["title"].length<=MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH&&typeof step["status"]==="string"&&STEP_STATUSES.has(step["status"]))}__name(isSteps,"isSteps");function isAuthor(value){return isObject(value)&&typeof value["agentId"]==="string"&&value["agentId"].length>0&&typeof value["name"]==="string"&&value["name"].length>0}__name(isAuthor,"isAuthor");function parseSessionExternalRecordParams(params){const{kind,recordKey,modelText,payload}=params;if(kind!=="agent_mention"&&kind!=="agent_message"){return"Invalid external record kind"}if(typeof recordKey!=="string"||recordKey.length===0||recordKey.length>MAX_EXTERNAL_RECORD_KEY_LENGTH){return"Invalid or missing external record recordKey"}if(typeof modelText!=="string"||modelText.length===0||modelText.length>MAX_EXTERNAL_RECORD_TEXT_LENGTH){return"Invalid or missing external record modelText"}if(!isObject(payload)||typeof payload["displayText"]!=="string"||payload["displayText"].length>(kind==="agent_message"?MAX_EXTERNAL_RECORD_DISPLAY_TEXT_LENGTH:MAX_EXTERNAL_RECORD_TEXT_LENGTH)){return"Invalid or missing external record payload.displayText"}if(kind==="agent_message"){if(!isAuthor(payload["author"])){return"Invalid agent_message payload.author"}if(typeof payload["runId"]!=="string"||payload["runId"].length===0){return"Invalid agent_message payload.runId"}if(typeof payload["status"]!=="string"||!TERMINAL_STATUSES.has(payload["status"])){return"Invalid agent_message payload.status"}if(payload["steps"]!==void 0&&!isSteps(payload["steps"])){return"Invalid or oversized agent_message payload.steps"}return{kind,recordKey,modelText,payload}}if(!isIdList(payload["mentionedAgentIds"])){return"Invalid or oversized agent_mention payload.mentionedAgentIds"}if(payload["mentionedSquadIds"]!==void 0&&!isIdList(payload["mentionedSquadIds"])){return"Invalid or oversized agent_mention payload.mentionedSquadIds"}if(payload["author"]!==void 0&&!isAuthor(payload["author"])){return"Invalid agent_mention payload.author"}return{kind,recordKey,modelText,payload}}__name(parseSessionExternalRecordParams,"parseSessionExternalRecordParams");export{isValidSessionAgentsSessionId,isTerminalSessionAgentRunStatus,trimTerminalRuns,readSessionAgents,updateSessionAgents,writeSessionAgents,listSessionAgentsSessionIds,findSessionAgentBinding,canReuseNativeSession,MAX_EXTERNAL_RECORD_TEXT_LENGTH,MAX_EXTERNAL_RECORD_MENTION_IDS,MAX_EXTERNAL_RECORD_ID_LENGTH,MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH,parseSessionExternalRecordParams};
|
|
3
|
+
import{MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS,MAX_AGENT_MESSAGE_STEPS,SESSION_AGENTS_SCHEMA_VERSION}from"./chunk-AVIDPC5K.js";import{STORE_DIR_MODE,STORE_FILE_OPTIONS,getAgentsDir,withAgentStoreTransaction}from"./chunk-LDXZT3SG.js";import{atomicWriteJSON}from"./chunk-BMHYEQTI.js";import{isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";var SESSIONS_DIRNAME="sessions";var MAX_TERMINAL_SESSION_AGENT_RUNS=50;var SESSION_ID_PATTERN=/^[0-9a-fA-F-]{32,36}$/;var MAX_BINDING_SCAN_FILES=5e3;var LIVE_RUN_STATUSES=new Set(["queued","running","awaiting_approval"]);var TERMINAL_RUN_STATUSES=new Set(["completed","failed","cancelled","offline"]);var EXECUTING_RUN_STATUSES=new Set(["running","awaiting_approval"]);function isValidSessionAgentsSessionId(value){return typeof value==="string"&&SESSION_ID_PATTERN.test(value)}__name(isValidSessionAgentsSessionId,"isValidSessionAgentsSessionId");function isTerminalSessionAgentRunStatus(status){return TERMINAL_RUN_STATUSES.has(status)}__name(isTerminalSessionAgentRunStatus,"isTerminalSessionAgentRunStatus");function getSessionAgentsDir(projectRoot){return path.join(getAgentsDir(projectRoot),SESSIONS_DIRNAME)}__name(getSessionAgentsDir,"getSessionAgentsDir");function getSessionAgentsFilePath(projectRoot,sessionId){if(!isValidSessionAgentsSessionId(sessionId)){throw new Error(`Invalid chat session id: ${JSON.stringify(sessionId)}`)}return path.join(getSessionAgentsDir(projectRoot),`${sessionId}.json`)}__name(getSessionAgentsFilePath,"getSessionAgentsFilePath");function emptySessionAgentsFile(sessionId){return{schemaVersion:SESSION_AGENTS_SCHEMA_VERSION,sessionId,bindings:{},runs:[]}}__name(emptySessionAgentsFile,"emptySessionAgentsFile");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function isOptionalString(value){return value===void 0||typeof value==="string"}__name(isOptionalString,"isOptionalString");function isOptionalFiniteNumber(value){return value===void 0||typeof value==="number"&&Number.isFinite(value)}__name(isOptionalFiniteNumber,"isOptionalFiniteNumber");var RUN_STATUSES=new Set([...LIVE_RUN_STATUSES,...TERMINAL_RUN_STATUSES]);function isValidBinding(value){return isRecord(value)&&typeof value["agentId"]==="string"&&isOptionalString(value["nativeSessionId"])&&isOptionalString(value["runtimeId"])&&(value["program"]===void 0||value["program"]==="qwen"||value["program"]==="claude"||value["program"]==="codex")&&isOptionalString(value["readThroughRecordId"])&&(value["remotePersona"]===void 0||isRecord(value["remotePersona"])&&typeof value["remotePersona"]["name"]==="string"&&isOptionalString(value["remotePersona"]["instructions"])&&isOptionalString(value["remotePersona"]["model"]))}__name(isValidBinding,"isValidBinding");function isValidLease(value){return value===void 0||isRecord(value)&&typeof value["hostId"]==="string"&&typeof value["leaseId"]==="string"&&typeof value["attempt"]==="number"&&typeof value["expiresAt"]==="number"&&isOptionalFiniteNumber(value["lastSequence"])}__name(isValidLease,"isValidLease");function isValidRun(value){return isRecord(value)&&typeof value["id"]==="string"&&typeof value["agentId"]==="string"&&typeof value["status"]==="string"&&RUN_STATUSES.has(value["status"])&&Array.isArray(value["triggerRecordIds"])&&value["triggerRecordIds"].every(id=>typeof id==="string")&&typeof value["chainDepth"]==="number"&&typeof value["createdAt"]==="number"&&typeof value["attempts"]==="number"&&isOptionalFiniteNumber(value["startedAt"])&&isOptionalFiniteNumber(value["endedAt"])&&isOptionalString(value["error"])&&isOptionalFiniteNumber(value["totalTokens"])&&isOptionalString(value["retryOf"])&&isOptionalString(value["squadId"])&&(value["recorded"]===void 0||typeof value["recorded"]==="boolean")&&isValidLease(value["lease"])}__name(isValidRun,"isValidRun");function isValidEngagement(value){return isRecord(value)&&typeof value["leaderAgentId"]==="string"&&typeof value["startedByRecordId"]==="string"&&Array.isArray(value["outstandingRunIds"])&&value["outstandingRunIds"].every(id=>typeof id==="string")&&(value["pendingWakeRunIds"]===void 0||Array.isArray(value["pendingWakeRunIds"])&&value["pendingWakeRunIds"].every(id=>typeof id==="string"))&&typeof value["active"]==="boolean"}__name(isValidEngagement,"isValidEngagement");function isValidEngagements(value){return value===void 0||isRecord(value)&&Object.values(value).every(isValidEngagement)}__name(isValidEngagements,"isValidEngagements");function parseSessionAgentsFile(value,sessionId,filePath="<memory>"){if(!isRecord(value)){throw new Error(`Malformed session agents file ${filePath}.`)}if(value["schemaVersion"]!==SESSION_AGENTS_SCHEMA_VERSION){throw new Error(`Unsupported session agents schema version ${JSON.stringify(value["schemaVersion"])} in ${filePath}; this build supports version ${SESSION_AGENTS_SCHEMA_VERSION}.`)}if(value["sessionId"]!==sessionId){throw new Error(`Session agents file ${filePath} names session ${JSON.stringify(value["sessionId"])}, not ${sessionId}.`)}const bindings=value["bindings"];const runs=value["runs"];if(!isRecord(bindings)||!Object.entries(bindings).every(([agentId,binding])=>isValidBinding(binding)&&binding.agentId===agentId)||!Array.isArray(runs)||!runs.every(isValidRun)||!isValidEngagements(value["squads"])){throw new Error(`Malformed session agents file ${filePath}.`)}const squads=value["squads"];return{schemaVersion:SESSION_AGENTS_SCHEMA_VERSION,sessionId,bindings,runs,...typeof value["chainTokens"]==="number"&&Number.isFinite(value["chainTokens"])&&value["chainTokens"]>0?{chainTokens:value["chainTokens"]}:{},...squads&&Object.keys(squads).length>0?{squads}:{}}}__name(parseSessionAgentsFile,"parseSessionAgentsFile");function trimTerminalRuns(runs,max=MAX_TERMINAL_SESSION_AGENT_RUNS){const terminal=runs.filter(run=>isTerminalSessionAgentRunStatus(run.status)&&run.recorded!==false);if(terminal.length<=max)return[...runs];const keep=new Set([...terminal].sort((a,b)=>(b.endedAt??b.createdAt)-(a.endedAt??a.createdAt)).slice(0,Math.max(0,max)).map(run=>run.id));return runs.filter(run=>!isTerminalSessionAgentRunStatus(run.status)||run.recorded===false||keep.has(run.id))}__name(trimTerminalRuns,"trimTerminalRuns");async function readFileUnlocked(projectRoot,sessionId){const filePath=getSessionAgentsFilePath(projectRoot,sessionId);let raw;try{raw=await fs.readFile(filePath,"utf-8")}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return void 0;throw error}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`Malformed JSON in ${filePath} \u2014 fix or delete the file; refusing to treat it as empty.`)}return parseSessionAgentsFile(parsed,sessionId,filePath)}__name(readFileUnlocked,"readFileUnlocked");async function readSessionAgents(projectRoot,sessionId){return await readFileUnlocked(projectRoot,sessionId)??emptySessionAgentsFile(sessionId)}__name(readSessionAgents,"readSessionAgents");async function updateSessionAgents(projectRoot,sessionId,mutate){const filePath=getSessionAgentsFilePath(projectRoot,sessionId);return withAgentStoreTransaction(projectRoot,async()=>{const current=await readFileUnlocked(projectRoot,sessionId)??emptySessionAgentsFile(sessionId);const mutated=mutate(current)??current;const next={schemaVersion:SESSION_AGENTS_SCHEMA_VERSION,sessionId,bindings:mutated.bindings,runs:trimTerminalRuns(mutated.runs),...mutated.chainTokens?{chainTokens:mutated.chainTokens}:{},...mutated.squads&&Object.keys(mutated.squads).length>0?{squads:mutated.squads}:{}};parseSessionAgentsFile(next,sessionId,filePath);await fs.mkdir(getSessionAgentsDir(projectRoot),{recursive:true,mode:STORE_DIR_MODE});await atomicWriteJSON(filePath,next,STORE_FILE_OPTIONS);return next})}__name(updateSessionAgents,"updateSessionAgents");async function writeSessionAgents(projectRoot,file){return updateSessionAgents(projectRoot,file.sessionId,()=>({...file,bindings:structuredClone(file.bindings),runs:structuredClone(file.runs),...file.chainTokens?{chainTokens:file.chainTokens}:{},...file.squads?{squads:structuredClone(file.squads)}:{}}))}__name(writeSessionAgents,"writeSessionAgents");async function listSessionAgentsSessionIds(projectRoot){let names;try{names=await fs.readdir(getSessionAgentsDir(projectRoot))}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return[];throw error}return names.filter(name=>name.endsWith(".json")).map(name=>name.slice(0,-".json".length)).filter(isValidSessionAgentsSessionId)}__name(listSessionAgentsSessionIds,"listSessionAgentsSessionIds");async function findSessionAgentBinding(projectRoot,nativeSessionId,agentId){if(!nativeSessionId||!agentId)return void 0;const ids=(await listSessionAgentsSessionIds(projectRoot)).slice(0,MAX_BINDING_SCAN_FILES);for(const chatSessionId of ids){let file;try{file=await readFileUnlocked(projectRoot,chatSessionId)}catch{continue}if(!file)continue;const binding=file.bindings[agentId];if(binding?.nativeSessionId!==nativeSessionId)continue;const run=file.runs.find(candidate=>candidate.agentId===agentId&&EXECUTING_RUN_STATUSES.has(candidate.status)&&candidate.lease===void 0);if(!run)continue;return{chatSessionId,agentId,runId:run.id,status:run.status,...binding.remotePersona?{remotePersona:{...binding.remotePersona}}:{}}}return void 0}__name(findSessionAgentBinding,"findSessionAgentBinding");function canReuseNativeSession(binding,runtimeId,program){return(binding.runtimeId===void 0||binding.runtimeId===runtimeId)&&(binding.program===void 0||binding.program===program)}__name(canReuseNativeSession,"canReuseNativeSession");init_esbuild_shims();var MAX_EXTERNAL_RECORD_KEY_LENGTH=256;var MAX_EXTERNAL_RECORD_TEXT_LENGTH=65536;var MAX_EXTERNAL_RECORD_DISPLAY_TEXT_LENGTH=MAX_AGENT_MESSAGE_DISPLAY_TEXT_CHARS;var MAX_EXTERNAL_RECORD_STEPS=MAX_AGENT_MESSAGE_STEPS;var MAX_EXTERNAL_RECORD_MENTION_IDS=32;var MAX_EXTERNAL_RECORD_ID_LENGTH=256;var MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH=1024;var STEP_STATUSES=new Set(["running","completed","failed"]);var TERMINAL_STATUSES=new Set(["completed","failed","cancelled","offline"]);function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObject,"isObject");function isBoundedString(value,maxLength){return typeof value==="string"&&value.length<=maxLength}__name(isBoundedString,"isBoundedString");function isIdList(value){return Array.isArray(value)&&value.length<=MAX_EXTERNAL_RECORD_MENTION_IDS&&value.every(id=>isBoundedString(id,MAX_EXTERNAL_RECORD_ID_LENGTH))}__name(isIdList,"isIdList");function isSteps(value){return Array.isArray(value)&&value.length<=MAX_EXTERNAL_RECORD_STEPS&&value.every(step=>isObject(step)&&isBoundedString(step["id"],MAX_EXTERNAL_RECORD_ID_LENGTH)&&typeof step["title"]==="string"&&step["title"].length<=MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH&&typeof step["status"]==="string"&&STEP_STATUSES.has(step["status"]))}__name(isSteps,"isSteps");function isAuthor(value){return isObject(value)&&typeof value["agentId"]==="string"&&value["agentId"].length>0&&typeof value["name"]==="string"&&value["name"].length>0}__name(isAuthor,"isAuthor");function parseSessionExternalRecordParams(params){const{kind,recordKey,modelText,payload}=params;if(kind!=="agent_mention"&&kind!=="agent_message"){return"Invalid external record kind"}if(typeof recordKey!=="string"||recordKey.length===0||recordKey.length>MAX_EXTERNAL_RECORD_KEY_LENGTH){return"Invalid or missing external record recordKey"}if(typeof modelText!=="string"||modelText.length===0||modelText.length>MAX_EXTERNAL_RECORD_TEXT_LENGTH){return"Invalid or missing external record modelText"}if(!isObject(payload)||typeof payload["displayText"]!=="string"||payload["displayText"].length>(kind==="agent_message"?MAX_EXTERNAL_RECORD_DISPLAY_TEXT_LENGTH:MAX_EXTERNAL_RECORD_TEXT_LENGTH)){return"Invalid or missing external record payload.displayText"}if(kind==="agent_message"){if(!isAuthor(payload["author"])){return"Invalid agent_message payload.author"}if(typeof payload["runId"]!=="string"||payload["runId"].length===0){return"Invalid agent_message payload.runId"}if(typeof payload["status"]!=="string"||!TERMINAL_STATUSES.has(payload["status"])){return"Invalid agent_message payload.status"}if(payload["steps"]!==void 0&&!isSteps(payload["steps"])){return"Invalid or oversized agent_message payload.steps"}return{kind,recordKey,modelText,payload}}if(!isIdList(payload["mentionedAgentIds"])){return"Invalid or oversized agent_mention payload.mentionedAgentIds"}if(payload["mentionedSquadIds"]!==void 0&&!isIdList(payload["mentionedSquadIds"])){return"Invalid or oversized agent_mention payload.mentionedSquadIds"}if(payload["author"]!==void 0&&!isAuthor(payload["author"])){return"Invalid agent_mention payload.author"}return{kind,recordKey,modelText,payload}}__name(parseSessionExternalRecordParams,"parseSessionExternalRecordParams");export{isValidSessionAgentsSessionId,isTerminalSessionAgentRunStatus,trimTerminalRuns,readSessionAgents,updateSessionAgents,writeSessionAgents,listSessionAgentsSessionIds,findSessionAgentBinding,canReuseNativeSession,MAX_EXTERNAL_RECORD_TEXT_LENGTH,MAX_EXTERNAL_RECORD_MENTION_IDS,MAX_EXTERNAL_RECORD_ID_LENGTH,MAX_EXTERNAL_RECORD_STEP_TITLE_LENGTH,parseSessionExternalRecordParams};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|