@qwen-code/qwen-code 0.27.2-preview.0 → 0.27.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
  3. package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
  4. package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
  5. package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
  6. package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
  7. package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
  8. package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
  9. package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
  11. package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
  12. package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
  13. package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
  14. package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
  15. package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
  16. package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
  17. package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
  18. package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
  19. package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
  20. package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
  21. package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
  22. package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
  23. package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
  24. package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
  25. package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
  26. package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
  27. package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
  28. package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
  29. package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
  30. package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
  31. package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
  32. package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
  33. package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
  34. package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
  35. package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
  36. package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
  37. package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
  38. package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
  39. package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
  40. package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
  41. package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
  42. package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
  43. package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
  44. package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
  45. package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
  46. package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
  47. package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
  48. package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
  49. package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
  50. package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
  51. package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
  52. package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
  53. package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
  54. package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
  55. package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
  56. package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
  57. package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
  58. package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
  59. package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
  60. package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
  61. package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
  62. package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
  63. package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
  64. package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
  65. package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
  66. package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
  67. package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
  68. package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
  69. package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
  70. package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
  71. package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
  72. package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
  73. package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
  74. package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
  75. package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
  76. package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
  77. package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
  78. package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
  79. package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
  80. package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
  81. package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
  82. package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
  83. package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
  84. package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
  85. package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
  86. package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
  87. package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
  88. package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
  89. package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
  90. package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
  91. package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
  92. package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
  93. package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
  94. package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
  95. package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
  96. package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
  97. package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
  98. package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
  99. package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
  100. package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
  101. package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
  102. package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
  103. package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
  104. package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
  105. package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
  106. package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
  107. package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
  108. package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
  109. package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
  110. package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
  111. package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
  112. package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
  113. package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
  114. package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
  115. package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
  116. package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
  117. package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
  118. package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
  119. package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
  120. package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
  121. package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
  122. package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
  123. package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
  124. package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
  125. package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
  126. package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
  127. package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
  128. package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
  129. package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
  130. package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
  131. package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
  132. package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
  133. package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
  134. package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
  135. package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
  136. package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
  137. package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
  138. package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
  139. package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
  140. package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
  141. package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
  142. package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
  143. package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
  144. package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
  145. package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
  146. package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
  147. package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
  148. package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
  149. package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
  150. package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
  155. package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
  156. package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
  157. package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
  158. package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
  159. package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
  160. package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
  161. package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
  162. package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
  163. package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
  164. package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
  165. package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
  166. package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
  167. package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
  168. package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
  169. package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
  170. package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
  171. package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
  172. package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
  173. package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
  174. package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
  175. package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
  176. package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
  177. package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
  178. package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
  179. package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
  180. package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
  181. package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
  182. package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
  183. package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
  184. package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
  185. package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
  186. package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
  187. package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
  188. package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
  189. package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
  190. package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
  191. package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
  192. package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
  193. package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
  194. package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
  195. package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
  196. package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
  197. package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
  198. package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
  199. package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
  200. package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
  201. package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
  202. package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
  203. package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
  204. package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
  205. package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
  206. package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
  207. package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
  208. package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
  209. package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
  210. package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
  211. package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
  212. package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
  213. package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
  214. package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
  215. package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
  216. package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
  217. package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
  218. package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
  219. package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
  220. package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
  221. package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
  222. package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
  223. package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
  224. package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
  225. package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
  226. package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
  227. package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
  228. package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
  229. package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
  230. package/cli.js +2 -2
  231. package/execution-worker.js +1 -1
  232. package/export-transcript-document.js +1 -1
  233. package/package.json +3 -3
  234. package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
  235. package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
  236. package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
  237. package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
  238. package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
  239. package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
  240. package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
  241. package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
  242. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
  243. package/web-shell/assets/channel-DtcoR96T.js +1 -0
  244. package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
  245. package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
  246. package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
  247. package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
  248. package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
  249. package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
  250. package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
  251. package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
  252. package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
  253. package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
  254. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
  255. package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
  256. package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
  257. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
  258. package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
  259. package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
  260. package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
  261. package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
  262. package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
  263. package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
  264. package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
  265. package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
  266. package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
  267. package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
  268. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
  269. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
  270. package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
  271. package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
  272. package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
  273. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
  274. package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
  275. package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
  276. package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
  277. package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
  278. package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
  279. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
  280. package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
  281. package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
  282. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
  283. package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
  284. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
  285. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
  286. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
  287. package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
  288. package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
  289. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
  290. package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
  291. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
  292. package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
  293. package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
  294. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
  295. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
  296. package/web-shell/index.html +1 -1
  297. package/web-shell/sw.js +1 -1
  298. package/web-shell/assets/channel-B31dxYCL.js +0 -1
  299. package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
  300. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
  301. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
  302. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{getNpmCliPath,getNpmNodePath}from"./chunk-ACKQAOX7.js";import"./chunk-2HLVSWM6.js";import"./chunk-HXYHIEMH.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-NKU3HS2G.js";import"./chunk-MD3ZEOBX.js";import"./chunk-J6X2K3AT.js";import"./chunk-QWGJ6NGH.js";import"./chunk-NGQDWVC6.js";import"./chunk-46VUDNCL.js";import"./chunk-UNDRWCST.js";import"./chunk-RJPELYUW.js";import"./chunk-N5S6SIRO.js";import"./chunk-VDNPMX5W.js";import"./chunk-W3GNV72O.js";import"./chunk-MUNBJIEX.js";import"./chunk-A4CHYJUQ.js";import"./chunk-6PNWMPY4.js";import"./chunk-VEVQB4CI.js";import"./chunk-KMAE5NUB.js";import"./chunk-SK2DTYBZ.js";import"./chunk-XWYUQMLN.js";import"./chunk-RKDS7A4H.js";import"./chunk-IVXR5JO2.js";import"./chunk-ROE5VZOU.js";import"./chunk-UGDAT4C4.js";import"./chunk-DECUAM3U.js";import"./chunk-LWVY42EK.js";import"./chunk-QXEU5WPV.js";import"./chunk-6EDEOERB.js";import"./chunk-XUB4JKSR.js";import"./chunk-R2EHHA2C.js";import"./chunk-SJYPUHXE.js";import"./chunk-ZIXAINJY.js";import"./chunk-HAALYXUJ.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-R7YLOR6I.js";import"./chunk-QVPT37XZ.js";import"./chunk-BPDVCOZ5.js";import"./chunk-DXUYBMFK.js";import"./chunk-MVGHVNW2.js";import"./chunk-MYPKMC5U.js";import"./chunk-B4ZATWBT.js";import"./chunk-PSKT6KWO.js";import"./chunk-KNIWP2YB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-ZQMSIRJV.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-KTNQXX2N.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-6NQMNEZN.js";import"./chunk-PNF77EBK.js";import"./chunk-QEF4EGUP.js";import"./chunk-6XLIEJP5.js";import"./chunk-RGUKFSBS.js";import"./chunk-PHIPLV2I.js";import"./chunk-G5PYYZMM.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-PWOLGVA3.js";import"./chunk-FYFNRJO5.js";import"./chunk-CL2RUJMN.js";import"./chunk-2SU7MN4F.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-LMM27XGW.js";import"./chunk-CZI6AF2S.js";import"./chunk-744VRMDB.js";import"./chunk-GJ67UOXA.js";import"./chunk-IWT6YN3M.js";import"./chunk-7UK4WJWS.js";import"./chunk-UYYKHWZ6.js";import"./chunk-CJ24OR2E.js";import"./chunk-KBDJRE76.js";import"./chunk-4ZRCV3JY.js";import"./chunk-MTPKKEGR.js";import"./chunk-INLKQF24.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import"./chunk-LMJPU2JM.js";import"./chunk-LMUYQBL7.js";import"./chunk-3YWXKSOI.js";import"./chunk-2W7KMUTJ.js";import"./chunk-33P4RB6G.js";import"./chunk-RQHIWFQL.js";import"./chunk-BSFNCIBS.js";import"./chunk-DLFX4M6C.js";import"./chunk-5AORBHSX.js";import"./chunk-66UTCJN2.js";import"./chunk-WXQQVXYN.js";import"./chunk-AGEDDL7Z.js";import"./chunk-BN4FIQ77.js";import"./chunk-2TT7GTWH.js";import"./chunk-VFB6Q74I.js";import"./chunk-NSZJIBK7.js";import"./chunk-KLC75CL4.js";import"./chunk-N3AKLLXG.js";import"./chunk-KZSUHQLD.js";import"./chunk-476F6QIM.js";import"./chunk-A6LYTPBP.js";import"./chunk-R5AA46IX.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-7XUYVD4W.js";import"./chunk-TQGZS3WN.js";import"./chunk-Z6AR5XE5.js";import"./chunk-NGXC4Y5Y.js";import"./chunk-JWTMTDHE.js";import"./chunk-EFTJIDS3.js";import"./chunk-SFDOJ2FF.js";import"./chunk-AZ4Q2ZWQ.js";import"./chunk-4ZBZL23U.js";import"./chunk-LNYY7GOJ.js";import"./chunk-E5XJBLSO.js";import"./chunk-RXKUQONJ.js";import"./chunk-2GF3E5MI.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-ZBWKMYJX.js";import"./chunk-XMANRGPK.js";import"./chunk-UFRESHR3.js";import"./chunk-KQX4H2D3.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-HJKG5VPJ.js";import"./chunk-RP57XAJ2.js";import"./chunk-7DOOXUDG.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import{require_semver}from"./chunk-73G3MZQR.js";import"./chunk-3ITJ3AIN.js";import"./chunk-N3U7SM67.js";import"./chunk-DBRQGEEI.js";import"./chunk-AAMQ5CMG.js";import"./chunk-ZQMVXHGH.js";import"./chunk-4WFJ5OPA.js";import"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import"./chunk-JOJLS3IB.js";import"./chunk-5KGH76NL.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-XKCXQPE7.js";import"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var import_semver=__toESM(require_semver(),1);import{execFile,execFileSync,spawn}from"node:child_process";import{createHash}from"node:crypto";import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as path from"node:path";import{promisify}from"node:util";var PACKAGE_NAME="@qwen-code/qwen-code";var debugLogger=createDebugLogger("MANAGED_NPM_UPDATE");var execFileAsync=promisify(execFile);function assertVersion(version){if(import_semver.default.valid(version)!==version){throw new Error(`Invalid update version: ${version}`)}}__name(assertVersion,"assertVersion");function packageDir(prefix){return path.join(prefix,"node_modules","@qwen-code","qwen-code")}__name(packageDir,"packageDir");function resolveBootstrapPath(bootstrapPath){if(!bootstrapPath){throw new Error("Unable to identify the Qwen Code npm launcher")}return fs.realpathSync(bootstrapPath)}__name(resolveBootstrapPath,"resolveBootstrapPath");function launcherId(bootstrapPath){return createHash("sha256").update(bootstrapPath).digest("hex").slice(0,16)}__name(launcherId,"launcherId");function processDoesNotExist(pidText){const pid=Number(pidText);if(!Number.isSafeInteger(pid))return false;try{process.kill(pid,0);return false}catch(error){return error.code==="ESRCH"}}__name(processDoesNotExist,"processDoesNotExist");function readDirectoryEntries(directory){try{return fs.readdirSync(directory,{withFileTypes:true})}catch{return[]}}__name(readDirectoryEntries,"readDirectoryEntries");function cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot,versionsDir){for(const entry of readDirectoryEntries(versionsDir)){const match=/^\.(.+)-([1-9]\d*)-[A-Za-z0-9]{6}$/.exec(entry.name);if(!entry.isDirectory()||entry.isSymbolicLink()||!match||import_semver.default.valid(match[1])!==match[1]||!processDoesNotExist(match[2])){continue}try{fs.rmSync(path.join(versionsDir,entry.name),{recursive:true,force:true})}catch{continue}}for(const entry of readDirectoryEntries(launcherRoot)){const match=/^active\.json\.([1-9]\d*)$/.exec(entry.name);if(!entry.isFile()||entry.isSymbolicLink()||!match||!processDoesNotExist(match[1])){continue}try{fs.rmSync(path.join(launcherRoot,entry.name),{force:true})}catch{continue}}}__name(cleanupOrphanedManagedNpmUpdateArtifacts,"cleanupOrphanedManagedNpmUpdateArtifacts");function resolveNpmGlobalConfigPath(){const configured=process.env["NPM_CONFIG_GLOBALCONFIG"];if(configured)return path.resolve(configured);const nodePath=getNpmNodePath();const npmCliPath=getNpmCliPath(nodePath,process.platform);const runNpm=__name(args=>execFileSync(nodePath,[npmCliPath,...args],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","pipe"]}).trim(),"runNpm");let output;try{output=runNpm(["config","get","globalconfig","--global"])}catch{output=runNpm(["exec","--offline","-c",`"${nodePath}" -p "process.env.npm_config_globalconfig || require('path').resolve(process.env.npm_config_global_prefix, 'etc', 'npmrc')"`]).split(/\r?\n/).at(-1)??""}if(!output||output==="null"||output==="undefined"){throw new Error("Unable to resolve the global npm configuration")}return output}__name(resolveNpmGlobalConfigPath,"resolveNpmGlobalConfigPath");function readBaseInstallation(bootstrapPath){const manifest=JSON.parse(fs.readFileSync(path.join(path.dirname(bootstrapPath),"package.json"),"utf8"));if(manifest.name!==PACKAGE_NAME||typeof manifest.version!=="string"){throw new Error("Unable to identify the base Qwen Code npm installation")}return{version:manifest.version,ctimeMs:fs.statSync(bootstrapPath).ctimeMs}}__name(readBaseInstallation,"readBaseInstallation");async function validateInstallation(prefix,version){const root=packageDir(prefix);const manifest=JSON.parse(await fsPromises.readFile(path.join(root,"package.json"),"utf8"));if(manifest.name!==PACKAGE_NAME||manifest.version!==version){throw new Error(`Installed package did not match ${PACKAGE_NAME}@${version}`)}await fsPromises.access(path.join(root,"cli.js"))}__name(validateInstallation,"validateInstallation");async function smokeTest(prefix){const env={...process.env};delete env["CLI_VERSION"];delete env["QWEN_CODE_RELAUNCH_ARGS"];await execFileAsync(getNpmNodePath(),[path.join(packageDir(prefix),"cli-entry.js"),"--help"],{encoding:"utf8",env,timeout:1e4})}__name(smokeTest,"smokeTest");async function restoreVendoredRipgrepExecBits(prefix){const ripgrepDir=path.join(packageDir(prefix),"vendor","ripgrep");let names;try{names=await fsPromises.readdir(ripgrepDir)}catch{return}for(const name of names){try{await fsPromises.chmod(path.join(ripgrepDir,name,"rg"),493)}catch{}}}__name(restoreVendoredRipgrepExecBits,"restoreVendoredRipgrepExecBits");async function readActiveVersion(activeFile,expected){try{const active=JSON.parse(await fsPromises.readFile(activeFile,"utf8"));return typeof active.version==="string"&&import_semver.default.valid(active.version)!==null&&active.bootstrap===expected.bootstrap&&active.baseVersion===expected.baseVersion&&active.bootstrapCtimeMs===expected.bootstrapCtimeMs?active.version:null}catch{return null}}__name(readActiveVersion,"readActiveVersion");function prepareManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm")){assertVersion(version);const resolvedBootstrapPath=resolveBootstrapPath(bootstrapPath);const base=readBaseInstallation(resolvedBootstrapPath);const npmGlobalConfigPath=resolveNpmGlobalConfigPath();const launcherRoot=path.join(updateRoot,launcherId(resolvedBootstrapPath));const versionsDir=path.join(launcherRoot,"versions");fs.mkdirSync(versionsDir,{recursive:true});cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot,versionsDir);const stagingDir=fs.mkdtempSync(path.join(versionsDir,`.${version}-${process.pid}-`));return{stagingDir,versionDir:path.join(versionsDir,version),launcherRoot,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs,installArgs:["install","--globalconfig",npmGlobalConfigPath,"--prefix",stagingDir,"--global=false","--no-save","--package-lock=false","--no-audit","--no-fund",`${PACKAGE_NAME}@${version}`]}}__name(prepareManagedNpmUpdate,"prepareManagedNpmUpdate");async function installManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm"),spawnFn=spawn){const update=await stageManagedNpmUpdate(version,bootstrapPath,updateRoot,spawnFn);try{await activateManagedNpmUpdate(update,version,bootstrapPath)}catch(error){await cleanupManagedNpmUpdate(update);throw error}}__name(installManagedNpmUpdate,"installManagedNpmUpdate");async function stageManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm"),spawnFn=spawn){const update=prepareManagedNpmUpdate(version,bootstrapPath,updateRoot);const env={...process.env};for(const key of["NPM_CONFIG_USERCONFIG","npm_config_userconfig"]){const configured=env[key];if(configured)env[key]=path.resolve(configured)}try{await new Promise((resolve2,reject)=>{const child=spawnFn(getNpmNodePath(),[getNpmCliPath(getNpmNodePath(),process.platform),...update.installArgs],{cwd:update.stagingDir,env,stdio:["ignore","ignore","inherit"],timeout:10*6e4,windowsHide:true});child.once("error",reject);child.once("close",code=>{if(code===0)resolve2();else reject(new Error(`npm install exited with code ${code}`))})});await validateInstallation(update.stagingDir,version);return update}catch(error){await cleanupManagedNpmUpdate(update);throw error}}__name(stageManagedNpmUpdate,"stageManagedNpmUpdate");async function activateManagedNpmUpdate(update,version,bootstrapPath=process.env["QWEN_CODE_CLI"]){assertVersion(version);const resolvedBootstrapPath=resolveBootstrapPath(bootstrapPath);if(path.join(path.dirname(update.launcherRoot),launcherId(resolvedBootstrapPath))!==update.launcherRoot){throw new Error("The npm update does not match the active launcher")}await validateInstallation(update.stagingDir,version);await smokeTest(update.stagingDir);await restoreVendoredRipgrepExecBits(update.stagingDir);const activeFile=path.join(update.launcherRoot,"active.json");const release=await import_proper_lockfile.default.lock(activeFile,{realpath:false,stale:3e4,retries:{retries:50,minTimeout:20,maxTimeout:100},onCompromised:__name(err=>{debugLogger.warn("managed npm update lock compromised:",err)},"onCompromised")});try{const base=readBaseInstallation(resolvedBootstrapPath);if(base.version!==update.baseVersion||base.ctimeMs!==update.bootstrapCtimeMs){throw new Error("The base Qwen Code npm installation changed during update")}const activeVersion=await readActiveVersion(activeFile,{bootstrap:resolvedBootstrapPath,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs});if(activeVersion&&import_semver.default.gt(activeVersion,version)){try{const activeDir=path.join(update.launcherRoot,"versions",activeVersion);await validateInstallation(activeDir,activeVersion);await restoreVendoredRipgrepExecBits(activeDir);await cleanupManagedNpmUpdate(update);return}catch{}}try{await fsPromises.rename(update.stagingDir,update.versionDir)}catch(error){if(!fs.existsSync(update.versionDir))throw error;await validateInstallation(update.versionDir,version);await restoreVendoredRipgrepExecBits(update.versionDir);await cleanupManagedNpmUpdate(update)}const temporaryActivePath=`${activeFile}.${process.pid}`;try{await fsPromises.writeFile(temporaryActivePath,JSON.stringify({version,bootstrap:resolvedBootstrapPath,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs}),{mode:384});await fsPromises.rename(temporaryActivePath,activeFile)}finally{await fsPromises.rm(temporaryActivePath,{force:true})}}finally{try{await release()}catch(error){debugLogger.warn("Failed to release managed npm update lock:",error)}}}__name(activateManagedNpmUpdate,"activateManagedNpmUpdate");async function cleanupManagedNpmUpdate(update){await fsPromises.rm(update.stagingDir,{recursive:true,force:true}).catch(()=>{})}__name(cleanupManagedNpmUpdate,"cleanupManagedNpmUpdate");export{activateManagedNpmUpdate,cleanupManagedNpmUpdate,installManagedNpmUpdate,prepareManagedNpmUpdate,stageManagedNpmUpdate};
3
+ import{getNpmCliPath,getNpmNodePath}from"./chunk-ACKQAOX7.js";import"./chunk-2HLVSWM6.js";import"./chunk-CXPRHT3E.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-NKU3HS2G.js";import"./chunk-MD3ZEOBX.js";import"./chunk-J6X2K3AT.js";import"./chunk-QWGJ6NGH.js";import"./chunk-NGQDWVC6.js";import"./chunk-46VUDNCL.js";import"./chunk-UNDRWCST.js";import"./chunk-6KU7LHBT.js";import"./chunk-IMTHBYJP.js";import"./chunk-FZQJOSHD.js";import"./chunk-W3GNV72O.js";import"./chunk-MUNBJIEX.js";import"./chunk-A4CHYJUQ.js";import"./chunk-6PNWMPY4.js";import"./chunk-NDTPBVER.js";import"./chunk-KMAE5NUB.js";import"./chunk-URMRX2MG.js";import"./chunk-XWYUQMLN.js";import"./chunk-RKDS7A4H.js";import"./chunk-WFJHBU7B.js";import"./chunk-ROE5VZOU.js";import"./chunk-UGDAT4C4.js";import"./chunk-DECUAM3U.js";import"./chunk-LWVY42EK.js";import"./chunk-QXEU5WPV.js";import"./chunk-6EDEOERB.js";import"./chunk-3NR3JBMA.js";import"./chunk-R2EHHA2C.js";import"./chunk-SJYPUHXE.js";import"./chunk-ZIXAINJY.js";import"./chunk-HAALYXUJ.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-R7YLOR6I.js";import"./chunk-QVPT37XZ.js";import"./chunk-BPDVCOZ5.js";import"./chunk-DXUYBMFK.js";import"./chunk-MVGHVNW2.js";import"./chunk-MYPKMC5U.js";import"./chunk-B4ZATWBT.js";import"./chunk-PSKT6KWO.js";import"./chunk-KNIWP2YB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-ZQMSIRJV.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-KTNQXX2N.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-6NQMNEZN.js";import"./chunk-PNF77EBK.js";import"./chunk-QEF4EGUP.js";import"./chunk-6XLIEJP5.js";import"./chunk-RGUKFSBS.js";import"./chunk-PHIPLV2I.js";import"./chunk-G5PYYZMM.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-PWOLGVA3.js";import"./chunk-FYFNRJO5.js";import"./chunk-CL2RUJMN.js";import"./chunk-2SU7MN4F.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-LMM27XGW.js";import"./chunk-CZI6AF2S.js";import"./chunk-744VRMDB.js";import"./chunk-GJ67UOXA.js";import"./chunk-IWT6YN3M.js";import"./chunk-7UK4WJWS.js";import"./chunk-UYYKHWZ6.js";import"./chunk-CJ24OR2E.js";import"./chunk-KBDJRE76.js";import"./chunk-4ZRCV3JY.js";import"./chunk-MTPKKEGR.js";import"./chunk-INLKQF24.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import"./chunk-LMJPU2JM.js";import"./chunk-LMUYQBL7.js";import"./chunk-3YWXKSOI.js";import"./chunk-2W7KMUTJ.js";import"./chunk-33P4RB6G.js";import"./chunk-RQHIWFQL.js";import"./chunk-BSFNCIBS.js";import"./chunk-DLFX4M6C.js";import"./chunk-5AORBHSX.js";import"./chunk-66UTCJN2.js";import"./chunk-WXQQVXYN.js";import"./chunk-AGEDDL7Z.js";import"./chunk-BN4FIQ77.js";import"./chunk-2TT7GTWH.js";import"./chunk-VFB6Q74I.js";import"./chunk-NSZJIBK7.js";import"./chunk-KLC75CL4.js";import"./chunk-N3AKLLXG.js";import"./chunk-KZSUHQLD.js";import"./chunk-476F6QIM.js";import"./chunk-A6LYTPBP.js";import"./chunk-R5AA46IX.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-7XUYVD4W.js";import"./chunk-TQGZS3WN.js";import"./chunk-Z6AR5XE5.js";import"./chunk-NGXC4Y5Y.js";import"./chunk-JWTMTDHE.js";import"./chunk-EFTJIDS3.js";import"./chunk-DN4QKOFL.js";import"./chunk-AZ4Q2ZWQ.js";import"./chunk-4ZBZL23U.js";import"./chunk-LNYY7GOJ.js";import"./chunk-E5XJBLSO.js";import"./chunk-RXKUQONJ.js";import"./chunk-2GF3E5MI.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-ZBWKMYJX.js";import"./chunk-XMANRGPK.js";import"./chunk-UFRESHR3.js";import"./chunk-KQX4H2D3.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-HJKG5VPJ.js";import"./chunk-RP57XAJ2.js";import"./chunk-7DOOXUDG.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import{require_semver}from"./chunk-73G3MZQR.js";import"./chunk-3ITJ3AIN.js";import"./chunk-N3U7SM67.js";import"./chunk-DBRQGEEI.js";import"./chunk-AAMQ5CMG.js";import"./chunk-ZQMVXHGH.js";import"./chunk-4WFJ5OPA.js";import"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import"./chunk-JOJLS3IB.js";import"./chunk-5KGH76NL.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-XKCXQPE7.js";import"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import{Storage}from"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var import_semver=__toESM(require_semver(),1);import{execFile,execFileSync,spawn}from"node:child_process";import{createHash}from"node:crypto";import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as path from"node:path";import{promisify}from"node:util";var PACKAGE_NAME="@qwen-code/qwen-code";var debugLogger=createDebugLogger("MANAGED_NPM_UPDATE");var execFileAsync=promisify(execFile);function assertVersion(version){if(import_semver.default.valid(version)!==version){throw new Error(`Invalid update version: ${version}`)}}__name(assertVersion,"assertVersion");function packageDir(prefix){return path.join(prefix,"node_modules","@qwen-code","qwen-code")}__name(packageDir,"packageDir");function resolveBootstrapPath(bootstrapPath){if(!bootstrapPath){throw new Error("Unable to identify the Qwen Code npm launcher")}return fs.realpathSync(bootstrapPath)}__name(resolveBootstrapPath,"resolveBootstrapPath");function launcherId(bootstrapPath){return createHash("sha256").update(bootstrapPath).digest("hex").slice(0,16)}__name(launcherId,"launcherId");function processDoesNotExist(pidText){const pid=Number(pidText);if(!Number.isSafeInteger(pid))return false;try{process.kill(pid,0);return false}catch(error){return error.code==="ESRCH"}}__name(processDoesNotExist,"processDoesNotExist");function readDirectoryEntries(directory){try{return fs.readdirSync(directory,{withFileTypes:true})}catch{return[]}}__name(readDirectoryEntries,"readDirectoryEntries");function cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot,versionsDir){for(const entry of readDirectoryEntries(versionsDir)){const match=/^\.(.+)-([1-9]\d*)-[A-Za-z0-9]{6}$/.exec(entry.name);if(!entry.isDirectory()||entry.isSymbolicLink()||!match||import_semver.default.valid(match[1])!==match[1]||!processDoesNotExist(match[2])){continue}try{fs.rmSync(path.join(versionsDir,entry.name),{recursive:true,force:true})}catch{continue}}for(const entry of readDirectoryEntries(launcherRoot)){const match=/^active\.json\.([1-9]\d*)$/.exec(entry.name);if(!entry.isFile()||entry.isSymbolicLink()||!match||!processDoesNotExist(match[1])){continue}try{fs.rmSync(path.join(launcherRoot,entry.name),{force:true})}catch{continue}}}__name(cleanupOrphanedManagedNpmUpdateArtifacts,"cleanupOrphanedManagedNpmUpdateArtifacts");function resolveNpmGlobalConfigPath(){const configured=process.env["NPM_CONFIG_GLOBALCONFIG"];if(configured)return path.resolve(configured);const nodePath=getNpmNodePath();const npmCliPath=getNpmCliPath(nodePath,process.platform);const runNpm=__name(args=>execFileSync(nodePath,[npmCliPath,...args],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","pipe"]}).trim(),"runNpm");let output;try{output=runNpm(["config","get","globalconfig","--global"])}catch{output=runNpm(["exec","--offline","-c",`"${nodePath}" -p "process.env.npm_config_globalconfig || require('path').resolve(process.env.npm_config_global_prefix, 'etc', 'npmrc')"`]).split(/\r?\n/).at(-1)??""}if(!output||output==="null"||output==="undefined"){throw new Error("Unable to resolve the global npm configuration")}return output}__name(resolveNpmGlobalConfigPath,"resolveNpmGlobalConfigPath");function readBaseInstallation(bootstrapPath){const manifest=JSON.parse(fs.readFileSync(path.join(path.dirname(bootstrapPath),"package.json"),"utf8"));if(manifest.name!==PACKAGE_NAME||typeof manifest.version!=="string"){throw new Error("Unable to identify the base Qwen Code npm installation")}return{version:manifest.version,ctimeMs:fs.statSync(bootstrapPath).ctimeMs}}__name(readBaseInstallation,"readBaseInstallation");async function validateInstallation(prefix,version){const root=packageDir(prefix);const manifest=JSON.parse(await fsPromises.readFile(path.join(root,"package.json"),"utf8"));if(manifest.name!==PACKAGE_NAME||manifest.version!==version){throw new Error(`Installed package did not match ${PACKAGE_NAME}@${version}`)}await fsPromises.access(path.join(root,"cli.js"))}__name(validateInstallation,"validateInstallation");async function smokeTest(prefix){const env={...process.env};delete env["CLI_VERSION"];delete env["QWEN_CODE_RELAUNCH_ARGS"];await execFileAsync(getNpmNodePath(),[path.join(packageDir(prefix),"cli-entry.js"),"--help"],{encoding:"utf8",env,timeout:1e4})}__name(smokeTest,"smokeTest");async function restoreVendoredRipgrepExecBits(prefix){const ripgrepDir=path.join(packageDir(prefix),"vendor","ripgrep");let names;try{names=await fsPromises.readdir(ripgrepDir)}catch{return}for(const name of names){try{await fsPromises.chmod(path.join(ripgrepDir,name,"rg"),493)}catch{}}}__name(restoreVendoredRipgrepExecBits,"restoreVendoredRipgrepExecBits");async function readActiveVersion(activeFile,expected){try{const active=JSON.parse(await fsPromises.readFile(activeFile,"utf8"));return typeof active.version==="string"&&import_semver.default.valid(active.version)!==null&&active.bootstrap===expected.bootstrap&&active.baseVersion===expected.baseVersion&&active.bootstrapCtimeMs===expected.bootstrapCtimeMs?active.version:null}catch{return null}}__name(readActiveVersion,"readActiveVersion");function prepareManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm")){assertVersion(version);const resolvedBootstrapPath=resolveBootstrapPath(bootstrapPath);const base=readBaseInstallation(resolvedBootstrapPath);const npmGlobalConfigPath=resolveNpmGlobalConfigPath();const launcherRoot=path.join(updateRoot,launcherId(resolvedBootstrapPath));const versionsDir=path.join(launcherRoot,"versions");fs.mkdirSync(versionsDir,{recursive:true});cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot,versionsDir);const stagingDir=fs.mkdtempSync(path.join(versionsDir,`.${version}-${process.pid}-`));return{stagingDir,versionDir:path.join(versionsDir,version),launcherRoot,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs,installArgs:["install","--globalconfig",npmGlobalConfigPath,"--prefix",stagingDir,"--global=false","--no-save","--package-lock=false","--no-audit","--no-fund",`${PACKAGE_NAME}@${version}`]}}__name(prepareManagedNpmUpdate,"prepareManagedNpmUpdate");async function installManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm"),spawnFn=spawn){const update=await stageManagedNpmUpdate(version,bootstrapPath,updateRoot,spawnFn);try{await activateManagedNpmUpdate(update,version,bootstrapPath)}catch(error){await cleanupManagedNpmUpdate(update);throw error}}__name(installManagedNpmUpdate,"installManagedNpmUpdate");async function stageManagedNpmUpdate(version,bootstrapPath=process.env["QWEN_CODE_CLI"],updateRoot=process.env["QWEN_CODE_MANAGED_NPM_ROOT"]??path.join(Storage.getGlobalQwenDir(),"updates","npm"),spawnFn=spawn){const update=prepareManagedNpmUpdate(version,bootstrapPath,updateRoot);const env={...process.env};for(const key of["NPM_CONFIG_USERCONFIG","npm_config_userconfig"]){const configured=env[key];if(configured)env[key]=path.resolve(configured)}try{await new Promise((resolve2,reject)=>{const child=spawnFn(getNpmNodePath(),[getNpmCliPath(getNpmNodePath(),process.platform),...update.installArgs],{cwd:update.stagingDir,env,stdio:["ignore","ignore","inherit"],timeout:10*6e4,windowsHide:true});child.once("error",reject);child.once("close",code=>{if(code===0)resolve2();else reject(new Error(`npm install exited with code ${code}`))})});await validateInstallation(update.stagingDir,version);return update}catch(error){await cleanupManagedNpmUpdate(update);throw error}}__name(stageManagedNpmUpdate,"stageManagedNpmUpdate");async function activateManagedNpmUpdate(update,version,bootstrapPath=process.env["QWEN_CODE_CLI"]){assertVersion(version);const resolvedBootstrapPath=resolveBootstrapPath(bootstrapPath);if(path.join(path.dirname(update.launcherRoot),launcherId(resolvedBootstrapPath))!==update.launcherRoot){throw new Error("The npm update does not match the active launcher")}await validateInstallation(update.stagingDir,version);await smokeTest(update.stagingDir);await restoreVendoredRipgrepExecBits(update.stagingDir);const activeFile=path.join(update.launcherRoot,"active.json");const release=await import_proper_lockfile.default.lock(activeFile,{realpath:false,stale:3e4,retries:{retries:50,minTimeout:20,maxTimeout:100},onCompromised:__name(err=>{debugLogger.warn("managed npm update lock compromised:",err)},"onCompromised")});try{const base=readBaseInstallation(resolvedBootstrapPath);if(base.version!==update.baseVersion||base.ctimeMs!==update.bootstrapCtimeMs){throw new Error("The base Qwen Code npm installation changed during update")}const activeVersion=await readActiveVersion(activeFile,{bootstrap:resolvedBootstrapPath,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs});if(activeVersion&&import_semver.default.gt(activeVersion,version)){try{const activeDir=path.join(update.launcherRoot,"versions",activeVersion);await validateInstallation(activeDir,activeVersion);await restoreVendoredRipgrepExecBits(activeDir);await cleanupManagedNpmUpdate(update);return}catch{}}try{await fsPromises.rename(update.stagingDir,update.versionDir)}catch(error){if(!fs.existsSync(update.versionDir))throw error;await validateInstallation(update.versionDir,version);await restoreVendoredRipgrepExecBits(update.versionDir);await cleanupManagedNpmUpdate(update)}const temporaryActivePath=`${activeFile}.${process.pid}`;try{await fsPromises.writeFile(temporaryActivePath,JSON.stringify({version,bootstrap:resolvedBootstrapPath,baseVersion:base.version,bootstrapCtimeMs:base.ctimeMs}),{mode:384});await fsPromises.rename(temporaryActivePath,activeFile)}finally{await fsPromises.rm(temporaryActivePath,{force:true})}}finally{try{await release()}catch(error){debugLogger.warn("Failed to release managed npm update lock:",error)}}}__name(activateManagedNpmUpdate,"activateManagedNpmUpdate");async function cleanupManagedNpmUpdate(update){await fsPromises.rm(update.stagingDir,{recursive:true,force:true}).catch(()=>{})}__name(cleanupManagedNpmUpdate,"cleanupManagedNpmUpdate");export{activateManagedNpmUpdate,cleanupManagedNpmUpdate,installManagedNpmUpdate,prepareManagedNpmUpdate,stageManagedNpmUpdate};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Code
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{CSI_FILE_FINALIZATION_FORMAT,CSI_FILE_HISTORY_PATH,HOSTED_GLOB_TOO_COMPLEX,LocalShellResultCapture,MANAGED_CSI_ACK_LIMIT_BYTES,MANAGED_CSI_ACK_PATH,MANAGED_CSI_ATTEST_PATH,MANAGED_CSI_DRAIN_PATH,MANAGED_CSI_FILE_PREFIX,MANAGED_CSI_FILE_PROTOCOL,MANAGED_CSI_FILE_ROUTES,MANAGED_CSI_PROTOCOL,MANAGED_HOOK_MAX_REQUEST_BYTES,MANAGED_HOOK_MAX_RUNNING,MANAGED_HOOK_ROUTE,MANAGED_MCP_MAX_CONNECTIONS,MANAGED_MCP_ROUTE,MANAGED_MCP_TOOL,MANAGED_PACKAGE_MAX_ARCHIVE_BYTES,MANAGED_RUNTIME_PROVIDER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES,MAX_PROVIDER_MEDIA_RESULT_BYTES,MEASURED_WORKSPACE_CAPABILITY_DIGEST,ManagedAutomationGateTool,ManagedCsiAckRequestError,ManagedCsiDrainRequestError,ManagedRuntimeProviderProtocolError,WORKSPACE_ACTIVATION_ROUTE,WORKSPACE_CONTEXT_CONFIG_REF,WorkspaceActivations,checkHostedGlobPattern,compileManagedExtensionPackage,createManagedCsiFileReady,fitManagedRuntimeProviderResult,isCsiFilesCapability,isWorkspaceToolCapability,linuxDeviceNumber,managedRuntimeProviderLimit,matchesCsiFilesProfile,minimatch,parseManagedCsiAckJson,parseManagedCsiAckRequest,parseManagedCsiAckResponse,parseManagedCsiAcknowledgement,parseManagedCsiBoot,parseManagedCsiCaptureIdentity,parseManagedCsiDrainRequest,parseManagedCsiFileBoot,parseManagedCsiFileJson,parseManagedMcpRecipe,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult,parseManagedSkillContent,readCsiFileHistoryEnvelope,readCsiFileHistoryObservation,readCsiNativeRequest,readCsiPreparationEvidence,readCurrentCsiNative,readManagedCsiFileContext,readManagedCsiFileDrain,resolveManagedShellPublisherMode,validateManagedCsiAttestationRequest,validateManagedCsiAttestationResponse,validateManagedCsiFileAttestationRequest,validateManagedCsiFileAttestationResponse,validateManagedCsiPodIdentity,wrapManagedCsiFileContext}from"./chunk-HHDQ5JAA.js";import"./chunk-4RXAH36C.js";import{MANAGED_CONTEXT_ROUTES,ManagedContextInstallations,checkManagedContextAttestation,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,historyPath,parseToolPublicationBinding}from"./chunk-NRJOUWP4.js";import{computeManagedContextDigest,normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import"./chunk-6S5XOXJ2.js";import{MANAGED_SHELL_PUBLISHER_ROUTE,ManagedShellPublisherRegistry,publisherFields}from"./chunk-6PHTF2XF.js";import{CLOSE_SWEEP_TIMEOUT_MS,GROUP_EXIT_EVIDENCE_TIMEOUT_MS,ManagedRuntimeLedger,managedRuntimeLedgerFromEnvironment,signalProcessGroup}from"./chunk-RAERKMZM.js";import{MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES,OWNED_MANAGED_RUNTIME_ROUTES,authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation,ownedManagedRuntimeRouteGate,registerManagedRuntimeAttestationRoute}from"./chunk-AHRFY5S3.js";import"./chunk-3Y4UVTLL.js";import"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-R337IZM4.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import{scrubAndReportInheritedLoaderEnv}from"./chunk-AJTR5LAF.js";import"./chunk-S7IKHQ6I.js";import{WebFetchTool}from"./chunk-DZWNLJXE.js";import{TodoWriteTool}from"./chunk-LCO75GQC.js";import{GlobTool}from"./chunk-IJD47F7Z.js";import{WriteFileTool}from"./chunk-EGMV4S6D.js";import{EditTool}from"./chunk-5DPXLL3H.js";import"./chunk-B7CYUTAO.js";import"./chunk-4RGPHRL7.js";import"./chunk-A4CHYJUQ.js";import"./chunk-6PNWMPY4.js";import{Config,Ct,DEFAULT_INHERITED_ENV_VARS,EventSource,FileHistoryService,HookCommandCgroup,HookCommandIsolationUnavailableError,HookRegistry,HookRunner,LocalManagedSessionResourceStore,MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,MAX_ARCHIVE_PATH_BYTES,ManagedSessionConflictError,ManagedToolProtocolError,Qn,SessionWriterLease,ShellTool,So,StdioClientTransport,deriveConfig,deserializeSnapshots,detectLineEnding,encodeTextFileContentAsync,firePostToolUseFailureHook,firePostToolUseHook,firePreToolUseHook,generateToolUseId,getDiffStat,interpolateUrl,isModifiableDeclarativeTool,isOperationGrantSuccessor,isSinglePathSegment,managedSessionResourceRoot,managedToolDigest,parseManagedExtensionApplyCommand,parseManagedExtensionPin,parseManagedExtensionPins,parseManagedToolContentModification,parseManagedToolMediaContext,parseOperationGrant,resolveCommandHookTimeoutMs,serializeManagedToolConfirmation,serializeSnapshot}from"./chunk-XUB4JKSR.js";import"./chunk-R2EHHA2C.js";import{ReadBuffer,serializeMessage}from"./chunk-SJYPUHXE.js";import"./chunk-ZIXAINJY.js";import{MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,MANAGED_TOOL_RESULT_ROUTES,ManagedSessionRecordError,assertManagedSessionDigest,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId,isToolResultPageAt,parseToolResultManifestBytes,parseToolResultPageBytes,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest}from"./chunk-HAALYXUJ.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import"./chunk-R7YLOR6I.js";import"./chunk-QVPT37XZ.js";import"./chunk-BPDVCOZ5.js";import"./chunk-DXUYBMFK.js";import"./chunk-MVGHVNW2.js";import"./chunk-MYPKMC5U.js";import"./chunk-B4ZATWBT.js";import{openNoFollow}from"./chunk-PSKT6KWO.js";import"./chunk-KNIWP2YB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-ZQMSIRJV.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-KTNQXX2N.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-6NQMNEZN.js";import"./chunk-PNF77EBK.js";import"./chunk-QEF4EGUP.js";import{Client,StreamableHTTPClientTransport,UnauthorizedError,auth,createFetchWithInit,extractWWWAuthenticateParams,normalizeHeaders}from"./chunk-6XLIEJP5.js";import{CallToolResultSchema,GetPromptResultSchema,JSONRPCMessageSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"./chunk-RGUKFSBS.js";import"./chunk-PHIPLV2I.js";import"./chunk-G5PYYZMM.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-PWOLGVA3.js";import"./chunk-FYFNRJO5.js";import"./chunk-CL2RUJMN.js";import"./chunk-2SU7MN4F.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-LMM27XGW.js";import"./chunk-CZI6AF2S.js";import"./chunk-744VRMDB.js";import"./chunk-GJ67UOXA.js";import"./chunk-IWT6YN3M.js";import"./chunk-7UK4WJWS.js";import"./chunk-UYYKHWZ6.js";import"./chunk-CJ24OR2E.js";import"./chunk-KBDJRE76.js";import"./chunk-4ZRCV3JY.js";import"./chunk-MTPKKEGR.js";import{getShellContextEnvVars}from"./chunk-INLKQF24.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import{sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import"./chunk-3YWXKSOI.js";import"./chunk-LG4NL2M7.js";import"./chunk-5AORBHSX.js";import"./chunk-66UTCJN2.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-WXQQVXYN.js";import"./chunk-AGEDDL7Z.js";import"./chunk-BN4FIQ77.js";import"./chunk-2TT7GTWH.js";import"./chunk-NSZJIBK7.js";import"./chunk-KLC75CL4.js";import"./chunk-N3AKLLXG.js";import"./chunk-KZSUHQLD.js";import{createAbortController}from"./chunk-476F6QIM.js";import"./chunk-A6LYTPBP.js";import{ReadFileTool}from"./chunk-R5AA46IX.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-7XUYVD4W.js";import{FileReadOpenError,decodeBufferWithEncodingInfoAsync,digestFileReadSource,readFileHandleBytes,readTextContentRangeFromHandle}from"./chunk-TQGZS3WN.js";import"./chunk-Z6AR5XE5.js";import"./chunk-NGXC4Y5Y.js";import"./chunk-JWTMTDHE.js";import{runWithInvocationContext}from"./chunk-EFTJIDS3.js";import"./chunk-SFDOJ2FF.js";import"./chunk-AZ4Q2ZWQ.js";import"./chunk-4ZBZL23U.js";import"./chunk-LNYY7GOJ.js";import"./chunk-E5XJBLSO.js";import"./chunk-RXKUQONJ.js";import{atomicWriteJSON}from"./chunk-2GF3E5MI.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-ZBWKMYJX.js";import"./chunk-XMANRGPK.js";import"./chunk-UFRESHR3.js";import"./chunk-KQX4H2D3.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-HJKG5VPJ.js";import"./chunk-RP57XAJ2.js";import"./chunk-7DOOXUDG.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import"./chunk-3ITJ3AIN.js";import"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-AAMQ5CMG.js";import"./chunk-ZQMVXHGH.js";import{HookEventName,HooksConfigSource,getHookKey}from"./chunk-4WFJ5OPA.js";import{getShellConfiguration}from"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import{isPathWithinRoot}from"./chunk-JOJLS3IB.js";import{ToolConfirmationOutcome}from"./chunk-5KGH76NL.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import"./chunk-XKCXQPE7.js";import"./chunk-3KUHQGOS.js";import{createDebugLogger,registerSessionProjectDir,sessionIdContext,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import{SKILL_PROVIDER_CONFIG_DIRS,Storage}from"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_express3=__toESM(require_express(),1);import{createServer as createServer2}from"node:http";import{createReadStream as createReadStream4}from"node:fs";import{mkdtemp as mkdtemp3}from"node:fs/promises";import path16 from"node:path";init_esbuild_shims();import{createHash as createHash11}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";init_esbuild_shims();import{constants,promises as fs}from"node:fs";import path from"node:path";async function executable(command,cwd,environment){const candidates=command.includes("/")?[path.resolve(cwd,command)]:(environment["PATH"]??"/usr/bin:/bin").split(path.delimiter).map(directory=>path.resolve(cwd,directory,command));for(const candidate of candidates){try{if(!(await fs.stat(candidate)).isFile())continue;await fs.access(candidate,constants.X_OK);return candidate}catch{}}throw new Error(`Extension executable is unavailable: ${command}`)}__name(executable,"executable");async function preflightManagedExtensionPackage(contributions,root,cwd,environment){const env={...environment,QWEN_EXTENSION_ROOT:root,CLAUDE_PLUGIN_ROOT:root,extensionPath:root};const expand=__name((value,executionEnvironment=env)=>value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/gu,(original,braced,plain)=>executionEnvironment[braced??plain]??original),"expand");let dynamicCommands=0;const check=__name(async(command,args,executionEnvironment=env)=>{const resolved=await executable(expand(command,executionEnvironment),cwd,executionEnvironment);const handle=await fs.open(resolved,"r");let head;try{const buffer=Buffer.alloc(512);const read=await handle.read(buffer,0,512,0);head=buffer.subarray(0,read.bytesRead).toString()}finally{await handle.close()}if(head.startsWith("#!")){const shebang=head.split("\n")[0].slice(2).trim().split(/\s+/u);await executable(shebang[0],cwd,executionEnvironment);if(path.basename(shebang[0])==="env"&&shebang[1]&&!shebang[1].startsWith("-"))await executable(shebang[1],cwd,executionEnvironment)}if(path.basename(resolved)==="env"&&args.length){if(args[0].startsWith("-")||args[0].includes("=")){dynamicCommands++;return}await check(args[0],args.slice(1),executionEnvironment);return}if(args.includes("-e")||args.includes("--eval")||args.includes("-c")){dynamicCommands++;return}for(const argument of args.filter(value=>!value.startsWith("-")&&/\.(?:[cm]?js|py|rb|sh)$/u.test(value))){const script=path.resolve(cwd,expand(argument,executionEnvironment));if(!(await fs.stat(script)).isFile())throw new Error("Extension script is unavailable.");await fs.access(script,constants.R_OK)}},"check");const shell=__name(async(command,executionEnvironment=env)=>{if(/[|;&><`\n]|\$\(/u.test(command)){dynamicCommands++;return}const tokens=[...command.matchAll(/"([^"]*)"|'([^']*)'|([^\s]+)/gu)].map(match=>match[1]??match[2]??match[3]);if(!tokens.length)return;if(tokens.some(token=>token.includes("$")&&expand(token,executionEnvironment)===token)){dynamicCommands++;return}if(/^[A-Za-z_][A-Za-z0-9_]*=/u.test(tokens[0])){dynamicCommands++;return}if([":","[","alias","bg","break","cd","continue","exit","export","false","fg","getopts","hash","jobs","pwd","read","readonly","return","set","shift","test","times","trap","true","type","ulimit","umask","unalias","unset","wait"].includes(tokens[0]))return;if(tokens[0]==="eval"){dynamicCommands++;return}if(["exec","command"].includes(tokens[0]))tokens.shift();if(tokens.length)await check(tokens[0],tokens.slice(1),executionEnvironment)},"shell");for(const value of Object.values(contributions.mcpServers)){const recipe=value;if(recipe.command)await check(recipe.command,recipe.args??[],{...env,...recipe.env})}for(const groups of Object.values(contributions.hooks)){for(const group of groups){for(const hook of group.hooks??[])if(hook.type==="command"&&hook.command)await shell(hook.command,{...env,...hook.env})}}for(const command of contributions.commands)for(const match of command.prompt.matchAll(/!\{([^}]*)\}/gu))await shell(match[1]);return{dynamicCommands}}__name(preflightManagedExtensionPackage,"preflightManagedExtensionPackage");init_esbuild_shims();function managedExtensionEnvironment(inherited,directory,extension={}){const environment={};for(const key of["PATH","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP"]){const value=inherited[key];if(value!==void 0)environment[key]=value}return{...environment,HOME:directory,USERPROFILE:directory,...extension}}__name(managedExtensionEnvironment,"managedExtensionEnvironment");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";import{promises as fs4}from"node:fs";import path4 from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{createReadStream,createWriteStream,promises as fs2}from"node:fs";import path2 from"node:path";import{Transform}from"node:stream";import{pipeline}from"node:stream/promises";var MANAGED_EXTENSION_ARCHIVE_MAX_BYTES=100*1024*1024;var DIGEST=/^[0-9a-f]{64}$/u;var ManagedExtensionCache=class{constructor(directory){this.directory=directory;if(!path2.isAbsolute(directory))throw new Error("Invalid package cache.")}static{__name(this,"ManagedExtensionCache")}async upload(digest3,source){this.assertDigest(digest3);await fs2.mkdir(this.directory,{recursive:true,mode:448});const temporary=path2.join(this.directory,`.upload-${randomUUID()}`);const hash=createHash("sha256");let bytes=0;const limit=new Transform({transform(chunk,_encoding,callback){bytes+=chunk.byteLength;if(bytes>MANAGED_EXTENSION_ARCHIVE_MAX_BYTES){callback(new Error("Package archive exceeds its size limit."));return}hash.update(chunk);callback(null,chunk)}});try{await pipeline(source,limit,createWriteStream(temporary,{flags:"wx",mode:384}));if(hash.digest("hex")!==digest3)throw new Error("Package archive digest mismatch.");await this.validateArchive(temporary);await fs2.rename(temporary,this.archivePath(digest3))}finally{await fs2.rm(temporary,{force:true})}}materialize(digest3){this.assertDigest(digest3);return this.extract(digest3)}async extract(digest3){const archive=this.archivePath(digest3);const hash=createHash("sha256");for await(const chunk of createReadStream(archive))hash.update(chunk);if(hash.digest("hex")!==digest3)throw new Error("Cached package archive digest mismatch.");await this.validateArchive(archive);const destination=path2.join(this.directory,`${digest3}-${randomUUID()}`);await fs2.mkdir(destination,{mode:448});try{await So({file:archive,cwd:destination,strict:true,noChmod:true});await fs2.writeFile(`${destination}.integrity`,await this.treeDigest(destination),{mode:384,flag:"wx"});return destination}catch(error){await fs2.rm(destination,{recursive:true,force:true});throw error}}async restoreMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!new RegExp(`^${digest3}-[0-9a-f-]{36}$`,"u").test(path2.basename(directory))||!(await fs2.lstat(this.directory)).isDirectory())throw new Error("Extension cache scope conflicts.");try{await this.verifyMaterialized(digest3,directory);return}catch{}const fresh=await this.materialize(digest3);const quarantine=path2.join(this.directory,`.quarantine-${randomUUID()}`);const moveIfPresent=__name(async(source,target)=>{try{await fs2.rename(source,target)}catch(error){if(error.code!=="ENOENT")throw error}},"moveIfPresent");try{await moveIfPresent(directory,quarantine);await moveIfPresent(`${directory}.integrity`,`${quarantine}.integrity`);await fs2.rename(fresh,directory);await fs2.rename(`${fresh}.integrity`,`${directory}.integrity`);await this.verifyMaterialized(digest3,directory);await fs2.rm(quarantine,{recursive:true,force:true});await fs2.rm(`${quarantine}.integrity`,{force:true})}finally{await fs2.rm(fresh,{recursive:true,force:true});await fs2.rm(`${fresh}.integrity`,{force:true})}}async verifyMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!path2.basename(directory).startsWith(`${digest3}-`))throw new Error("Extension cache scope conflicts.");if(!(await fs2.lstat(directory)).isDirectory())throw new Error("Extension cache root is unsafe.");const expected=await fs2.readFile(`${directory}.integrity`,"utf8");if(await this.treeDigest(directory)!==expected)throw new Error("Extension package assets drifted.")}async treeDigest(directory){const hash=createHash("sha256");const visit=__name(async relative2=>{const entries=await fs2.readdir(path2.join(directory,relative2),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name,"en"))){const child=path2.posix.join(relative2,entry.name);if(!entry.isDirectory()&&!entry.isFile())throw new Error("Extension assets contain an unsafe entry.");hash.update(JSON.stringify([child,entry.isDirectory()?"directory":"file"]));if(entry.isDirectory())await visit(child);else{const content=createHash("sha256");for await(const chunk of createReadStream(path2.join(directory,child)))content.update(chunk);hash.update(content.digest())}}},"visit");await visit("");return hash.digest("hex")}async validateArchive(file){let count=0;let bytes=0;let pathBytes=0;let invalid3=false;const seen=new Set;const source=createReadStream(file);const parser=Ct({strict:true,onReadEntry(entry){const normalized=path2.posix.normalize(entry.path).replace(/\/$/u,"");count++;bytes+=entry.size;pathBytes+=Buffer.byteLength(entry.path);if(!["File","Directory","OldFile","ContiguousFile"].includes(entry.type)||entry.path.includes("\\")||entry.path.includes("\0")||path2.posix.isAbsolute(entry.path)||/^[a-zA-Z]:/u.test(entry.path)||normalized===".."||normalized.startsWith("../")||seen.has(normalized)||count>MAX_ARCHIVE_ENTRIES||bytes>MAX_ARCHIVE_EXPANDED_BYTES||pathBytes>MAX_ARCHIVE_PATH_BYTES){invalid3=true;source.destroy(new Error("Unsafe package archive."))}seen.add(normalized)}});await pipeline(source,parser);if(invalid3)throw new Error("Unsafe package archive.")}archivePath(digest3){return path2.join(this.directory,`${digest3}.tar.gz`)}assertDigest(digest3){if(!DIGEST.test(digest3))throw new Error("Invalid package digest.")}};init_esbuild_shims();import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{constants as constants2,createReadStream as createReadStream2,createWriteStream as createWriteStream2}from"node:fs";import*as fs3 from"node:fs/promises";import*as path3 from"node:path";import{pipeline as pipeline2}from"node:stream/promises";import{Transform as Transform2,Writable}from"node:stream";var privateNames=new Set([".git",".env",".qwen-extension-settings.json",".qwen-extension-git-credentials.json",".qwen-extension-install.json",".qwen-managed-skill-origin.json"]);var UUID=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu;var CHUNK_BYTES=256*1024;var MAX_RETAINED_BYTES=512*1024*1024;function failed(code){throw new Error(code)}__name(failed,"failed");function contains(root,file){const relative2=path3.relative(root,file);return relative2!==".."&&!relative2.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative2)}__name(contains,"contains");async function boundedEntries(directory,limit,code){const entries=[];for await(const entry of await fs3.opendir(directory)){if(entries.length>=limit)failed(code);entries.push(entry)}return entries.sort((a,b)=>a.name.localeCompare(b.name))}__name(boundedEntries,"boundedEntries");function parseManagedRuntimeSkillControl(value){if(!value||typeof value!=="object"||Array.isArray(value))failed("invalid_skill_control");const op=value;if(typeof op["operationId"]!=="string"||!UUID.test(op["operationId"]))failed("invalid_skill_control");if(op["kind"]==="extension-skill-candidates"){if(Object.keys(op).sort().join(",")!=="kind,operationId")failed("invalid_skill_control")}else if(op["kind"]==="extension-skill-snapshot"){if(Object.keys(op).sort().join(",")!=="digest,kind,operationId,path"||typeof op["path"]!=="string"||!/^\.(?:qwen|agents)\/skills\/[^/\\]+$/u.test(op["path"])||op["path"].includes("\0")||op["path"].length>4096||op["path"].split("/").some(part=>part===".."||part===".")||typeof op["digest"]!=="string"||!/^[a-f0-9]{64}$/u.test(op["digest"]))failed("invalid_skill_control")}else if(op["kind"]==="extension-skill-archive"){if(Object.keys(op).sort().join(",")!=="kind,offset,operationId,preparationId"||typeof op["preparationId"]!=="string"||!UUID.test(op["preparationId"])||!Number.isSafeInteger(op["offset"])||Number(op["offset"])<0||Number(op["offset"])>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES)failed("invalid_skill_control")}else failed("invalid_skill_control");return structuredClone(op)}__name(parseManagedRuntimeSkillControl,"parseManagedRuntimeSkillControl");var ManagedRuntimeSkillSources=class{constructor(cacheDirectory,source){this.cacheDirectory=cacheDirectory;this.source=source;this.timer=setInterval(()=>{void this.sweep().catch(()=>void 0)},6e4);this.timer.unref()}static{__name(this,"ManagedRuntimeSkillSources")}snapshots=new Map;retainedBytes=0;preparing=0;pending=new Set;timer;closed=false;async close(){this.closed=true;clearInterval(this.timer);for(const snapshot of this.snapshots.values())await fs3.rm(snapshot.directory,{recursive:true,force:true});this.snapshots.clear();this.retainedBytes=0}async sweep(){for(const[id,snapshot]of this.snapshots)if(snapshot.expiresAt<=Date.now()){this.snapshots.delete(id);this.retainedBytes-=snapshot.byteLength;await fs3.rm(snapshot.directory,{recursive:true,force:true})}const known=new Set([...this.snapshots.values()].map(snapshot=>snapshot.directory));try{for await(const entry of await fs3.opendir(this.cacheDirectory)){if(!entry.isDirectory()||!entry.name.startsWith("skill-"))continue;const directory=path3.join(this.cacheDirectory,entry.name);if(known.has(directory))continue;const stat2=await fs3.lstat(directory).catch(()=>void 0);if(stat2&&stat2.mtimeMs+15*6e4<=Date.now())await fs3.rm(directory,{recursive:true,force:true})}}catch(error){if(error.code!=="ENOENT")throw error}}async manifest(root,file,source){await this.checked(root,file,source);const handle=await fs3.open(file,constants2.O_RDONLY|(constants2.O_NOFOLLOW??0)|(constants2.O_NONBLOCK??0));try{const before=await handle.stat();if(!before.isFile()||before.size>1024*1024)failed("invalid_skill_manifest");const bytes=Buffer.alloc(before.size);let offset=0;while(offset<bytes.length){const result=await handle.read(bytes,offset,bytes.length-offset,offset);if(!result.bytesRead)failed("source_changed");offset+=result.bytesRead}const after=await handle.stat();const named=await fs3.lstat(file);if(before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs||named.ino!==before.ino||named.dev!==before.dev)failed("source_changed");await this.checked(root,file,source);return new TextDecoder("utf-8",{fatal:true}).decode(bytes)}finally{await handle.close()}}async control(sessionId,operation){if(this.closed)failed("skill_source_unavailable");const op=parseManagedRuntimeSkillControl(operation);const source=await this.source(sessionId);const root=await fs3.realpath(source.directory);if(!await source.admits(root))failed("skill_source_unavailable");await this.sweep();if(op.kind==="extension-skill-archive"){const snapshot=this.snapshots.get(op.preparationId);if(!snapshot||snapshot.sessionId!==sessionId||snapshot.operationId!==op.operationId||snapshot.expiresAt<=Date.now()||op.offset>snapshot.byteLength)failed("skill_snapshot_unavailable");const handle=await fs3.open(path3.join(snapshot.directory,"skill.tar.gz"),"r");try{const buffer=Buffer.alloc(Math.min(CHUNK_BYTES,snapshot.byteLength-op.offset));const{bytesRead}=await handle.read(buffer,0,buffer.length,op.offset);if(bytesRead!==buffer.length||!await source.admits(root)||this.closed)failed("skill_snapshot_unavailable");return{operationId:op.operationId,preparationId:op.preparationId,offset:op.offset,totalBytes:snapshot.byteLength,base64:buffer.toString("base64")}}finally{await handle.close()}}if(op.kind==="extension-skill-candidates"){const candidates=[];const names=new Set;const budget={bytes:0,entries:0};let candidateBytes=0;for(const provider of SKILL_PROVIDER_CONFIG_DIRS){const relative2=`${provider}/skills`;const base=path3.join(root,relative2);try{await this.checked(root,base,source)}catch(error){if(error.code==="ENOENT")continue;throw error}const entries=await boundedEntries(base,1024,"skill_candidate_limit");for(const entry of entries){if(!entry.isDirectory()){if(entry.isSymbolicLink())failed("skill_source_unavailable");continue}if(candidates.length>=256)failed("skill_candidate_limit");const relativePath=`${relative2}/${entry.name}`;const directory=path3.join(root,relativePath);let candidate;try{const manifest=path3.join(directory,"SKILL.md");const content=await this.manifest(root,manifest,source);const skill=parseManagedSkillContent(content,manifest);if(skill.name.length>256||skill.description.length>4096||skill.description.includes("\0"))failed("invalid_skill_manifest");const observed=await this.scan(root,directory,source,budget);if(observed.files.filter(file=>file==="SKILL.md"||file.endsWith("/SKILL.md")).length!==1)failed("invalid_skill_manifest");candidate={name:skill.name,description:skill.description,path:relativePath,digest:observed.digest,shadowed:names.has(skill.name),compatible:true};names.add(skill.name)}catch(error){if(error.code==="ENOENT")continue;if(error instanceof Error&&["skill_source_unavailable","skill_source_limit","source_changed"].includes(error.message))throw error;candidate={name:entry.name,description:"",path:relativePath,digest:createHash2("sha256").update(relativePath).digest("hex"),shadowed:false,compatible:false,error:"Unsupported or invalid Skill content."}}candidateBytes+=Buffer.byteLength(JSON.stringify(candidate));if(candidateBytes>2*1024*1024)failed("skill_candidate_limit");candidates.push(candidate)}}if(!await source.admits(root)||this.closed)failed("skill_source_unavailable");return{operationId:op.operationId,candidates}}const identity=JSON.stringify([op.path,op.digest]);const existing=[...this.snapshots.entries()].find(([,value])=>value.sessionId===sessionId&&value.operationId===op.operationId);if(existing){if(existing[1].identity!==identity)failed("skill_snapshot_conflict");return this.descriptor(op.operationId,existing[0],existing[1])}if(this.preparing>=2||this.snapshots.size+this.preparing>=256)failed("skill_snapshot_capacity");const key=`${sessionId}\0${op.operationId}`;if(this.pending.has(key))failed("skill_snapshot_pending");this.pending.add(key);this.preparing++;let temporary;try{await fs3.mkdir(this.cacheDirectory,{recursive:true,mode:448});temporary=await fs3.mkdtemp(path3.join(this.cacheDirectory,"skill-"));const copied=path3.join(temporary,"source");await fs3.mkdir(copied);const directory=path3.join(root,op.path);const first=await this.scan(root,directory,source,{bytes:0,entries:0},copied);const second=await this.scan(root,directory,source,{bytes:0,entries:0});if(first.files.filter(file=>file==="SKILL.md"||file.endsWith("/SKILL.md")).length!==1)failed("invalid_skill_manifest");if(first.digest!==op.digest||second.digest!==first.digest)failed("source_changed");const manifest=path3.join(copied,"SKILL.md");if((await fs3.stat(manifest)).size>1024*1024)failed("invalid_skill_manifest");parseManagedSkillContent(await fs3.readFile(manifest,"utf8"),manifest);if(source.origin){const name=".qwen-managed-skill-origin.json";await fs3.writeFile(path3.join(copied,name),JSON.stringify({version:1,...source.origin,path:op.path,digest:op.digest}),{mode:420});await fs3.chmod(path3.join(copied,name),420);first.files.push(name);first.files.sort()}const archive=path3.join(temporary,"skill.tar.gz");await Qn({cwd:copied,file:archive,gzip:true,portable:true,noMtime:true},first.files);const byteLength=(await fs3.stat(archive)).size;if(byteLength>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES||this.retainedBytes+byteLength>MAX_RETAINED_BYTES)failed("skill_snapshot_capacity");const hash=createHash2("sha256");for await(const chunk of createReadStream2(archive))hash.update(chunk);await fs3.rm(copied,{recursive:true,force:true});await fs3.utimes(temporary,new Date,new Date);if(!await source.admits(root)||this.closed)failed("skill_source_unavailable");const snapshot={sessionId,operationId:op.operationId,identity,directory:temporary,sourceDigest:hash.digest("hex"),byteLength,expiresAt:Date.now()+15*6e4};const preparationId=randomUUID2();this.snapshots.set(preparationId,snapshot);this.retainedBytes+=byteLength;temporary=void 0;return this.descriptor(op.operationId,preparationId,snapshot)}finally{this.preparing--;this.pending.delete(key);if(temporary)await fs3.rm(temporary,{recursive:true,force:true})}}descriptor(operationId,preparationId,snapshot){return{operationId,preparationId,sourceDigest:snapshot.sourceDigest,byteLength:snapshot.byteLength}}async checked(root,file,source){const relative2=path3.relative(root,file);if(!contains(root,file))failed("skill_source_unavailable");let cursor=root;for(const segment of relative2.split(path3.sep).filter(Boolean)){cursor=path3.join(cursor,segment);const stat2=await fs3.lstat(cursor);if(stat2.isSymbolicLink()||!stat2.isDirectory()&&!stat2.isFile())failed("skill_source_unavailable")}const real=await fs3.realpath(file);if(!contains(root,real)||!await source.admits(real))failed("skill_source_unavailable")}async scan(root,directory,source,budget,destination){const hash=createHash2("sha256");const files=[];await this.checked(root,directory,source);const visit=__name(async relative2=>{const current=path3.join(directory,relative2);const before=await fs3.lstat(current);const entries=await boundedEntries(current,MAX_ARCHIVE_ENTRIES-budget.entries,"skill_source_limit");budget.entries+=entries.length;for(const entry of entries){if(privateNames.has(entry.name)||entry.name.startsWith(".env."))continue;const name=relative2?`${relative2}/${entry.name}`:entry.name;if(Buffer.byteLength(name)>4096)failed("skill_source_limit");budget.pathBytes=(budget.pathBytes??0)+Buffer.byteLength(name);if(budget.pathBytes>MAX_ARCHIVE_PATH_BYTES)failed("skill_source_limit");const file=path3.join(directory,name);await this.checked(root,file,source);if(entry.isDirectory()){await visit(name);continue}const handle=await fs3.open(file,constants2.O_RDONLY|(constants2.O_NOFOLLOW??0)|(constants2.O_NONBLOCK??0));try{const stat2=await handle.stat();if(!stat2.isFile())failed("skill_source_unavailable");budget.bytes+=stat2.size;if(budget.bytes>MAX_ARCHIVE_EXPANDED_BYTES||budget.entries>MAX_ARCHIVE_ENTRIES)failed("skill_source_limit");const mode=stat2.mode&73?493:420;hash.update(JSON.stringify([name,stat2.size,mode]));const sink=destination?(()=>{const target=path3.join(destination,name);return fs3.mkdir(path3.dirname(target),{recursive:true}).then(()=>createWriteStream2(target,{mode,flags:"wx"}))})():Promise.resolve(new Writable({write(_chunk,_encoding,done){done()}}));let read=0;await pipeline2(handle.createReadStream({autoClose:false}),new Transform2({transform(chunk,_encoding,done){read+=chunk.length;if(read>stat2.size){done(new Error("source_changed"));return}hash.update(chunk);done(null,chunk)}}),await sink);if(destination)await fs3.chmod(path3.join(destination,name),mode);const after2=await handle.stat();const named=await fs3.lstat(file);if(stat2.ino!==after2.ino||stat2.size!==after2.size||stat2.mtimeMs!==after2.mtimeMs||stat2.ctimeMs!==after2.ctimeMs||named.ino!==stat2.ino||named.dev!==stat2.dev)failed("source_changed");await this.checked(root,file,source);files.push(name)}finally{await handle.close()}}const after=await fs3.lstat(current);if(before.ino!==after.ino||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs)failed("source_changed")},"visit");await visit("");return{digest:hash.digest("hex"),files}}};var MANAGED_EXTENSION_RUNTIME_ROUTE=Object.freeze({key:"extensions",method:"POST",path:"/internal/managed-runtime/v3/extensions"});var MANAGED_EXTENSION_RETIRE_ROUTE=Object.freeze({key:"extension-retire",method:"POST",path:"/internal/managed-runtime/v3/extensions/retire"});var MANAGED_EXTENSION_UPLOAD_ROUTE=Object.freeze({key:"extension-package-upload",method:"PUT",path:"/internal/managed-runtime/v3/extensions/packages/:digest"});var ManagedExtensionRuntime=class{constructor(dependencies){this.dependencies=dependencies;if(!path4.isAbsolute(dependencies.directory))throw new Error("Invalid extension Runtime directory.");this.cache=new ManagedExtensionCache(path4.join(dependencies.directory,"packages"));if(dependencies.skillSource)this.skillSources=new ManagedRuntimeSkillSources(path4.join(dependencies.directory,"skill-snapshots"),dependencies.skillSource)}static{__name(this,"ManagedExtensionRuntime")}cache;skillSources;prepared=new Map;active=new Map;busy=new Set;environments=new Map;sessionOwners=new Map;ownerSessions=new Map;async skillControl(sessionId,operation){await this.requireSession(sessionId);if(!this.skillSources||this.isChanging(sessionId))throw new Error("skill_source_unavailable");if(operation.kind==="extension-skill-snapshot"&&!this.dependencies.idle(sessionId))throw new Error("skill_source_busy");const result=await this.skillSources.control(sessionId,operation);await this.requireSession(sessionId);return result}async closeSkillSnapshots(){await this.skillSources?.close()}async status(sessionId){await this.requireSession(sessionId);let pendingOperationId;try{pendingOperationId=parseManagedExtensionApplyCommand(JSON.parse(await fs4.readFile(this.pendingPath(sessionId),"utf8"))).operationId}catch(error){if(error.code!=="ENOENT")throw error}const pending=pendingOperationId?{pendingOperationId}:{};const installed=this.active.get(sessionId);if(installed)return{...this.state(installed.command),...pending};try{const stored=JSON.parse(await fs4.readFile(this.statePath(sessionId),"utf8"));const command=parseManagedExtensionApplyCommand(stored);const stopped=await fs4.stat(`${this.operationPath(sessionId,command.operationId)}.stopped`).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error});return{...this.state(command),...stopped?{state:"failed"}:{},...pending}}catch(error){if(error.code==="ENOENT")return{state:pendingOperationId?"outcome_unknown":"active",executionMode:this.dependencies.executionMode,revision:0,extensions:[],operationId:null,...pending};throw error}}async operationStatus(sessionId,operationId){const current=await this.status(sessionId);try{const proof=JSON.parse(await fs4.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof["operationId"]!==operationId||proof["executionMode"]!==this.dependencies.executionMode||proof["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof}catch(error){if(error.code!=="ENOENT")throw error}if(current.operationId===operationId&&!current.pendingOperationId)return current;const prepared=this.prepared.get(this.preparedKey(sessionId,operationId))??await this.loadPrepared(sessionId,operationId);if(prepared&&!current.pendingOperationId)return this.preparedView(prepared);return{...current,state:"outcome_unknown",operationId}}async prepare(sessionId,value,base={baseMcpServers:[],baseHookCatalog:null}){const command=parseManagedExtensionApplyCommand(value);return this.lock(sessionId,async()=>{const status=await this.status(sessionId);const key=this.preparedKey(sessionId,command.operationId);const existing=this.prepared.get(key)??await this.loadPrepared(sessionId,command.operationId);const publicBase={baseMcpServers:base.baseMcpServers,baseHookCatalog:base.baseHookCatalog};if(existing){if(JSON.stringify(existing.command)!==JSON.stringify(command)||JSON.stringify(existing.base)!==JSON.stringify(publicBase))throw new Error("Extension operation identity conflicts.");for(const pkg of existing.packages){await this.cache.restoreMaterialized(pkg.pin.packageDigest,pkg.assetRoot);const contributions=await this.dependencies.compile(pkg.assetRoot,pkg.pin,base.settings?.[pkg.pin.extensionId]??{},sessionId,base.packageManifests?.[pkg.pin.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);if(JSON.stringify(contributions)!==JSON.stringify(pkg.contributions))throw new Error("Prepared extension package drifted.")}const catalogs2=this.dependencies.stage?await this.dependencies.stage(sessionId,command,existing.packages,{...publicBase,preparedMcpServers:existing.mcpServers}):{mcpServers:[],hookCatalog:null};if(JSON.stringify(catalogs2.mcpServers)!==JSON.stringify(existing.mcpServers)||JSON.stringify(catalogs2.hookCatalog)!==JSON.stringify(existing.hookCatalog))throw new Error("Prepared extension catalogs drifted.");this.environments.set(key,base.settings??{});this.prepared.set(key,existing);return this.preparedView(existing)}if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.revision!==command.expectedRevision)throw new Error("Extension configuration revision conflicts.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");const packages=[];try{for(const pin2 of command.extensions){const unchanged=this.active.get(sessionId)?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));const assetRoot=unchanged?.assetRoot??await this.cache.materialize(pin2.packageDigest);await this.cache.restoreMaterialized(pin2.packageDigest,assetRoot);packages.push({pin:pin2,assetRoot,contributions:{skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]}});const contributions=await this.dependencies.compile(assetRoot,pin2,base.settings?.[pin2.extensionId]??{},sessionId,base.packageManifests?.[pin2.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);packages[packages.length-1]={pin:pin2,assetRoot,contributions}}}catch(error){await Promise.all(packages.map(entry=>this.active.get(sessionId)?.packages.some(active=>active.assetRoot===entry.assetRoot)?Promise.resolve():fs4.rm(entry.assetRoot,{recursive:true,force:true})));throw error}const catalogs=this.dependencies.stage?await this.dependencies.stage(sessionId,command,packages,base):{mcpServers:[],hookCatalog:null};if(!this.dependencies.stage&&packages.some(entry=>Object.keys(entry.contributions.mcpServers).length||Object.keys(entry.contributions.hooks).length))throw new Error("Extension process components are unsupported.");const prepared={ownerJournalId:this.dependencies.ownerJournalId??"in-memory",command,packages,base:publicBase,mcpServers:catalogs.mcpServers,hookCatalog:catalogs.hookCatalog};const view2=this.preparedView(prepared);await fs4.mkdir(path4.dirname(this.operationPath(sessionId,command.operationId)),{recursive:true,mode:448});await atomicWriteJSON(this.operationPath(sessionId,command.operationId),prepared,{mode:384});this.environments.set(key,base.settings??{});this.prepared.set(key,prepared);return view2})}async reconcile(sessionId,operationId,expectedRevision,revision){return this.lock(sessionId,async()=>{const prepared=await this.loadPrepared(sessionId,operationId);if(!prepared)throw new Error("Original extension owner journal is unavailable.");try{const proof2=JSON.parse(await fs4.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof2["operationId"]!==operationId||proof2["revision"]!==revision||expectedRevision+1!==revision||proof2["executionMode"]!==this.dependencies.executionMode||proof2["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof2}catch(error){if(error.code!=="ENOENT")throw error}const command=prepared.command;const current=await this.status(sessionId);if(command.operationId!==operationId||command.expectedRevision!==expectedRevision||revision!==expectedRevision+1||current.pendingOperationId!==void 0&&current.pendingOperationId!==operationId||current.revision!==expectedRevision&&(current.operationId!==operationId||current.revision!==revision||JSON.stringify(current.extensions)!==JSON.stringify(command.extensions)))throw new Error("Original extension operation conflicts.");const receipts=this.dependencies.reconcile?await this.dependencies.reconcile(sessionId):void 0;if(!receipts||receipts.length===0||receipts.some(entry=>entry.state!=="stopped"))return{operationId,revision,state:"outcome_unknown",executionMode:this.dependencies.executionMode};const proof={operationId,revision,state:"stopped",executionMode:this.dependencies.executionMode,receipts};await atomicWriteJSON(`${this.operationPath(sessionId,operationId)}.stopped`,proof,{mode:384});await atomicWriteJSON(this.statePath(sessionId),command,{mode:384});this.active.delete(sessionId);await fs4.rm(this.pendingPath(sessionId),{force:true});return proof})}async activate(sessionId,operationId){return this.lock(sessionId,async()=>{const status=await this.status(sessionId);if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.operationId===operationId){if(!this.active.has(sessionId)){const restored=this.prepared.get(this.preparedKey(sessionId,operationId));if(!restored)throw new Error("Active extension configuration requires exact reprepare.");await this.dependencies.install(sessionId,restored.packages,restored.command);this.active.set(sessionId,restored)}return status}const prepared=this.prepared.get(this.preparedKey(sessionId,operationId));if(!prepared||status.revision!==prepared.command.expectedRevision)throw new Error("Extension configuration was not prepared.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");await fs4.mkdir(path4.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.pendingPath(sessionId),prepared.command,{mode:384});await this.dependencies.drain(sessionId,prepared.command);await this.requireSession(sessionId);if(!this.dependencies.idle(sessionId))throw new Error("Extension Session acquired work while draining.");await this.dependencies.install(sessionId,prepared.packages,prepared.command);await fs4.mkdir(path4.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.statePath(sessionId),prepared.command,{mode:384});this.active.set(sessionId,prepared);await fs4.rm(this.pendingPath(sessionId));return this.state(prepared.command)})}async getToolContext(sessionId,configRevision,value){await this.requireSession(sessionId);if(this.busy.has(sessionId))throw new Error("Extension configuration is changing.");const status=await this.status(sessionId);const active=this.active.get(sessionId);const pin2=parseManagedExtensionPin(value);const pkg=active?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));if(!active||!pkg||status.pendingOperationId||status.revision!==configRevision)throw new Error("Extension tool configuration is unavailable.");const environment=this.environments.get(this.preparedKey(sessionId,active.command.operationId));if(!environment)throw new Error("Extension settings require exact reprepare.");await this.cache.verifyMaterialized(pin2.packageDigest,pkg.assetRoot);return{assetRoot:pkg.assetRoot,environment:{...environment[pin2.extensionId],QWEN_EXTENSION_ROOT:pkg.assetRoot}}}async bindSession(sessionId,runtimeSessionId,contextBinding){if(this.dependencies.bindContext)await this.dependencies.bindContext(sessionId,contextBinding);if(runtimeSessionId===void 0)return;const existing=this.ownerSessions.get(runtimeSessionId);if(existing&&existing!==sessionId)throw new Error("Extension Runtime owner conflicts.");this.ownerSessions.set(runtimeSessionId,sessionId);this.sessionOwners.set(sessionId,runtimeSessionId)}runtimeSessionId(sessionId){return this.sessionOwners.get(sessionId)??sessionId}isChanging(sessionId){return this.busy.has(this.ownerSessions.get(sessionId)??sessionId)}async readAsset(sessionId,revision,extensionId,relativePath){const root=await this.assetRoot(sessionId,revision,extensionId);const file=await this.contained(root,relativePath);const handle=await fs4.open(file,"r");try{const stat2=await handle.stat();if(!stat2.isFile()||stat2.size>256*1024)throw new Error("Extension asset exceeds the read limit.");return{path:relativePath,content:await handle.readFile("utf8")}}finally{await handle.close()}}async globAssets(sessionId,revision,extensionId,pattern){const root=await this.assetRoot(sessionId,revision,extensionId);if(pattern.length>1024||pattern.includes("\0"))throw new Error("Invalid extension glob.");const paths=[];const visit=__name(async directory=>{for(const entry of await fs4.readdir(directory,{withFileTypes:true})){const filename=path4.join(directory,entry.name);const relative2=path4.relative(root,filename).split(path4.sep).join("/");if(entry.isSymbolicLink())throw new Error("Extension assets contain a link.");if(entry.isDirectory())await visit(filename);else if(entry.isFile()&&minimatch(relative2,pattern,{dot:true})){if(paths.length===2048)throw new Error("Extension glob exceeds its result limit.");paths.push(relative2)}}},"visit");await visit(root);return paths.sort()}async assetRoot(sessionId,revision,extensionId){const status=await this.status(sessionId);const active=this.active.get(sessionId);if(this.isChanging(sessionId)||!active||status.revision!==revision)throw new Error("Extension configuration is unavailable.");const entry=active.packages.find(item=>item.pin.extensionId===extensionId);if(!entry)throw new Error("Extension package is not active in this Session.");if(status.pendingOperationId)throw new Error("Extension activation outcome is unknown.");await this.cache.verifyMaterialized(entry.pin.packageDigest,entry.assetRoot);return fs4.realpath(entry.assetRoot)}async contained(root,relative2){if(!relative2||relative2.includes("\\")||relative2.includes("\0")||path4.isAbsolute(relative2))throw new Error("Invalid extension asset path.");const filename=await fs4.realpath(path4.resolve(root,relative2));const resolved=path4.relative(root,filename);if(resolved===".."||resolved.startsWith(`..${path4.sep}`)||path4.isAbsolute(resolved))throw new Error("Extension asset path escapes its package.");return filename}preparedView(value){const result={operationId:value.command.operationId,state:"prepared",expectedRevision:value.command.expectedRevision,revision:value.command.expectedRevision+1,executionMode:this.dependencies.executionMode,packages:value.packages,mcpServers:value.mcpServers,hookCatalog:value.hookCatalog};if(Buffer.byteLength(JSON.stringify(result))>8*1024*1024)throw new Error("Extension prepare response exceeds its size limit.");return result}state(command){return{state:"active",executionMode:this.dependencies.executionMode,revision:command.expectedRevision+1,extensions:command.extensions,operationId:command.operationId}}async loadPrepared(sessionId,operationId){try{const value=JSON.parse(await fs4.readFile(this.operationPath(sessionId,operationId),"utf8"));if(value.ownerJournalId!==(this.dependencies.ownerJournalId??"in-memory"))throw new Error("Original extension owner journal is unavailable.");const command=parseManagedExtensionApplyCommand(value.command);if(command.operationId!==operationId||!Array.isArray(value.packages)||value.packages.length!==command.extensions.length)throw new Error("Invalid prepared extension receipt.");const pins=parseManagedExtensionPins(value.packages.map(pkg=>pkg.pin));if(JSON.stringify(pins)!==JSON.stringify(command.extensions))throw new Error("Prepared extension pins conflict.");for(const pkg of value.packages){if(typeof pkg.assetRoot!=="string"||path4.dirname(pkg.assetRoot)!==this.cache.directory||!path4.basename(pkg.assetRoot).startsWith(`${pkg.pin.packageDigest}-`))throw new Error("Invalid prepared extension asset root.")}this.preparedView(value);return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}operationPath(sessionId,operationId){return`${this.statePath(sessionId)}.${createHash3("sha256").update(operationId).digest("hex")}.prepared`}statePath(sessionId){return path4.join(this.dependencies.directory,"sessions",`${createHash3("sha256").update(sessionId).digest("hex")}.json`)}pendingPath(sessionId){return`${this.statePath(sessionId)}.pending`}preparedKey(sessionId,operationId){return`${sessionId}\0${operationId}`}async requireSession(sessionId){if(!sessionId||!await this.dependencies.admitted(sessionId))throw new Error("Extension Session is unavailable.")}async lock(sessionId,work){if(this.busy.has(sessionId))throw new Error("Extension Session configuration is changing.");this.busy.add(sessionId);try{await this.requireSession(sessionId);return await work()}finally{this.busy.delete(sessionId)}}};function registerManagedExtensionRuntimeRoutes(app,identity,runtime){app.put(MANAGED_EXTENSION_UPLOAD_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),async(req,res)=>{try{if(req.headers["content-type"]!=="application/gzip")throw new Error("Invalid package content type.");await runtime.cache.upload(String(req.params["digest"]),req);res.json({protocolVersion:1,packageDigest:req.params["digest"]})}catch{res.status(400).json({code:"managed_extension_package_invalid"})}});app.post(MANAGED_EXTENSION_RUNTIME_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(512*1024),async(req,res)=>{try{const body2=req.body;if(!body2||!["contextBinding,operation,protocolVersion,sessionKey","contextBinding,operation,protocolVersion,runtimeSessionId,sessionKey"].includes(Object.keys(body2).sort().join(","))||body2["protocolVersion"]!==1||body2["runtimeSessionId"]!==void 0&&typeof body2["runtimeSessionId"]!=="string")throw new Error("Invalid extension request.");const runtimeSessionId=body2["runtimeSessionId"];const sessionKey=body2["sessionKey"];if(!sessionKey||Object.keys(sessionKey).sort().join(",")!=="sessionId,tenantId,workspaceId"||sessionKey["tenantId"]!==identity.tenantId||sessionKey["workspaceId"]!==identity.workspaceId||typeof sessionKey["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/u.test(sessionKey["sessionId"]))throw new Error("Extension Session scope conflicts.");const sessionId=sessionKey["sessionId"];await runtime.bindSession(sessionId,runtimeSessionId,body2["contextBinding"]);const operation=body2["operation"];let result;if(operation["kind"]==="prepare"||operation["kind"]==="extension-prepare"){const control=operation;const parsed=parseManagedExtensionApplyCommand(control.command);if(control.kind==="extension-prepare"&&(control.operationId!==parsed.operationId||control.expectedRevision!==parsed.expectedRevision||JSON.stringify(control.extensions)!==JSON.stringify(parsed.extensions)))throw new Error("Extension prepare identity conflicts.");result=await runtime.prepare(sessionId,parsed,control.kind==="extension-prepare"?{toolProfile:typeof operation["toolProfile"]==="string"?operation["toolProfile"]:void 0,packageManifests:operation["packageManifests"],baseMcpServers:control.baseMcpServers,baseHookCatalog:control.baseHookCatalog,settings:operation["settings"]}:void 0)}else if(typeof operation["kind"]==="string"&&operation["kind"].startsWith("extension-skill-")){result=await runtime.skillControl(sessionId,parseManagedRuntimeSkillControl(operation))}else if((operation["kind"]==="activate"||operation["kind"]==="extension-activate")&&typeof operation["operationId"]==="string")result=await runtime.activate(sessionId,operation["operationId"]);else if(operation["kind"]==="extension-reconcile"&&typeof operation["operationId"]==="string"&&Number.isSafeInteger(operation["expectedRevision"])&&Number.isSafeInteger(operation["revision"]))result=await runtime.reconcile(sessionId,operation["operationId"],Number(operation["expectedRevision"]),Number(operation["revision"]));else if(operation["kind"]==="status"||operation["kind"]==="extension-status")result=typeof operation["operationId"]==="string"?await runtime.operationStatus(sessionId,operation["operationId"]):await runtime.status(sessionId);else if((operation["kind"]==="asset-read"||operation["kind"]==="extension-asset-read")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["path"]==="string")result=await runtime.readAsset(sessionId,Number(operation["revision"]),operation["extensionId"],operation["path"]);else if((operation["kind"]==="asset-glob"||operation["kind"]==="extension-asset-glob")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["pattern"]==="string")result=await runtime.globAssets(sessionId,Number(operation["revision"]),operation["extensionId"],operation["pattern"]);else throw new Error("Invalid extension operation.");if(typeof operation["operationId"]==="string"&&String(operation["kind"]).includes("asset-"))result=Array.isArray(result)?{operationId:operation["operationId"],paths:result}:{...result,operationId:operation["operationId"]};res.json({protocolVersion:1,sessionKey,...runtimeSessionId?{runtimeSessionId}:{},result})}catch(error){res.status(409).json({code:error instanceof Error&&["source_changed","skill_source_unavailable","skill_source_busy","skill_snapshot_unavailable","skill_snapshot_capacity","skill_snapshot_pending","skill_snapshot_conflict","skill_source_limit","skill_candidate_limit"].includes(error.message)?error.message:"managed_extension_configuration_unavailable"})}})}__name(registerManagedExtensionRuntimeRoutes,"registerManagedExtensionRuntimeRoutes");function validateExtensionToolProfile(value,profile){if(profile===void 0)return;const shell=profile==="hosted-workspace-shell/1"||profile==="hosted-workspace-team-lead/1";const mcp=shell||profile==="hosted-workspace-mcp/1";if(!mcp&&Object.keys(value.mcpServers).length)throw new Error("Session profile does not admit extension MCP.");if(!shell&&(JSON.stringify(value.hooks).includes('"type":"command"')||Object.values(value.mcpServers).some(recipe=>recipe&&typeof recipe==="object"&&"command"in recipe)||value.commands.some(command=>/!\{|!`/u.test(command.prompt))))throw new Error("Session profile does not admit extension Shell execution.");const base=["read_file","glob"];if(profile!=="hosted-workspace-read/1")base.push("write_file","edit","list_directory","grep_search","todo_write");if(shell)base.push("run_shell_command");for(const agent of value.agents)if(agent.tools?.some(tool=>!base.includes(tool)&&!(mcp&&tool.startsWith("mcp__"))))throw new Error("Extension agent tools exceed the Session profile.")}__name(validateExtensionToolProfile,"validateExtensionToolProfile");init_esbuild_shims();init_esbuild_shims();var ManagedExtensionExecutionUnknownError=class extends Error{static{__name(this,"ManagedExtensionExecutionUnknownError")}};async function runManagedExtensionShell(owners,input){input.signal.throwIfAborted();const shell=getShellConfiguration();const{child,ownerId,preread,detachPreread}=await owners.start({sessionId:input.sessionId,configRevision:input.configRevision,executable:shell.executable,args:[...shell.argsPrefix,input.command],cwd:input.cwd,env:input.environment,prereadOutput:true});const streamsClosed=new Promise(resolve=>{if((child.exitCode!==null||child.signalCode!==null)&&child.stdout?.destroyed===true&&child.stderr?.destroyed===true)resolve();else child.once("close",()=>resolve())});if(child.pid)input.capture?.setStarted(child.pid);child.stdin?.end();const chunks=[];let retained=0;let exceeded=false;const captures={stdout:Promise.resolve(),stderr:Promise.resolve()};const consume=__name((id,chunk)=>{if(input.capture){child[id]?.pause();captures[id]=captures[id].then(()=>input.capture.write(id,chunk)).finally(()=>child[id]?.resume())}const remaining=Math.max(0,1024*1024-retained);if(chunk.length>remaining)exceeded=true;if(remaining){const prefix=chunk.subarray(0,remaining);chunks.push(prefix);retained+=prefix.length}},"consume");detachPreread?.();if(preread){for(const chunk of preread.stdout)consume("stdout",chunk);for(const chunk of preread.stderr)consume("stderr",chunk);if(preread.overflow)exceeded=true}for(const id of["stdout","stderr"])child[id]?.on("data",chunk=>consume(id,chunk));let timedOut=false;let timer;let wake;const stop=__name(()=>{wake?.()},"stop");try{const exited=new Promise(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once("exit",()=>resolve())});const interrupted=new Promise(resolve=>{wake=resolve;input.signal.addEventListener("abort",stop,{once:true});if(input.signal.aborted)resolve();timer=setTimeout(()=>{timedOut=true;resolve()},input.timeoutMs??12e4)});await Promise.race([exited,interrupted]);const receipt2=await owners.stop(ownerId).catch(()=>{throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.")});if(receipt2.state!=="stopped")throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.");let drainTimer;try{await Promise.race([streamsClosed,new Promise((_resolve,reject)=>{drainTimer=setTimeout(()=>reject(new ManagedExtensionExecutionUnknownError("Extension Shell output closure is unknown.")),5e3)})])}finally{if(drainTimer)clearTimeout(drainTimer)}await Promise.all(Object.values(captures));const rawOutput=Buffer.concat(chunks);const output=rawOutput.toString("utf8");const result={rawOutput,output,exitCode:child.exitCode,signal:null,error:null,aborted:input.signal.aborted||timedOut,pid:child.pid,executionMethod:"child_process",outputCaptureLimitExceeded:exceeded};input.capture?.setProcessResult(result);await input.capture?.finish("stdout",true);await input.capture?.finish("stderr",true);return{llmContent:`${output}${exceeded?"\n[Output truncated]":""}${timedOut?"\n[Command timed out]":""}`,returnDisplay:output,...child.exitCode!==0||result.aborted?{error:{message:result.aborted?"Shell command stopped.":`Shell exited with code ${child.exitCode}.`,type:"execution_failed"}}:{}}}finally{if(timer)clearTimeout(timer);input.signal.removeEventListener("abort",stop)}}__name(runManagedExtensionShell,"runManagedExtensionShell");init_esbuild_shims();import{createHash as createHash6}from"node:crypto";import{promises as fs6}from"node:fs";import path7 from"node:path";init_esbuild_shims();function gateKey(sessionKey,operationId){const key=assertManagedSessionKey(sessionKey);const id=assertManagedSessionStableId(operationId,"operationId");return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}\0${id}`}__name(gateKey,"gateKey");var ManagedOperationGrantGate=class{static{__name(this,"ManagedOperationGrantGate")}entries=new Map;install(value){const grant=parseOperationGrant(value);const key=gateKey(grant.sessionKey,grant.operationId);const entry=this.entries.get(key);if(entry!==void 0&&grant.operationRevision<=entry.revokedThrough){throw new ManagedSessionConflictError(`operation ${grant.operationId} revision ${grant.operationRevision} was revoked.`)}const current=entry?.grant;if(current!==void 0){if(JSON.stringify(current)===JSON.stringify(grant)){return"unchanged"}if(!isOperationGrantSuccessor(current,grant)){throw new ManagedSessionConflictError(`grant revision ${grant.operationRevision} of operation ${grant.operationId} cannot replace revision ${current.operationRevision}.`)}}this.entries.set(key,{grant,revokedThrough:entry?.revokedThrough??0});return"installed"}revoke(sessionKey,operationId,operationRevision){const key=gateKey(sessionKey,operationId);assertManagedSessionSequence(operationRevision,"operationRevision");if(operationRevision<1){throw new ManagedSessionRecordError("operationRevision must be a positive safe integer.")}const entry=this.entries.get(key)??{grant:void 0,revokedThrough:0};entry.revokedThrough=Math.max(entry.revokedThrough,operationRevision);this.entries.set(key,entry)}admits(sessionKey,operationId,phase,now){const entry=this.entries.get(gateKey(sessionKey,operationId));if(entry?.grant===void 0)return false;const{grant}=entry;return grant.operationRevision>entry.revokedThrough&&now<grant.expiresAt&&grant.resourceScope.phases.includes(phase)}};init_esbuild_shims();import path6 from"node:path";import{promises as fs5}from"node:fs";import{lstat as lstat3,readlink,realpath as realpath2}from"node:fs/promises";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";init_esbuild_shims();import{createHash as createHash4}from"node:crypto";import{createReadStream as createReadStream3}from"node:fs";import{lstat as lstat2}from"node:fs/promises";import path5 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();function copySnapshots(snapshots){return snapshots.map(snapshot=>({promptId:snapshot.promptId,timestamp:snapshot.timestamp,trackedFileBackups:Object.fromEntries(Object.entries(snapshot.trackedFileBackups).map(([filePath,backup])=>{if(!Number.isSafeInteger(backup.version)||backup.version<0){throw new Error("Invalid managed file history backup version.")}return[filePath,{backupFileName:backup.backupFileName,version:backup.version,backupTime:backup.backupTime,...backup.failed?{failed:true}:{}}]}))}))}__name(copySnapshots,"copySnapshots");var ManagedToolFileHistory=class{constructor(ownerSessionId,cwd,serializedSnapshots,retainedStorage){this.ownerSessionId=ownerSessionId;this.service=new FileHistoryService(ownerSessionId,true,cwd,()=>this.capture(),retainedStorage);this.service.restoreFromSnapshots(deserializeSnapshots(copySnapshots(serializedSnapshots)));this.snapshots=this.readSnapshots();this.snapshotJson=JSON.stringify(this.snapshots);this.startedPrompts=new Set(this.snapshots.map(({promptId})=>promptId));this.initialization=this.service.validateRestoredSnapshots();void this.initialization.catch(()=>{})}static{__name(this,"ManagedToolFileHistory")}service;initialization;pending=Promise.resolve();startedPrompts;revision=0;snapshots;snapshotJson;ready(){return this.initialization}state(){return{ownerSessionId:this.ownerSessionId,revision:this.revision,snapshots:structuredClone(this.snapshots)}}checkpoint(promptId){return this.run(async()=>{if(this.service.getSnapshots().at(-1)?.promptId===promptId)return;if(this.startedPrompts.has(promptId)){throw new Error("Managed file history cannot reopen an earlier turn.")}await this.service.makeSnapshot(promptId);this.startedPrompts.add(promptId)})}run(operation){const result=this.pending.then(async()=>{await this.initialization;try{return await operation()}finally{this.capture()}});this.pending=result.then(()=>{},()=>{});return result}async drain(){const pending=this.pending;await this.initialization;await pending}readSnapshots(){return copySnapshots(this.service.getSnapshots().map(serializeSnapshot))}capture(){const snapshots=this.readSnapshots();const snapshotJson=JSON.stringify(snapshots);if(snapshotJson===this.snapshotJson)return;this.snapshots=snapshots;this.snapshotJson=snapshotJson;this.revision++}};var ManagedRuntimeFileHistory=class{constructor(ownerSessionId,directory,state,retainedStorage){this.ownerSessionId=ownerSessionId;this.directory=directory;this.retainedStorage=retainedStorage;this.history=new ManagedToolFileHistory(ownerSessionId,directory,state?.snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split("/").join(path5.sep),backup]))}))??[],retainedStorage);this.files=Object.assign(Object.create(null),structuredClone(state?.files??{}))}static{__name(this,"ManagedRuntimeFileHistory")}history;files;prepared=new Set;async ready(checkPaths=true){await this.history.ready();await this.history.service.validateRestoredSnapshots();const checked=new Set;for(const snapshot of this.history.state().snapshots){for(const[file,backup]of Object.entries(snapshot.trackedFileBackups)){if(backup.failed)throw new Error("Hosted file history backup is unavailable.");if(checkPaths&&!checked.has(file)){await this.resolve(file.split(path5.sep).join("/"));checked.add(file)}}}}state(){return{ownerSessionId:this.ownerSessionId,snapshots:this.history.state().snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split(path5.sep).join("/"),backup]))})),files:structuredClone(this.files)}}async prepare(promptId,paths){await this.ready();const snapshots=this.history.state().snapshots;if(snapshots.length>=100&&snapshots.at(-1)?.promptId!==promptId)throw new Error("Hosted file history has reached its 100 snapshot limit.");const newPrompt=snapshots.at(-1)?.promptId!==promptId;const observed=Object.create(null);for(const file of new Set([...newPrompt?Object.keys(this.files):[],...paths])){observed[file]=await this.fingerprint(file);if(!newPrompt&&Object.hasOwn(this.files,file)&&!isDeepStrictEqual(observed[file],this.files[file]))throw new Error("Hosted file changed outside tracked mutations.")}const previous=new ManagedToolFileHistory(this.ownerSessionId,this.directory,snapshots,this.retainedStorage);await previous.ready();try{await this.history.checkpoint(promptId);await this.history.run(async()=>{for(const file of paths){const absolute=await this.resolve(file);await this.history.service.trackEdit(absolute);const backups=this.history.service.getSnapshots().at(-1)?.trackedFileBackups;const key=file.split("/").join(path5.sep);if(!backups||!Object.hasOwn(backups,key)||backups[key].failed)throw new Error("Hosted file backup failed; mutation was not started.")}await this.ready();for(const[file,expected]of Object.entries(observed))if(!isDeepStrictEqual(await this.fingerprint(file),expected))throw new Error("Hosted file changed during backup preparation.");Object.assign(this.files,observed);if(newPrompt)this.prepared.clear();for(const file of paths)this.prepared.add(file)})}catch(error){this.history=previous;throw error}}async execute(file,action){historyPath(file);if(!this.prepared.has(file))throw new Error("Hosted file mutation has no prepared backup.");return this.history.run(async()=>{await this.ready();if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file]))throw new Error("Hosted file changed after backup preparation.");try{return await action()}finally{this.files[file]=await this.fingerprint(file)}})}async rewind(promptId){if(this.retainedStorage)throw new Error("Retained history cannot rewind.");await this.ready(false);return this.history.run(async()=>{let conflict2=false;try{for(const file of Object.keys(this.files)){if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file])){conflict2=true;break}}}catch{conflict2=true}if(conflict2)return{state:this.state(),filesChanged:[],filesFailed:[],conflict:true};const result=await this.history.service.rewind(promptId,false);for(const file of Object.keys(this.files))this.files[file]=await this.fingerprint(file);return{state:this.state(),filesChanged:result.filesChanged.map(file=>path5.relative(this.directory,file).split(path5.sep).join("/")),filesFailed:result.filesFailed.map(file=>path5.relative(this.directory,file).split(path5.sep).join("/")),conflict:false}})}async resolve(file){historyPath(file);if(this.retainedStorage){const absolute=path5.join(this.directory,file);return this.retainedStorage.withWorkingFile(absolute,async()=>absolute)}let current=this.directory;const segments=file.split("/");for(const[index,segment]of segments.entries()){current=path5.join(current,segment);try{const info=await lstat2(current);if(info.isSymbolicLink()||(index<segments.length-1?!info.isDirectory():!info.isFile()))throw new Error("Hosted file history requires ordinary Workspace files.")}catch(error){if(error.code!=="ENOENT")throw error}}return current}async fingerprint(file){historyPath(file);if(this.retainedStorage)return this.retainedStorage.withWorkingFile(path5.join(this.directory,file),async source=>source?{digest:`sha256:${await digestFileReadSource(source)}`,mode:source.stats.mode&4095}:null);const absolute=await this.resolve(file);try{const before=await lstat2(absolute);const digest3=createHash4("sha256");for await(const chunk of createReadStream3(absolute))digest3.update(chunk);const after=await lstat2(absolute);if(before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.mode!==after.mode)throw new Error("Hosted file changed while reading history.");return{digest:`sha256:${digest3.digest("hex")}`,mode:after.mode&4095}}catch(error){if(error.code==="ENOENT")return null;throw error}}};init_esbuild_shims();import{createHash as createHash5}from"node:crypto";import{readFileSync}from"node:fs";init_esbuild_shims();var SseError=class extends Error{static{__name(this,"SseError")}constructor(code,message,event){super(`SSE error: ${message}`);this.code=code;this.event=event}};var SSEClientTransport=class{static{__name(this,"SSEClientTransport")}constructor(url,opts){this._url=url;this._resourceMetadataUrl=void 0;this._scope=void 0;this._eventSourceInit=opts?.eventSourceInit;this._requestInit=opts?.requestInit;this._authProvider=opts?.authProvider;this._fetch=opts?.fetch;this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit)}async _authThenStart(){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}let result;try{result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(error){this.onerror?.(error);throw error}if(result!=="AUTHORIZED"){throw new UnauthorizedError}return await this._startOrAuth()}async _commonHeaders(){const headers={};if(this._authProvider){const tokens=await this._authProvider.tokens();if(tokens){headers["Authorization"]=`Bearer ${tokens.access_token}`}}if(this._protocolVersion){headers["mcp-protocol-version"]=this._protocolVersion}const extraHeaders=normalizeHeaders(this._requestInit?.headers);return new Headers({...headers,...extraHeaders})}_startOrAuth(){const fetchImpl=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((resolve,reject)=>{this._eventSource=new EventSource(this._url.href,{...this._eventSourceInit,fetch:__name(async(url,init)=>{const headers=await this._commonHeaders();headers.set("Accept","text/event-stream");const response=await fetchImpl(url,{...init,headers});if(response.status===401&&response.headers.has("www-authenticate")){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3}return response},"fetch")});this._abortController=new AbortController;this._eventSource.onerror=event=>{if(event.code===401&&this._authProvider){this._authThenStart().then(resolve,reject);return}const error=new SseError(event.code,event.message,event);reject(error);this.onerror?.(error)};this._eventSource.onopen=()=>{};this._eventSource.addEventListener("endpoint",event=>{const messageEvent=event;try{this._endpoint=new URL(messageEvent.data,this._url);if(this._endpoint.origin!==this._url.origin){throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}}catch(error){reject(error);this.onerror?.(error);void this.close();return}resolve()});this._eventSource.onmessage=event=>{const messageEvent=event;let message;try{message=JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data))}catch(error){this.onerror?.(error);return}this.onmessage?.(message)}})}async start(){if(this._eventSource){throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.")}return await this._startOrAuth()}async finishAuth(authorizationCode){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}const result=await auth(this._authProvider,{serverUrl:this._url,authorizationCode,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError("Failed to authorize")}}async close(){this._abortController?.abort();this._eventSource?.close();this.onclose?.()}async send(message){if(!this._endpoint){throw new Error("Not connected")}try{const headers=await this._commonHeaders();headers.set("content-type","application/json");const init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal:this._abortController?.signal};const response=await(this._fetch??fetch)(this._endpoint,init);if(!response.ok){const text2=await response.text().catch(()=>null);if(response.status===401&&this._authProvider){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3;const result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError}return this.send(message)}throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`)}await response.body?.cancel()}catch(error){this.onerror?.(error);throw error}}setProtocolVersion(version){this._protocolVersion=version}};init_esbuild_shims();var LAUNCHER=String.raw`
3
+ import{CSI_FILE_FINALIZATION_FORMAT,CSI_FILE_HISTORY_PATH,HOSTED_GLOB_TOO_COMPLEX,LocalShellResultCapture,MANAGED_CSI_ACK_LIMIT_BYTES,MANAGED_CSI_ACK_PATH,MANAGED_CSI_ATTEST_PATH,MANAGED_CSI_DRAIN_PATH,MANAGED_CSI_FILE_PREFIX,MANAGED_CSI_FILE_PROTOCOL,MANAGED_CSI_FILE_ROUTES,MANAGED_CSI_PROTOCOL,MANAGED_HOOK_MAX_REQUEST_BYTES,MANAGED_HOOK_MAX_RUNNING,MANAGED_HOOK_ROUTE,MANAGED_MCP_MAX_CONNECTIONS,MANAGED_MCP_ROUTE,MANAGED_MCP_TOOL,MANAGED_PACKAGE_MAX_ARCHIVE_BYTES,MANAGED_RUNTIME_PROVIDER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES,MAX_PROVIDER_MEDIA_RESULT_BYTES,MEASURED_WORKSPACE_CAPABILITY_DIGEST,ManagedAutomationGateTool,ManagedCsiAckRequestError,ManagedCsiDrainRequestError,ManagedRuntimeProviderProtocolError,WORKSPACE_ACTIVATION_ROUTE,WORKSPACE_CONTEXT_CONFIG_REF,WorkspaceActivations,checkHostedGlobPattern,compileManagedExtensionPackage,createManagedCsiFileReady,fitManagedRuntimeProviderResult,isCsiFilesCapability,isWorkspaceToolCapability,linuxDeviceNumber,managedRuntimeProviderLimit,matchesCsiFilesProfile,minimatch,parseManagedCsiAckJson,parseManagedCsiAckRequest,parseManagedCsiAckResponse,parseManagedCsiAcknowledgement,parseManagedCsiBoot,parseManagedCsiCaptureIdentity,parseManagedCsiDrainRequest,parseManagedCsiFileBoot,parseManagedCsiFileJson,parseManagedMcpRecipe,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult,parseManagedSkillContent,readCsiFileHistoryEnvelope,readCsiFileHistoryObservation,readCsiNativeRequest,readCsiPreparationEvidence,readCurrentCsiNative,readManagedCsiFileContext,readManagedCsiFileDrain,resolveManagedShellPublisherMode,validateManagedCsiAttestationRequest,validateManagedCsiAttestationResponse,validateManagedCsiFileAttestationRequest,validateManagedCsiFileAttestationResponse,validateManagedCsiPodIdentity,wrapManagedCsiFileContext}from"./chunk-66LFVQJP.js";import"./chunk-4RXAH36C.js";import{MANAGED_CONTEXT_ROUTES,ManagedContextInstallations,checkManagedContextAttestation,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,historyPath,parseToolPublicationBinding}from"./chunk-3QCFMVI6.js";import{computeManagedContextDigest,normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import"./chunk-6S5XOXJ2.js";import{MANAGED_SHELL_PUBLISHER_ROUTE,ManagedShellPublisherRegistry,publisherFields}from"./chunk-6PHTF2XF.js";import{CLOSE_SWEEP_TIMEOUT_MS,GROUP_EXIT_EVIDENCE_TIMEOUT_MS,ManagedRuntimeLedger,managedRuntimeLedgerFromEnvironment,signalProcessGroup}from"./chunk-RAERKMZM.js";import{MANAGED_RUNTIME_TOOL_RESULT_BODY_LIMIT_BYTES,OWNED_MANAGED_RUNTIME_ROUTES,authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore,nameManagedRuntimeIncarnation,ownedManagedRuntimeRouteGate,registerManagedRuntimeAttestationRoute}from"./chunk-AHRFY5S3.js";import"./chunk-3Y4UVTLL.js";import"./chunk-3SHHYK7S.js";import{require_express}from"./chunk-R337IZM4.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import{scrubAndReportInheritedLoaderEnv}from"./chunk-AJTR5LAF.js";import"./chunk-S7IKHQ6I.js";import{WebFetchTool}from"./chunk-DZWNLJXE.js";import{TodoWriteTool}from"./chunk-LCO75GQC.js";import{GlobTool}from"./chunk-IJD47F7Z.js";import{WriteFileTool}from"./chunk-3YOERSU5.js";import{EditTool}from"./chunk-TM6IVXAM.js";import"./chunk-AKDODQCI.js";import"./chunk-4RGPHRL7.js";import"./chunk-A4CHYJUQ.js";import"./chunk-6PNWMPY4.js";import{Config,Ct,DEFAULT_INHERITED_ENV_VARS,EventSource,FileHistoryService,HookCommandCgroup,HookCommandIsolationUnavailableError,HookRegistry,HookRunner,LocalManagedSessionResourceStore,MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,MAX_ARCHIVE_PATH_BYTES,ManagedSessionConflictError,ManagedToolProtocolError,Qn,SessionWriterLease,ShellTool,So,StdioClientTransport,deriveConfig,deserializeSnapshots,detectLineEnding,encodeTextFileContentAsync,firePostToolUseFailureHook,firePostToolUseHook,firePreToolUseHook,generateToolUseId,getDiffStat,interpolateUrl,isModifiableDeclarativeTool,isOperationGrantSuccessor,isSinglePathSegment,managedSessionResourceRoot,managedToolDigest,parseManagedExtensionApplyCommand,parseManagedExtensionPin,parseManagedExtensionPins,parseManagedToolContentModification,parseManagedToolMediaContext,parseOperationGrant,resolveCommandHookTimeoutMs,serializeManagedToolConfirmation,serializeSnapshot}from"./chunk-3NR3JBMA.js";import"./chunk-R2EHHA2C.js";import{ReadBuffer,serializeMessage}from"./chunk-SJYPUHXE.js";import"./chunk-ZIXAINJY.js";import{MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,MANAGED_TOOL_RESULT_ROUTES,ManagedSessionRecordError,assertManagedSessionDigest,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId,isToolResultPageAt,parseToolResultManifestBytes,parseToolResultPageBytes,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest}from"./chunk-HAALYXUJ.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import"./chunk-R7YLOR6I.js";import"./chunk-QVPT37XZ.js";import"./chunk-BPDVCOZ5.js";import"./chunk-DXUYBMFK.js";import"./chunk-MVGHVNW2.js";import"./chunk-MYPKMC5U.js";import"./chunk-B4ZATWBT.js";import{openNoFollow}from"./chunk-PSKT6KWO.js";import"./chunk-KNIWP2YB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-ZQMSIRJV.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-KTNQXX2N.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-6NQMNEZN.js";import"./chunk-PNF77EBK.js";import"./chunk-QEF4EGUP.js";import{Client,StreamableHTTPClientTransport,UnauthorizedError,auth,createFetchWithInit,extractWWWAuthenticateParams,normalizeHeaders}from"./chunk-6XLIEJP5.js";import{CallToolResultSchema,GetPromptResultSchema,JSONRPCMessageSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"./chunk-RGUKFSBS.js";import"./chunk-PHIPLV2I.js";import"./chunk-G5PYYZMM.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-PWOLGVA3.js";import"./chunk-FYFNRJO5.js";import"./chunk-CL2RUJMN.js";import"./chunk-2SU7MN4F.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-LMM27XGW.js";import"./chunk-CZI6AF2S.js";import"./chunk-744VRMDB.js";import"./chunk-GJ67UOXA.js";import"./chunk-IWT6YN3M.js";import"./chunk-7UK4WJWS.js";import"./chunk-UYYKHWZ6.js";import"./chunk-CJ24OR2E.js";import"./chunk-KBDJRE76.js";import"./chunk-4ZRCV3JY.js";import"./chunk-MTPKKEGR.js";import{getShellContextEnvVars}from"./chunk-INLKQF24.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import{sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import"./chunk-3YWXKSOI.js";import"./chunk-LG4NL2M7.js";import"./chunk-5AORBHSX.js";import"./chunk-66UTCJN2.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-WXQQVXYN.js";import"./chunk-AGEDDL7Z.js";import"./chunk-BN4FIQ77.js";import"./chunk-2TT7GTWH.js";import"./chunk-NSZJIBK7.js";import"./chunk-KLC75CL4.js";import"./chunk-N3AKLLXG.js";import"./chunk-KZSUHQLD.js";import{createAbortController}from"./chunk-476F6QIM.js";import"./chunk-A6LYTPBP.js";import{ReadFileTool}from"./chunk-R5AA46IX.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-7XUYVD4W.js";import{FileReadOpenError,decodeBufferWithEncodingInfoAsync,digestFileReadSource,readFileHandleBytes,readTextContentRangeFromHandle}from"./chunk-TQGZS3WN.js";import"./chunk-Z6AR5XE5.js";import"./chunk-NGXC4Y5Y.js";import"./chunk-JWTMTDHE.js";import{runWithInvocationContext}from"./chunk-EFTJIDS3.js";import"./chunk-DN4QKOFL.js";import"./chunk-AZ4Q2ZWQ.js";import"./chunk-4ZBZL23U.js";import"./chunk-LNYY7GOJ.js";import"./chunk-E5XJBLSO.js";import"./chunk-RXKUQONJ.js";import{atomicWriteJSON}from"./chunk-2GF3E5MI.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-ZBWKMYJX.js";import"./chunk-XMANRGPK.js";import"./chunk-UFRESHR3.js";import"./chunk-KQX4H2D3.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-HJKG5VPJ.js";import"./chunk-RP57XAJ2.js";import"./chunk-7DOOXUDG.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import"./chunk-3ITJ3AIN.js";import"./chunk-M4ECEHLX.js";import"./chunk-DBRQGEEI.js";import"./chunk-AAMQ5CMG.js";import"./chunk-ZQMVXHGH.js";import{HookEventName,HooksConfigSource,getHookKey}from"./chunk-4WFJ5OPA.js";import{getShellConfiguration}from"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import{isPathWithinRoot}from"./chunk-JOJLS3IB.js";import{ToolConfirmationOutcome}from"./chunk-5KGH76NL.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import"./chunk-XKCXQPE7.js";import"./chunk-3KUHQGOS.js";import{createDebugLogger,registerSessionProjectDir,sessionIdContext,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import{SKILL_PROVIDER_CONFIG_DIRS,Storage}from"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_express3=__toESM(require_express(),1);import{createServer as createServer2}from"node:http";import{createReadStream as createReadStream4}from"node:fs";import{mkdtemp as mkdtemp3}from"node:fs/promises";import path16 from"node:path";init_esbuild_shims();import{createHash as createHash11}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";init_esbuild_shims();import{constants,promises as fs}from"node:fs";import path from"node:path";async function executable(command,cwd,environment){const candidates=command.includes("/")?[path.resolve(cwd,command)]:(environment["PATH"]??"/usr/bin:/bin").split(path.delimiter).map(directory=>path.resolve(cwd,directory,command));for(const candidate of candidates){try{if(!(await fs.stat(candidate)).isFile())continue;await fs.access(candidate,constants.X_OK);return candidate}catch{}}throw new Error(`Extension executable is unavailable: ${command}`)}__name(executable,"executable");async function preflightManagedExtensionPackage(contributions,root,cwd,environment){const env={...environment,QWEN_EXTENSION_ROOT:root,CLAUDE_PLUGIN_ROOT:root,extensionPath:root};const expand=__name((value,executionEnvironment=env)=>value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/gu,(original,braced,plain)=>executionEnvironment[braced??plain]??original),"expand");let dynamicCommands=0;const check=__name(async(command,args,executionEnvironment=env)=>{const resolved=await executable(expand(command,executionEnvironment),cwd,executionEnvironment);const handle=await fs.open(resolved,"r");let head;try{const buffer=Buffer.alloc(512);const read=await handle.read(buffer,0,512,0);head=buffer.subarray(0,read.bytesRead).toString()}finally{await handle.close()}if(head.startsWith("#!")){const shebang=head.split("\n")[0].slice(2).trim().split(/\s+/u);await executable(shebang[0],cwd,executionEnvironment);if(path.basename(shebang[0])==="env"&&shebang[1]&&!shebang[1].startsWith("-"))await executable(shebang[1],cwd,executionEnvironment)}if(path.basename(resolved)==="env"&&args.length){if(args[0].startsWith("-")||args[0].includes("=")){dynamicCommands++;return}await check(args[0],args.slice(1),executionEnvironment);return}if(args.includes("-e")||args.includes("--eval")||args.includes("-c")){dynamicCommands++;return}for(const argument of args.filter(value=>!value.startsWith("-")&&/\.(?:[cm]?js|py|rb|sh)$/u.test(value))){const script=path.resolve(cwd,expand(argument,executionEnvironment));if(!(await fs.stat(script)).isFile())throw new Error("Extension script is unavailable.");await fs.access(script,constants.R_OK)}},"check");const shell=__name(async(command,executionEnvironment=env)=>{if(/[|;&><`\n]|\$\(/u.test(command)){dynamicCommands++;return}const tokens=[...command.matchAll(/"([^"]*)"|'([^']*)'|([^\s]+)/gu)].map(match=>match[1]??match[2]??match[3]);if(!tokens.length)return;if(tokens.some(token=>token.includes("$")&&expand(token,executionEnvironment)===token)){dynamicCommands++;return}if(/^[A-Za-z_][A-Za-z0-9_]*=/u.test(tokens[0])){dynamicCommands++;return}if([":","[","alias","bg","break","cd","continue","exit","export","false","fg","getopts","hash","jobs","pwd","read","readonly","return","set","shift","test","times","trap","true","type","ulimit","umask","unalias","unset","wait"].includes(tokens[0]))return;if(tokens[0]==="eval"){dynamicCommands++;return}if(["exec","command"].includes(tokens[0]))tokens.shift();if(tokens.length)await check(tokens[0],tokens.slice(1),executionEnvironment)},"shell");for(const value of Object.values(contributions.mcpServers)){const recipe=value;if(recipe.command)await check(recipe.command,recipe.args??[],{...env,...recipe.env})}for(const groups of Object.values(contributions.hooks)){for(const group of groups){for(const hook of group.hooks??[])if(hook.type==="command"&&hook.command)await shell(hook.command,{...env,...hook.env})}}for(const command of contributions.commands)for(const match of command.prompt.matchAll(/!\{([^}]*)\}/gu))await shell(match[1]);return{dynamicCommands}}__name(preflightManagedExtensionPackage,"preflightManagedExtensionPackage");init_esbuild_shims();function managedExtensionEnvironment(inherited,directory,extension={}){const environment={};for(const key of["PATH","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP"]){const value=inherited[key];if(value!==void 0)environment[key]=value}return{...environment,HOME:directory,USERPROFILE:directory,...extension}}__name(managedExtensionEnvironment,"managedExtensionEnvironment");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";import{promises as fs4}from"node:fs";import path4 from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{createReadStream,createWriteStream,promises as fs2}from"node:fs";import path2 from"node:path";import{Transform}from"node:stream";import{pipeline}from"node:stream/promises";var MANAGED_EXTENSION_ARCHIVE_MAX_BYTES=100*1024*1024;var DIGEST=/^[0-9a-f]{64}$/u;var ManagedExtensionCache=class{constructor(directory){this.directory=directory;if(!path2.isAbsolute(directory))throw new Error("Invalid package cache.")}static{__name(this,"ManagedExtensionCache")}async upload(digest3,source){this.assertDigest(digest3);await fs2.mkdir(this.directory,{recursive:true,mode:448});const temporary=path2.join(this.directory,`.upload-${randomUUID()}`);const hash=createHash("sha256");let bytes=0;const limit=new Transform({transform(chunk,_encoding,callback){bytes+=chunk.byteLength;if(bytes>MANAGED_EXTENSION_ARCHIVE_MAX_BYTES){callback(new Error("Package archive exceeds its size limit."));return}hash.update(chunk);callback(null,chunk)}});try{await pipeline(source,limit,createWriteStream(temporary,{flags:"wx",mode:384}));if(hash.digest("hex")!==digest3)throw new Error("Package archive digest mismatch.");await this.validateArchive(temporary);await fs2.rename(temporary,this.archivePath(digest3))}finally{await fs2.rm(temporary,{force:true})}}materialize(digest3){this.assertDigest(digest3);return this.extract(digest3)}async extract(digest3){const archive=this.archivePath(digest3);const hash=createHash("sha256");for await(const chunk of createReadStream(archive))hash.update(chunk);if(hash.digest("hex")!==digest3)throw new Error("Cached package archive digest mismatch.");await this.validateArchive(archive);const destination=path2.join(this.directory,`${digest3}-${randomUUID()}`);await fs2.mkdir(destination,{mode:448});try{await So({file:archive,cwd:destination,strict:true,noChmod:true});await fs2.writeFile(`${destination}.integrity`,await this.treeDigest(destination),{mode:384,flag:"wx"});return destination}catch(error){await fs2.rm(destination,{recursive:true,force:true});throw error}}async restoreMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!new RegExp(`^${digest3}-[0-9a-f-]{36}$`,"u").test(path2.basename(directory))||!(await fs2.lstat(this.directory)).isDirectory())throw new Error("Extension cache scope conflicts.");try{await this.verifyMaterialized(digest3,directory);return}catch{}const fresh=await this.materialize(digest3);const quarantine=path2.join(this.directory,`.quarantine-${randomUUID()}`);const moveIfPresent=__name(async(source,target)=>{try{await fs2.rename(source,target)}catch(error){if(error.code!=="ENOENT")throw error}},"moveIfPresent");try{await moveIfPresent(directory,quarantine);await moveIfPresent(`${directory}.integrity`,`${quarantine}.integrity`);await fs2.rename(fresh,directory);await fs2.rename(`${fresh}.integrity`,`${directory}.integrity`);await this.verifyMaterialized(digest3,directory);await fs2.rm(quarantine,{recursive:true,force:true});await fs2.rm(`${quarantine}.integrity`,{force:true})}finally{await fs2.rm(fresh,{recursive:true,force:true});await fs2.rm(`${fresh}.integrity`,{force:true})}}async verifyMaterialized(digest3,directory){this.assertDigest(digest3);if(path2.dirname(directory)!==this.directory||!path2.basename(directory).startsWith(`${digest3}-`))throw new Error("Extension cache scope conflicts.");if(!(await fs2.lstat(directory)).isDirectory())throw new Error("Extension cache root is unsafe.");const expected=await fs2.readFile(`${directory}.integrity`,"utf8");if(await this.treeDigest(directory)!==expected)throw new Error("Extension package assets drifted.")}async treeDigest(directory){const hash=createHash("sha256");const visit=__name(async relative2=>{const entries=await fs2.readdir(path2.join(directory,relative2),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name,"en"))){const child=path2.posix.join(relative2,entry.name);if(!entry.isDirectory()&&!entry.isFile())throw new Error("Extension assets contain an unsafe entry.");hash.update(JSON.stringify([child,entry.isDirectory()?"directory":"file"]));if(entry.isDirectory())await visit(child);else{const content=createHash("sha256");for await(const chunk of createReadStream(path2.join(directory,child)))content.update(chunk);hash.update(content.digest())}}},"visit");await visit("");return hash.digest("hex")}async validateArchive(file){let count=0;let bytes=0;let pathBytes=0;let invalid3=false;const seen=new Set;const source=createReadStream(file);const parser=Ct({strict:true,onReadEntry(entry){const normalized=path2.posix.normalize(entry.path).replace(/\/$/u,"");count++;bytes+=entry.size;pathBytes+=Buffer.byteLength(entry.path);if(!["File","Directory","OldFile","ContiguousFile"].includes(entry.type)||entry.path.includes("\\")||entry.path.includes("\0")||path2.posix.isAbsolute(entry.path)||/^[a-zA-Z]:/u.test(entry.path)||normalized===".."||normalized.startsWith("../")||seen.has(normalized)||count>MAX_ARCHIVE_ENTRIES||bytes>MAX_ARCHIVE_EXPANDED_BYTES||pathBytes>MAX_ARCHIVE_PATH_BYTES){invalid3=true;source.destroy(new Error("Unsafe package archive."))}seen.add(normalized)}});await pipeline(source,parser);if(invalid3)throw new Error("Unsafe package archive.")}archivePath(digest3){return path2.join(this.directory,`${digest3}.tar.gz`)}assertDigest(digest3){if(!DIGEST.test(digest3))throw new Error("Invalid package digest.")}};init_esbuild_shims();import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{constants as constants2,createReadStream as createReadStream2,createWriteStream as createWriteStream2}from"node:fs";import*as fs3 from"node:fs/promises";import*as path3 from"node:path";import{pipeline as pipeline2}from"node:stream/promises";import{Transform as Transform2,Writable}from"node:stream";var privateNames=new Set([".git",".env",".qwen-extension-settings.json",".qwen-extension-git-credentials.json",".qwen-extension-install.json",".qwen-managed-skill-origin.json"]);var UUID=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu;var CHUNK_BYTES=256*1024;var MAX_RETAINED_BYTES=512*1024*1024;function failed(code){throw new Error(code)}__name(failed,"failed");function contains(root,file){const relative2=path3.relative(root,file);return relative2!==".."&&!relative2.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative2)}__name(contains,"contains");async function boundedEntries(directory,limit,code){const entries=[];for await(const entry of await fs3.opendir(directory)){if(entries.length>=limit)failed(code);entries.push(entry)}return entries.sort((a,b)=>a.name.localeCompare(b.name))}__name(boundedEntries,"boundedEntries");function parseManagedRuntimeSkillControl(value){if(!value||typeof value!=="object"||Array.isArray(value))failed("invalid_skill_control");const op=value;if(typeof op["operationId"]!=="string"||!UUID.test(op["operationId"]))failed("invalid_skill_control");if(op["kind"]==="extension-skill-candidates"){if(Object.keys(op).sort().join(",")!=="kind,operationId")failed("invalid_skill_control")}else if(op["kind"]==="extension-skill-snapshot"){if(Object.keys(op).sort().join(",")!=="digest,kind,operationId,path"||typeof op["path"]!=="string"||!/^\.(?:qwen|agents)\/skills\/[^/\\]+$/u.test(op["path"])||op["path"].includes("\0")||op["path"].length>4096||op["path"].split("/").some(part=>part===".."||part===".")||typeof op["digest"]!=="string"||!/^[a-f0-9]{64}$/u.test(op["digest"]))failed("invalid_skill_control")}else if(op["kind"]==="extension-skill-archive"){if(Object.keys(op).sort().join(",")!=="kind,offset,operationId,preparationId"||typeof op["preparationId"]!=="string"||!UUID.test(op["preparationId"])||!Number.isSafeInteger(op["offset"])||Number(op["offset"])<0||Number(op["offset"])>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES)failed("invalid_skill_control")}else failed("invalid_skill_control");return structuredClone(op)}__name(parseManagedRuntimeSkillControl,"parseManagedRuntimeSkillControl");var ManagedRuntimeSkillSources=class{constructor(cacheDirectory,source){this.cacheDirectory=cacheDirectory;this.source=source;this.timer=setInterval(()=>{void this.sweep().catch(()=>void 0)},6e4);this.timer.unref()}static{__name(this,"ManagedRuntimeSkillSources")}snapshots=new Map;retainedBytes=0;preparing=0;pending=new Set;timer;closed=false;async close(){this.closed=true;clearInterval(this.timer);for(const snapshot of this.snapshots.values())await fs3.rm(snapshot.directory,{recursive:true,force:true});this.snapshots.clear();this.retainedBytes=0}async sweep(){for(const[id,snapshot]of this.snapshots)if(snapshot.expiresAt<=Date.now()){this.snapshots.delete(id);this.retainedBytes-=snapshot.byteLength;await fs3.rm(snapshot.directory,{recursive:true,force:true})}const known=new Set([...this.snapshots.values()].map(snapshot=>snapshot.directory));try{for await(const entry of await fs3.opendir(this.cacheDirectory)){if(!entry.isDirectory()||!entry.name.startsWith("skill-"))continue;const directory=path3.join(this.cacheDirectory,entry.name);if(known.has(directory))continue;const stat2=await fs3.lstat(directory).catch(()=>void 0);if(stat2&&stat2.mtimeMs+15*6e4<=Date.now())await fs3.rm(directory,{recursive:true,force:true})}}catch(error){if(error.code!=="ENOENT")throw error}}async manifest(root,file,source){await this.checked(root,file,source);const handle=await fs3.open(file,constants2.O_RDONLY|(constants2.O_NOFOLLOW??0)|(constants2.O_NONBLOCK??0));try{const before=await handle.stat();if(!before.isFile()||before.size>1024*1024)failed("invalid_skill_manifest");const bytes=Buffer.alloc(before.size);let offset=0;while(offset<bytes.length){const result=await handle.read(bytes,offset,bytes.length-offset,offset);if(!result.bytesRead)failed("source_changed");offset+=result.bytesRead}const after=await handle.stat();const named=await fs3.lstat(file);if(before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs||named.ino!==before.ino||named.dev!==before.dev)failed("source_changed");await this.checked(root,file,source);return new TextDecoder("utf-8",{fatal:true}).decode(bytes)}finally{await handle.close()}}async control(sessionId,operation){if(this.closed)failed("skill_source_unavailable");const op=parseManagedRuntimeSkillControl(operation);const source=await this.source(sessionId);const root=await fs3.realpath(source.directory);if(!await source.admits(root))failed("skill_source_unavailable");await this.sweep();if(op.kind==="extension-skill-archive"){const snapshot=this.snapshots.get(op.preparationId);if(!snapshot||snapshot.sessionId!==sessionId||snapshot.operationId!==op.operationId||snapshot.expiresAt<=Date.now()||op.offset>snapshot.byteLength)failed("skill_snapshot_unavailable");const handle=await fs3.open(path3.join(snapshot.directory,"skill.tar.gz"),"r");try{const buffer=Buffer.alloc(Math.min(CHUNK_BYTES,snapshot.byteLength-op.offset));const{bytesRead}=await handle.read(buffer,0,buffer.length,op.offset);if(bytesRead!==buffer.length||!await source.admits(root)||this.closed)failed("skill_snapshot_unavailable");return{operationId:op.operationId,preparationId:op.preparationId,offset:op.offset,totalBytes:snapshot.byteLength,base64:buffer.toString("base64")}}finally{await handle.close()}}if(op.kind==="extension-skill-candidates"){const candidates=[];const names=new Set;const budget={bytes:0,entries:0};let candidateBytes=0;for(const provider of SKILL_PROVIDER_CONFIG_DIRS){const relative2=`${provider}/skills`;const base=path3.join(root,relative2);try{await this.checked(root,base,source)}catch(error){if(error.code==="ENOENT")continue;throw error}const entries=await boundedEntries(base,1024,"skill_candidate_limit");for(const entry of entries){if(!entry.isDirectory()){if(entry.isSymbolicLink())failed("skill_source_unavailable");continue}if(candidates.length>=256)failed("skill_candidate_limit");const relativePath=`${relative2}/${entry.name}`;const directory=path3.join(root,relativePath);let candidate;try{const manifest=path3.join(directory,"SKILL.md");const content=await this.manifest(root,manifest,source);const skill=parseManagedSkillContent(content,manifest);if(skill.name.length>256||skill.description.length>4096||skill.description.includes("\0"))failed("invalid_skill_manifest");const observed=await this.scan(root,directory,source,budget);if(observed.files.filter(file=>file==="SKILL.md"||file.endsWith("/SKILL.md")).length!==1)failed("invalid_skill_manifest");candidate={name:skill.name,description:skill.description,path:relativePath,digest:observed.digest,shadowed:names.has(skill.name),compatible:true};names.add(skill.name)}catch(error){if(error.code==="ENOENT")continue;if(error instanceof Error&&["skill_source_unavailable","skill_source_limit","source_changed"].includes(error.message))throw error;candidate={name:entry.name,description:"",path:relativePath,digest:createHash2("sha256").update(relativePath).digest("hex"),shadowed:false,compatible:false,error:"Unsupported or invalid Skill content."}}candidateBytes+=Buffer.byteLength(JSON.stringify(candidate));if(candidateBytes>2*1024*1024)failed("skill_candidate_limit");candidates.push(candidate)}}if(!await source.admits(root)||this.closed)failed("skill_source_unavailable");return{operationId:op.operationId,candidates}}const identity=JSON.stringify([op.path,op.digest]);const existing=[...this.snapshots.entries()].find(([,value])=>value.sessionId===sessionId&&value.operationId===op.operationId);if(existing){if(existing[1].identity!==identity)failed("skill_snapshot_conflict");return this.descriptor(op.operationId,existing[0],existing[1])}if(this.preparing>=2||this.snapshots.size+this.preparing>=256)failed("skill_snapshot_capacity");const key=`${sessionId}\0${op.operationId}`;if(this.pending.has(key))failed("skill_snapshot_pending");this.pending.add(key);this.preparing++;let temporary;try{await fs3.mkdir(this.cacheDirectory,{recursive:true,mode:448});temporary=await fs3.mkdtemp(path3.join(this.cacheDirectory,"skill-"));const copied=path3.join(temporary,"source");await fs3.mkdir(copied);const directory=path3.join(root,op.path);const first=await this.scan(root,directory,source,{bytes:0,entries:0},copied);const second=await this.scan(root,directory,source,{bytes:0,entries:0});if(first.files.filter(file=>file==="SKILL.md"||file.endsWith("/SKILL.md")).length!==1)failed("invalid_skill_manifest");if(first.digest!==op.digest||second.digest!==first.digest)failed("source_changed");const manifest=path3.join(copied,"SKILL.md");if((await fs3.stat(manifest)).size>1024*1024)failed("invalid_skill_manifest");parseManagedSkillContent(await fs3.readFile(manifest,"utf8"),manifest);if(source.origin){const name=".qwen-managed-skill-origin.json";await fs3.writeFile(path3.join(copied,name),JSON.stringify({version:1,...source.origin,path:op.path,digest:op.digest}),{mode:420});await fs3.chmod(path3.join(copied,name),420);first.files.push(name);first.files.sort()}const archive=path3.join(temporary,"skill.tar.gz");await Qn({cwd:copied,file:archive,gzip:true,portable:true,noMtime:true},first.files);const byteLength=(await fs3.stat(archive)).size;if(byteLength>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES||this.retainedBytes+byteLength>MAX_RETAINED_BYTES)failed("skill_snapshot_capacity");const hash=createHash2("sha256");for await(const chunk of createReadStream2(archive))hash.update(chunk);await fs3.rm(copied,{recursive:true,force:true});await fs3.utimes(temporary,new Date,new Date);if(!await source.admits(root)||this.closed)failed("skill_source_unavailable");const snapshot={sessionId,operationId:op.operationId,identity,directory:temporary,sourceDigest:hash.digest("hex"),byteLength,expiresAt:Date.now()+15*6e4};const preparationId=randomUUID2();this.snapshots.set(preparationId,snapshot);this.retainedBytes+=byteLength;temporary=void 0;return this.descriptor(op.operationId,preparationId,snapshot)}finally{this.preparing--;this.pending.delete(key);if(temporary)await fs3.rm(temporary,{recursive:true,force:true})}}descriptor(operationId,preparationId,snapshot){return{operationId,preparationId,sourceDigest:snapshot.sourceDigest,byteLength:snapshot.byteLength}}async checked(root,file,source){const relative2=path3.relative(root,file);if(!contains(root,file))failed("skill_source_unavailable");let cursor=root;for(const segment of relative2.split(path3.sep).filter(Boolean)){cursor=path3.join(cursor,segment);const stat2=await fs3.lstat(cursor);if(stat2.isSymbolicLink()||!stat2.isDirectory()&&!stat2.isFile())failed("skill_source_unavailable")}const real=await fs3.realpath(file);if(!contains(root,real)||!await source.admits(real))failed("skill_source_unavailable")}async scan(root,directory,source,budget,destination){const hash=createHash2("sha256");const files=[];await this.checked(root,directory,source);const visit=__name(async relative2=>{const current=path3.join(directory,relative2);const before=await fs3.lstat(current);const entries=await boundedEntries(current,MAX_ARCHIVE_ENTRIES-budget.entries,"skill_source_limit");budget.entries+=entries.length;for(const entry of entries){if(privateNames.has(entry.name)||entry.name.startsWith(".env."))continue;const name=relative2?`${relative2}/${entry.name}`:entry.name;if(Buffer.byteLength(name)>4096)failed("skill_source_limit");budget.pathBytes=(budget.pathBytes??0)+Buffer.byteLength(name);if(budget.pathBytes>MAX_ARCHIVE_PATH_BYTES)failed("skill_source_limit");const file=path3.join(directory,name);await this.checked(root,file,source);if(entry.isDirectory()){await visit(name);continue}const handle=await fs3.open(file,constants2.O_RDONLY|(constants2.O_NOFOLLOW??0)|(constants2.O_NONBLOCK??0));try{const stat2=await handle.stat();if(!stat2.isFile())failed("skill_source_unavailable");budget.bytes+=stat2.size;if(budget.bytes>MAX_ARCHIVE_EXPANDED_BYTES||budget.entries>MAX_ARCHIVE_ENTRIES)failed("skill_source_limit");const mode=stat2.mode&73?493:420;hash.update(JSON.stringify([name,stat2.size,mode]));const sink=destination?(()=>{const target=path3.join(destination,name);return fs3.mkdir(path3.dirname(target),{recursive:true}).then(()=>createWriteStream2(target,{mode,flags:"wx"}))})():Promise.resolve(new Writable({write(_chunk,_encoding,done){done()}}));let read=0;await pipeline2(handle.createReadStream({autoClose:false}),new Transform2({transform(chunk,_encoding,done){read+=chunk.length;if(read>stat2.size){done(new Error("source_changed"));return}hash.update(chunk);done(null,chunk)}}),await sink);if(destination)await fs3.chmod(path3.join(destination,name),mode);const after2=await handle.stat();const named=await fs3.lstat(file);if(stat2.ino!==after2.ino||stat2.size!==after2.size||stat2.mtimeMs!==after2.mtimeMs||stat2.ctimeMs!==after2.ctimeMs||named.ino!==stat2.ino||named.dev!==stat2.dev)failed("source_changed");await this.checked(root,file,source);files.push(name)}finally{await handle.close()}}const after=await fs3.lstat(current);if(before.ino!==after.ino||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs)failed("source_changed")},"visit");await visit("");return{digest:hash.digest("hex"),files}}};var MANAGED_EXTENSION_RUNTIME_ROUTE=Object.freeze({key:"extensions",method:"POST",path:"/internal/managed-runtime/v3/extensions"});var MANAGED_EXTENSION_RETIRE_ROUTE=Object.freeze({key:"extension-retire",method:"POST",path:"/internal/managed-runtime/v3/extensions/retire"});var MANAGED_EXTENSION_UPLOAD_ROUTE=Object.freeze({key:"extension-package-upload",method:"PUT",path:"/internal/managed-runtime/v3/extensions/packages/:digest"});var ManagedExtensionRuntime=class{constructor(dependencies){this.dependencies=dependencies;if(!path4.isAbsolute(dependencies.directory))throw new Error("Invalid extension Runtime directory.");this.cache=new ManagedExtensionCache(path4.join(dependencies.directory,"packages"));if(dependencies.skillSource)this.skillSources=new ManagedRuntimeSkillSources(path4.join(dependencies.directory,"skill-snapshots"),dependencies.skillSource)}static{__name(this,"ManagedExtensionRuntime")}cache;skillSources;prepared=new Map;active=new Map;busy=new Set;environments=new Map;sessionOwners=new Map;ownerSessions=new Map;async skillControl(sessionId,operation){await this.requireSession(sessionId);if(!this.skillSources||this.isChanging(sessionId))throw new Error("skill_source_unavailable");if(operation.kind==="extension-skill-snapshot"&&!this.dependencies.idle(sessionId))throw new Error("skill_source_busy");const result=await this.skillSources.control(sessionId,operation);await this.requireSession(sessionId);return result}async closeSkillSnapshots(){await this.skillSources?.close()}async status(sessionId){await this.requireSession(sessionId);let pendingOperationId;try{pendingOperationId=parseManagedExtensionApplyCommand(JSON.parse(await fs4.readFile(this.pendingPath(sessionId),"utf8"))).operationId}catch(error){if(error.code!=="ENOENT")throw error}const pending=pendingOperationId?{pendingOperationId}:{};const installed=this.active.get(sessionId);if(installed)return{...this.state(installed.command),...pending};try{const stored=JSON.parse(await fs4.readFile(this.statePath(sessionId),"utf8"));const command=parseManagedExtensionApplyCommand(stored);const stopped=await fs4.stat(`${this.operationPath(sessionId,command.operationId)}.stopped`).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error});return{...this.state(command),...stopped?{state:"failed"}:{},...pending}}catch(error){if(error.code==="ENOENT")return{state:pendingOperationId?"outcome_unknown":"active",executionMode:this.dependencies.executionMode,revision:0,extensions:[],operationId:null,...pending};throw error}}async operationStatus(sessionId,operationId){const current=await this.status(sessionId);try{const proof=JSON.parse(await fs4.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof["operationId"]!==operationId||proof["executionMode"]!==this.dependencies.executionMode||proof["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof}catch(error){if(error.code!=="ENOENT")throw error}if(current.operationId===operationId&&!current.pendingOperationId)return current;const prepared=this.prepared.get(this.preparedKey(sessionId,operationId))??await this.loadPrepared(sessionId,operationId);if(prepared&&!current.pendingOperationId)return this.preparedView(prepared);return{...current,state:"outcome_unknown",operationId}}async prepare(sessionId,value,base={baseMcpServers:[],baseHookCatalog:null}){const command=parseManagedExtensionApplyCommand(value);return this.lock(sessionId,async()=>{const status=await this.status(sessionId);const key=this.preparedKey(sessionId,command.operationId);const existing=this.prepared.get(key)??await this.loadPrepared(sessionId,command.operationId);const publicBase={baseMcpServers:base.baseMcpServers,baseHookCatalog:base.baseHookCatalog};if(existing){if(JSON.stringify(existing.command)!==JSON.stringify(command)||JSON.stringify(existing.base)!==JSON.stringify(publicBase))throw new Error("Extension operation identity conflicts.");for(const pkg of existing.packages){await this.cache.restoreMaterialized(pkg.pin.packageDigest,pkg.assetRoot);const contributions=await this.dependencies.compile(pkg.assetRoot,pkg.pin,base.settings?.[pkg.pin.extensionId]??{},sessionId,base.packageManifests?.[pkg.pin.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);if(JSON.stringify(contributions)!==JSON.stringify(pkg.contributions))throw new Error("Prepared extension package drifted.")}const catalogs2=this.dependencies.stage?await this.dependencies.stage(sessionId,command,existing.packages,{...publicBase,preparedMcpServers:existing.mcpServers}):{mcpServers:[],hookCatalog:null};if(JSON.stringify(catalogs2.mcpServers)!==JSON.stringify(existing.mcpServers)||JSON.stringify(catalogs2.hookCatalog)!==JSON.stringify(existing.hookCatalog))throw new Error("Prepared extension catalogs drifted.");this.environments.set(key,base.settings??{});this.prepared.set(key,existing);return this.preparedView(existing)}if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.revision!==command.expectedRevision)throw new Error("Extension configuration revision conflicts.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");const packages=[];try{for(const pin2 of command.extensions){const unchanged=this.active.get(sessionId)?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));const assetRoot=unchanged?.assetRoot??await this.cache.materialize(pin2.packageDigest);await this.cache.restoreMaterialized(pin2.packageDigest,assetRoot);packages.push({pin:pin2,assetRoot,contributions:{skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]}});const contributions=await this.dependencies.compile(assetRoot,pin2,base.settings?.[pin2.extensionId]??{},sessionId,base.packageManifests?.[pin2.extensionId]);validateExtensionToolProfile(contributions,base.toolProfile);packages[packages.length-1]={pin:pin2,assetRoot,contributions}}}catch(error){await Promise.all(packages.map(entry=>this.active.get(sessionId)?.packages.some(active=>active.assetRoot===entry.assetRoot)?Promise.resolve():fs4.rm(entry.assetRoot,{recursive:true,force:true})));throw error}const catalogs=this.dependencies.stage?await this.dependencies.stage(sessionId,command,packages,base):{mcpServers:[],hookCatalog:null};if(!this.dependencies.stage&&packages.some(entry=>Object.keys(entry.contributions.mcpServers).length||Object.keys(entry.contributions.hooks).length))throw new Error("Extension process components are unsupported.");const prepared={ownerJournalId:this.dependencies.ownerJournalId??"in-memory",command,packages,base:publicBase,mcpServers:catalogs.mcpServers,hookCatalog:catalogs.hookCatalog};const view2=this.preparedView(prepared);await fs4.mkdir(path4.dirname(this.operationPath(sessionId,command.operationId)),{recursive:true,mode:448});await atomicWriteJSON(this.operationPath(sessionId,command.operationId),prepared,{mode:384});this.environments.set(key,base.settings??{});this.prepared.set(key,prepared);return view2})}async reconcile(sessionId,operationId,expectedRevision,revision){return this.lock(sessionId,async()=>{const prepared=await this.loadPrepared(sessionId,operationId);if(!prepared)throw new Error("Original extension owner journal is unavailable.");try{const proof2=JSON.parse(await fs4.readFile(`${this.operationPath(sessionId,operationId)}.stopped`,"utf8"));if(proof2["operationId"]!==operationId||proof2["revision"]!==revision||expectedRevision+1!==revision||proof2["executionMode"]!==this.dependencies.executionMode||proof2["state"]!=="stopped")throw new Error("Original stop proof conflicts.");return proof2}catch(error){if(error.code!=="ENOENT")throw error}const command=prepared.command;const current=await this.status(sessionId);if(command.operationId!==operationId||command.expectedRevision!==expectedRevision||revision!==expectedRevision+1||current.pendingOperationId!==void 0&&current.pendingOperationId!==operationId||current.revision!==expectedRevision&&(current.operationId!==operationId||current.revision!==revision||JSON.stringify(current.extensions)!==JSON.stringify(command.extensions)))throw new Error("Original extension operation conflicts.");const receipts=this.dependencies.reconcile?await this.dependencies.reconcile(sessionId):void 0;if(!receipts||receipts.length===0||receipts.some(entry=>entry.state!=="stopped"))return{operationId,revision,state:"outcome_unknown",executionMode:this.dependencies.executionMode};const proof={operationId,revision,state:"stopped",executionMode:this.dependencies.executionMode,receipts};await atomicWriteJSON(`${this.operationPath(sessionId,operationId)}.stopped`,proof,{mode:384});await atomicWriteJSON(this.statePath(sessionId),command,{mode:384});this.active.delete(sessionId);await fs4.rm(this.pendingPath(sessionId),{force:true});return proof})}async activate(sessionId,operationId){return this.lock(sessionId,async()=>{const status=await this.status(sessionId);if(status.pendingOperationId)throw new Error("Original extension activation outcome is unknown.");if(status.operationId===operationId){if(!this.active.has(sessionId)){const restored=this.prepared.get(this.preparedKey(sessionId,operationId));if(!restored)throw new Error("Active extension configuration requires exact reprepare.");await this.dependencies.install(sessionId,restored.packages,restored.command);this.active.set(sessionId,restored)}return status}const prepared=this.prepared.get(this.preparedKey(sessionId,operationId));if(!prepared||status.revision!==prepared.command.expectedRevision)throw new Error("Extension configuration was not prepared.");if(!this.dependencies.idle(sessionId))throw new Error("Extension configuration requires an idle Session.");await fs4.mkdir(path4.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.pendingPath(sessionId),prepared.command,{mode:384});await this.dependencies.drain(sessionId,prepared.command);await this.requireSession(sessionId);if(!this.dependencies.idle(sessionId))throw new Error("Extension Session acquired work while draining.");await this.dependencies.install(sessionId,prepared.packages,prepared.command);await fs4.mkdir(path4.dirname(this.statePath(sessionId)),{recursive:true,mode:448});await atomicWriteJSON(this.statePath(sessionId),prepared.command,{mode:384});this.active.set(sessionId,prepared);await fs4.rm(this.pendingPath(sessionId));return this.state(prepared.command)})}async getToolContext(sessionId,configRevision,value){await this.requireSession(sessionId);if(this.busy.has(sessionId))throw new Error("Extension configuration is changing.");const status=await this.status(sessionId);const active=this.active.get(sessionId);const pin2=parseManagedExtensionPin(value);const pkg=active?.packages.find(entry=>JSON.stringify(entry.pin)===JSON.stringify(pin2));if(!active||!pkg||status.pendingOperationId||status.revision!==configRevision)throw new Error("Extension tool configuration is unavailable.");const environment=this.environments.get(this.preparedKey(sessionId,active.command.operationId));if(!environment)throw new Error("Extension settings require exact reprepare.");await this.cache.verifyMaterialized(pin2.packageDigest,pkg.assetRoot);return{assetRoot:pkg.assetRoot,environment:{...environment[pin2.extensionId],QWEN_EXTENSION_ROOT:pkg.assetRoot}}}async bindSession(sessionId,runtimeSessionId,contextBinding){if(this.dependencies.bindContext)await this.dependencies.bindContext(sessionId,contextBinding);if(runtimeSessionId===void 0)return;const existing=this.ownerSessions.get(runtimeSessionId);if(existing&&existing!==sessionId)throw new Error("Extension Runtime owner conflicts.");this.ownerSessions.set(runtimeSessionId,sessionId);this.sessionOwners.set(sessionId,runtimeSessionId)}runtimeSessionId(sessionId){return this.sessionOwners.get(sessionId)??sessionId}isChanging(sessionId){return this.busy.has(this.ownerSessions.get(sessionId)??sessionId)}async readAsset(sessionId,revision,extensionId,relativePath){const root=await this.assetRoot(sessionId,revision,extensionId);const file=await this.contained(root,relativePath);const handle=await fs4.open(file,"r");try{const stat2=await handle.stat();if(!stat2.isFile()||stat2.size>256*1024)throw new Error("Extension asset exceeds the read limit.");return{path:relativePath,content:await handle.readFile("utf8")}}finally{await handle.close()}}async globAssets(sessionId,revision,extensionId,pattern){const root=await this.assetRoot(sessionId,revision,extensionId);if(pattern.length>1024||pattern.includes("\0"))throw new Error("Invalid extension glob.");const paths=[];const visit=__name(async directory=>{for(const entry of await fs4.readdir(directory,{withFileTypes:true})){const filename=path4.join(directory,entry.name);const relative2=path4.relative(root,filename).split(path4.sep).join("/");if(entry.isSymbolicLink())throw new Error("Extension assets contain a link.");if(entry.isDirectory())await visit(filename);else if(entry.isFile()&&minimatch(relative2,pattern,{dot:true})){if(paths.length===2048)throw new Error("Extension glob exceeds its result limit.");paths.push(relative2)}}},"visit");await visit(root);return paths.sort()}async assetRoot(sessionId,revision,extensionId){const status=await this.status(sessionId);const active=this.active.get(sessionId);if(this.isChanging(sessionId)||!active||status.revision!==revision)throw new Error("Extension configuration is unavailable.");const entry=active.packages.find(item=>item.pin.extensionId===extensionId);if(!entry)throw new Error("Extension package is not active in this Session.");if(status.pendingOperationId)throw new Error("Extension activation outcome is unknown.");await this.cache.verifyMaterialized(entry.pin.packageDigest,entry.assetRoot);return fs4.realpath(entry.assetRoot)}async contained(root,relative2){if(!relative2||relative2.includes("\\")||relative2.includes("\0")||path4.isAbsolute(relative2))throw new Error("Invalid extension asset path.");const filename=await fs4.realpath(path4.resolve(root,relative2));const resolved=path4.relative(root,filename);if(resolved===".."||resolved.startsWith(`..${path4.sep}`)||path4.isAbsolute(resolved))throw new Error("Extension asset path escapes its package.");return filename}preparedView(value){const result={operationId:value.command.operationId,state:"prepared",expectedRevision:value.command.expectedRevision,revision:value.command.expectedRevision+1,executionMode:this.dependencies.executionMode,packages:value.packages,mcpServers:value.mcpServers,hookCatalog:value.hookCatalog};if(Buffer.byteLength(JSON.stringify(result))>8*1024*1024)throw new Error("Extension prepare response exceeds its size limit.");return result}state(command){return{state:"active",executionMode:this.dependencies.executionMode,revision:command.expectedRevision+1,extensions:command.extensions,operationId:command.operationId}}async loadPrepared(sessionId,operationId){try{const value=JSON.parse(await fs4.readFile(this.operationPath(sessionId,operationId),"utf8"));if(value.ownerJournalId!==(this.dependencies.ownerJournalId??"in-memory"))throw new Error("Original extension owner journal is unavailable.");const command=parseManagedExtensionApplyCommand(value.command);if(command.operationId!==operationId||!Array.isArray(value.packages)||value.packages.length!==command.extensions.length)throw new Error("Invalid prepared extension receipt.");const pins=parseManagedExtensionPins(value.packages.map(pkg=>pkg.pin));if(JSON.stringify(pins)!==JSON.stringify(command.extensions))throw new Error("Prepared extension pins conflict.");for(const pkg of value.packages){if(typeof pkg.assetRoot!=="string"||path4.dirname(pkg.assetRoot)!==this.cache.directory||!path4.basename(pkg.assetRoot).startsWith(`${pkg.pin.packageDigest}-`))throw new Error("Invalid prepared extension asset root.")}this.preparedView(value);return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}operationPath(sessionId,operationId){return`${this.statePath(sessionId)}.${createHash3("sha256").update(operationId).digest("hex")}.prepared`}statePath(sessionId){return path4.join(this.dependencies.directory,"sessions",`${createHash3("sha256").update(sessionId).digest("hex")}.json`)}pendingPath(sessionId){return`${this.statePath(sessionId)}.pending`}preparedKey(sessionId,operationId){return`${sessionId}\0${operationId}`}async requireSession(sessionId){if(!sessionId||!await this.dependencies.admitted(sessionId))throw new Error("Extension Session is unavailable.")}async lock(sessionId,work){if(this.busy.has(sessionId))throw new Error("Extension Session configuration is changing.");this.busy.add(sessionId);try{await this.requireSession(sessionId);return await work()}finally{this.busy.delete(sessionId)}}};function registerManagedExtensionRuntimeRoutes(app,identity,runtime){app.put(MANAGED_EXTENSION_UPLOAD_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),async(req,res)=>{try{if(req.headers["content-type"]!=="application/gzip")throw new Error("Invalid package content type.");await runtime.cache.upload(String(req.params["digest"]),req);res.json({protocolVersion:1,packageDigest:req.params["digest"]})}catch{res.status(400).json({code:"managed_extension_package_invalid"})}});app.post(MANAGED_EXTENSION_RUNTIME_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(identity),managedRuntimeJsonBody(512*1024),async(req,res)=>{try{const body2=req.body;if(!body2||!["contextBinding,operation,protocolVersion,sessionKey","contextBinding,operation,protocolVersion,runtimeSessionId,sessionKey"].includes(Object.keys(body2).sort().join(","))||body2["protocolVersion"]!==1||body2["runtimeSessionId"]!==void 0&&typeof body2["runtimeSessionId"]!=="string")throw new Error("Invalid extension request.");const runtimeSessionId=body2["runtimeSessionId"];const sessionKey=body2["sessionKey"];if(!sessionKey||Object.keys(sessionKey).sort().join(",")!=="sessionId,tenantId,workspaceId"||sessionKey["tenantId"]!==identity.tenantId||sessionKey["workspaceId"]!==identity.workspaceId||typeof sessionKey["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/u.test(sessionKey["sessionId"]))throw new Error("Extension Session scope conflicts.");const sessionId=sessionKey["sessionId"];await runtime.bindSession(sessionId,runtimeSessionId,body2["contextBinding"]);const operation=body2["operation"];let result;if(operation["kind"]==="prepare"||operation["kind"]==="extension-prepare"){const control=operation;const parsed=parseManagedExtensionApplyCommand(control.command);if(control.kind==="extension-prepare"&&(control.operationId!==parsed.operationId||control.expectedRevision!==parsed.expectedRevision||JSON.stringify(control.extensions)!==JSON.stringify(parsed.extensions)))throw new Error("Extension prepare identity conflicts.");result=await runtime.prepare(sessionId,parsed,control.kind==="extension-prepare"?{toolProfile:typeof operation["toolProfile"]==="string"?operation["toolProfile"]:void 0,packageManifests:operation["packageManifests"],baseMcpServers:control.baseMcpServers,baseHookCatalog:control.baseHookCatalog,settings:operation["settings"]}:void 0)}else if(typeof operation["kind"]==="string"&&operation["kind"].startsWith("extension-skill-")){result=await runtime.skillControl(sessionId,parseManagedRuntimeSkillControl(operation))}else if((operation["kind"]==="activate"||operation["kind"]==="extension-activate")&&typeof operation["operationId"]==="string")result=await runtime.activate(sessionId,operation["operationId"]);else if(operation["kind"]==="extension-reconcile"&&typeof operation["operationId"]==="string"&&Number.isSafeInteger(operation["expectedRevision"])&&Number.isSafeInteger(operation["revision"]))result=await runtime.reconcile(sessionId,operation["operationId"],Number(operation["expectedRevision"]),Number(operation["revision"]));else if(operation["kind"]==="status"||operation["kind"]==="extension-status")result=typeof operation["operationId"]==="string"?await runtime.operationStatus(sessionId,operation["operationId"]):await runtime.status(sessionId);else if((operation["kind"]==="asset-read"||operation["kind"]==="extension-asset-read")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["path"]==="string")result=await runtime.readAsset(sessionId,Number(operation["revision"]),operation["extensionId"],operation["path"]);else if((operation["kind"]==="asset-glob"||operation["kind"]==="extension-asset-glob")&&Number.isSafeInteger(operation["revision"])&&typeof operation["extensionId"]==="string"&&typeof operation["pattern"]==="string")result=await runtime.globAssets(sessionId,Number(operation["revision"]),operation["extensionId"],operation["pattern"]);else throw new Error("Invalid extension operation.");if(typeof operation["operationId"]==="string"&&String(operation["kind"]).includes("asset-"))result=Array.isArray(result)?{operationId:operation["operationId"],paths:result}:{...result,operationId:operation["operationId"]};res.json({protocolVersion:1,sessionKey,...runtimeSessionId?{runtimeSessionId}:{},result})}catch(error){res.status(409).json({code:error instanceof Error&&["source_changed","skill_source_unavailable","skill_source_busy","skill_snapshot_unavailable","skill_snapshot_capacity","skill_snapshot_pending","skill_snapshot_conflict","skill_source_limit","skill_candidate_limit"].includes(error.message)?error.message:"managed_extension_configuration_unavailable"})}})}__name(registerManagedExtensionRuntimeRoutes,"registerManagedExtensionRuntimeRoutes");function validateExtensionToolProfile(value,profile){if(profile===void 0)return;const shell=profile==="hosted-workspace-shell/1"||profile==="hosted-workspace-team-lead/1";const mcp=shell||profile==="hosted-workspace-mcp/1";if(!mcp&&Object.keys(value.mcpServers).length)throw new Error("Session profile does not admit extension MCP.");if(!shell&&(JSON.stringify(value.hooks).includes('"type":"command"')||Object.values(value.mcpServers).some(recipe=>recipe&&typeof recipe==="object"&&"command"in recipe)||value.commands.some(command=>/!\{|!`/u.test(command.prompt))))throw new Error("Session profile does not admit extension Shell execution.");const base=["read_file","glob"];if(profile!=="hosted-workspace-read/1")base.push("write_file","edit","list_directory","grep_search","todo_write");if(shell)base.push("run_shell_command");for(const agent of value.agents)if(agent.tools?.some(tool=>!base.includes(tool)&&!(mcp&&tool.startsWith("mcp__"))))throw new Error("Extension agent tools exceed the Session profile.")}__name(validateExtensionToolProfile,"validateExtensionToolProfile");init_esbuild_shims();init_esbuild_shims();var ManagedExtensionExecutionUnknownError=class extends Error{static{__name(this,"ManagedExtensionExecutionUnknownError")}};async function runManagedExtensionShell(owners,input){input.signal.throwIfAborted();const shell=getShellConfiguration();const{child,ownerId,preread,detachPreread}=await owners.start({sessionId:input.sessionId,configRevision:input.configRevision,executable:shell.executable,args:[...shell.argsPrefix,input.command],cwd:input.cwd,env:input.environment,prereadOutput:true});const streamsClosed=new Promise(resolve=>{if((child.exitCode!==null||child.signalCode!==null)&&child.stdout?.destroyed===true&&child.stderr?.destroyed===true)resolve();else child.once("close",()=>resolve())});if(child.pid)input.capture?.setStarted(child.pid);child.stdin?.end();const chunks=[];let retained=0;let exceeded=false;const captures={stdout:Promise.resolve(),stderr:Promise.resolve()};const consume=__name((id,chunk)=>{if(input.capture){child[id]?.pause();captures[id]=captures[id].then(()=>input.capture.write(id,chunk)).finally(()=>child[id]?.resume())}const remaining=Math.max(0,1024*1024-retained);if(chunk.length>remaining)exceeded=true;if(remaining){const prefix=chunk.subarray(0,remaining);chunks.push(prefix);retained+=prefix.length}},"consume");detachPreread?.();if(preread){for(const chunk of preread.stdout)consume("stdout",chunk);for(const chunk of preread.stderr)consume("stderr",chunk);if(preread.overflow)exceeded=true}for(const id of["stdout","stderr"])child[id]?.on("data",chunk=>consume(id,chunk));let timedOut=false;let timer;let wake;const stop=__name(()=>{wake?.()},"stop");try{const exited=new Promise(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once("exit",()=>resolve())});const interrupted=new Promise(resolve=>{wake=resolve;input.signal.addEventListener("abort",stop,{once:true});if(input.signal.aborted)resolve();timer=setTimeout(()=>{timedOut=true;resolve()},input.timeoutMs??12e4)});await Promise.race([exited,interrupted]);const receipt2=await owners.stop(ownerId).catch(()=>{throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.")});if(receipt2.state!=="stopped")throw new ManagedExtensionExecutionUnknownError("Extension Shell process stop is unknown.");let drainTimer;try{await Promise.race([streamsClosed,new Promise((_resolve,reject)=>{drainTimer=setTimeout(()=>reject(new ManagedExtensionExecutionUnknownError("Extension Shell output closure is unknown.")),5e3)})])}finally{if(drainTimer)clearTimeout(drainTimer)}await Promise.all(Object.values(captures));const rawOutput=Buffer.concat(chunks);const output=rawOutput.toString("utf8");const result={rawOutput,output,exitCode:child.exitCode,signal:null,error:null,aborted:input.signal.aborted||timedOut,pid:child.pid,executionMethod:"child_process",outputCaptureLimitExceeded:exceeded};input.capture?.setProcessResult(result);await input.capture?.finish("stdout",true);await input.capture?.finish("stderr",true);return{llmContent:`${output}${exceeded?"\n[Output truncated]":""}${timedOut?"\n[Command timed out]":""}`,returnDisplay:output,...child.exitCode!==0||result.aborted?{error:{message:result.aborted?"Shell command stopped.":`Shell exited with code ${child.exitCode}.`,type:"execution_failed"}}:{}}}finally{if(timer)clearTimeout(timer);input.signal.removeEventListener("abort",stop)}}__name(runManagedExtensionShell,"runManagedExtensionShell");init_esbuild_shims();import{createHash as createHash6}from"node:crypto";import{promises as fs6}from"node:fs";import path7 from"node:path";init_esbuild_shims();function gateKey(sessionKey,operationId){const key=assertManagedSessionKey(sessionKey);const id=assertManagedSessionStableId(operationId,"operationId");return`${key.tenantId}\0${key.workspaceId}\0${key.sessionId}\0${id}`}__name(gateKey,"gateKey");var ManagedOperationGrantGate=class{static{__name(this,"ManagedOperationGrantGate")}entries=new Map;install(value){const grant=parseOperationGrant(value);const key=gateKey(grant.sessionKey,grant.operationId);const entry=this.entries.get(key);if(entry!==void 0&&grant.operationRevision<=entry.revokedThrough){throw new ManagedSessionConflictError(`operation ${grant.operationId} revision ${grant.operationRevision} was revoked.`)}const current=entry?.grant;if(current!==void 0){if(JSON.stringify(current)===JSON.stringify(grant)){return"unchanged"}if(!isOperationGrantSuccessor(current,grant)){throw new ManagedSessionConflictError(`grant revision ${grant.operationRevision} of operation ${grant.operationId} cannot replace revision ${current.operationRevision}.`)}}this.entries.set(key,{grant,revokedThrough:entry?.revokedThrough??0});return"installed"}revoke(sessionKey,operationId,operationRevision){const key=gateKey(sessionKey,operationId);assertManagedSessionSequence(operationRevision,"operationRevision");if(operationRevision<1){throw new ManagedSessionRecordError("operationRevision must be a positive safe integer.")}const entry=this.entries.get(key)??{grant:void 0,revokedThrough:0};entry.revokedThrough=Math.max(entry.revokedThrough,operationRevision);this.entries.set(key,entry)}admits(sessionKey,operationId,phase,now){const entry=this.entries.get(gateKey(sessionKey,operationId));if(entry?.grant===void 0)return false;const{grant}=entry;return grant.operationRevision>entry.revokedThrough&&now<grant.expiresAt&&grant.resourceScope.phases.includes(phase)}};init_esbuild_shims();import path6 from"node:path";import{promises as fs5}from"node:fs";import{lstat as lstat3,readlink,realpath as realpath2}from"node:fs/promises";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";init_esbuild_shims();import{createHash as createHash4}from"node:crypto";import{createReadStream as createReadStream3}from"node:fs";import{lstat as lstat2}from"node:fs/promises";import path5 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();function copySnapshots(snapshots){return snapshots.map(snapshot=>({promptId:snapshot.promptId,timestamp:snapshot.timestamp,trackedFileBackups:Object.fromEntries(Object.entries(snapshot.trackedFileBackups).map(([filePath,backup])=>{if(!Number.isSafeInteger(backup.version)||backup.version<0){throw new Error("Invalid managed file history backup version.")}return[filePath,{backupFileName:backup.backupFileName,version:backup.version,backupTime:backup.backupTime,...backup.failed?{failed:true}:{}}]}))}))}__name(copySnapshots,"copySnapshots");var ManagedToolFileHistory=class{constructor(ownerSessionId,cwd,serializedSnapshots,retainedStorage){this.ownerSessionId=ownerSessionId;this.service=new FileHistoryService(ownerSessionId,true,cwd,()=>this.capture(),retainedStorage);this.service.restoreFromSnapshots(deserializeSnapshots(copySnapshots(serializedSnapshots)));this.snapshots=this.readSnapshots();this.snapshotJson=JSON.stringify(this.snapshots);this.startedPrompts=new Set(this.snapshots.map(({promptId})=>promptId));this.initialization=this.service.validateRestoredSnapshots();void this.initialization.catch(()=>{})}static{__name(this,"ManagedToolFileHistory")}service;initialization;pending=Promise.resolve();startedPrompts;revision=0;snapshots;snapshotJson;ready(){return this.initialization}state(){return{ownerSessionId:this.ownerSessionId,revision:this.revision,snapshots:structuredClone(this.snapshots)}}checkpoint(promptId){return this.run(async()=>{if(this.service.getSnapshots().at(-1)?.promptId===promptId)return;if(this.startedPrompts.has(promptId)){throw new Error("Managed file history cannot reopen an earlier turn.")}await this.service.makeSnapshot(promptId);this.startedPrompts.add(promptId)})}run(operation){const result=this.pending.then(async()=>{await this.initialization;try{return await operation()}finally{this.capture()}});this.pending=result.then(()=>{},()=>{});return result}async drain(){const pending=this.pending;await this.initialization;await pending}readSnapshots(){return copySnapshots(this.service.getSnapshots().map(serializeSnapshot))}capture(){const snapshots=this.readSnapshots();const snapshotJson=JSON.stringify(snapshots);if(snapshotJson===this.snapshotJson)return;this.snapshots=snapshots;this.snapshotJson=snapshotJson;this.revision++}};var ManagedRuntimeFileHistory=class{constructor(ownerSessionId,directory,state,retainedStorage){this.ownerSessionId=ownerSessionId;this.directory=directory;this.retainedStorage=retainedStorage;this.history=new ManagedToolFileHistory(ownerSessionId,directory,state?.snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split("/").join(path5.sep),backup]))}))??[],retainedStorage);this.files=Object.assign(Object.create(null),structuredClone(state?.files??{}))}static{__name(this,"ManagedRuntimeFileHistory")}history;files;prepared=new Set;async ready(checkPaths=true){await this.history.ready();await this.history.service.validateRestoredSnapshots();const checked=new Set;for(const snapshot of this.history.state().snapshots){for(const[file,backup]of Object.entries(snapshot.trackedFileBackups)){if(backup.failed)throw new Error("Hosted file history backup is unavailable.");if(checkPaths&&!checked.has(file)){await this.resolve(file.split(path5.sep).join("/"));checked.add(file)}}}}state(){return{ownerSessionId:this.ownerSessionId,snapshots:this.history.state().snapshots.map(s=>({...s,trackedFileBackups:Object.fromEntries(Object.entries(s.trackedFileBackups).map(([file,backup])=>[file.split(path5.sep).join("/"),backup]))})),files:structuredClone(this.files)}}async prepare(promptId,paths){await this.ready();const snapshots=this.history.state().snapshots;if(snapshots.length>=100&&snapshots.at(-1)?.promptId!==promptId)throw new Error("Hosted file history has reached its 100 snapshot limit.");const newPrompt=snapshots.at(-1)?.promptId!==promptId;const observed=Object.create(null);for(const file of new Set([...newPrompt?Object.keys(this.files):[],...paths])){observed[file]=await this.fingerprint(file);if(!newPrompt&&Object.hasOwn(this.files,file)&&!isDeepStrictEqual(observed[file],this.files[file]))throw new Error("Hosted file changed outside tracked mutations.")}const previous=new ManagedToolFileHistory(this.ownerSessionId,this.directory,snapshots,this.retainedStorage);await previous.ready();try{await this.history.checkpoint(promptId);await this.history.run(async()=>{for(const file of paths){const absolute=await this.resolve(file);await this.history.service.trackEdit(absolute);const backups=this.history.service.getSnapshots().at(-1)?.trackedFileBackups;const key=file.split("/").join(path5.sep);if(!backups||!Object.hasOwn(backups,key)||backups[key].failed)throw new Error("Hosted file backup failed; mutation was not started.")}await this.ready();for(const[file,expected]of Object.entries(observed))if(!isDeepStrictEqual(await this.fingerprint(file),expected))throw new Error("Hosted file changed during backup preparation.");Object.assign(this.files,observed);if(newPrompt)this.prepared.clear();for(const file of paths)this.prepared.add(file)})}catch(error){this.history=previous;throw error}}async execute(file,action){historyPath(file);if(!this.prepared.has(file))throw new Error("Hosted file mutation has no prepared backup.");return this.history.run(async()=>{await this.ready();if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file]))throw new Error("Hosted file changed after backup preparation.");try{return await action()}finally{this.files[file]=await this.fingerprint(file)}})}async rewind(promptId){if(this.retainedStorage)throw new Error("Retained history cannot rewind.");await this.ready(false);return this.history.run(async()=>{let conflict2=false;try{for(const file of Object.keys(this.files)){if(!isDeepStrictEqual(await this.fingerprint(file),this.files[file])){conflict2=true;break}}}catch{conflict2=true}if(conflict2)return{state:this.state(),filesChanged:[],filesFailed:[],conflict:true};const result=await this.history.service.rewind(promptId,false);for(const file of Object.keys(this.files))this.files[file]=await this.fingerprint(file);return{state:this.state(),filesChanged:result.filesChanged.map(file=>path5.relative(this.directory,file).split(path5.sep).join("/")),filesFailed:result.filesFailed.map(file=>path5.relative(this.directory,file).split(path5.sep).join("/")),conflict:false}})}async resolve(file){historyPath(file);if(this.retainedStorage){const absolute=path5.join(this.directory,file);return this.retainedStorage.withWorkingFile(absolute,async()=>absolute)}let current=this.directory;const segments=file.split("/");for(const[index,segment]of segments.entries()){current=path5.join(current,segment);try{const info=await lstat2(current);if(info.isSymbolicLink()||(index<segments.length-1?!info.isDirectory():!info.isFile()))throw new Error("Hosted file history requires ordinary Workspace files.")}catch(error){if(error.code!=="ENOENT")throw error}}return current}async fingerprint(file){historyPath(file);if(this.retainedStorage)return this.retainedStorage.withWorkingFile(path5.join(this.directory,file),async source=>source?{digest:`sha256:${await digestFileReadSource(source)}`,mode:source.stats.mode&4095}:null);const absolute=await this.resolve(file);try{const before=await lstat2(absolute);const digest3=createHash4("sha256");for await(const chunk of createReadStream3(absolute))digest3.update(chunk);const after=await lstat2(absolute);if(before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.mode!==after.mode)throw new Error("Hosted file changed while reading history.");return{digest:`sha256:${digest3.digest("hex")}`,mode:after.mode&4095}}catch(error){if(error.code==="ENOENT")return null;throw error}}};init_esbuild_shims();import{createHash as createHash5}from"node:crypto";import{readFileSync}from"node:fs";init_esbuild_shims();var SseError=class extends Error{static{__name(this,"SseError")}constructor(code,message,event){super(`SSE error: ${message}`);this.code=code;this.event=event}};var SSEClientTransport=class{static{__name(this,"SSEClientTransport")}constructor(url,opts){this._url=url;this._resourceMetadataUrl=void 0;this._scope=void 0;this._eventSourceInit=opts?.eventSourceInit;this._requestInit=opts?.requestInit;this._authProvider=opts?.authProvider;this._fetch=opts?.fetch;this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit)}async _authThenStart(){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}let result;try{result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(error){this.onerror?.(error);throw error}if(result!=="AUTHORIZED"){throw new UnauthorizedError}return await this._startOrAuth()}async _commonHeaders(){const headers={};if(this._authProvider){const tokens=await this._authProvider.tokens();if(tokens){headers["Authorization"]=`Bearer ${tokens.access_token}`}}if(this._protocolVersion){headers["mcp-protocol-version"]=this._protocolVersion}const extraHeaders=normalizeHeaders(this._requestInit?.headers);return new Headers({...headers,...extraHeaders})}_startOrAuth(){const fetchImpl=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((resolve,reject)=>{this._eventSource=new EventSource(this._url.href,{...this._eventSourceInit,fetch:__name(async(url,init)=>{const headers=await this._commonHeaders();headers.set("Accept","text/event-stream");const response=await fetchImpl(url,{...init,headers});if(response.status===401&&response.headers.has("www-authenticate")){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3}return response},"fetch")});this._abortController=new AbortController;this._eventSource.onerror=event=>{if(event.code===401&&this._authProvider){this._authThenStart().then(resolve,reject);return}const error=new SseError(event.code,event.message,event);reject(error);this.onerror?.(error)};this._eventSource.onopen=()=>{};this._eventSource.addEventListener("endpoint",event=>{const messageEvent=event;try{this._endpoint=new URL(messageEvent.data,this._url);if(this._endpoint.origin!==this._url.origin){throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}}catch(error){reject(error);this.onerror?.(error);void this.close();return}resolve()});this._eventSource.onmessage=event=>{const messageEvent=event;let message;try{message=JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data))}catch(error){this.onerror?.(error);return}this.onmessage?.(message)}})}async start(){if(this._eventSource){throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.")}return await this._startOrAuth()}async finishAuth(authorizationCode){if(!this._authProvider){throw new UnauthorizedError("No auth provider")}const result=await auth(this._authProvider,{serverUrl:this._url,authorizationCode,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError("Failed to authorize")}}async close(){this._abortController?.abort();this._eventSource?.close();this.onclose?.()}async send(message){if(!this._endpoint){throw new Error("Not connected")}try{const headers=await this._commonHeaders();headers.set("content-type","application/json");const init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal:this._abortController?.signal};const response=await(this._fetch??fetch)(this._endpoint,init);if(!response.ok){const text2=await response.text().catch(()=>null);if(response.status===401&&this._authProvider){const{resourceMetadataUrl,scope:scope3}=extractWWWAuthenticateParams(response);this._resourceMetadataUrl=resourceMetadataUrl;this._scope=scope3;const result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if(result!=="AUTHORIZED"){throw new UnauthorizedError}return this.send(message)}throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`)}await response.body?.cancel()}catch(error){this.onerror?.(error);throw error}}setProtocolVersion(version){this._protocolVersion=version}};init_esbuild_shims();var LAUNCHER=String.raw`
4
4
  const { spawn } = require('node:child_process');
5
5
  const [executable, argsJson] = process.argv.slice(1);
6
6
  const args = JSON.parse(argsJson);
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson}from"./chunk-ASQ7BSJ4.js";import"./chunk-36TKFM4Z.js";import"./chunk-YJ6APXNB.js";import"./chunk-ESXBBANA.js";import"./chunk-6KMPLONS.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson};
3
+ import{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson}from"./chunk-JJ4UPR4A.js";import"./chunk-36TKFM4Z.js";import"./chunk-YJ6APXNB.js";import"./chunk-OPBSEVFC.js";import"./chunk-6KMPLONS.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{SSH_RETIRE_PATH,SshBootstrapError,executeSshBootstrap,inspectSshStorage,readSshPrivateJson,readSshRuntimeRecord,runManagedRuntimeBootstrap,sshCleanProof,sshResourcePath,sshRuntimeHeaders,verifySshStorage,writeSshPrivateJson};